rosefc 0.2.0 → 0.2.1
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/LICENSE +1 -1
- package/deploy/Dockerfile.node +2 -2
- package/deploy/Dockerfile.static +5 -5
- package/deploy/cloudflare/functions/[[path]].ts +2 -2
- package/deploy/cloudflare/wrangler.toml +2 -2
- package/deploy/fly.toml +4 -4
- package/deploy/k8s/{rosefd.yaml → rosefc.yaml} +22 -22
- package/deploy/native/{RosefdApp.xcscheme → RosefcApp.xcscheme} +16 -16
- package/deploy/native/android.yml +3 -3
- package/deploy/native/flutter.yml +8 -8
- package/deploy/native/ios.yml +8 -8
- package/deploy/netlify/functions/{rosefd.ts → rosefc.ts} +5 -5
- package/deploy/netlify.toml +1 -1
- package/deploy/vercel.json +2 -2
- package/dist-cli/compiler.mjs +149 -149
- package/dist-cli/edge.mjs +14 -14
- package/dist-cli/export.mjs +546 -546
- package/dist-cli/{rosefd.mjs → rosefc.mjs} +398 -398
- package/dist-cli/runtime.mjs +2 -2
- package/dist-cli/test.mjs +159 -159
- package/package.json +7 -7
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +1 -1
- package/src/cli/edge.ts +3 -3
- package/src/cli/prod-server.ts +12 -12
- package/src/cli/shell.ts +17 -17
- package/src/cli/shutdown.ts +3 -3
- package/src/runtime/db.ts +3 -3
- package/src/runtime/index.ts +60 -60
- package/src/types/{rosefd.d.ts → rosefc.d.ts} +12 -12
- /package/deploy/api/{rosefd.ts → rosefc.ts} +0 -0
|
@@ -16,25 +16,25 @@ var fg=Object.defineProperty;var De=(e,t)=>()=>(e&&(t=e(e=0)),t);var hg=(e,t)=>{
|
|
|
16
16
|
`,t+1)+1).replace(/^\s*\n/,""),r={};for(let i of n.split(`
|
|
17
17
|
`)){let o=/^(\w[\w-]*):\s*(.*)$/.exec(i.trim());if(!o)continue;let[,a,c]=o,d=/^\[(.+)\]$/.exec(c.trim());r[a]=d?d[1].split(",").map(u=>u.trim().replace(/^["']|["']$/g,"")):c.trim().replace(/^["']|["']$/g,"")}return{frontmatter:r,body:s}}function kg(e,t){return e.replace(/{{(\w[\w.]*)}}/g,(n,s)=>{let r=s.split(".").reduce((i,o)=>i==null?i:i[o],t);return r==null?"":String(r)})}function Ku(e,t){t&&(e=kg(e,t));let n=[],s=e.replace(/```(\w*)\n([\s\S]*?)```/g,(c,d,u)=>(n.push(`<pre data-lang="${d}"><code>${u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}</code></pre>`),`\0CODE${n.length-1}\0`)),r=c=>c.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/\*([^*]+)\*/g,"<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" rel="noopener">$1</a>'),i=[],o=null,a=()=>{o&&(i.push(`</${o}>`),o=null)};for(let c of s.split(`
|
|
18
18
|
`)){let d=/^(#{1,4})\s+(.*)$/.exec(c),u=/^\s*[-*]\s+(.*)$/.exec(c),l=/^\s*\d+\.\s+(.*)$/.exec(c);d?(a(),i.push(`<h${d[1].length}>${r(d[2])}</h${d[1].length}>`)):u?(o!=="ul"&&(a(),i.push("<ul>"),o="ul"),i.push(`<li>${r(u[1])}</li>`)):l?(o!=="ol"&&(a(),i.push("<ol>"),o="ol"),i.push(`<li>${r(l[1])}</li>`)):c.trim()===""?a():c.startsWith("\0CODE")?(a(),i.push(c)):(a(),i.push(`<p>${r(c)}</p>`))}return a(),i.join(`
|
|
19
|
-
`).replace(/\u0000CODE(\d+)\u0000/g,(c,d)=>n[Number(d)])}function Io(e){let t={};if(!Bo.existsSync(e))return t;for(let n of Bo.readdirSync(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let s=[],r=Qu.join(e,n.name);for(let i of Bo.readdirSync(r)){if(!i.endsWith(".md"))continue;let o=Bo.readFileSync(Qu.join(r,i),"utf-8"),{frontmatter:a,body:c}=xg(o);if(String(a.draft??"").toLowerCase()==="true")continue;let d=i.replace(/\.md$/,""),u=Ku(c),l=c.replace(/[#*`\[\]()>-]/g," ").split(/\s+/).filter(Boolean).length,p=[],f=u.replace(/<h([1-4])>([^<]+)<\/h\1>/g,(h,g,y)=>{let m=y.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-");return p.push({level:Number(g),text:y,id:m}),`<h${g} id="${m}">${y}</h${g}>`});s.push({slug:d,frontmatter:a,body:c,html:f,readingTime:Math.max(1,Math.round(l/200)),wordCount:l,toc:p,excerpt:String(a.summary??"")||(u.match(/<p>([\s\S]*?)<\/p>/)?.[1]??"").replace(/<[^>]+>/g,"").slice(0,160)})}s.sort((i,o)=>String(o.frontmatter.date??"").localeCompare(String(i.frontmatter.date??""))),t[n.name]=s}return t}var jl=De(()=>{"use strict";globalThis.
|
|
19
|
+
`).replace(/\u0000CODE(\d+)\u0000/g,(c,d)=>n[Number(d)])}function Io(e){let t={};if(!Bo.existsSync(e))return t;for(let n of Bo.readdirSync(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let s=[],r=Qu.join(e,n.name);for(let i of Bo.readdirSync(r)){if(!i.endsWith(".md"))continue;let o=Bo.readFileSync(Qu.join(r,i),"utf-8"),{frontmatter:a,body:c}=xg(o);if(String(a.draft??"").toLowerCase()==="true")continue;let d=i.replace(/\.md$/,""),u=Ku(c),l=c.replace(/[#*`\[\]()>-]/g," ").split(/\s+/).filter(Boolean).length,p=[],f=u.replace(/<h([1-4])>([^<]+)<\/h\1>/g,(h,g,y)=>{let m=y.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-");return p.push({level:Number(g),text:y,id:m}),`<h${g} id="${m}">${y}</h${g}>`});s.push({slug:d,frontmatter:a,body:c,html:f,readingTime:Math.max(1,Math.round(l/200)),wordCount:l,toc:p,excerpt:String(a.summary??"")||(u.match(/<p>([\s\S]*?)<\/p>/)?.[1]??"").replace(/<[^>]+>/g,"").slice(0,160)})}s.sort((i,o)=>String(o.frontmatter.date??"").localeCompare(String(i.frontmatter.date??""))),t[n.name]=s}return t}var jl=De(()=>{"use strict";globalThis.__rosefcContentMk=Ku});import*as te from"fs";import*as z from"path";import*as md from"os";import{pathToFileURL as Rg,fileURLToPath as Ni}from"url";import*as Jr from"esbuild";function br(e,t,n){let s=Mg(),r={...t,define:{...Fg(),...t.define??{}}};if(e+=`|env:${s}`,!n||t.splitting)return Jr.build(r);let i=Tl.get(e);return i?i.rebuild().catch(o=>{throw Tl.delete(e),o}):Jr.context(r).then(o=>(Tl.set(e,o),o.rebuild()))}function Xu(e){let t=/\bname\s*=\s*["'](\w+)["']/.exec(e)?.[1];if(!t)throw new ee("E-TEMPLATE",'<slot> with attributes must declare a name: <slot name="row" ... />',{hint:'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />'});let n=[...e.matchAll(/\b(\w+)\s*=\s*\{([^}]*)\}/g)].filter(s=>s[1]!=="name").map(s=>`['${s[1]}', (${s[2].trim()})]`);return`${JSON.stringify(t)}, [${n.join(", ")}]`}function Fg(){let e=Object.fromEntries(Vl()),t={};for(let[n,s]of Object.entries(e))Ng.test(n)&&(t[`import.meta.env.${n}`]=JSON.stringify(s).replace(/</g,"\\u003c"));return t["import.meta.env"]=JSON.stringify(e).replace(/</g,"\\u003c"),t}function Yu(e){return[...e.matchAll(/\bimport\.meta\.env\.([A-Za-z_$][\w$]*)/g)].map(t=>t[1])}function El(e,t){let n={"(":")","[":"]","{":"}"}[e[t]]??"";if(!n)return-1;let s=0;for(let r=t;r<e.length;r++)if(e[r]===e[t])s++;else if(e[r]===n&&(s--,s===0))return r;return-1}function Pg(e,t){let n={")":"(","]":"[","}":"{"}[e[t]]??"";if(!n)return-1;let s=0;for(let r=t;r>=0;r--)if(e[r]===e[t])s++;else if(e[r]===n&&(s--,s===0))return r;return-1}function Lg(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==="("||r==="["||r==="{"){n++;continue}if(r===")"||r==="]"||r==="}"){if(n===0)return s;n--;continue}if(n===0&&(r===","||r===";"))return s}return e.length}function Bg(e){let t=Wo(e),n=[],s=(r,i)=>{let o=[];for(let a of t.slice(r,i).matchAll(/\b(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/g))o.push(a[1]);return o};for(let r of t.matchAll(/\bfunction\b/g)){let i=r.index+r[0].length;for(;i<t.length&&/\s/.test(t[i]);)i++;for(t[i]==="*"&&i++;i<t.length&&/[A-Za-z_$]/.test(t[i]);)i++;for(;i<t.length&&/\s/.test(t[i]);)i++;if(t[i]!=="(")continue;let o=El(t,i);if(o<0)continue;let a=o+1;for(;a<t.length&&/\s/.test(t[a]);)a++;if(t[a]!=="{")continue;let c=El(t,a);if(c<0)continue;let d=new Set(Li(e.slice(i+1,o)));for(let u of s(a,c))d.add(u);n.push({start:i,end:c+1,names:d})}for(let r of t.matchAll(/=>/g)){let i=r.index,o=i-1;for(;o>=0&&/\s/.test(t[o]);)o--;let a="",c=i;if(t[o]===")"){let p=Pg(t,o);if(p<0)continue;a=e.slice(p+1,o),c=p}else if(/[A-Za-z_$]/.test(t[o]??"")){let p=o;for(;p>=0&&/[\w$]/.test(t[p]);)p--;a=e.slice(p+1,o+1),c=p+1}else continue;let d=i+2;for(;d<t.length&&/\s/.test(t[d]);)d++;let u=t[d]==="{"?El(t,d)+1:Lg(t,d);if(u<=0)continue;let l=new Set(Li(a));n.push({start:c,end:u,names:l})}return n.sort((r,i)=>r.start-i.start)}function Ps(e,t,n){if(t.length===0&&!n)return e;let s=Bg(e),r=(o,a)=>{for(let c of s){if(c.start>o)break;if(o<c.end&&c.names.has(a))return!0}return!1},i=(o,a=0)=>{let c="",d=0;for(;d<o.length;){let u=o[d];if(u==="'"||u==='"'){let l=d+1;for(;l<o.length&&o[l]!==u;)o[l]==="\\"&&l++,l++;c+=o.slice(d,Math.min(l+1,o.length)),d=l+1;continue}if(u==="`"){for(c+=u,d++;d<o.length&&o[d]!=="`";){if(o[d]==="\\"){c+=o.slice(d,d+2),d+=2;continue}if(o[d]==="$"&&o[d+1]==="{"){let l=1,p=d+2;for(;p<o.length&&l>0&&(o[p]==="{"?l++:o[p]==="}"&&l--,l!==0);)p++;c+="${"+i(o.slice(d+2,p),a+d+2)+"}",d=p+1;continue}c+=o[d],d++}c+="`",d++;continue}if(u==="/"&&o[d+1]==="/"){let l=o.indexOf(`
|
|
20
20
|
`,d),p=l===-1?o.length:l;c+=o.slice(d,p),d=p;continue}if(u==="/"&&o[d+1]==="*"){let l=o.indexOf("*/",d+2),p=l===-1?o.length:l+2;c+=o.slice(d,p),d=p;continue}if(/[A-Za-z_$]/.test(u)){let l=d;for(;l<o.length&&/[\w$]/.test(o[l]);)l++;let p=o.slice(d,l),f=c.length?c[c.length-1]:"",h=o[l]??"",g=f==="@",y=!/[\w$.]/.test(f)&&!/[\w$:(]/.test(h),m=y&&!g&&t.includes(p)&&!r(a+d,p),b=y&&n!=null&&Object.prototype.hasOwnProperty.call(n,p);c+=m?`${p}()`:b?`${n[p]}()`:p,d=l;continue}c+=u,d++}return c};return i(e)}function Li(e){return e.replace(/^[{[]/,"").replace(/[}\]]$/,"").split(",").map(n=>{let s=n.split("=")[0].trim(),r=s.indexOf(":");return r>=0?s.slice(r+1).trim():s}).filter(n=>/^[A-Za-z_$][\w$]*$/.test(n))}function vd(e,t){let n=[],s=0;for(;s<e.length;){let r=Om(e.slice(s),t);if(!r)break;if(r.selfClosing){s+=r.end;continue}let i=zo(e,s+r.end,r.name),o=i>=0?i+r.name.length+3:e.length;n.push([s+r.start,o]),s=o}return n}function zg(e,t){let n=[],s=0,r=t.size>0?vd(e,t):[],i=0,o=-1;for(let a of Hr(e)){for(;i<r.length&&r[i][0]<=a.start;)o=r[i++][1];if(a.start<o)continue;let c=a.expr;if($d.test(c)){s>0&&s--;continue}if(bd.test(c)){s++;continue}if(!wd.test(c)&&s===0){let d=/^\s*@const\s+([A-Za-z_$][\w$]*)\s*=/.exec(c);d&&n.push(d[1])}}return n}function Pl(e,t,n,s){if(t.length===0&&!n)return e;let r="",i=0,o=[new Set],a=()=>o[o.length-1],c=f=>o.some(h=>h.has(f)),d=s?.ownScope?f=>{for(let h=o.length-1;h>=0;h--)if(o[h].has(f))return h===0;return!1}:f=>!c(f),u=()=>[t.filter(f=>!c(f)),n?Object.fromEntries(Object.entries(n).filter(([f])=>d(f))):void 0],l=[];if(s?.comps&&s.comps.size>0)for(let[f,h]of vd(e,s.comps))l.push({pos:f,open:!0}),l.push({pos:h,open:!1});let p=0;for(let f of Hr(e)){for(;p<l.length&&l[p].pos<=f.start;)l[p].open?o.push(new Set):o.length>1&&o.pop(),p++;let h=f.expr;if($d.test(h)){o.length>1&&o.pop(),r+=e.slice(i,f.end+1),i=f.end+1;continue}if(bd.test(h)){let b=Ig.exec(h);if(b){let[,_,k,S,C]=b,[x,A]=u(),R=` as ${k}${S?`, ${S}`:""}`;o.push(new Set([...Li(k),...S?[S]:[]]));let T=C!=null&&C.trim()!==""?` (${Ps(C,...u())})`:"";r+=e.slice(i,f.start)+`{#each ${Ps(_,x,A)}${R}${T}}`,i=f.end+1;continue}let $=Wg.exec(h);if($){o.push(new Set($[2]?Li($[2]):[])),r+=e.slice(i,f.end+1),i=f.end+1;continue}let[w,v]=u();r+=e.slice(i,f.start)+"{"+Ps(h,w,v)+"}",o.push(new Set),i=f.end+1;continue}if(wd.test(h)){a().clear();let b=Dg.exec(h);if(b){a().add(b[1]),r+=e.slice(i,f.end+1),i=f.end+1;continue}let[$,w]=u();r+=e.slice(i,f.start)+"{"+Ps(h,$,w)+"}",i=f.end+1;continue}let g=/^\s*@const\s+([A-Za-z_$][\w$]*)\s*=([\s\S]*)$/.exec(h),[y,m]=u();if(g){let b=g[2],$=Ps(b,y,m);a().add(g[1]),r+=e.slice(i,f.start)+($===b?e.slice(f.start,f.end+1):`{@const ${g[1]} =${$}}`),i=f.end+1;continue}r+=e.slice(i,f.start)+"{"+Ps(h,y,m)+"}",i=f.end+1}return r+e.slice(i)}function Hr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="{"){let s=Bi(e,n);if(s>n+1){t.push({start:n,end:s,expr:e.slice(n+1,s)}),n=s+1;continue}}n++}return t}function Hg(e,t){let n=t;for(;n<e.length;){if(e[n]==="{"){let s=Bi(e,n);if(s>n+1)return{index:n,end:s,expr:e.slice(n+1,s)}}n++}return null}function Bi(e,t){let n=0,s=t;for(;s<e.length;){let r=e[s];if(r==="'"||r==='"'){s=Bs(e,s);continue}if(r==="`"){s=Ho(e,s);continue}if(r==="/"){let i=$r(e,s);if(i!==null){s=i;continue}}if(r==="{")n++;else if(r==="}"&&--n===0)return s;s++}return-1}function Ls(e,t){let n=t+2,s=1;for(;n<e.length;){let r=e[n];if(r==="'"||r==='"'){n=Bs(e,n);continue}if(r==="`"){n=Ho(e,n);continue}if(r==="{")s++;else if(r==="}"&&--s===0)return n+1;n++}return-1}function Bs(e,t){let n=e[t],s=t+1;for(;s<e.length;){if(e[s]==="\\"){s+=2;continue}if(e[s]===n)return s+1;s++}return s}function Ho(e,t){let n=t+1;for(;n<e.length;){let s=e[n];if(s==="\\"){n+=2;continue}if(s==="`")return n+1;if(s==="$"&&e[n+1]==="{"){let r=Bi(e,n+1);n=r<0?e.length:r+1;continue}n++}return n}function Sd(e,t){let n=t;for(;n>=0&&/[\w$]/.test(e[n]);)n--;return n===t?"":e.slice(n+1,t+1)}function $r(e,t){let n=e[t];if(n==='"'||n==="'")return Bs(e,t);if(n==="`")return Ho(e,t);if(n!=="/"||e[t+1]==="/"||e[t+1]==="*")return null;let s=t-1;for(;s>=0&&/\s/.test(e[s]);)s--;if(s>=0&&!"(,=:[!&|?{};+-*%~^".includes(e[s])){let o=Sd(e,s);if(!["return","typeof","case","in","of","new","delete","void","do","else","instanceof","yield","await"].includes(o))return null}let r=t+1,i=!1;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===`
|
|
21
21
|
`)return null;if(i)o==="]"&&(i=!1);else if(o==="[")i=!0;else if(o==="/"){r++;break}r++}if(r>e.length)return null;for(;r<e.length&&/[dgimsuvy]/.test(e[r]);)r++;return r}function ed(e){let t="",n=0;for(;n<e.length;){let s=$r(e,n);if(s!==null){t+=e.slice(n,s),n=s;continue}if(e.startsWith("//",n)){for(;n<e.length&&e[n]!==`
|
|
22
22
|
`;)n++;continue}if(e.startsWith("/*",n)){for(n+=2;n<e.length&&!e.startsWith("*/",n);)n++;n=Math.min(n+2,e.length);continue}if(e.startsWith("<!--",n)){for(n+=4;n<e.length&&!e.startsWith("-->",n);)n++;n=Math.min(n+3,e.length);continue}t+=e[n++]}return t}function Vg(e){let t=/typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y,n=l=>{for(;l<e.length&&/\s/.test(e[l]);)l++;return l},s=l=>{let p=0,f=l+1;for(;f<e.length;){let h=e[f],g=$r(e,f);if(g!==null){f=g;continue}if(h==="("||h==="["||h==="{")p++;else if(h===")"||h==="]"||h==="}"){if(p--,p<0)return-1}else{if(p===0&&h===":")return f;if(p===0&&h==="?"){let y=s(f);if(y<0)return-1;f=y+1;continue}}f++}return-1},r=l=>{let p=0;for(;l<e.length;){let f=e[l],h=$r(e,l);if(h!==null){l=h;continue}if(f==="("||f==="["||f==="{")p++;else if(f===")"||f==="]"||f==="}"){if(p===0)return l;p--}else{if(p===0&&(f===","||f===";"))return l;if(p===0&&f==="?"){let g=s(l);if(g<0)return e.length;l=g+1;continue}}l++}return e.length},i=l=>{let p=0,f=l;for(;f<e.length;){let h=e[f],g=$r(e,f);if(g!==null){f=g;continue}if(h==="{")p++;else if(h==="}"&&(p--,p===0))return f;f++}return e.length},o=l=>{let p=0;for(;l<e.length;){let f=e[l],h=$r(e,l);if(h!==null){l=h;continue}if(f==="("||f==="["||f==="{")p++;else if(f===")"||f==="]"||f==="}"){if(p===0)return l;p--}else if(p===0&&(f===";"||f===`
|
|
23
23
|
`))return l;l++}return e.length},a=(l,p)=>{let f=p-1;for(;f>=0&&/\s/.test(l[f]);)f--;if(f<0||l[f]!=="(")return!1;for(f--;f>=0&&/\s/.test(l[f]);)f--;return f>=1&&l[f]==="f"&&l[f-1]==="i"&&(f<2||!/[\w$]/.test(l[f-2]))},c=[],d=0;for(;d<e.length;){let l=$r(e,d);if(l!==null){d=l;continue}t.lastIndex=d;let p=t.exec(e);if(!p){d++;continue}let f=p[1]==="!==",h=n(d+p[0].length),g=e.slice(h,h+2);if(g==="&&"&&f)c.push([h+2,r(h+2)]);else if(g==="||"&&!f)c.push([h+2,r(h+2)]);else if(e[h]==="?"){let y=s(h);y<0?f&&c.push([h+1,e.length]):f?c.push([h+1,y]):c.push([y+1,r(y+1)])}else if(e[h]===")"&&a(e,d)){let y,m=n(h+1);e[m]==="{"?(y=i(m),f&&c.push([m+1,y])):(y=o(m),f&&c.push([m,y]));let b=n(y+1);if(e.startsWith("else",b)){let $=n(b+4);if(e[$]==="{"){let w=i($);f||c.push([$+1,w])}else{let w=o($);f||c.push([$,w])}}}d=h}if(c.length===0)return e;let u=[...e];for(let[l,p]of c)for(let f=l;f<p&&f<u.length;f++)u[f]!==`
|
|
24
|
-
`&&(u[f]=" ");return u.join("")}function vr(e){return e.match(Dr)?.[1]??null}async function Jl(e){let t=z.join(e,"
|
|
24
|
+
`&&(u[f]=" ");return u.join("")}function vr(e){return e.match(Dr)?.[1]??null}async function Jl(e){let t=z.join(e,"rosefc.config.js");if(!te.existsSync(t))return{plugins:[],i18n:{}};let n=await import(Rg(t).href+`?t=${Date.now()}`);return{plugins:n.default??[],i18n:n.i18n??{},pwa:n.pwa??void 0,brotli:n.brotli??void 0,csp:n.csp??void 0,watch:n.watch??void 0}}function td(e,t,n){let s=[],r=(o,a)=>{let c=z.resolve(z.dirname(t),o),d=n.get(c);if(!d)throw new ee("E-IMPORT",`${z.basename(t)}: cannot import '${o}' - no .rose file at ${c}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,{file:t,line:Lr(e,a),hint:`create ${c} (a .rose component) or fix the import path - a .rose import resolves to a file, never to a package`});return d},i=e.replace(/import\s+(\w+)\s+from\s*(['"])([^'"]+\.rose)\2/g,(o,a,c,d,u)=>{let l=r(d,u);return s.push({name:a,specifier:d,index:l.index}),`import { render as ${a} } from ${c}__rose_${l.index}__${c}`});return i=i.replace(/import\s*(\{[^}]*\})\s+from\s*(['"])([^'"]+\.rose)\2/g,(o,a,c,d,u)=>{let l=r(d,u),p=/\bas\s+(\w+)/.exec(a)?.[1]??"render";return s.push({name:p,specifier:d,index:l.index}),`import ${a} from ${c}__rose_${l.index}__${c}`}),{script:i,imports:s}}function Ol(e,t){return e.replace(/from\s*(['"])__rose_(\d+)__\1/g,(n,s,r)=>`from ${s}./comp-${r}.${t}.js${s}`)}function Ug(e){let t=[];for(let n of e.matchAll(/import\s+(type\s+)?[\s\S]*?from\s*['"]([^'"]+)['"]/g))n[1]||Jg.test(n[2])&&t.push(n[2]);return t}function qg(e){let t=[];for(let n=0;;){let s=Wr(e,"each",n);if(!s)break;n=s.index+1;let r=Ls(e,s.index),i=s[5];r<0||i==null||t.push({names:new Set([...Li(s[2]??""),...s[3]?[s[3]]:[]]),contentStart:r,contentEnd:r+i.length})}return t}function Gg(e,t,n){let s=0;for(let r of e.slice(t,n).matchAll(/\{#(?:snippet|key|await)\b|\{\/(?:snippet|key|await)\s*\}/g))if(s+=r[0][1]==="/"?-1:1,s>0)return!0;return!1}function Qg(e,t,n="<template>",s=""){let r=[],i=0,o=null,a="",c=e,d=0,u={window:"w",document:"d"},l={preventDefault:()=>"e.preventDefault()",stopPropagation:()=>"e.stopPropagation()",self:h=>`const __self = e.target.closest && e.target.closest('[data-${h}-' + e.type + ']'); if (__self && e.target !== __self) return;`},p={once:h=>`const __o = e.target && e.target.closest ? e.target.closest('[data-${h}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${h}-' + e.type);`},f=[...Object.keys(l),...Object.keys(p),...Object.keys(u)];for(;;){let h=/\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(c);if(!h){a+=c;break}let g=!1,y=h[2]?h[2].slice(1).split("|"):[],m=y.filter(S=>u[S]);if(m.length>1)throw new ee("E-TEMPLATE",`${n}: on:${h[1]} carries both |${m.join(" and |")}`,{hint:"a handler binds to one target - the element (default), |window or |document"});let b=m.length?"on"+u[m[0]]:"on";for(let S of y)if(!f.includes(S))throw new ee("E-TEMPLATE",`${n}: unknown event modifier |${S}`,{hint:`the supported modifiers are ${f.map(C=>"|"+C).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body`});a+=c.slice(0,h.index);let $=h.index+h[0].length,w=1;for(;$<c.length;){let S=c[$];if(S==='"'||S==="'"){$=Bs(c,$);continue}if(S==="`"){$=Ho(c,$);continue}if(S==="{")w++;else if(S==="}"&&(w--,w===0))break;$++}let v=c.slice(h.index+h[0].length,$).trim(),_=new Set;for(let S of e.matchAll(/\{#each\s+[\s\S]+?\s+as\s+([A-Za-z_$][\w$]*)\s*(?:,\s*([A-Za-z_$][\w$]*))?/g))_.add(S[1]),S[2]&&_.add(S[2]);if(/=>/.test(v)&&!/^\w+$/.test(v)){let S=[..._].filter(C=>new RegExp(`\\b${C}\\b`).test(v));if(S.length>0){let C=d+h.index,x=(o??=qg(e)).filter(R=>C>=R.contentStart&&C<R.contentEnd).sort((R,T)=>R.contentStart-T.contentStart).pop()??null;if(x!=null&&!Gg(e,x.contentStart,C)&&S.every(R=>x.names.has(R)))g=!0;else{let R=S.find(T=>!x||!x.names.has(T))??S[0];throw new ee("E-TEMPLATE",`${n}: this inline handler reads the {#each} variable "${R}" but is hoisted to the page module, where it does not exist`,{file:n,line:Lr(e,d+h.index),hint:`name the handler in the script block (function onX(e) { ... }) and write on:${h[1]}={onX} - the named form closes over nothing and works for every item`})}}}let k=S=>{if(!y.length)return S;let C=y.filter(A=>l[A]).map(A=>l[A](b)),x=y.filter(A=>p[A]).map(A=>p[A](b));return`(e) => {${C.length?" "+C.join("; ")+";":""} (${S})(e);${x.length?" "+x.join("; ")+";":""} }`};if(y.length&&t.has(v))throw new ee("E-TEMPLATE",`${n}: event modifiers are not supported on the server action ${v}`,{hint:"$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action"});if(g){let S=s?`__rh_${s}_`:"__rh_";a+=`data-${b}-${h[1]}={__rhreg(${JSON.stringify(S)}, ${y.length?k(v):v})}`,i++}else if(y.length){let S=s?`__h_${s}_${r.length}`:`__h${r.length}`;a+=`data-${b}-${h[1]}="${S}"`,r.push({event:h[1],fn:`${S}: ${k(v)}`})}else if(t.has(v))a+=`data-on-${h[1]}="$action:${v}"`;else if(/^\w+$/.test(v))a+=`data-on-${h[1]}="${v}"`,r.push({event:h[1],fn:v});else{let S=s?`__h_${s}_${r.length}`:`__h${r.length}`;a+=`data-on-${h[1]}="${S}"`,r.push({event:h[1],fn:`${S}: ${v}`})}d+=$+1,c=c.slice($+1)}return{template:a,bindings:r,inlineCount:i}}function Kg(e){let t;try{t=te.readFileSync(e,"utf-8")}catch{return[]}let s=t.replace(Dr,"").replace(Fl,""),r=s.match(yd)?.[1]??s.replace(Ml,"").trim(),i=[];for(let o of r.matchAll(/<slot\s+([^>]*?)\/?>/g)){let a=/\bname\s*=\s*["'](\w+)["']/.exec(o[1]);if(!a)continue;let c=[...o[1].matchAll(/\b(\w+)\s*=\s*\{/g)].map(d=>d[1]).filter(d=>d!=="name");i.push({name:a[1],props:c})}return i}function nd(e){let t=[],n=[],s=null,r=0,i=o=>r<=0&&/from\s*['"][^'"]+['"]\s*;?\s*$/.test(o);for(let o of e.split(`
|
|
25
25
|
`)){if(s){s.push(o);for(let a of o)a==="{"||a==="("?r++:(a==="}"||a===")")&&r--;i(o)&&(t.push(s.join(`
|
|
26
26
|
`)),s=null);continue}if(/^\s*import\b/.test(o)){s=[o],r=0;for(let a of o)a==="{"||a==="("?r++:(a==="}"||a===")")&&r--;i(o)&&(t.push(o),s=null);continue}n.push(o)}return s&&t.push(s.join(`
|
|
27
27
|
`)),{imports:t.join(`
|
|
28
28
|
`),rest:n.join(`
|
|
29
|
-
`)}}function _d(e){let t=sd.get(e);return t||(t=new Set,sd.set(e,t)),t}function Xg(e){let t=rd.get(e);if(t===void 0){let n=[];for(let[s,r]of e)n.push(`${s}#${r.index}:${r.scopeKey}:${r.slots.join("|")}`);t=n.join(";"),rd.set(e,t)}return t}function Yg(e){let t=id.get(e);if(t===void 0){let n=[];for(let s of e){if(!s.transform)continue;let r;try{r=String(s.transform)}catch{r="opaque"}n.push(`${s.name}${Vo(r)}`)}t=n.join(""),id.set(e,t)}return t}function em(e,t,n,s,r){let i;try{i=te.statSync(e)}catch{return null}let o=[e,String(i.mtimeMs),String(i.size),t,n?"1":"0",Xg(s),Yg(r)],a=_d(e);for(let c of a)try{o.push(`${c}${String(te.statSync(c).mtimeMs)}`)}catch{o.push(`${c}gone`)}for(let c of xd)try{o.push(`watch:${c}${String(te.statSync(c).mtimeMs)}`)}catch{}return o.join("\0")}function Vo(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function kd(e){return z.join(zr,Vo(e+"|"+tm)+".json")}function sm(e){if(!zr||process.env.
|
|
29
|
+
`)}}function _d(e){let t=sd.get(e);return t||(t=new Set,sd.set(e,t)),t}function Xg(e){let t=rd.get(e);if(t===void 0){let n=[];for(let[s,r]of e)n.push(`${s}#${r.index}:${r.scopeKey}:${r.slots.join("|")}`);t=n.join(";"),rd.set(e,t)}return t}function Yg(e){let t=id.get(e);if(t===void 0){let n=[];for(let s of e){if(!s.transform)continue;let r;try{r=String(s.transform)}catch{r="opaque"}n.push(`${s.name}${Vo(r)}`)}t=n.join(""),id.set(e,t)}return t}function em(e,t,n,s,r){let i;try{i=te.statSync(e)}catch{return null}let o=[e,String(i.mtimeMs),String(i.size),t,n?"1":"0",Xg(s),Yg(r)],a=_d(e);for(let c of a)try{o.push(`${c}${String(te.statSync(c).mtimeMs)}`)}catch{o.push(`${c}gone`)}for(let c of xd)try{o.push(`watch:${c}${String(te.statSync(c).mtimeMs)}`)}catch{}return o.join("\0")}function Vo(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function kd(e){return z.join(zr,Vo(e+"|"+tm)+".json")}function sm(e){if(!zr||process.env.ROSEFC_NO_DISK_CACHE==="1")return null;try{let t=JSON.parse(te.readFileSync(kd(e),"utf-8"));if(t&&typeof t=="object"&&typeof t.ssr=="string")return t}catch{}return null}function rm(e,t){if(!zr||process.env.ROSEFC_NO_DISK_CACHE==="1")return;let n=kd(e),s=JSON.stringify(t);te.promises.writeFile(n,s).catch(()=>{te.promises.mkdir(zr,{recursive:!0}).then(()=>te.promises.writeFile(n,s)).catch(()=>{})});try{if(!(nm++&511)){let r=te.readdirSync(zr);if(r.length>5e3)for(let i of r)try{te.unlinkSync(z.join(zr,i))}catch{}}}catch{}}async function im(e,t,n,s,r,i){let o=em(e,n,s,i,r);if(o){let c=Oi.get(o);if(c)return{...c};let d=sm(o);if(d)return d}let a=await om(e,t,n,s,r,i);if(o){if(Oi.size>=Zg){let c=Oi.keys().next().value;c!==void 0&&Oi.delete(c)}Oi.set(o,a),rm(o,a)}return a}function od(e,t){let n=e.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+hotVary\s*=\s*\[([\s\S]*?)\]\s*;?/);if(!n)return;let s=[];for(let r of n[1].split(",")){let i=r.trim().replace(/^['"`]|['"`]$/g,"");if(!i)continue;let o=i.toLowerCase();if(!/^[a-z0-9!#$%&'*+.^_`|~-]+$/.test(o))throw new ee("E-EXPORT",`${t}: export const hotVary must list request header names (got '${i}')`,{file:t,line:en(e,n),hint:"hotVary is a list of the request headers this route negotiates on, e.g. export const hotVary = ['x-locale', 'x-rv-url']"});if(o==="accept-encoding")throw new ee("E-EXPORT",`${t}: hotVary must not name accept-encoding - the server stores raw bytes and re-negotiates the encoding on every request`,{file:t,line:en(e,n),hint:"drop accept-encoding from hotVary; it is already handled per request"});o==="cookie"||o==="accept-language"||s.includes(o)||s.push(o)}return s.length?s:void 0}async function om(e,t,n,s=!1,r=[],i=new Map){let o=await te.promises.readFile(e,"utf-8");for(let D of r)if(D.transform)try{let q=await D.transform(o,e);if(typeof q=="string")o=q;else{o=q.code;for(let Y of q.deps??[])_d(e).add(Y)}}catch(q){throw new ee("E-PLUGIN",`plugin ${D.name} failed on ${z.basename(e)}: ${q instanceof Error?q.message:String(q)}`,{file:e,hint:"the error above came from inside the plugin - fix its transform() (or remove the plugin from rosefc.config.js)"})}if(o=Po(o,"web"),s){let q=o.match(Dr)?.[1]??"",Y=[...new Set([...[...q.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)].map(Yt=>Yt[1]),...[...q.matchAll(/(?:^|\n)\s*export\s+(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?(?:function\b|(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/g)].map(Yt=>Yt[1])])].filter(Yt=>Og.has(Yt)),we=/getContext\s*\(/.test(q)||/\$store\s*\(/.test(q)||/\$query\s*\(/.test(q),Pe=/\$store\s*\(/.test(q),Ve=q.includes("__rosefcAuth"),kt=!we&&/(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(q),qt=nd(td(q,e,i).script),is=new Set([...q.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap(Yt=>Yt[1].split(",").map(xn=>xn.trim().split(/\s+as\s+/)[0]).filter(Boolean))),Ks=Gm.filter(Yt=>!is.has(Yt)),yt=Ks.length>0?`import { ${Ks.join(", ")} } from './runtime.js';
|
|
30
30
|
`:"";return{ssr:"",client:"",stateKeys:[],actionNames:[],guardName:null,style:"",hasParams:!1,api:`${yt}${Ol(`${qt.imports}
|
|
31
|
-
${qt.rest}`,"ssr").trim()}`,apiMethods:Y,hasPrerender:kt,usesContext:we,usesStore:Pe,
|
|
31
|
+
${qt.rest}`,"ssr").trim()}`,apiMethods:Y,hasPrerender:kt,usesContext:we,usesStore:Pe,usesRosefcAuth:Ve,hotVary:od(q,e)}}let a=o.replace(Dr,""),c=a.replace(Ml,""),d=c.match(Fl),u=n==="_layout"||n.endsWith("/_layout"),l=d?.[1]?u?Rd(d[1]):Ad(d[1],n):"",p=c.replace(Fl,""),f=o.match(Dr),h=td(f?.[1]??"",e,i),g=h.script,y=g.includes("__rosefcAuth"),m=h.imports,{imports:b,rest:$}=nd(g);if(z.basename(e)!=="_middleware.rose")for(let D of Ug(b)){let q=b.indexOf(D);throw new ee("E-NODE-ONLY",`${e}: cannot import '${D}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,{file:e,line:q>=0?Lr(b,q):void 0,hint:`'${D}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`})}let w=i.get(e)?.scopeKey.startsWith("components/")??!1;if(w&&/\$data\s*\(/.test(g))throw new ee("E-EXPORT",`${e}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,{file:e,hint:"move the fetch to the page (or the middleware) and pass the value down as a prop"});let v=/getContext\s*\(/.test(g)||/\$store\s*\(/.test(g)||/\$query\s*\(/.test(g),_=/\$store\s*\(/.test(g),k=/(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(g),S=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/),C=S?Number(S[1]):void 0,x=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/),A=x?Number(x[1]):void 0,R=od(g,e),T=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/),M=T?T[1]:void 0;if(M&&!["off","hover","viewport","all"].includes(M))throw new ee("E-EXPORT",`${e}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,{file:e,line:en(g,T),hint:"prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'"});let F=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+lazyHydration\s*=\s*(true|false)\s*;?/),I=F?F[1]==="true":void 0;if(F&&!I)throw new ee("E-EXPORT",`${e}: export const lazyHydration must be true (or be absent - hydration is eager by default)`,{file:e,line:en(g,F),hint:"omit the export entirely, or set it to exactly true - lazy hydration is opt-in per app, declared once in the root _layout.rose"});let O=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/),P=O?O[1].trim()==="true":void 0;if(O&&!P)throw new ee("E-EXPORT",`${e}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,{file:e,line:en(g,O),hint:"omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app"});let j=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/),B=j?j[1]:void 0;if(B&&!["inline","split","sliced"].includes(B))throw new ee("E-EXPORT",`${e}: export const bundle must be 'inline', 'split' or 'sliced'`,{file:e,line:en(g,j),hint:"'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand; 'sliced' inlines the runtime plus each route's own render chain and shares the rest via a nav chunk"});let U=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/),ce=U?U[1]!=="false":void 0,N=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/),W=N?N[1]!=="false":void 0,re=g.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/),xe=re?re[1]!=="false":void 0,X=/\b(?:redirect|notFound)\s*\(/.test(g)||void 0;if(ce===!1){let D=/\son:[a-z]+\s*=/.exec(o)??/\b(?:onMount|onCleanup|refresh)\s*\(/.exec(g);if(D){let q=D===(/\son:[a-z]+\s*=/.exec(o)??void 0)?o:g;throw new ee("E-EXPORT",`${e}: csr = false cannot ship ${D[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,{file:e,line:en(q,D),hint:'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'})}}let ne,ge=cd(g,"headers");if(ge){let D;try{D=new Function(`return ${ge}`)()}catch{throw new ee("E-EXPORT",`${e}: export const headers must be an object literal`,{file:e,hint:"write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }"})}if(!D||typeof D!="object"||Array.isArray(D)||Object.values(D).some(q=>typeof q!="string"))throw new ee("E-EXPORT",`${e}: export const headers must be a flat map of string -> string`,{file:e,hint:"every value must be a string literal (a number or an array fails here instead of shipping verbatim)"});ne=D}let Ee,Xe=cd(g,"csp");if(Xe){let D;try{D=new Function(`return ${Xe}`)()}catch{throw new ee("E-EXPORT",`${e}: export const csp must be an object literal`,{file:e,hint:"write it as one literal: export const csp = { nonce: true }"})}let q=D?.nonce;if(q!==void 0&&typeof q!="boolean")throw new ee("E-EXPORT",`${e}: csp.nonce must be a boolean`,{file:e,hint:"csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)"});Ee=q===!0}let{clean:Ae,exports:ct,actions:ht,props:Re,guard:ut}=Qe($),oe=Ae,gt=new Set(ht.map(D=>D.name)),Ge=[];/\son:[a-z]+\s*=/.test(o)&&Ge.push("event wiring (on:)"),(/<form[^>]*\son:[a-z]+\s*=/i.test(o)||/\$action:|data-on-/.test(o))&&Ge.push("a form bound to a client dispatch ($action)");let Jt=g.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);Jt&&Ge.push(`${Jt[0].replace(/\s*\($/,"")}()`),o.includes("{#defer")&&Ge.push("{#defer} progressive content"),o.includes("{#await")&&Ge.push("{#await} async block");let ds=Ge.length>0,vn=[];if(!ds){let D=ed(o),q=ed(g),Y=Vg(q);/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(D)&&vn.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true'),/javascript:/i.test(D)&&vn.push("a javascript: URL - it needs the bundle to run; link to a real route"),/\b(?:eval|new Function)\s*\(/.test(Y)&&vn.push("eval()/new Function() - client code the predicate cannot see"),/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(Y)&&vn.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true")}let mt=p.match(yd),Sn=a.match(Ml)?.[1]??"",Os=mt?mt[1]:p.replace(Dr,"").trim(),ps=l?am(fd(Os,t),n):fd(Os,t),fs=cm(oe),Qs=fs.filter(D=>D.kind==="state"||D.kind==="kv"||D.kind==="persist"),ko=fs.filter(D=>D.kind==="derived").map(D=>D.name),$i=[...Qs.map(D=>D.name),...ko],_n=new Map;Qs.forEach(D=>_n.set(D.name,`set${Fs(D.name)}`));{let D=Wo(g),q=new Set;for(let Y of D.matchAll(/(?:^|\n)\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g))q.add(Y[1]);for(let Y of D.matchAll(/(?:^|\n)\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g))q.add(Y[1]);for(let Y of Qs){let we=_n.get(Y.name);if(q.has(we))throw new ee("E-SCRIPT",`${e}: the automatic setter "${we}" for $state("${Y.name}") collides with a same-named declaration in the script`,{file:e,hint:`rename your function, or drop the auto setter and write $setState("${Y.name}", v) - the explicit form never collides`})}}let wi=(()=>{let D=["state","derived","kv","persist"],q=fs.map((Ve,kt)=>({d:Ve,i:kt})).filter(({d:Ve})=>D.includes(Ve.kind)),Y=new Set(q.map(({d:Ve})=>Ve.name)),we=[],Pe=new Set;for(let Ve=0;Ve<=q.length;Ve++){let kt=!1;for(let{d:qt,i:is}of q){if(Pe.has(qt.name))continue;[...new Set([...qt.expr.matchAll(/\b([A-Za-z_$][\w$]*)\b/g)].map(yt=>yt[1]))].filter(yt=>Y.has(yt)&&yt!==qt.name).every(yt=>Pe.has(yt))&&(we.push(is),Pe.add(qt.name),kt=!0)}if(!kt)break}return we})(),gr=D=>{let q=w?`${n}:${D.name}`:D.name;if(D.kind==="state")return`const [${D.name}, ${_n.get(D.name)}] = state(${JSON.stringify(q)}, ${D.expr});`;let we=D.expr.includes("=>")||D.expr.startsWith("function")?D.expr:`() => (${D.expr})`;if(D.kind==="persist")return`const [${D.name}, ${_n.get(D.name)}] = persistState(${JSON.stringify(q)}, ${D.expr});`;if(D.kind==="derived")return`const ${D.name} = () => (${Ps(D.expr,$i)});`;if(D.kind==="kv"){let Pe=/^(.*)\s*,\s*(\d+)\s*$/s.exec(D.expr),Ve=Pe?Pe[1]:D.expr,kt=Pe?Pe[2]:"300";return`const __seeded_${D.name} = isSeeded(${JSON.stringify(q)});
|
|
32
32
|
const [${D.name}, set${Fs(D.name)}] = state(${JSON.stringify(q)}, null);
|
|
33
|
-
if (!__seeded_${D.name}) { const __v_${D.name} = await globalThis.
|
|
33
|
+
if (!__seeded_${D.name}) { const __v_${D.name} = await globalThis.__rosefcKvApi.kvMemo(${JSON.stringify("__kvh:"+n+":"+D.name)}, ${Ve}, ${kt}); set${Fs(D.name)}(__v_${D.name}); markSeeded(${JSON.stringify(q)}); }`}return`const __seeded_${D.name} = isSeeded(${JSON.stringify(q)});
|
|
34
34
|
const [${D.name}, set${Fs(D.name)}] = state(${JSON.stringify(q)}, null);
|
|
35
35
|
if (!__seeded_${D.name}) { const __v_${D.name} = await $data(${we}); set${Fs(D.name)}(__v_${D.name}); markSeeded(${JSON.stringify(q)}); }`},vi=[],Fr="",Pr=0;fs.forEach((D,q)=>{let Y=um(oe,D.start)===0;if(!Y){if(D.kind==="derived")throw new Error(`${e}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`);vi.push(D)}Fr+=oe.slice(Pr,D.start)+(Y?`'__rvdecl${q}__';`:""),Pr=D.end}),Fr+=oe.slice(Pr);let bl=new Set(Qs.map(D=>D.name)),Ro=D=>bl.has(D),Si=No(oe);if(Si)throw new ee("E-STATE",`${e}: ${Si} is a $derived value and is written here - a $derived is read-only`,{hint:`make ${Si} a $state, or derive a different name from it`});let In=Zs(Fr,Ro).replace(Cg,(D,q,Y)=>{let we=q.trim().replace(/^['"`]|['"`]$/g,"");if(ko.includes(we))throw new Error(`${e}: $setState('${we}', ...) - a $derived value is read-only; make it $state or derive a different expression`);return`${_n.get(we)||`set${Fs(we)}`}(${Y})`});if(In=Ps(In,$i),[...In.matchAll(/'__rvdecl(\d+)__';/g)].length===wi.length){let q=0;In=In.replace(/'__rvdecl(\d+)__';/g,(Y,we)=>gr(fs[wi[q++]??Number(we)]))}else In=In.replace(/'__rvdecl(\d+)__';/g,(q,Y)=>gr(fs[Number(Y)]));let _i=vi.filter(D=>D.kind==="state").map(gr).join(`
|
|
36
36
|
`),Co=vi.filter(D=>D.kind==="data").map(gr).join(`
|
|
37
|
-
`),jo=Pl(Zs(ps,Ro),$i).replace(/<img\b(?![^>]*?\sloading=)/gi,'<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi,'<img decoding="async"'),$l=e.replace(/[^\w]/g,"_").replace(/^_+|_+$/g,"").slice(-40),mr=Qg(jo,gt,e,$l),To=mr.inlineCount,Ns=fs.filter(D=>D.kind!=="derived").map(D=>D.name),rs=[],yr=0,Eo=new Set(m.map(D=>D.name)),xi=new Set(Re.map(D=>D.name)),ki=mr.template.replace(/\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,(D,q,Y,we,Pe)=>{let Ve=Pe.lastIndexOf("<",we),kt=Ve>=0?Pe.slice(Ve,we):"",qt=/^<([a-zA-Z][^\s/>]*)/.exec(kt)?.[1]??"";if(!Ns.includes(Y)&&!xi.has(Y))throw new Error(`${e}: bind:${q}={${Y}} must name a $state declaration`+(Ns.length?` (state keys here: ${Ns.join(", ")})`:" (this file declares no $state)"));if(q==="this")return` data-bind-this="${Y}"`;if(!Ns.includes(Y)){let xn="on"+Fs(q)+"Change",Rt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;return/^<select[\s>]/i.test(kt)&&/\smultiple\b/i.test(kt)?(rs.push({event:"change",fn:`${Rt}: (e) => __p.${xn}?.(Array.from(e.target.selectedOptions, (o) => o.value))`}),` data-selmulti={(__rvlive('value', ${Y}) || []).join(',')} data-on-change="${Rt}"`):q==="checked"?(rs.push({event:"change",fn:`${Rt}: (e) => __p.${xn}?.(e.target.checked)`}),` checked={__rvlive('checked', ${Y})} data-on-change="${Rt}"`):q==="open"?(rs.push({event:"toggle",fn:`${Rt}: (e) => __p.${xn}?.(e.target.open)`}),` open={__rvlive('open', ${Y})} data-on-toggle="${Rt}"`):(rs.push({event:"input",fn:`${Rt}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; __p.${xn}?.(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`}),` value={__rvlive('value', ${Y})} data-on-input="${Rt}" data-on-change="${Rt}"`)}if(qt&&Eo.has(qt)){let xn=_n.get(Y),Rt="on"+Fs(q)+"Change";return` ${q}={${Y}()} __live-${q}={${Y}} ${Rt}={${xn}}`}if(q==="value"&&/^<select[\s>]/i.test(kt)&&/\smultiple\b/i.test(kt)){let xn=_n.get(Y),Rt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;return rs.push({event:"change",fn:`${Rt}: (e) => ${xn}(Array.from(e.target.selectedOptions, (o) => o.value))`}),` data-selmulti={${Y}().join(',')} data-on-change="${Rt}"`}if(q==="open"){let xn=_n.get(Y),Rt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;return rs.push({event:"toggle",fn:`${Rt}: (e) => ${xn}(e.target.open)`}),` open={${Y}()} data-on-toggle="${Rt}"`}let is=_n.get(Y),Ks=q==="checked"?"change":"input",yt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;rs.push({event:Ks,fn:q==="checked"?`${yt}: (e) => ${is}(e.target.checked)`:`${yt}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; ${is}(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`});let Yt=q==="checked"?` data-on-change="${yt}"`:` data-on-input="${yt}" data-on-change="${yt}"`;return` ${q}={${Y}()}${Yt}`}),Ri=new Map(m.map(D=>{let q=z.resolve(z.dirname(e),D.specifier),Y=i.get(q);return[D.name,{index:Y.index,slots:Y.slots}]})),Ai=[],Ci=0,E=!xi.size||!/<(input|textarea|select)[\s>]/i.test(ki)?ki:Vr(ki,D=>{let{tag:q,attrs:Y}=D;if(!/^(input|textarea|select)$/i.test(q)||/\sdata-on-input=|\sdata-selmulti=/.test(Y))return null;let we=/\svalue\s*=\s*\{([\w$]+)\}/.exec(Y);if(!we||!xi.has(we[1]))return null;let Pe=we[1],Ve=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;rs.push({event:"input",fn:`${Ve}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; __p.onValueChange?.(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`});let kt=/^select$/i.test(q)&&/\smultiple\b/i.test(Y),qt=Y.replace(we[0],` value={__rvlive('value', ${Pe})}`),is=kt?` data-selmulti={(__rvlive('value', ${Pe}) || []).join(',')} data-on-change="${Ve}"`:` data-on-input="${Ve}" data-on-change="${Ve}"`;return qt+is}),L=E.includes("bind:group")?Vr(E,D=>{let{tag:q,attrs:Y}=D,we=/\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(Y);if(!we)return null;let Pe=we[1],Ve=!Ns.includes(Pe);if(Ve&&!xi.has(Pe))throw new ee("E-TEMPLATE",`${e}: bind:group={${Pe}} must name a $state declaration`,{hint:"the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let "+Pe+' = $state("")'});if(!Ve&&Eo.has(q)){let pg=_n.get(Pe);return Y.replace(we[0],` group={${Pe}()} __live-group={${Pe}} onGroupChange={${pg}}`)}if(!/\stype\s*=\s*["'](radio|checkbox)["']/.test(Y))throw new ee("E-TEMPLATE",`${e}: bind:group is for radio and checkbox inputs`,{hint:'<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))'});let kt=/\stype\s*=\s*["']checkbox["']/.test(Y),qt=/\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(Y);if(!qt||/\{/.test(qt[0]))throw new ee("E-TEMPLATE",`${e}: a bind:group input needs a static value attribute`,{hint:'<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives'});if(/\schecked\s*=/.test(Y))throw new ee("E-TEMPLATE",`${e}: a bind:group input cannot also carry checked=`,{hint:"the group state alone decides which inputs are checked"});let is=Ve?"":_n.get(Pe),Ks=`__rvbg_${n.replace(/\W/g,"_")}_${Ci++}`,yt=JSON.stringify(qt[1]??qt[2]),Yt=Ve?`__rvlive('group', ${Pe})`:`${Pe}()`,xn=kt?`${Yt}.includes(${yt})`:`${Yt} === ${yt}`,Rt=kt?Ve?`__p.onGroupChange?.(e.target.checked ? [...${Yt}, ${yt}] : ${Yt}.filter((x) => x !== ${yt}))`:`${is}(e.target.checked ? [...${Pe}(), ${yt}] : ${Pe}().filter((x) => x !== ${yt}))`:Ve?"__p.onGroupChange?.(e.target.value)":`${is}(e.target.value)`;return Ai.push({event:"change",fn:`${Ks}: (e) => { ${Rt}; }`}),Y.replace(we[0],` checked={${xn}} data-on-change="${Ks}"`)}):E,ae=mr.bindings.concat(rs,Ai),me=L.replace(/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,(D,q,Y,we)=>Y?` data-use="${q}" data-use-param={JSON.stringify(${we})}`:` data-use="${q}"`),ye=Lo(me,"web"),de=ym(ye,e),pe=gm(de),Fe=wm(pe,e),Ut=bm(Fe,e),Et=$m(Ut,e),Ms=fm(Et,e),og=Sm(Ms),wl=_m(og),vl=km(wl.template,e),ag=vm(vl.template,e),Cu=Em(ag.replace(Tg,(D,q,Y)=>{let we=`{__slot(${Xu(q)})}`;if(Y){if(/\{[^{}]*\}/.test(Y))throw new ee("E-TEMPLATE",`${e}: slot fallback content must be static markup`,{hint:"a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content"});return`{__slot(${Xu(q)}, ${JSON.stringify(Y)})}`}return we}).replace(jg,(D,q)=>q&&q.trim()?`{__slotDefault(${JSON.stringify(q)})}`:"{__slot__}"),Ri);Tm(Cu,e);let ju=new Set;{let D=Wo(g),q=new Set(Qs.map(we=>we.name)),Y=we=>/^(?:async\s*)?(?:function\b|\([^)]*\)\s*=>)/.test(we)||/^(?:async\s*)?\(/.test(we)&&we.includes("=>")||/^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(we);for(let we of D.matchAll(/(?:^|\n)\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*([^;]{0,200})/g))q.has(we[1])||/^\s*\$state\b/.test(we[2])||Y(we[2].trim())||ju.add(we[1])}Ll=0,Fi=e,Do=new Set,Bl=!0,Dl=new Set(ju);let Tu=hs(Cu,"h","__c",null,0,!0,Ri);Bl=!1,Dl=new Set;let Eu=Il,lg=Wl;Il="",Wl={},Do=new Set;let Ou=zl;if(zl=null,Ou)throw new ee("E-TEMPLATE",`${e}: {@const ${Ou}} is declared twice at the top level`,{file:e,hint:"a const cannot be redeclared in the same scope - rename one of them, or wrap the second in a block ({#if}/{#each}) where it shadows the first instead of colliding with it"});for(let D of ae)/^\w+$/.test(D.fn)||(D.fn=Ps(D.fn,[],lg));let ji=Sn.trim()?Am(Sn):"";if(!w&&l){let q=`<style id="${"
|
|
37
|
+
`),jo=Pl(Zs(ps,Ro),$i).replace(/<img\b(?![^>]*?\sloading=)/gi,'<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi,'<img decoding="async"'),$l=e.replace(/[^\w]/g,"_").replace(/^_+|_+$/g,"").slice(-40),mr=Qg(jo,gt,e,$l),To=mr.inlineCount,Ns=fs.filter(D=>D.kind!=="derived").map(D=>D.name),rs=[],yr=0,Eo=new Set(m.map(D=>D.name)),xi=new Set(Re.map(D=>D.name)),ki=mr.template.replace(/\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,(D,q,Y,we,Pe)=>{let Ve=Pe.lastIndexOf("<",we),kt=Ve>=0?Pe.slice(Ve,we):"",qt=/^<([a-zA-Z][^\s/>]*)/.exec(kt)?.[1]??"";if(!Ns.includes(Y)&&!xi.has(Y))throw new Error(`${e}: bind:${q}={${Y}} must name a $state declaration`+(Ns.length?` (state keys here: ${Ns.join(", ")})`:" (this file declares no $state)"));if(q==="this")return` data-bind-this="${Y}"`;if(!Ns.includes(Y)){let xn="on"+Fs(q)+"Change",Rt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;return/^<select[\s>]/i.test(kt)&&/\smultiple\b/i.test(kt)?(rs.push({event:"change",fn:`${Rt}: (e) => __p.${xn}?.(Array.from(e.target.selectedOptions, (o) => o.value))`}),` data-selmulti={(__rvlive('value', ${Y}) || []).join(',')} data-on-change="${Rt}"`):q==="checked"?(rs.push({event:"change",fn:`${Rt}: (e) => __p.${xn}?.(e.target.checked)`}),` checked={__rvlive('checked', ${Y})} data-on-change="${Rt}"`):q==="open"?(rs.push({event:"toggle",fn:`${Rt}: (e) => __p.${xn}?.(e.target.open)`}),` open={__rvlive('open', ${Y})} data-on-toggle="${Rt}"`):(rs.push({event:"input",fn:`${Rt}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; __p.${xn}?.(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`}),` value={__rvlive('value', ${Y})} data-on-input="${Rt}" data-on-change="${Rt}"`)}if(qt&&Eo.has(qt)){let xn=_n.get(Y),Rt="on"+Fs(q)+"Change";return` ${q}={${Y}()} __live-${q}={${Y}} ${Rt}={${xn}}`}if(q==="value"&&/^<select[\s>]/i.test(kt)&&/\smultiple\b/i.test(kt)){let xn=_n.get(Y),Rt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;return rs.push({event:"change",fn:`${Rt}: (e) => ${xn}(Array.from(e.target.selectedOptions, (o) => o.value))`}),` data-selmulti={${Y}().join(',')} data-on-change="${Rt}"`}if(q==="open"){let xn=_n.get(Y),Rt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;return rs.push({event:"toggle",fn:`${Rt}: (e) => ${xn}(e.target.open)`}),` open={${Y}()} data-on-toggle="${Rt}"`}let is=_n.get(Y),Ks=q==="checked"?"change":"input",yt=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;rs.push({event:Ks,fn:q==="checked"?`${yt}: (e) => ${is}(e.target.checked)`:`${yt}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; ${is}(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`});let Yt=q==="checked"?` data-on-change="${yt}"`:` data-on-input="${yt}" data-on-change="${yt}"`;return` ${q}={${Y}()}${Yt}`}),Ri=new Map(m.map(D=>{let q=z.resolve(z.dirname(e),D.specifier),Y=i.get(q);return[D.name,{index:Y.index,slots:Y.slots}]})),Ai=[],Ci=0,E=!xi.size||!/<(input|textarea|select)[\s>]/i.test(ki)?ki:Vr(ki,D=>{let{tag:q,attrs:Y}=D;if(!/^(input|textarea|select)$/i.test(q)||/\sdata-on-input=|\sdata-selmulti=/.test(Y))return null;let we=/\svalue\s*=\s*\{([\w$]+)\}/.exec(Y);if(!we||!xi.has(we[1]))return null;let Pe=we[1],Ve=`__rvbind_${n.replace(/\W/g,"_")}_${yr++}`;rs.push({event:"input",fn:`${Ve}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; __p.onValueChange?.(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`});let kt=/^select$/i.test(q)&&/\smultiple\b/i.test(Y),qt=Y.replace(we[0],` value={__rvlive('value', ${Pe})}`),is=kt?` data-selmulti={(__rvlive('value', ${Pe}) || []).join(',')} data-on-change="${Ve}"`:` data-on-input="${Ve}" data-on-change="${Ve}"`;return qt+is}),L=E.includes("bind:group")?Vr(E,D=>{let{tag:q,attrs:Y}=D,we=/\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(Y);if(!we)return null;let Pe=we[1],Ve=!Ns.includes(Pe);if(Ve&&!xi.has(Pe))throw new ee("E-TEMPLATE",`${e}: bind:group={${Pe}} must name a $state declaration`,{hint:"the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let "+Pe+' = $state("")'});if(!Ve&&Eo.has(q)){let pg=_n.get(Pe);return Y.replace(we[0],` group={${Pe}()} __live-group={${Pe}} onGroupChange={${pg}}`)}if(!/\stype\s*=\s*["'](radio|checkbox)["']/.test(Y))throw new ee("E-TEMPLATE",`${e}: bind:group is for radio and checkbox inputs`,{hint:'<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))'});let kt=/\stype\s*=\s*["']checkbox["']/.test(Y),qt=/\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(Y);if(!qt||/\{/.test(qt[0]))throw new ee("E-TEMPLATE",`${e}: a bind:group input needs a static value attribute`,{hint:'<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives'});if(/\schecked\s*=/.test(Y))throw new ee("E-TEMPLATE",`${e}: a bind:group input cannot also carry checked=`,{hint:"the group state alone decides which inputs are checked"});let is=Ve?"":_n.get(Pe),Ks=`__rvbg_${n.replace(/\W/g,"_")}_${Ci++}`,yt=JSON.stringify(qt[1]??qt[2]),Yt=Ve?`__rvlive('group', ${Pe})`:`${Pe}()`,xn=kt?`${Yt}.includes(${yt})`:`${Yt} === ${yt}`,Rt=kt?Ve?`__p.onGroupChange?.(e.target.checked ? [...${Yt}, ${yt}] : ${Yt}.filter((x) => x !== ${yt}))`:`${is}(e.target.checked ? [...${Pe}(), ${yt}] : ${Pe}().filter((x) => x !== ${yt}))`:Ve?"__p.onGroupChange?.(e.target.value)":`${is}(e.target.value)`;return Ai.push({event:"change",fn:`${Ks}: (e) => { ${Rt}; }`}),Y.replace(we[0],` checked={${xn}} data-on-change="${Ks}"`)}):E,ae=mr.bindings.concat(rs,Ai),me=L.replace(/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,(D,q,Y,we)=>Y?` data-use="${q}" data-use-param={JSON.stringify(${we})}`:` data-use="${q}"`),ye=Lo(me,"web"),de=ym(ye,e),pe=gm(de),Fe=wm(pe,e),Ut=bm(Fe,e),Et=$m(Ut,e),Ms=fm(Et,e),og=Sm(Ms),wl=_m(og),vl=km(wl.template,e),ag=vm(vl.template,e),Cu=Em(ag.replace(Tg,(D,q,Y)=>{let we=`{__slot(${Xu(q)})}`;if(Y){if(/\{[^{}]*\}/.test(Y))throw new ee("E-TEMPLATE",`${e}: slot fallback content must be static markup`,{hint:"a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content"});return`{__slot(${Xu(q)}, ${JSON.stringify(Y)})}`}return we}).replace(jg,(D,q)=>q&&q.trim()?`{__slotDefault(${JSON.stringify(q)})}`:"{__slot__}"),Ri);Tm(Cu,e);let ju=new Set;{let D=Wo(g),q=new Set(Qs.map(we=>we.name)),Y=we=>/^(?:async\s*)?(?:function\b|\([^)]*\)\s*=>)/.test(we)||/^(?:async\s*)?\(/.test(we)&&we.includes("=>")||/^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(we);for(let we of D.matchAll(/(?:^|\n)\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*([^;]{0,200})/g))q.has(we[1])||/^\s*\$state\b/.test(we[2])||Y(we[2].trim())||ju.add(we[1])}Ll=0,Fi=e,Do=new Set,Bl=!0,Dl=new Set(ju);let Tu=hs(Cu,"h","__c",null,0,!0,Ri);Bl=!1,Dl=new Set;let Eu=Il,lg=Wl;Il="",Wl={},Do=new Set;let Ou=zl;if(zl=null,Ou)throw new ee("E-TEMPLATE",`${e}: {@const ${Ou}} is declared twice at the top level`,{file:e,hint:"a const cannot be redeclared in the same scope - rename one of them, or wrap the second in a block ({#if}/{#each}) where it shadows the first instead of colliding with it"});for(let D of ae)/^\w+$/.test(D.fn)||(D.fn=Ps(D.fn,[],lg));let ji=Sn.trim()?Am(Sn):"";if(!w&&l){let q=`<style id="${"rosefc-style-"+n.replace(/[^a-zA-Z0-9_-]/g,"-")}">${l}</style>`;ji=(ji?ji+`
|
|
38
38
|
`:"")+`__hd += ${JSON.stringify(q)};`}let Nu=/<slot\s+[^>]*\bname\s*=/.test(ps),Mu=ht.length>0?`${ct}
|
|
39
39
|
${ht.map(D=>D.stmt).join(`
|
|
40
40
|
`)}`:ct,Fu=ut?`
|
|
@@ -47,8 +47,8 @@ ${Mu}
|
|
|
47
47
|
${Fu}
|
|
48
48
|
|
|
49
49
|
${In}
|
|
50
|
-
`:Qm(In+Pu,Tu,_i,Mu,ji,Re,Nu,b,w,Fu,ht.length>0,Co,Eu,To>0),dg=Km(In+Pu,Tu,_i,ae,ct,ji,Re,Nu,b,w,Co,Eu,To>0);return{ssr:Ol(ug,"ssr"),client:Ol(dg,"client"),stateKeys:Ns,actionNames:[...gt],guardName:ut?"beforeAction":null,style:l,hasParams:k,usesContext:v,usesStore:_,revalidate:C,cache:A,hotVary:R,csr:ce,shell:W,buffer:xe,controlSignal:X,prefetch:M,lazyHydration:I,vitals:P,bundle:B,needsClient:ds,clientReasons:Ge,jsWarnings:vn,headers:ne,cspNonce:Ee,
|
|
51
|
-
`&&c!=="\r"?o+=c:c==="}"&&(o=""),a++}return i.trim()}function am(e,t){let n=` data-
|
|
50
|
+
`:Qm(In+Pu,Tu,_i,Mu,ji,Re,Nu,b,w,Fu,ht.length>0,Co,Eu,To>0),dg=Km(In+Pu,Tu,_i,ae,ct,ji,Re,Nu,b,w,Co,Eu,To>0);return{ssr:Ol(ug,"ssr"),client:Ol(dg,"client"),stateKeys:Ns,actionNames:[...gt],guardName:ut?"beforeAction":null,style:l,hasParams:k,usesContext:v,usesStore:_,revalidate:C,cache:A,hotVary:R,csr:ce,shell:W,buffer:xe,controlSignal:X,prefetch:M,lazyHydration:I,vitals:P,bundle:B,needsClient:ds,clientReasons:Ge,jsWarnings:vn,headers:ne,cspNonce:Ee,usesRosefcAuth:y,props:Re,roseImports:m,isComponent:w}}function Rd(e){return e.replace(/(-?\d*\.?\d+)rpx/g,(t,n)=>{let s=Number(n)/2;return s===0?"0":`${Math.round(s*100)/100}px`})}function ad(e){return e.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,t=>t[0]==='"'||t[0]==="'"?t:t.replace(/\s+/g," ").replace(/\s*([:;{},])\s*/g,"$1").trim()).trim()}function Ad(e,t){let n=`[data-rosefc-c="${t}"]`,s=c=>{let d=c.trim();if(!d.includes(":global"))return`${n} ${d}, ${n}${d}`;let u=d.replace(/:global\([^()]*\)/g,p=>p.slice(8,-1)).trim();return d.replace(/:global\([^()]*\)/g,"").trim()?`${n} ${u}, ${n}${u}`:u},r=Rd(e.replace(/\/\*[\s\S]*?\*\//g,"")),i="",o="",a=0;for(;a<r.length;){let c=r[a];if(c==="{"){let d=1,u=a+1;for(;u<r.length&&d>0;)r[u]==="{"?d++:r[u]==="}"&&d--,u++;let l=r.slice(a+1,u-1),p=o.trim();if(p.startsWith("@"))i+=`${p}{${/^@(?:-[\w]+-)?keyframes/.test(p)?ad(l):Ad(l,t)}}`;else if(p){let f=p.split(",").map(h=>s(h)).join(",");i+=`${f}{${ad(l)}}`}o="",a=u;continue}c!=="}"&&c!==`
|
|
51
|
+
`&&c!=="\r"?o+=c:c==="}"&&(o=""),a++}return i.trim()}function am(e,t){let n=` data-rosefc-c="${t}"`,s="",r=0,i=0;for(;i<e.length;){let o=e.indexOf("<",i);if(o===-1){s+=e.slice(i);break}s+=e.slice(i,o);let a=o+1,c="",d=0,u=0;for(;a<e.length;){let g=e[a];if(c)g===c&&(c="");else if(g==='"'||g==="'")c=g;else if(g==="(")d++;else if(g===")")d=Math.max(0,d-1);else if(g==="{")u++;else if(g==="}")u=Math.max(0,u-1);else if(g===">"&&d===0&&u===0)break;a++}let l=e.slice(o,a+1),p=/^<\//.test(l),f=l.match(/^<\/?([a-zA-Z][\w-]*)/),h=/\/>$/.test(l)||f&&Cd.has(f[1].toLowerCase());if(f&&!p&&r===0&&!h){let g=l.endsWith("/>")?l.length-2:l.length-1;s+=l.slice(0,g)+n+l.slice(g),r++}else s+=l,f&&(r+=p?-1:h?0:1);i=a+1}return s}function cd(e,t){let n=new RegExp(`(?:^|\\n)\\s*export\\s+(?:const|let|var)\\s+${t}\\s*=\\s*`).exec(e);if(!n)return null;let s=n.index+n[0].length;if(e[s]!=="{")return null;let r=s,i=0;for(;s<e.length;s++){let o=e[s];if(o==="{")i++;else if(o==="}"&&(i--,i===0)){s++;break}}return e.slice(r,s)}function Qe(e){let t=[],n=[],s=[],r=[],i="",o=0,a;for(ld.lastIndex=0;a=ld.exec(e);){let c=a[1],d=a.index+a[0].indexOf("export"),u=d+a[0].length-a[0].indexOf("export");if(c){let h=0;for(;u<e.length;){let g=e[u];if(g==="("||g==="{"||g==="[")h++;else if(g===")"||g==="}"||g==="]"){if(h--,h===0){u++;break}}else if(h===0&&g===";"){u++;break}else if(h===0&&g===`
|
|
52
52
|
`){let y=e.slice(u+1);if(!/^\s*[.([{+\-*/?:,=&|]/.test(y)){u++;break}}u++}e[u]===";"&&u++}else{for(;u<e.length&&e[u]!=="{";)u++;let h=0;for(;u<e.length;){let g=e[u];if(g==="{")h++;else if(g==="}"&&(h--,h===0)){u++;break}u++}}i+=e.slice(o,d);let l=e.slice(d,u).trim(),p=l.match(/^export\s+async\s+function\s+(\w+)/);if(l.match(/^export\s+(?:async\s+)?function\s+(\w+)/)?.[1]==="beforeAction")r.push(l);else if(p)n.push({name:p[1],stmt:l});else if(c==="let"){let h=l.match(/^export\s+let\s+(\w+)\s*(?:=\s*([\s\S]*?))?\s*;?$/);h?s.push({name:h[1],def:h[2]?.trim()??null}):t.push(l)}else t.push(l);o=u}return i+=e.slice(o),{clean:i,exports:t.join(`
|
|
53
53
|
`),actions:n,props:s,guard:r.join(`
|
|
54
54
|
`)}}function jd(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return!0;let s=e[n];if(lm.has(s))return!0;if(/[A-Za-z0-9_$]/.test(s)){let r=Sd(e,n);return r?["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else"].includes(r):!1}return!1}function cm(e){let t=[],n=Wo(e);Zu.lastIndex=0;let s;for(;s=Zu.exec(n);){let r=s.index+s[0].length,i=()=>{for(;r<e.length&&/\s/.test(e[r]);)r++};if(i(),e[r]==="<"){let l=0;for(;r<e.length;){let p=e[r];if(p==="<")l++;else if(p===">"&&e[r-1]!=="="){if(l--,l===0){r++;break}}else p==="="&&e[r+1]===">"&&r++;r++}i()}if(e[r]!=="(")continue;let o=r+1,a=1,c=o;for(;c<e.length&&a>0;){let l=e[c];l==="("?a++:l===")"&&a--,c++}let d=c,u=Ag.exec(e.slice(c));u&&(d=c+u[0].length),e[d]===";"&&d++,t.push({name:s[1],kind:s[2],expr:e.slice(o,c-1).trim(),start:s.index,end:d})}return t}function um(e,t){let n=0,s=0;for(;s<t;){let r=e[s];if(r==="'"||r==='"'||r==="`"){let i=r;for(s++;s<t;){if(e[s]==="\\"){s+=2;continue}if(e[s]===i){s++;break}if(i==="`"&&e[s]==="$"&&e[s+1]==="{"){let o=1;for(s+=2;s<t&&o>0;)e[s]==="{"?o++:e[s]==="}"&&o--,s++;continue}s++}continue}if(r==="/"&&e[s+1]==="/"){let i=e.indexOf(`
|
|
@@ -75,7 +75,7 @@ ${In}
|
|
|
75
75
|
`,t+=` set${s}({ status: 'rejected', error: __rvAwaitErr });
|
|
76
76
|
`,t+=` });
|
|
77
77
|
`,t+=`});
|
|
78
|
-
`}return t}function Ul(e,t){if(e==="if"){let s=/^\s*([\s\S]+?)\s*$/.exec(t);return s?[s[1]]:null}if(e==="each"){let s=/^\s*([\s\S]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([\s\S]+)\))?\s*$/.exec(t);return s?[s[1],s[2],s[3]??"",s[4]??""]:null}if(e==="boundary")return[t];if(e==="island"){let s=/^\s*(?:name="([^"]*)")?(?:\s*hydrate="([^"]*)")?\s*$/.exec(t);return s?[s[1]??"",s[2]??""]:null}let n=/^\s*(\w+)(?:\s*\(([\s\S]+)\))?\s*$/.exec(t);return n?[n[1],n[2]??""]:null}function Wr(e,t,n){let s=new RegExp(`\\{#${t}\\b`,"g"),r=new RegExp(`\\{/${t}\\}`,"g");s.lastIndex=n;let i;for(;i=s.exec(e);){let o=i.index,a=Ls(e,o);if(a<0)continue;let c=Ul(t,e.slice(o+2+t.length,a-1));if(!c)continue;let d=1,u=a;for(;;){s.lastIndex=u,r.lastIndex=u;let l=s.exec(e),p=r.exec(e);if(!p)break;if(l&&l.index<p.index){let f=Ls(e,l.index);d++,u=f<0?l.index+l[0].length:f;continue}if(u=p.index+p[0].length,--d===0){let f=e.slice(a,p.index),h=[e.slice(o,u),...c,f];return h.index=o,h}}s.lastIndex=a}return null}function Am(e){let t=/<(style|script|noscript)\b[^>]*>/iy,n="",s="",r=0,i=0,o=()=>{s.trim()&&(n+=hs(s,"__hd","__hc",null,r++,!1)),s=""};for(;i<e.length;){if(e.startsWith("<!--",i)){let c=e.indexOf("-->",i+4);i=c<0?e.length:c+3;continue}t.lastIndex=i;let a=t.exec(e);if(a){let c=a[1].toLowerCase(),d=e.toLowerCase().indexOf(`</${c}`,i+a[0].length),u=d<0?-1:e.indexOf(">",d),l=u<0?e.length:u+1;o(),n+=Ed(a[0],"__hd","__hc",null),n+=Lm(e.slice(i+a[0].length,l),"__hd","__hc",null),i=l;continue}s+=e[i++]}return o(),n}function jm(e){let t=dd.get(e);return t||(t={open:new RegExp(`\\{#${e}\\b`,"g"),close:new RegExp(`\\{/${e}\\}`,"g")},dd.set(e,t)),t}function Tm(e,t){let n=[],s=/<(style|script|noscript)\b[^>]*>/gi,r;for(;r=s.exec(e);){let l=r[1].toLowerCase(),p=e.toLowerCase().indexOf(`</${l}`,r.index+r[0].length),f=p<0?-1:e.indexOf(">",p),h=f<0?e.length:f+1;n.push([r.index,h]),s.lastIndex=h}let i=/<!--[\s\S]*?-->/g,o;for(;o=i.exec(e);)n.push([o.index,o.index+o[0].length]);n.sort((l,p)=>l[0]-p[0]);let a=l=>n.some(([p,f])=>l>=p&&l<f),c=/\{([:/])(\w+)\}/g,d;for(;d=c.exec(e);){if(a(d.index))continue;let[,l,p]=d;if(!(l==="/"&&Cm.has(p))){if(l==="/")throw new ee("E-TEMPLATE",`${t}: {/${p}} does not close anything`,{file:t,line:en(e,d),hint:"the closers are {/if}, {/each} and {/boundary} - one per block you opened"});if(p==="else"){let f=(y,m,b)=>{let $=0,w;for(y.lastIndex=0;(w=y.exec(e))&&!(w.index>=b);)a(w.index)||$++;let v=new RegExp(m,"g"),_=0;for(;(w=v.exec(e))&&!(w.index>=b);)a(w.index)||_++;return $-_},h=f(/\{#if\b/g,"\\{/if\\b",d.index),g=f(/\{#each\b/g,"\\{/each\\b",d.index);if(h<=0&&g<=0)throw new ee("E-TEMPLATE",`${t}: a stray {:else} with no {#if} or {#each} above it`,{file:t,line:en(e,d),hint:"{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block"});continue}if(p==="fallback")throw new ee("E-TEMPLATE",`${t}: a stray {:fallback} with no {#boundary} above it`,{file:t,line:en(e,d),hint:"{:fallback} belongs directly inside a {#boundary} ... {/boundary} block"});if(p==="then"||p==="catch"){let f=(y,m)=>{y.lastIndex=0;let b=0,$;for(;($=y.exec(e))&&!($.index>=m);)a($.index)||b++;return b},h=f(/\{#await\b/g,d.index),g=f(/\{\/await\b/g,d.index);if(h<=g)throw new ee("E-TEMPLATE",`${t}: a stray {:${p}} with no {#await} above it`,{file:t,line:en(e,d),hint:"{:then} / {:catch} belong inside an {#await} ... {/await} block"});continue}throw new ee("E-TEMPLATE",`${t}: {:${p}} is not a
|
|
78
|
+
`}return t}function Ul(e,t){if(e==="if"){let s=/^\s*([\s\S]+?)\s*$/.exec(t);return s?[s[1]]:null}if(e==="each"){let s=/^\s*([\s\S]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([\s\S]+)\))?\s*$/.exec(t);return s?[s[1],s[2],s[3]??"",s[4]??""]:null}if(e==="boundary")return[t];if(e==="island"){let s=/^\s*(?:name="([^"]*)")?(?:\s*hydrate="([^"]*)")?\s*$/.exec(t);return s?[s[1]??"",s[2]??""]:null}let n=/^\s*(\w+)(?:\s*\(([\s\S]+)\))?\s*$/.exec(t);return n?[n[1],n[2]??""]:null}function Wr(e,t,n){let s=new RegExp(`\\{#${t}\\b`,"g"),r=new RegExp(`\\{/${t}\\}`,"g");s.lastIndex=n;let i;for(;i=s.exec(e);){let o=i.index,a=Ls(e,o);if(a<0)continue;let c=Ul(t,e.slice(o+2+t.length,a-1));if(!c)continue;let d=1,u=a;for(;;){s.lastIndex=u,r.lastIndex=u;let l=s.exec(e),p=r.exec(e);if(!p)break;if(l&&l.index<p.index){let f=Ls(e,l.index);d++,u=f<0?l.index+l[0].length:f;continue}if(u=p.index+p[0].length,--d===0){let f=e.slice(a,p.index),h=[e.slice(o,u),...c,f];return h.index=o,h}}s.lastIndex=a}return null}function Am(e){let t=/<(style|script|noscript)\b[^>]*>/iy,n="",s="",r=0,i=0,o=()=>{s.trim()&&(n+=hs(s,"__hd","__hc",null,r++,!1)),s=""};for(;i<e.length;){if(e.startsWith("<!--",i)){let c=e.indexOf("-->",i+4);i=c<0?e.length:c+3;continue}t.lastIndex=i;let a=t.exec(e);if(a){let c=a[1].toLowerCase(),d=e.toLowerCase().indexOf(`</${c}`,i+a[0].length),u=d<0?-1:e.indexOf(">",d),l=u<0?e.length:u+1;o(),n+=Ed(a[0],"__hd","__hc",null),n+=Lm(e.slice(i+a[0].length,l),"__hd","__hc",null),i=l;continue}s+=e[i++]}return o(),n}function jm(e){let t=dd.get(e);return t||(t={open:new RegExp(`\\{#${e}\\b`,"g"),close:new RegExp(`\\{/${e}\\}`,"g")},dd.set(e,t)),t}function Tm(e,t){let n=[],s=/<(style|script|noscript)\b[^>]*>/gi,r;for(;r=s.exec(e);){let l=r[1].toLowerCase(),p=e.toLowerCase().indexOf(`</${l}`,r.index+r[0].length),f=p<0?-1:e.indexOf(">",p),h=f<0?e.length:f+1;n.push([r.index,h]),s.lastIndex=h}let i=/<!--[\s\S]*?-->/g,o;for(;o=i.exec(e);)n.push([o.index,o.index+o[0].length]);n.sort((l,p)=>l[0]-p[0]);let a=l=>n.some(([p,f])=>l>=p&&l<f),c=/\{([:/])(\w+)\}/g,d;for(;d=c.exec(e);){if(a(d.index))continue;let[,l,p]=d;if(!(l==="/"&&Cm.has(p))){if(l==="/")throw new ee("E-TEMPLATE",`${t}: {/${p}} does not close anything`,{file:t,line:en(e,d),hint:"the closers are {/if}, {/each} and {/boundary} - one per block you opened"});if(p==="else"){let f=(y,m,b)=>{let $=0,w;for(y.lastIndex=0;(w=y.exec(e))&&!(w.index>=b);)a(w.index)||$++;let v=new RegExp(m,"g"),_=0;for(;(w=v.exec(e))&&!(w.index>=b);)a(w.index)||_++;return $-_},h=f(/\{#if\b/g,"\\{/if\\b",d.index),g=f(/\{#each\b/g,"\\{/each\\b",d.index);if(h<=0&&g<=0)throw new ee("E-TEMPLATE",`${t}: a stray {:else} with no {#if} or {#each} above it`,{file:t,line:en(e,d),hint:"{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block"});continue}if(p==="fallback")throw new ee("E-TEMPLATE",`${t}: a stray {:fallback} with no {#boundary} above it`,{file:t,line:en(e,d),hint:"{:fallback} belongs directly inside a {#boundary} ... {/boundary} block"});if(p==="then"||p==="catch"){let f=(y,m)=>{y.lastIndex=0;let b=0,$;for(;($=y.exec(e))&&!($.index>=m);)a($.index)||b++;return b},h=f(/\{#await\b/g,d.index),g=f(/\{\/await\b/g,d.index);if(h<=g)throw new ee("E-TEMPLATE",`${t}: a stray {:${p}} with no {#await} above it`,{file:t,line:en(e,d),hint:"{:then} / {:catch} belong inside an {#await} ... {/await} block"});continue}throw new ee("E-TEMPLATE",`${t}: {:${p}} is not a Rosefc directive`,{file:t,line:en(e,d),hint:"Rosefc templates support {#if}/{:else}, {#each} and {#boundary}"})}}let u=/\{#(if|each|boundary|island|await)\b/g;for(;d=u.exec(e);){if(a(d.index))continue;let l=d[1],p=Ls(e,d.index);if(p<0)continue;let f=e.slice(d.index+2+l.length,p-1);if(l==="each"&&!Ul("each",f))throw new ee("E-TEMPLATE",`${t}: {#each ${f.trim()}} is missing its item name`,{file:t,line:en(e,d),hint:"write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)"});let{open:h,close:g}=jm(l),y=1,m=p;for(;;){h.lastIndex=m,g.lastIndex=m;let b=h.exec(e),$=g.exec(e);if(!$)break;if(b&&b.index<$.index){let w=Ls(e,b.index);m=w<0?b.index+b[0].length:w;continue}if(m=$.index+$[0].length,--y===0)break}if(y!==0)throw new ee("E-TEMPLATE",`${t}: unclosed {#${l}} - every block needs its {/${l}}`,{file:t,line:en(e,d),hint:`add the matching {/${l}} (an inner {#if} or {#each} closes first, deepest first)`})}}function Em(e,t){let n=/<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|`[^`]*`|[^\s"'>]+))?)*)\s*(\/?)>/g;return e.replace(n,(s,r,i,o)=>{if(t.has(r)||!/\{/.test(i))return s;let a=i.replace(/([\w:-]+)=("([^"]*)"|'([^']*)'|`([^`]*)`)/g,(c,d,u,l,p,f)=>{let h=l??p??f??"";if(!/\{/.test(h)||f===void 0&&h.includes("`"))return c;let g=Hr(h);if(g.length===0)return c;let y="",m=0;for(let b of g)m<b.start&&(y+=(y?" + ":"")+JSON.stringify(h.slice(m,b.start))),y+=(y?" + ":"")+`(${b.expr})`,m=b.end+1;return m<h.length&&(y+=(y?" + ":"")+JSON.stringify(h.slice(m))),`${d}={${y}}`});return`<${r}${a}${o?" /":""}>`})}function hs(e,t,n,s,r,i=!0,o=new Map,a=0){let c="",d=e,u=0,l=0,p=0,f=/\{#island\b/.test(e),h=i&&(!f||a>0),g=()=>`${r}_${p++}`;r===0&&(c+=`const __snip = {};
|
|
79
79
|
`);let y=new Map,m=zg(e,o),b=new Set(m).size===m.length;if(m.length>0&&b){let F={};for(let I of m){let O=`__rvct${Ll++}`;y.set(I,O),F[I]=O}d=Pl(e,[],F,{ownScope:!0,comps:o})}let $=F=>{let I,O=-1;return()=>((O!==l||I===void 0||I!==null&&I.index<u)&&(I=F(u),O=l),I)},w=/<(style|script|noscript)\b[^>]*>/g,v=null,_=$(F=>Wr(d,"if",F)),k=$(F=>Wr(d,"each",F)),S=$(F=>Wr(d,"boundary",F)),C=$(F=>Wr(d,"island",F)),x=$(F=>Wr(d,"snippet",F)),A=$(F=>Hg(d,F)),R=$(F=>{let I=o.size>0?Td(d,F,o):null;return I?{index:I.start,tag:I}:null}),T=$(F=>{w.lastIndex=F;let I=w.exec(d);return I?{index:I.index,tag:I[0],name:I[1].toLowerCase()}:null}),M=$(F=>{let I=d.indexOf("<!--",F);if(I<0)return null;let O=d.indexOf("-->",I+4);return{index:I,end:O<0?d.length:O+3}});for(;u<d.length;){let F=_(),I=k(),O=S(),P=A(),j=P?Object.assign([d.slice(P.index,P.end+1),P.expr],{index:P.index}):null,B=R()?.tag??null,U=C(),ce=x(),N=[];F?.index!==void 0&&N.push({type:"if",match:F,index:F.index}),I?.index!==void 0&&N.push({type:"each",match:I,index:I.index}),O?.index!==void 0&&N.push({type:"boundary",match:O,index:O.index}),U?.index!==void 0&&N.push({type:"island",match:U,index:U.index}),ce?.index!==void 0&&N.push({type:"snippet",match:ce,index:ce.index}),j?.index!==void 0&&N.push({type:"expr",match:j,index:j.index}),B&&N.push({type:"comp",match:j,index:B.start,tag:B});let W=N.length>0?N.reduce((X,ne)=>X.index<=ne.index?X:ne):null,re=T();if(re&&W&&re.index<W.index){v===null&&(v=d.toLowerCase());let X=v.indexOf(`</${re.name}`,re.index+re.tag.length),ne=X<0?-1:d.indexOf(">",X),ge=ne<0?d.length:ne+1;c+=dt(d.slice(u,re.index),t,n,s),c+=Ed(re.tag,t,n,s),c+=dt(d.slice(re.index+re.tag.length,ge),t,n,s),u=ge;continue}let xe=M();if(xe&&(!W||xe.index<W.index)){c+=dt(d.slice(u,xe.end),t,n,s),u=xe.end;continue}if(!W){c+=dt(d.slice(u),t,n,s);break}if(W.type==="if"){let[,X,ne]=W.match,ge=d.slice(u,W.index);ge&&(c+=dt(ge,t,n,s));let Ee=ud(X),Xe=g(),Ae=s??"__s",ct=hs(ne.trim(),"h","__c",Ae,r+1,h,o,a);c+=`const __b${Xe} = (__s, __c) => { let h = ''; ${ct} return h; };
|
|
80
80
|
`,h?c+=`${t} += ifMark(${n}, () => (${Ee}), __b${Xe}${s?`, ${s}`:""});
|
|
81
81
|
`:c+=`${t} += (${Ee}) ? __b${Xe}(${s??"undefined"}, []) : '';
|
|
@@ -98,8 +98,8 @@ ${In}
|
|
|
98
98
|
`,u=W.index+W.match[0].length;continue}let Ae=/^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(ne);if(Ae){ge&&(c+=dt(ge,t,n,s));let oe=Ae[4]?`, ${Ae[4]}`:"";c+=`${t} += __slotBlock(${n}, __sl, ${JSON.stringify(Ae[2])}, [${Ae[3]}]${oe});
|
|
99
99
|
`,u=W.index+W.match[0].length;continue}let ct=/^@html\s+([\s\S]+)$/.exec(ne);if(ct){ge&&(c+=dt(ge,t,n,s));let oe=ct[1].trim();if(!h)c+=`${t} += String(${oe} ?? '');
|
|
100
100
|
`;else{let gt=s?`(${s}) => (${oe})`:`() => (${oe})`;c+=`${t} += rawMark(${n}, ${gt}${s?`, ${s}`:""});
|
|
101
|
-
`}u=W.index+W.match[0].length;continue}let ht=/^@debug\b([\s\S]*)$/.exec(ne);if(ht){ge&&(c+=dt(ge,t,n,s));let oe=ht[1].trim().replace(/,$/,"");c+=oe?`console.log('[
|
|
102
|
-
`:`console.log('[
|
|
101
|
+
`}u=W.index+W.match[0].length;continue}let ht=/^@debug\b([\s\S]*)$/.exec(ne);if(ht){ge&&(c+=dt(ge,t,n,s));let oe=ht[1].trim().replace(/,$/,"");c+=oe?`console.log('[rosefc:debug]', { ${oe} });
|
|
102
|
+
`:`console.log('[rosefc:debug]'); debugger;
|
|
103
103
|
`,u=W.index+W.match[0].length;continue}let Re=/^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(ne);if(Re){if(new RegExp(`\\{#snippet\\s+${Re[1]}\\b`).test(d.slice(W.index+W.match[0].length)))throw new ee("E-TEMPLATE",`${Fi}: {@render ${Re[1]}} runs before its {#snippet ${Re[1]}} is defined`,{file:Fi,hint:"move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them"});ge&&(c+=dt(ge,t,n,s));let gt=Re[2].trim();c+=`${t} += ((__snip && __snip.${Re[1]}) ? __snip.${Re[1]}(${s??"null"}, ${n}${gt?", "+gt:""}) : '');
|
|
104
104
|
`,u=W.index+W.match[0].length;continue}let ut=Pm(d,W.index)?/([\w-]+)=\s*$/.exec(ge)??null:null;if(ut){let oe=ge.slice(0,ge.length-ut[0].length);oe&&(c+=dt(oe,t,n,s)),c+=Um(ut[1],ne,t,n,s,h)}else{ge&&(c+=dt(ge,t,n,s));let oe=d.slice(W.index+W.match[0].length);if(/=[\"'][^\"']*$/.test(ge))c+=`${t} += esc(${ne});
|
|
105
105
|
`;else{let Ge=oe.length>0&&!/^<[a-zA-Z/!]/.test(oe)&&!oe.startsWith("{");c+=Vm(ne,t,n,s,h,Ge)}}u=W.index+W.match[0].length}}return c=c.replace(/\+= "\s*([a-zA-Z][\w-]*)=";\r?\n\s*\w+\s*\+=\s*textMark\((\w+), (.+?), 1, ([^;]+?)\);/g,(F,I,O,P,j)=>`+= attrMark(${O}, ${P}, '${I}', ${j});`),c}function Jo(e,t){let n=t+1,s="",r=0;for(;n<e.length;){let i=e[n];if(s)i===s&&(s="");else if(i==='"'||i==="'")s=i;else if(i==="{")r++;else if(i==="}")r=Math.max(0,r-1);else if(i===">"&&r===0)return n+1;n++}return-1}function Td(e,t,n){let s=t;for(;s<e.length;){let r=e.indexOf("<",s);if(r<0)return null;let i=/^<([a-zA-Z][\w-]*)/.exec(e.slice(r,r+64));if(i&&n.has(i[1])){let o=Jo(e,r);if(o>0){let a=e.slice(r,o),c=/\/>$/.test(a);return{start:r,end:o,name:i[1],attrs:a.slice(1+i[1].length,c?-2:-1),selfClosing:c}}}s=r+1}return null}function Om(e,t){return Td(e,0,t)}function zo(e,t,n){let s=new RegExp(`<(/?)${n}(?=[\\s/>])`,"g");s.lastIndex=t;let r=1,i;for(;i=s.exec(e);){let o=Jo(e,i.index);if(o<0)return-1;if(i[1]==="/"){if(r--,r===0)return i.index}else/\/>$/.test(e.slice(i.index,o))||r++}return-1}function Nm(e){let t=[],n=0;for(;n<e.length;){let s=/^\s*\{\.\.\.([^}]*)\}/.exec(e.slice(n));if(s){t.push({name:"...",kind:"spread",value:s[1].trim()}),n+=s[0].length;continue}let r=/^\s*([\w:.-]+)/.exec(e.slice(n));if(!r)break;n+=r[0].length;let i=/^\s*=\s*/.exec(e.slice(n));if(!i){t.push({name:r[1],kind:"bool",value:""});continue}n+=i[0].length;let o=e[n];if(o==="{"){let a=1,c=n+1;for(;c<e.length&&a>0;)e[c]==="{"?a++:e[c]==="}"&&a--,c++;t.push({name:r[1],kind:"expr",value:e.slice(n+1,c-1).trim()}),n=c}else if(o==='"'||o==="'"){let a=e.indexOf(o,n+1);t.push({name:r[1],kind:"str",value:e.slice(n+1,a<0?e.length:a)}),n=a<0?e.length:a+1}else break}return t}function Mm(e,t){let n=0;for(;n<e.length;){let s=e.indexOf("<",n);if(s<0)return;let r=/^<(\/?)([a-zA-Z][\w-]*)/.exec(e.slice(s,s+64));if(!r){n=s+1;continue}let i=Jo(e,s);if(i<0)return;let o=/\bslot\s*=\s*["'](\w+)["']/.exec(e.slice(s,i));if(o&&r[1]!=="/")throw new ee("E-TEMPLATE",`slot="${o[1]}" on <${r[2]}> is nested inside slot="${t}" - a slot must be a direct child of the component`,{hint:"move the inner <slot> out of the outer one - a slot is a direct child of the component tag, never nested in another slot"});n=i}}function Fm(e){let t="",n=new Map,s=0,r=0,i=0,o=[];for(;s<e.length;){let a=e.indexOf("<",s),c=e.indexOf("{#",s),d=e.indexOf("{/",s),u=[a,c,d].filter(b=>b>=0);if(u.length===0){t+=e.slice(s);break}let l=Math.min(...u);if(l>s&&(t+=e.slice(s,l)),l===c||l===d){let b=e.indexOf("}",l),$=e.slice(l,b<0?e.length:b+1);if(l===c){let w=/^\{#(\w+)/.exec($);o.push({header:$,type:w?w[1]:""}),i++}else i=Math.max(0,i-1),o.length&&o.pop();t+=$,s=l+$.length;continue}let p=/^<(\/?)([a-zA-Z][\w-]*)/.exec(e.slice(l,l+64));if(!p){t+="<",s=l+1;continue}let f=Jo(e,l);if(f<0){t+=e.slice(l);break}let h=e.slice(l,f),g=/\/>$/.test(h),y=Cd.has(p[2].toLowerCase());if(p[1]==="/"){r=Math.max(0,r-1),t+=h,s=f;continue}!g&&!y&&r++;let m=/\bslot\s*=\s*["'](\w+)["']/.exec(h)?.[1];if(m&&r===1&&i===0){if(g||y)n.set(m,(n.get(m)??"")+h.replace(/\s*slot\s*=\s*["']\w+["']/,""));else{let b=zo(e,f,p[2]);if(b<0)throw new ee("E-TEMPLATE",`unclosed <${p[2]}> inside slot="${m}"`,{hint:`add the matching </${p[2]}>`});let $=`</${p[2]}>`,w=e.slice(f,b);Mm(w,m),n.set(m,(n.get(m)??"")+h.replace(/\s*slot\s*=\s*["']\w+["']/,"")+w+$),r=Math.max(0,r-1),s=b+$.length;continue}s=f;continue}if(m&&i>0){let b=h.replace(/\s*slot\s*=\s*["']\w+["']/,""),$="";for(let _ of o)$+=_.header;if($+=b,g||y){for(let _=o.length-1;_>=0;_--)$+=`{/${o[_].type}}`;n.set(m,(n.get(m)??"")+$),s=f;continue}let w=zo(e,f,p[2]);if(w<0)throw new ee("E-TEMPLATE",`unclosed <${p[2]}> inside slot="${m}"`,{hint:`add the matching </${p[2]}>`});let v=`</${p[2]}>`;$+=e.slice(f,w)+v;for(let _=o.length-1;_>=0;_--)$+=`{/${o[_].type}}`;n.set(m,(n.get(m)??"")+$),r=Math.max(0,r-1),s=w+v.length;continue}if(m)throw new ee("E-TEMPLATE",`slot="${m}" on <${p[2]}> must be a direct child of the component, or wrapped only by an {#if}/{#each}/{#boundary} block - it is nested inside another element`,{hint:'place the element with slot="..." directly inside the component tag, or inside a single {#if}/{#each} block - wrapping it in another element is not yet supported'});t+=h,s=f}return{def:t,named:[...n.entries()]}}function Pm(e,t){let s=e.slice(0,t).lastIndexOf("<");if(s<0||!/^<[a-zA-Z]/.test(e.slice(s)))return!1;let r=s+1,i="",o=0;for(;r<t;){let a=e[r];if(i)a===i&&(i="");else if(a==='"'||a==="'")i=a;else if(a==="{")o++;else if(a==="}")o=Math.max(0,o-1);else if(a===">"&&o===0)return!1;r++}return!0}function dt(e,t,n,s){return e?`${t} += ${JSON.stringify(e)};
|
|
@@ -172,12 +172,12 @@ export ${d?"function":"async function"} render(closes, children, __props, __slot
|
|
|
172
172
|
let __html = ${d?"":"await "}__root(closes, children);${b}
|
|
173
173
|
return __html;
|
|
174
174
|
}
|
|
175
|
-
`}function Zm(e,t){return e.map((n,s)=>({info:n,i:s})).filter(({info:n})=>!n.isLayout&&!n.isNotFound&&!n.isError&&!n.isApi&&!n.isMiddleware&&!n.isComponent).map(({info:n,i:s})=>{if(Pi(e,t,s))return`${n.routePath} zero-JS nothing in the chain needs the client`;let r=[s,...wr(e,s)].filter(o=>t[o].needsClient).map(o=>`${(t[o].clientReasons??["needs the client"]).join(" + ")} in ${z.basename(e[o].filePath)}`).join("; "),i=t[s].csr===!0?" (csr = true forces the bundle)":"";return`${n.routePath} client JS ${r}${i}`})}async function Uo(e,t,n={}){let s=z.resolve(e),r=z.resolve(t),i=n.minify!==!1,o=n.incremental===!0;await te.promises.mkdir(r,{recursive:!0});let a=(await te.promises.readdir(r)).filter(E=>/^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(E));await Promise.all(a.map(E=>te.promises.rm(z.join(r,E),{force:!0})));let[c,d]=await Promise.all([Ye(s),Ke(s)]),u=[...c,...d];if(c.length===0)throw new ee("E-ROUTE",`no .rose pages found under ${z.join(s,"src","pages")} - run
|
|
175
|
+
`}function Zm(e,t){return e.map((n,s)=>({info:n,i:s})).filter(({info:n})=>!n.isLayout&&!n.isNotFound&&!n.isError&&!n.isApi&&!n.isMiddleware&&!n.isComponent).map(({info:n,i:s})=>{if(Pi(e,t,s))return`${n.routePath} zero-JS nothing in the chain needs the client`;let r=[s,...wr(e,s)].filter(o=>t[o].needsClient).map(o=>`${(t[o].clientReasons??["needs the client"]).join(" + ")} in ${z.basename(e[o].filePath)}`).join("; "),i=t[s].csr===!0?" (csr = true forces the bundle)":"";return`${n.routePath} client JS ${r}${i}`})}async function Uo(e,t,n={}){let s=z.resolve(e),r=z.resolve(t),i=n.minify!==!1,o=n.incremental===!0;await te.promises.mkdir(r,{recursive:!0});let a=(await te.promises.readdir(r)).filter(E=>/^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(E));await Promise.all(a.map(E=>te.promises.rm(z.join(r,E),{force:!0})));let[c,d]=await Promise.all([Ye(s),Ke(s)]),u=[...c,...d];if(c.length===0)throw new ee("E-ROUTE",`no .rose pages found under ${z.join(s,"src","pages")} - run rosefc from a project root, or pass one: rosefc build <dir>`,{file:z.join(s,"src","pages"),hint:"create src/pages/index.rose in that directory (or run the command from the project root)"});let l=u.map(E=>({...Ym(E,s)})),p=await Jl(s);xd=(p.watch??[]).map(E=>z.isAbsolute(E)?E:z.join(s,E));let f=p.plugins,h=u.map((E,L)=>{let ae=l[L].isComponent?z.join(s,"src"):z.join(s,"src","pages");return z.relative(ae,E).replace(/\\/g,"/").replace(/\.rose$/,"")}),g=new Map(u.map((E,L)=>[E,{index:L,scopeKey:h[L],slots:Kg(E)}])),y=Jr.transform("export default 0",{loader:"js"}).catch(()=>{}),m=await Promise.all(u.map((E,L)=>im(E,z.join(s,"public"),h[L],l[L].isApi,f,g)));await y;{let E=new Set(Vl().map(([me])=>me)),L=[],ae=new Set;for(let me=0;me<m.length;me++)for(let ye of[...Yu(m[me].ssr),...Yu(m[me].client)]){if(E.has(ye)||ae.has(ye))continue;ae.add(ye);let de=`${z.relative(s,u[me]).replace(/\\/g,"/")} reads import.meta.env.${ye}`;L.push(ye.startsWith(Mi)?` ${de}
|
|
176
176
|
-> it has the public prefix but is not set in this build's environment (an unset public var is undefined in the bundle; the server render does not fall back to it)`:` ${de}
|
|
177
|
-
-> only ${Mi}* is exposed to the client; rename it to ${Mi}${ye} if it is public config, or keep it server-only (it stays undefined here, in dev and in the bundle)`)}L.length>0&&console.warn(`
|
|
177
|
+
-> only ${Mi}* is exposed to the client; rename it to ${Mi}${ye} if it is public config, or keep it server-only (it stays undefined here, in dev and in the bundle)`)}L.length>0&&console.warn(`Rosefc warning: import.meta.env.<name> carries only ${Mi}* variables:
|
|
178
178
|
${L.join(`
|
|
179
179
|
`)}`)}let b=new Map;u.forEach((E,L)=>{let ae=[];for(let me of m[L].roseImports??[]){let ye=z.resolve(z.dirname(u[L]),me.specifier),de=g.get(ye);de&&ae.push(de.index)}b.set(L,ae)});let $=(E,L=new Set)=>{if(m[E].needsClient)return z.basename(u[E]);if(L.has(E))return null;L.add(E);for(let ae of b.get(E)??[]){let me=$(ae,L);if(me)return me}return null};m.forEach((E,L)=>{if(E.needsClient)return;let ae=$(L);ae&&(E.needsClient=!0,E.clientReasons=[...E.clientReasons??[],`imported component ${ae} needs the client`])});let w=new Set,v=E=>{if(!w.has(E)){w.add(E);for(let L of m[E].roseImports??[]){let ae=z.resolve(z.dirname(u[E]),L.specifier),me=g.get(ae);me&&v(me.index)}}};u.forEach((E,L)=>{l[L].isComponent||v(L)});let _=m.map((E,L)=>w.has(L)&&l[L].isComponent?E.style:"").filter(Boolean).join(`
|
|
180
|
-
`);_?await te.promises.writeFile(z.join(r,"styles.css"),_):await te.promises.rm(z.join(r,"styles.css"),{force:!0});let k={};try{let E=z.join(s,"src","locales"),L=(await te.promises.readdir(E)).filter(me=>me.endsWith(".json")),ae=await Promise.all(L.map(async me=>[me.slice(0,-5),JSON.parse(await te.promises.readFile(z.join(E,me),"utf-8"))]));k=Object.fromEntries(ae)}catch{k={}}let S=k.en?"en":Object.keys(k).sort()[0]??"en",C=JSON.stringify(k).replace(/</g,"\\u003c"),x=p.i18n.preload??Object.keys(k),A=Object.keys(k).filter(E=>!x.includes(E));for(let E of x)k[E]||console.warn(`
|
|
180
|
+
`);_?await te.promises.writeFile(z.join(r,"styles.css"),_):await te.promises.rm(z.join(r,"styles.css"),{force:!0});let k={};try{let E=z.join(s,"src","locales"),L=(await te.promises.readdir(E)).filter(me=>me.endsWith(".json")),ae=await Promise.all(L.map(async me=>[me.slice(0,-5),JSON.parse(await te.promises.readFile(z.join(E,me),"utf-8"))]));k=Object.fromEntries(ae)}catch{k={}}let S=k.en?"en":Object.keys(k).sort()[0]??"en",C=JSON.stringify(k).replace(/</g,"\\u003c"),x=p.i18n.preload??Object.keys(k),A=Object.keys(k).filter(E=>!x.includes(E));for(let E of x)k[E]||console.warn(`Rosefc: i18n.preload lists '${E}' but there is no src/locales/${E}.json - ignored`);if(await te.promises.rm(z.join(r,"locales"),{recursive:!0,force:!0}),A.length>0){let E=z.join(r,"locales");await te.promises.mkdir(E,{recursive:!0});for(let L of A)await te.promises.writeFile(z.join(E,`${L}.json`),JSON.stringify(k[L]))}let R=Object.fromEntries(Object.keys(k).filter(E=>!A.includes(E)).map(E=>[E,k[E]])),T=JSON.stringify(R).replace(/</g,"\\u003c"),M=z.join(s,".rosefc-build"),F=z.join(M,`${process.pid}-${Vo(z.resolve(s))}`),I=te.existsSync(F);await te.promises.mkdir(F,{recursive:!0});let O=new Date;await te.promises.utimes(F,O,O),(!I||gd!==F)&&(Nl.clear(),gd=F),zu(M);let P=[z.join(z.dirname(Ni(import.meta.url)),"..","cli","content.ts"),z.join(z.dirname(Ni(import.meta.url)),"..","src","cli","content.ts")],j=P.find(E=>te.existsSync(E))??P[0];te.copyFileSync(j,z.join(F,"content-md.ts"));let B=f.filter(E=>E&&(E.onRequest||E.onResponse));if(B.length>0){let E=z.relative(F,z.join(s,"rosefc.config.js")).replace(/\\/g,"/");await te.promises.writeFile(z.join(F,"plugins.js"),`
|
|
181
181
|
import config from ${JSON.stringify(E)};
|
|
182
182
|
|
|
183
183
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -187,19 +187,19 @@ export const hooks = list
|
|
|
187
187
|
|
|
188
188
|
export const hasRequestHooks = hooks.some((p) => p.onRequest);
|
|
189
189
|
export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
190
|
-
`)}let U=["../runtime/index.ts","../src/runtime/index.ts"].map(E=>Ni(new URL(E,import.meta.url))).find(E=>te.existsSync(E));if(!U)throw new ee("E-INTERNAL","
|
|
190
|
+
`)}let U=["../runtime/index.ts","../src/runtime/index.ts"].map(E=>Ni(new URL(E,import.meta.url))).find(E=>te.existsSync(E));if(!U)throw new ee("E-INTERNAL","Rosefc: the runtime source (src/runtime/index.ts) was not found next to the compiler",{hint:"the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout"});let ce=br(U,{entryPoints:[U],bundle:!0,outfile:z.join(F,"runtime.js"),format:"esm",platform:"browser",write:!0},o),N=(()=>{let E=z.dirname(Ni(import.meta.url));for(let L of[z.join(E,"..","cli","prod-server.ts"),z.join(E,"..","src","cli","prod-server.ts")])if(te.existsSync(L))return L;return z.join(E,"..","cli","prod-server.ts")})(),W="import { createRequire as __cr } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = __cr(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);",re=o?Promise.resolve({}):br(N,{entryPoints:[N],bundle:!0,outfile:z.join(r,"prod.mjs"),format:"esm",platform:"node",write:!0,banner:{js:W},...Ir,...i?{minify:!0,keepNames:!0}:{}},o);ce.catch(()=>{}),re.catch(()=>{});let xe=[],X=(E,L)=>{Nl.get(E)!==L&&(Nl.set(E,L),xe.push(te.promises.writeFile(z.join(F,E),L)))};for(let E=0;E<m.length;E++){let L=m[E].api??m[E].ssr;X(`comp-${E}.ssr.js`,L),l[E].isApi||X(`comp-${E}.client.js`,m[E].client)}for(let E=0;E<xe.length;E+=64)await Promise.all(xe.slice(E,E+64));let ne=l.map((E,L)=>({info:E,i:L})).filter(({info:E})=>!E.isLayout&&!E.isNotFound&&!E.isError&&!E.isApi&&!E.isMiddleware&&!E.isComponent).sort((E,L)=>{let ae=de=>{let pe=de.split("/");return[pe.filter(Fe=>Fe.startsWith("**")).length,pe.filter(Fe=>Fe.startsWith("*")).length,pe.filter(Fe=>Fe.startsWith(":")).length]},me=ae(E.info.pattern),ye=ae(L.info.pattern);for(let de=0;de<3;de++)if(me[de]!==ye[de])return me[de]-ye[de];return E.info.filePath<L.info.filePath?-1:1}),ge=l.map((E,L)=>({info:E,i:L})).filter(({info:E})=>E.isApi).sort((E,L)=>{let ae=de=>{let pe=de.split("/");return[pe.filter(Fe=>Fe.startsWith("**")).length,pe.filter(Fe=>Fe.startsWith("*")).length,pe.filter(Fe=>Fe.startsWith(":")).length]},me=ae(E.info.pattern),ye=ae(L.info.pattern);for(let de=0;de<3;de++)if(me[de]!==ye[de])return me[de]-ye[de];return E.info.filePath<L.info.filePath?-1:1}),Ee=E=>{let L=`render_${E}`;for(let ae of wr(l,E))L=`(async (closes, children) => await render_${ae}(closes, await (${L})(closes, children)))`;return L},Xe=z.join(s,"src","pages","_layout.rose"),Ae=u.findIndex((E,L)=>m[L].bundle&&E!==Xe);if(Ae>=0)throw new ee("E-BUNDLE",`${z.basename(u[Ae])}: export const bundle switches the whole app's bundle mode, so it belongs in the root layout (src/pages/_layout.rose)`,{file:u[Ae],hint:"move `export const bundle = 'split'` (or 'inline') to src/pages/_layout.rose - the mode is per-app, not per-page"});let ct=m[u.indexOf(Xe)]?.bundle??"inline",ht=ct==="split",Re=ct==="sliced",ut=E=>"s"+Br(E).toString(36),oe=Ii.replace(/^import\s*\{/,"").replace(/\}\s*from[\s\S]*$/,"").split(",").map(E=>E.trim()).filter(Boolean),gt=(()=>{let E=ae=>ae.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),L=new Set;for(let ae of m){if(!ae.client)continue;let me=ae.client.replace(/^import\s*\{[^}]*\}\s*from\s*'\.\/runtime\.js';/m,"");for(let ye of oe)L.has(ye)||new RegExp(`(?<![\\w$])${E(ye)}(?![\\w$])`).test(me)&&L.add(ye)}return oe.filter(ae=>L.has(ae))})(),Ge=E=>[E,...wr(l,E)],Jt=E=>`load: () => loadChain([${Ge(E).map(L=>`() => import('./comp-${L}.client.js')`).join(", ")}])`,ds=E=>`{ ${Jt(E)} }`,vn=E=>Pi(l,m,E),mt=m.map((E,L)=>{if(!w.has(L))return"";if(l[L].isMiddleware)return`import * as middlewareMod from './comp-${L}.ssr.js';`;if(l[L].isApi){let Ut=(m[L].apiMethods??[]).map(Et=>`${Et} as ${Et}_${L}`).join(", ");return Ut?`import { ${Ut} } from './comp-${L}.ssr.js';`:`import './comp-${L}.ssr.js';`}let ae=!l[L].isLayout&&!l[L].isNotFound,ye=(ae?m[L].actionNames:[]).map(Fe=>`${Fe} as ${Fe}_${L}`).join(", "),de=ae&&m[L].guardName?`beforeAction as beforeAction_${L}`:"",pe=[ye,de].filter(Boolean).join(", ");return pe?`import { render as render_${L}, ${pe} } from './comp-${L}.ssr.js';`:`import { render as render_${L} } from './comp-${L}.ssr.js';`}).join(`
|
|
191
191
|
`),Sn=l.map((E,L)=>({info:E,i:L})).filter(({info:E})=>E.isNotFound).map(({info:E,i:L})=>{let ae=z.relative(z.join(s,"src","pages"),E.filePath).replace(/\\/g,"/"),me=z.posix.dirname(ae),ye=me==="."?"/":"/"+me,de=[];Hl(l,m,L)&&de.push("shell: false"),Pi(l,m,L)&&de.push("csr: false");let pe=de.length?`, { ${de.join(", ")} }`:"";return{prefix:ye,render:Ee(L),flags:pe}}).sort((E,L)=>L.prefix.length-E.prefix.length),Os=`[
|
|
192
192
|
${Sn.map(E=>` ['${E.prefix}', ${E.render}${E.flags}],`).join(`
|
|
193
193
|
`)}
|
|
194
194
|
]`,ps=l.findIndex(E=>E.isError),fs=ps>=0?Ee(ps):"null",Qs=ps>=0?Pi(l,m,ps):!1,ko=l.findIndex(E=>E.isMiddleware),$i=ne.map(({info:E,i:L})=>{let ae=m[L].actionNames.map(Et=>`${Et}: ${Et}_${L}`).join(", ");if(m[L].csr===!1&&m[L].needsClient)throw new ee("E-EXPORT",`${E.filePath}: csr = false but this route needs the client bundle (${(m[L].clientReasons??["needs the client"]).join(" + ")}).`,{file:E.filePath,hint:"remove csr = false (the compiler decides zero-JS by itself), or remove the client-only code listed above"});if(m[L].csr===!1){let Et=wr(l,L).find(Ms=>m[Ms].needsClient);if(Et!==void 0)throw new ee("E-EXPORT",`${E.filePath}: csr = false cannot ship under ${l[Et].filePath} - the layout needs the client bundle (event wiring, onMount/onCleanup, refresh() or a server action).`,{file:E.filePath,hint:"a layout needing the runtime bundles every route under it - drop csr = false here, or make the layout content-only"})}let me=vn(L)?", csr: false":"",ye=Hl(l,m,L)?", shell: false":"",de=m[L].buffer?", buffer: true":"",pe=m[L].controlSignal?", signal: true":"",Fe=m[L].guardName?`, guard: beforeAction_${L}`:"",Ut=Re&&!vn(L)?`, slice: '${ut(E.pattern)}'`:"";return`{ pattern: '${E.pattern}', path: '${E.routePath}', render: ${Ee(L)}, actions: ${ae?`{ ${ae} }`:"null"}${Fe}${me}${ye}${de}${pe}${Ut} }`}).join(`,
|
|
195
|
-
`),_n=m.some(E=>E.
|
|
195
|
+
`),_n=m.some(E=>E.usesRosefcAuth),wi=m.some(E=>/\$(?:udp|tcp|listen|mqtt)\s*\(/.test((E.ssr||"")+(E.client||"")+(E.api||""))),gr=m.some(E=>/\$websocket\s*\(/.test((E.ssr||"")+(E.client||"")+(E.api||""))),vi=`
|
|
196
196
|
${mt}
|
|
197
197
|
import { renderMarkdown } from './content-md.ts';
|
|
198
|
-
${_n?"import crypto from 'node:crypto';":"// no route references
|
|
199
|
-
${wi?`import * as
|
|
200
|
-
import * as
|
|
201
|
-
${gr?`import * as
|
|
202
|
-
import * as
|
|
198
|
+
${_n?"import crypto from 'node:crypto';":"// no route references __rosefcAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
|
|
199
|
+
${wi?`import * as __rosefcDgram from 'node:dgram';
|
|
200
|
+
import * as __rosefcNet from 'node:net';`:"// no route opens a network listener ($udp/$tcp/$listen): the node:dgram/node:net imports are omitted, keeping the bundle edge-loadable"}
|
|
201
|
+
${gr?`import * as __rosefcHttp from 'node:http';
|
|
202
|
+
import * as __rosefcCrypto from 'node:crypto';`:"// no route opens a WebSocket server ($websocket): the node:http/node:crypto imports are omitted, keeping the bundle edge-loadable"}
|
|
203
203
|
import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, getRequestQuery, getContext, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc, __startNetwork, __stopNetwork, $udp, $tcp, $listen, $websocket, $mqtt } from './runtime.js';
|
|
204
204
|
export { __startNetwork, __stopNetwork };
|
|
205
205
|
${B.length>0?"import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';":`// no plugin declares a runtime hook, so there is no plugins
|
|
@@ -217,7 +217,7 @@ export async function runRequestHooks(ctx) {
|
|
|
217
217
|
const r = await p.onRequest(ctx);
|
|
218
218
|
if (r instanceof Response) return r;
|
|
219
219
|
} catch (err) {
|
|
220
|
-
console.error('
|
|
220
|
+
console.error('Rosefc: plugin', p.name, 'onRequest failed:', err instanceof Error ? err.message : err);
|
|
221
221
|
}
|
|
222
222
|
}
|
|
223
223
|
return null;
|
|
@@ -231,7 +231,7 @@ export async function runResponseHooks(ctx, res) {
|
|
|
231
231
|
const r = await p.onResponse(ctx, out);
|
|
232
232
|
if (r instanceof Response) out = r;
|
|
233
233
|
} catch (err) {
|
|
234
|
-
console.error('
|
|
234
|
+
console.error('Rosefc: plugin', p.name, 'onResponse failed:', err instanceof Error ? err.message : err);
|
|
235
235
|
}
|
|
236
236
|
}
|
|
237
237
|
return out;
|
|
@@ -255,7 +255,7 @@ setLocales(${C}, '${S}');
|
|
|
255
255
|
// globalThis so a dev hot-re-import (a fresh module instance) keeps serving the
|
|
256
256
|
// same live connections. __addStoreClient/__removeStoreClient are called by the
|
|
257
257
|
// host (cli serve worker / devWrap) as SSE connections open and close.
|
|
258
|
-
const __storeClients: Set<any> = (globalThis as any).
|
|
258
|
+
const __storeClients: Set<any> = (globalThis as any).__rosefc_storeClients || ((globalThis as any).__rosefc_storeClients = new Set());
|
|
259
259
|
function __broadcastStore(name: string, value: unknown): void {
|
|
260
260
|
if (__storeClients.size === 0) return;
|
|
261
261
|
const frame = 'event: store\\ndata: ' + JSON.stringify({ name: name, value: value }) + '\\n\\n';
|
|
@@ -265,11 +265,11 @@ function __broadcastStore(name: string, value: unknown): void {
|
|
|
265
265
|
}
|
|
266
266
|
setStoreTransport((name, value) => {
|
|
267
267
|
__broadcastStore(name, value);
|
|
268
|
-
if (typeof process !== 'undefined' && typeof process.send === 'function') process.send({ type: '
|
|
268
|
+
if (typeof process !== 'undefined' && typeof process.send === 'function') process.send({ type: 'rosefc:store', name, value });
|
|
269
269
|
});
|
|
270
270
|
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
271
271
|
process.on('message', (msg) => {
|
|
272
|
-
if (msg && msg.type === '
|
|
272
|
+
if (msg && msg.type === 'rosefc:store') {
|
|
273
273
|
applyStorePatch(msg.name, msg.value);
|
|
274
274
|
__broadcastStore(msg.name, msg.value);
|
|
275
275
|
}
|
|
@@ -387,8 +387,8 @@ export const kv = {
|
|
|
387
387
|
return !!e && e.exp >= Date.now();
|
|
388
388
|
},
|
|
389
389
|
};
|
|
390
|
-
globalThis.
|
|
391
|
-
globalThis.
|
|
390
|
+
globalThis.__rosefcKvApi = { kv, kvMemo: $kv };
|
|
391
|
+
globalThis.__rosefcContent = {
|
|
392
392
|
list: (coll: string, filter?: { tag: string }) => {
|
|
393
393
|
let items = contentCollections[coll] ?? [];
|
|
394
394
|
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
@@ -474,12 +474,12 @@ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<
|
|
|
474
474
|
});
|
|
475
475
|
}
|
|
476
476
|
${wi?`// The isomorphic runtime's $udp/$tcp reach Node's dgram/net only through these globals; injecting them at server boot is what lets __startNetwork() turn a registered spec into a bound socket.
|
|
477
|
-
(globalThis as any).
|
|
478
|
-
(globalThis as any).
|
|
477
|
+
(globalThis as any).__rosefc_dgram = __rosefcDgram;
|
|
478
|
+
(globalThis as any).__rosefc_net = __rosefcNet;`:""}
|
|
479
479
|
${gr?`// The isomorphic runtime's $websocket performs the RFC 6455 handshake (sha1) on a node:http upgrade socket; both reach it only through these globals.
|
|
480
|
-
(globalThis as any).
|
|
481
|
-
(globalThis as any).
|
|
482
|
-
globalThis.
|
|
480
|
+
(globalThis as any).__rosefc_http = __rosefcHttp;
|
|
481
|
+
(globalThis as any).__rosefc_crypto = __rosefcCrypto;`:""}
|
|
482
|
+
globalThis.__rosefcExtras = { v, jobs, sse, udp: $udp, tcp: $tcp, listen: $listen, websocket: $websocket, mqtt: $mqtt };
|
|
483
483
|
${_n?`
|
|
484
484
|
const auth = {
|
|
485
485
|
hashPassword(password: string): string {
|
|
@@ -521,8 +521,8 @@ const auth = {
|
|
|
521
521
|
} catch { return false; }
|
|
522
522
|
},
|
|
523
523
|
};
|
|
524
|
-
globalThis.
|
|
525
|
-
`:"//
|
|
524
|
+
globalThis.__rosefcAuth = auth;
|
|
525
|
+
`:"// __rosefcAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
|
|
526
526
|
|
|
527
527
|
// Concurrent missers on a cold key share ONE compute through this inflight map - the check-then-set shape alone lets N simultaneous cold readers hammer.
|
|
528
528
|
const __kvInflight = new Map<string, Promise<unknown>>();
|
|
@@ -848,7 +848,7 @@ export async function renderPage(pathname, form, options) {
|
|
|
848
848
|
async function renderPageIsolated(pathname, form, options) {
|
|
849
849
|
clearRequestState();
|
|
850
850
|
// Cold-start readiness gate (Oboext #8): await the app's published DB-ready promise before any $data() read.
|
|
851
|
-
const appReady = globalThis.
|
|
851
|
+
const appReady = globalThis.__rosefcAppReady;
|
|
852
852
|
if (appReady) await appReady;
|
|
853
853
|
const route = routeClass(pathname).route;
|
|
854
854
|
if (route) {
|
|
@@ -889,10 +889,10 @@ async function renderPageIsolated(pathname, form, options) {
|
|
|
889
889
|
if (err instanceof ActionError) {
|
|
890
890
|
setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
|
|
891
891
|
actionStatus = err.code;
|
|
892
|
-
} else if (err && err.
|
|
892
|
+
} else if (err && err.__rosefc === 'redirect') {
|
|
893
893
|
|
|
894
894
|
return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
|
|
895
|
-
} else if (err && err.
|
|
895
|
+
} else if (err && err.__rosefc === 'notFound') {
|
|
896
896
|
|
|
897
897
|
return await notFoundPage(pathname);
|
|
898
898
|
} else {
|
|
@@ -906,7 +906,7 @@ async function renderPageIsolated(pathname, form, options) {
|
|
|
906
906
|
rendered = extractHead(await route.render([], ''));
|
|
907
907
|
} catch (err) {
|
|
908
908
|
// The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
|
|
909
|
-
const signal = err && err.
|
|
909
|
+
const signal = err && err.__rosefc;
|
|
910
910
|
if (signal === 'redirect') {
|
|
911
911
|
return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
|
|
912
912
|
}
|
|
@@ -914,10 +914,10 @@ async function renderPageIsolated(pathname, form, options) {
|
|
|
914
914
|
return await notFoundPage(pathname);
|
|
915
915
|
}
|
|
916
916
|
|
|
917
|
-
console.error('
|
|
917
|
+
console.error('Rosefc: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
918
918
|
// F10: in dev the response body carries the real error \u95B3?message, file:line and the fix hint.
|
|
919
919
|
let devDetail = '';
|
|
920
|
-
if (process.env.
|
|
920
|
+
if (process.env.ROSEFC_DEV === '1' && err) {
|
|
921
921
|
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
922
922
|
const file = esc(String(err.file || ''));
|
|
923
923
|
const line = err.line != null ? esc(String(err.line)) : '';
|
|
@@ -940,7 +940,7 @@ async function renderPageIsolated(pathname, form, options) {
|
|
|
940
940
|
}
|
|
941
941
|
// __route tells the bootstrap which route this document was rendered for.
|
|
942
942
|
// A zero-JS route ships no state script - but a NATIVE client asking for the
|
|
943
|
-
// JSON half of the render (the /
|
|
943
|
+
// JSON half of the render (the /__rosefc/data channel) still needs the values
|
|
944
944
|
// its $data produced, so the withState option asks for them explicitly.
|
|
945
945
|
const noJs = route.csr === false && !(options && options.withState);
|
|
946
946
|
let state = '{}';
|
|
@@ -991,7 +991,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
991
991
|
// Object.prototype's member and CALL it as the handler - a 200 whose
|
|
992
992
|
// body was the prototype's return value, or a TypeError from the
|
|
993
993
|
// dispatch. Not reachable through Node's HTTP parser (it rejects those
|
|
994
|
-
// methods), but the edge adapter and
|
|
994
|
+
// methods), but the edge adapter and rosefc/test pass the method through.
|
|
995
995
|
const fn = Object.prototype.hasOwnProperty.call(route.handlers, verb) ? route.handlers[verb] : null;
|
|
996
996
|
if (!fn) {
|
|
997
997
|
return new Response(JSON.stringify({ error: 'method not allowed' }), {
|
|
@@ -1016,7 +1016,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
1016
1016
|
else if (seg.startsWith('*')) params[seg.replace(/^\\*+/, '')] = pathParts.slice(i).map(decodeURIComponent);
|
|
1017
1017
|
}
|
|
1018
1018
|
// The bag must describe THIS request: a host without a context store
|
|
1019
|
-
// (the edge adapter,
|
|
1019
|
+
// (the edge adapter, rosefc/test) reuses one module-level object, so a
|
|
1020
1020
|
// static route used to inherit the previous request's params - a
|
|
1021
1021
|
// /api/posts/42 call made /api/health report an id it was never sent.
|
|
1022
1022
|
// Assigning (rather than only when non-empty) drops the stale value.
|
|
@@ -1032,7 +1032,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
1032
1032
|
return toResponse(await fn(request));
|
|
1033
1033
|
} catch (err) {
|
|
1034
1034
|
|
|
1035
|
-
const signal = err && err.
|
|
1035
|
+
const signal = err && err.__rosefc;
|
|
1036
1036
|
if (signal === 'redirect') {
|
|
1037
1037
|
return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
|
|
1038
1038
|
status: err.status ?? 307,
|
|
@@ -1064,7 +1064,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
1064
1064
|
async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
|
|
1065
1065
|
clearRequestState();
|
|
1066
1066
|
// Cold-start readiness gate (Oboext #8): same contract as renderPage \u95B3?await the app's published DB-ready promise before streaming the shell.
|
|
1067
|
-
const appReady = globalThis.
|
|
1067
|
+
const appReady = globalThis.__rosefcAppReady;
|
|
1068
1068
|
if (appReady) await appReady;
|
|
1069
1069
|
const route = routeClass(pathname).route;
|
|
1070
1070
|
if (route) {
|
|
@@ -1085,10 +1085,10 @@ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
|
|
|
1085
1085
|
// nonce routes: an un-nonced inline <style> would be CSP-blocked, so strip to markers (applyHead re-injects under the nonce). Otherwise keep the head content in the streamed body so page/layout <style> applies on first paint (no FOUC) and no-JS routes stay styled.
|
|
1086
1086
|
html = routeClass(pathname).nonce ? extractHead(await route.render([], '')).html : await route.render([], '');
|
|
1087
1087
|
} catch (err) {
|
|
1088
|
-
console.error('
|
|
1088
|
+
console.error('Rosefc: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
1089
1089
|
// F10: dev carries the real error in the body here too \u95B3?the shell
|
|
1090
1090
|
let devDetail = '';
|
|
1091
|
-
if (process.env.
|
|
1091
|
+
if (process.env.ROSEFC_DEV === '1' && err) {
|
|
1092
1092
|
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
1093
1093
|
const file = esc(String(err.file || ''));
|
|
1094
1094
|
const line = err.line != null ? esc(String(err.line)) : '';
|
|
@@ -1113,7 +1113,7 @@ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
|
|
|
1113
1113
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
1114
1114
|
// P1-6 (bug report): the JSON data block is embedded in the document.
|
|
1115
1115
|
const stateSafe = state.replace(/</g, '\\\\u003c');
|
|
1116
|
-
write('</div>\\n <script type="application/json" id="
|
|
1116
|
+
write('</div>\\n <script type="application/json" id="__rosefc_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
1117
1117
|
return 200;
|
|
1118
1118
|
}
|
|
1119
1119
|
return 404;
|
|
@@ -1124,7 +1124,7 @@ void invalidateRenderCache;
|
|
|
1124
1124
|
// Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
|
|
1125
1125
|
export { installContextStore };
|
|
1126
1126
|
`;try{let E=[...ne,...ge].map(({info:Ut})=>Ut.pattern),L=[...new Set(E)].sort(),ae=L.map(Ut=>JSON.stringify(Ut)).join(" | ")||"'/'",me=Ut=>(Ut.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g)??[]).map(Et=>Et.replace(/^[*:]+/,"")),ye=L.map(Ut=>{let Et=me(Ut);return Et.length?" "+JSON.stringify(Ut)+": { "+Et.map(Ms=>Ms+": string | number").join("; ")+` };
|
|
1127
|
-
`:""}).join(""),de=z.join(s,"src",".
|
|
1127
|
+
`:""}).join(""),de=z.join(s,"src",".rosefc");await te.promises.mkdir(de,{recursive:!0});let pe=["// GENERATED by rosefc build - do not edit.","export type RoutePath = "+ae+";","export const routePatterns = "+JSON.stringify(L)+" as const;","export type RouteParams = {",ye,"};","/** Build a URL from a route pattern and its params. */","export function url("," path: RoutePath,"," params: RouteParams[keyof RouteParams] = {} as never,","): string {"," let out = path as string;"," for (const [k, v] of Object.entries(params as Record<string, string | number>)) {"," out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));"," }"," return out;","}"].join(`
|
|
1128
1128
|
`)+`
|
|
1129
1129
|
`,Fe=z.join(de,"routes.ts");try{await te.promises.readFile(Fe,"utf8")!==pe&&await te.promises.writeFile(Fe,pe)}catch{await te.promises.writeFile(Fe,pe)}}catch{}await te.promises.writeFile(z.join(F,"server-entry.js"),vi),await ce;let Fr=br(z.join(F,"server-entry.js"),{entryPoints:[z.join(F,"server-entry.js")],bundle:!0,outfile:z.join(r,"server.js"),format:"esm",platform:"node",write:!0,...Ir,...i?{minify:!0,keepNames:!0}:{}},o);Fr.catch(()=>{});let Pr=m.map((E,L)=>({i:L})).filter(({i:E})=>!l[E].isApi&&!l[E].isMiddleware&&w.has(E)).map(({i:E})=>`import { render as render_${E} } from './comp-${E}.client.js';`).join(`
|
|
1130
1130
|
`),bl=ht||Re?"":Pr,Ro=ht?ne.map(({info:E,i:L})=>`{ pattern: '${E.pattern}', ${Jt(L)} }`).join(`,
|
|
@@ -1162,13 +1162,13 @@ import { state, setState, resumeState, clearRequestState, resetEffects, wire, is
|
|
|
1162
1162
|
${E.publish}
|
|
1163
1163
|
${m.some(L=>L.usesStore)?`
|
|
1164
1164
|
// Live store channel: an app that reads a shared $store() keeps one EventSource to
|
|
1165
|
-
// /
|
|
1165
|
+
// /__rosefc_store. A server-side write ($store.set/update from a network listener,
|
|
1166
1166
|
// a job, or an action) is pushed here as an {name,value} patch; applyStorePatch
|
|
1167
1167
|
// writes it into the reactive store box, re-running the wire() effects that render
|
|
1168
1168
|
// {store.get()} / {#each store.get()}. No store in the app - no connection.
|
|
1169
1169
|
if (typeof window !== 'undefined' && typeof EventSource !== 'undefined') {
|
|
1170
1170
|
try {
|
|
1171
|
-
var __storeEs = new EventSource('/
|
|
1171
|
+
var __storeEs = new EventSource('/__rosefc_store');
|
|
1172
1172
|
__storeEs.addEventListener('store', function (m) {
|
|
1173
1173
|
try { var p = JSON.parse(m.data); applyStorePatch(p.name, p.value); } catch (e) {}
|
|
1174
1174
|
});
|
|
@@ -1189,7 +1189,7 @@ import { reportVitals } from './runtime.js';`:""}
|
|
|
1189
1189
|
// the root _layout.rose), the bootstrap defers the initial wire() to
|
|
1190
1190
|
// requestIdleCallback. The flag is set here (module eval runs before the
|
|
1191
1191
|
// bootstrap's start() call) so the bootstrap can read it without a second channel.
|
|
1192
|
-
if (typeof window !== 'undefined') window.
|
|
1192
|
+
if (typeof window !== 'undefined') window.__rosefcLazy = ${JSON.stringify(Au)};
|
|
1193
1193
|
// The two pack doors, re-exported for an app that wants to warm a language before its visitor asks for it (ensureLocale) or to feed a dictionary.
|
|
1194
1194
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
1195
1195
|
${E.prefetchDoor}
|
|
@@ -1253,7 +1253,7 @@ async function paintFallback(container, page, builtin, keepState = false) {
|
|
|
1253
1253
|
|
|
1254
1254
|
|
|
1255
1255
|
export async function startNotFound(container, pathname) {
|
|
1256
|
-
const el = document.getElementById('
|
|
1256
|
+
const el = document.getElementById('__rosefc_state');
|
|
1257
1257
|
if (el) resumeState(el.textContent);
|
|
1258
1258
|
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
|
|
1259
1259
|
}
|
|
@@ -1372,8 +1372,8 @@ export function prefetchStats() {
|
|
|
1372
1372
|
// One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
|
|
1373
1373
|
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
1374
1374
|
function bindEvents(container) {
|
|
1375
|
-
if (container.
|
|
1376
|
-
container.
|
|
1375
|
+
if (container.__rosefc_bound) return;
|
|
1376
|
+
container.__rosefc_bound = true;
|
|
1377
1377
|
for (const ev of DELEGATED) {
|
|
1378
1378
|
container.addEventListener(ev, (e) => {
|
|
1379
1379
|
const el = e.target.closest('[data-on-' + ev + ']');
|
|
@@ -1395,7 +1395,7 @@ async function postForm(body, container, pathname) {
|
|
|
1395
1395
|
const html = await res.text();
|
|
1396
1396
|
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
1397
1397
|
const next = doc.getElementById('app');
|
|
1398
|
-
const st = doc.getElementById('
|
|
1398
|
+
const st = doc.getElementById('__rosefc_state');
|
|
1399
1399
|
const paint = () => {
|
|
1400
1400
|
adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
|
|
1401
1401
|
};
|
|
@@ -1412,9 +1412,9 @@ export async function $action(name, e) {
|
|
|
1412
1412
|
const body = new FormData();
|
|
1413
1413
|
body.append('__action', name);
|
|
1414
1414
|
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
1415
|
-
const box = e && e.target && e.target.closest ? e.target.closest('[data-
|
|
1415
|
+
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosefc]') : null;
|
|
1416
1416
|
try {
|
|
1417
|
-
return await postForm(body, box || undefined, box ? box.getAttribute('data-
|
|
1417
|
+
return await postForm(body, box || undefined, box ? box.getAttribute('data-rosefc') : undefined);
|
|
1418
1418
|
} finally {
|
|
1419
1419
|
__rvSetPending(false);
|
|
1420
1420
|
}
|
|
@@ -1465,7 +1465,7 @@ export async function start(container, pathname, initial) {
|
|
|
1465
1465
|
clearMounts();
|
|
1466
1466
|
// stale mounts from a failed render never fire
|
|
1467
1467
|
if (initial) {
|
|
1468
|
-
const el = document.getElementById('
|
|
1468
|
+
const el = document.getElementById('__rosefc_state');
|
|
1469
1469
|
if (el) resumeState(el.textContent);
|
|
1470
1470
|
}
|
|
1471
1471
|
for (const route of routes) {
|
|
@@ -1510,10 +1510,10 @@ ${To}
|
|
|
1510
1510
|
html = await render(closes, '');
|
|
1511
1511
|
} catch (err) {
|
|
1512
1512
|
|
|
1513
|
-
if (err && err.
|
|
1514
|
-
if (err && err.
|
|
1513
|
+
if (err && err.__rosefc === 'notFound') { signal = 'notFound'; return; }
|
|
1514
|
+
if (err && err.__rosefc === 'redirect') { signal = err.path; return; }
|
|
1515
1515
|
|
|
1516
|
-
console.error('
|
|
1516
|
+
console.error('Rosefc: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
1517
1517
|
broken = true;
|
|
1518
1518
|
return;
|
|
1519
1519
|
}
|
|
@@ -1557,7 +1557,7 @@ export async function adopt(container, html, stateJson, pathname) {
|
|
|
1557
1557
|
resumeState(stateJson);
|
|
1558
1558
|
container.innerHTML = html;
|
|
1559
1559
|
|
|
1560
|
-
const st = document.getElementById('
|
|
1560
|
+
const st = document.getElementById('__rosefc_state');
|
|
1561
1561
|
if (st) st.textContent = stateJson;
|
|
1562
1562
|
for (const route of routes) {
|
|
1563
1563
|
if (matchRoute(route.pattern, route0)) {
|
|
@@ -1589,20 +1589,20 @@ setRefreshHook(async () => {
|
|
|
1589
1589
|
// inline ride the shared nav chunk, whose components resolve the runtime
|
|
1590
1590
|
// through this object instead of bundling a second copy. Published before any
|
|
1591
1591
|
// render runs; the chunk's shim throws if it loads first.
|
|
1592
|
-
globalThis.
|
|
1592
|
+
globalThis.__rosefc_rt = { ${gt.join(", ")} };`:"",yr=E=>Re?`
|
|
1593
1593
|
// === Sliced mode: the shared nav chunk === One file holds every route's
|
|
1594
1594
|
// render chain this document did not inline, fetched on the first cross-route
|
|
1595
|
-
// navigation (or a hover prefetch).
|
|
1595
|
+
// navigation (or a hover prefetch). __rosefc_navImport is the override seam
|
|
1596
1596
|
// (tests, or a host page with its own loader); the browser default is a plain
|
|
1597
1597
|
// dynamic import of the versioned URL, which 'self' in the CSP allows.
|
|
1598
1598
|
const __navUrl = ${JSON.stringify(E)};
|
|
1599
|
-
const __navImport = globalThis.
|
|
1599
|
+
const __navImport = globalThis.__rosefc_navImport || ((u) => import(u));
|
|
1600
1600
|
let __navMod = null;
|
|
1601
1601
|
const __nav = async () => (__navMod ??= await __navImport(__navUrl));
|
|
1602
1602
|
const __navRoute = async (pattern) => (await __nav()).navRenders[pattern];
|
|
1603
1603
|
const __navNotFound = async (prefix) => (await __nav()).navNotFound[prefix];
|
|
1604
1604
|
const __navError = async () => (await __nav()).navError;
|
|
1605
|
-
`:"",Eo=Ns({imports:Re?Ao(null).imports:bl,routes:Re?Ao(null).routes:Ro,publish:"",nav:"",notFoundTable:Re?In:Os,errorRender:Re?_i:fs,prefetchDoor:""});Re||await te.promises.writeFile(z.join(F,"client-entry.js"),Eo);let ki=Re?(async()=>{X("runtime-global.js",["// Sliced-mode bridge (generated): the nav chunk resolves the runtime","// through the copy the route slice published, so a page runs exactly one","// runtime. Exports are tree-shaken to what the chunk references.","const __rt = globalThis.
|
|
1605
|
+
`:"",Eo=Ns({imports:Re?Ao(null).imports:bl,routes:Re?Ao(null).routes:Ro,publish:"",nav:"",notFoundTable:Re?In:Os,errorRender:Re?_i:fs,prefetchDoor:""});Re||await te.promises.writeFile(z.join(F,"client-entry.js"),Eo);let ki=Re?(async()=>{X("runtime-global.js",["// Sliced-mode bridge (generated): the nav chunk resolves the runtime","// through the copy the route slice published, so a page runs exactly one","// runtime. Exports are tree-shaken to what the chunk references.","const __rt = globalThis.__rosefc_rt;","if (!__rt) throw new Error('rosefc: the sliced bundle bridge is missing - the route slice did not publish the runtime before the nav chunk loaded');",...oe.map(pe=>`export const ${pe} = __rt.${pe};`)].join(`
|
|
1606
1606
|
`)+`
|
|
1607
1607
|
`);let E=[];for(let pe=0;pe<m.length;pe++)l[pe].isApi||!w.has(pe)||!m[pe].client||E.push(te.promises.writeFile(z.join(F,`nav-comp-${pe}.client.js`),m[pe].client.replace(/from '\.\/runtime\.js'/g,"from './runtime-global.js'").replace(/from '\.\/comp-(\d+)\.client\.js'/g,"from './nav-comp-$1.client.js'")));let L=`
|
|
1608
1608
|
${Pr.replace(/from '\.\/comp-(\d+)\.client\.js'/g,"from './nav-comp-$1.client.js'")}
|
|
@@ -1616,7 +1616,7 @@ export const navNotFound = {
|
|
|
1616
1616
|
};
|
|
1617
1617
|
export const navError = ${ps>=0?`{ render: ${Ee(ps)} }`:"null"};
|
|
1618
1618
|
`;await Promise.all([...E,te.promises.writeFile(z.join(F,"nav-entry.js"),L)]),await br(z.join(F,"nav-entry.js"),{entryPoints:[z.join(F,"nav-entry.js")],bundle:!0,outfile:z.join(r,"nav.js"),format:"esm",platform:"browser",minify:!0,write:!0,...Ir},o);let ae=await te.promises.readFile(z.join(r,"nav.js")),me="/nav.js?v="+Br(ae);await Ei(z.join(r,"slices")),await te.promises.mkdir(z.join(r,"slices"),{recursive:!0});let ye=[{entryFile:"client-entry.js",outFile:z.join(r,"client.js"),own:null},...ne.map(({i:pe})=>{let Fe=ut(l[pe].pattern);return{entryFile:`slice-entry-${Fe}.js`,outFile:z.join(r,"slices",`${Fe}.js`),own:pe}})],de=[];for(let{entryFile:pe,outFile:Fe,own:Ut}of ye){let Et=Ao(Ut),Ms=z.join(F,pe);await te.promises.writeFile(Ms,Ns({imports:Et.imports,routes:Et.routes,publish:rs,nav:yr(me),notFoundTable:In,errorRender:_i,prefetchDoor:`
|
|
1619
|
-
export { setPrefetchOverride } from './runtime.js';`})),de.push(br(Ms+":slice",{entryPoints:[Ms],bundle:!0,outfile:Fe,format:"esm",platform:"browser",minify:!0,write:!0,...Ir},o))}return await Promise.all(de),{}})():ht?(async()=>(await Ei(z.join(r,"chunks")),br(z.join(F,"client-entry.js")+":split",{entryPoints:[z.join(F,"client-entry.js")],bundle:!0,format:"esm",platform:"browser",minify:!0,splitting:!0,outdir:r,entryNames:"client",chunkNames:"chunks/[name]-[hash]",write:!0,...Ir},o)))():br(z.join(F,"client-entry.js"),{entryPoints:[z.join(F,"client-entry.js")],bundle:!0,outfile:z.join(r,"client.js"),format:"esm",platform:"browser",minify:!0,write:!0,...Ir},o);await Promise.all([Fr,ki,re]);for(let E of[z.join(r,"server.js"),z.join(r,"prod.mjs")])try{if(!te.existsSync(E))continue;let L=await te.promises.readFile(E,"utf8");if(L.startsWith(W))continue;(/Dynamic require of/.test(L)||/(?<![\w$])require\s*\(/.test(L))&&await te.promises.writeFile(E,W+L,"utf8")}catch{}let Ri=hd;try{let E=te.readFileSync(z.join(r,"client.js"));Ri=hd.replace("from '/client.js'",`from '/client.js?v=${Br(E)}'`)}catch{}await te.promises.writeFile(z.join(r,"mount.js"),Ri);let Ai=z.join(s,"public");te.existsSync(Ai)&&await te.promises.cp(Ai,z.join(r,"public"),{recursive:!0}),console.log("
|
|
1619
|
+
export { setPrefetchOverride } from './runtime.js';`})),de.push(br(Ms+":slice",{entryPoints:[Ms],bundle:!0,outfile:Fe,format:"esm",platform:"browser",minify:!0,write:!0,...Ir},o))}return await Promise.all(de),{}})():ht?(async()=>(await Ei(z.join(r,"chunks")),br(z.join(F,"client-entry.js")+":split",{entryPoints:[z.join(F,"client-entry.js")],bundle:!0,format:"esm",platform:"browser",minify:!0,splitting:!0,outdir:r,entryNames:"client",chunkNames:"chunks/[name]-[hash]",write:!0,...Ir},o)))():br(z.join(F,"client-entry.js"),{entryPoints:[z.join(F,"client-entry.js")],bundle:!0,outfile:z.join(r,"client.js"),format:"esm",platform:"browser",minify:!0,write:!0,...Ir},o);await Promise.all([Fr,ki,re]);for(let E of[z.join(r,"server.js"),z.join(r,"prod.mjs")])try{if(!te.existsSync(E))continue;let L=await te.promises.readFile(E,"utf8");if(L.startsWith(W))continue;(/Dynamic require of/.test(L)||/(?<![\w$])require\s*\(/.test(L))&&await te.promises.writeFile(E,W+L,"utf8")}catch{}let Ri=hd;try{let E=te.readFileSync(z.join(r,"client.js"));Ri=hd.replace("from '/client.js'",`from '/client.js?v=${Br(E)}'`)}catch{}await te.promises.writeFile(z.join(r,"mount.js"),Ri);let Ai=z.join(s,"public");te.existsSync(Ai)&&await te.promises.cp(Ai,z.join(r,"public"),{recursive:!0}),console.log("Rosefc zero-JS report:");for(let E of Zm(l,m))console.log(" "+E);let Ci=new Map;for(let{info:E,i:L}of ne)if(Pi(l,m,L))for(let ae of[L,...wr(l,L)])for(let me of m[ae].jsWarnings??[]){let ye=Ci.get(me);ye||(ye={why:me,files:new Map},Ci.set(me,ye));let de=z.relative(s,l[ae].filePath).replace(/\\/g,"/"),pe=ye.files.get(de);pe||(pe=new Set,ye.files.set(de,pe)),pe.add(E.routePath)}for(let E of Ci.values()){let L=new Set;for(let de of E.files.values())for(let pe of de)L.add(pe);let ae=[...E.files.entries()].sort((de,pe)=>pe[1].size-de[1].size).map(([de,pe])=>`${de} (${pe.size===1?[...pe][0]:`${pe.size} routes`})`),me=ae.slice(0,4).join(", "),ye=ae.length>4?`, +${ae.length-4} more files`:"";console.warn(`Rosefc warning: ${L.size} routes ship zero JavaScript while their chain contains ${E.why} - ${me}${ye}`)}return{routes:ne.map(({info:E})=>E),bundle:ct,config:p}}async function Ye(e){let t=z.join(e,"src","pages");if(!te.existsSync(t))return[];async function n(s){let r=await te.promises.readdir(s,{withFileTypes:!0}),i=[];for(let o of r){let a=z.join(s,o.name);o.isDirectory()?i.push(...await n(a)):o.name.endsWith(".rose")&&i.push(a)}return i}return n(t)}async function Ke(e){let t=z.join(e,"src","components");if(!te.existsSync(t))return[];async function n(s){let r=await te.promises.readdir(s,{withFileTypes:!0}),i=[];for(let o of r){let a=z.join(s,o.name);o.isDirectory()?i.push(...await n(a)):o.name.endsWith(".rose")&&i.push(a)}return i}return n(t)}function Xm(e,t){let n=z.dirname(e),s=z.dirname(t);return s===n||s.startsWith(n+z.sep)}function Ym(e,t){let n=z.join(t,"src","pages"),r=z.relative(n,e).replace(/\\/g,"/").replace(/\.rose$/,""),i=z.posix.basename(r),o=e.replace(/\\/g,"/").includes("/src/components/"),a=!o&&i==="_layout",c=!o&&(i==="404"||i==="_notfound"),d=!o&&i==="500",u=!o&&(r==="api"||r.startsWith("api/")),l=!o&&r==="_middleware",p=r.split("/").filter(m=>m!=="_layout"&&m!=="_notfound");p.length>1&&p[p.length-1]==="index"&&(p=p.slice(0,-1));let f=/^\[\.\.\.(\w+)\]$/,h=/^\[\[\.\.\.(\w+)\]\]$/,g=p.map(m=>{let b=h.exec(m);if(b)return`**${b[1]}`;let $=f.exec(m);return $?`*${$[1]}`:m.startsWith("[")&&m.endsWith("]")?`:${m.slice(1,-1)}`:m}),y;return g.length===0||g.length===1&&g[0]==="index"?y="/":y="/"+g.join("/"),{filePath:e,routePath:y,pattern:y,paramNames:p.flatMap(m=>{let b=h.exec(m);if(b)return[b[1]];let $=f.exec(m);return $?[$[1]]:m.startsWith("[")&&m.endsWith("]")?[m.slice(1,-1)]:[]}),isLayout:a,isNotFound:c,isError:d,isApi:u,isMiddleware:l,isComponent:o}}function Fs(e){return e.charAt(0).toUpperCase()+e.slice(1)}var Tl,Dr,yd,Ml,Fl,Zu,Ag,Cg,jg,Tg,Eg,Og,Ir,Mi,Ng,Vl,Mg,bd,$d,wd,Ig,Wg,Dg,Jg,Oi,sd,xd,Zg,rd,id,tm,zr,nm,Cd,ld,lm,dm,pm,Cm,dd,Ll,Bl,Il,Wl,Do,Dl,zl,Fi,Bm,Im,Wm,Dm,pd,Jm,Ii,Gm,Nd,Md,wr,Pi,Hl,hd,Nl,gd,kn=De(()=>{"use strict";Oo();Mo();Rl();Al();Cl();Oo();Gu();jl();Tl=new Map;Dr=/<script>([\s\S]*?)<\/script>/,yd=/<template>([\s\S]*?)<\/template>/,Ml=/<head>([\s\S]*?)<\/head>/,Fl=/<style>([\s\S]*?)<\/style>/,Zu=/(?<=^|[;}{\n])[ \t]*(?:let|const|var)\s+(\w+)[^\n;{}=]*=\s*\$(state|data|kv|persist|derived)\b/g,Ag=/^\s+as\s+[^;\n]+/,Cg=/\$setState\(([^,]+),\s*([^)]+)\)/g,jg=/<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g,Tg=/<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;Eg="<p>This section failed to render.</p>",Og=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ir={loader:{".js":"ts"}},Mi="ROSEFC_PUBLIC_",Ng=/^[A-Za-z_$][\w$]*$/,Vl=()=>Object.entries(process.env).filter(e=>e[0].startsWith(Mi)&&typeof e[1]=="string").sort(([e],[t])=>e<t?-1:e>t?1:0),Mg=()=>Vo(JSON.stringify(Vl()));bd=/^\s*#(?:if|each|await|key|snippet|boundary|island|defer)\b/,$d=/^\s*\/(?:if|each|await|key|snippet|boundary|island|defer)\s*$/,wd=/^\s*:(?:else|then|catch|fallback)\b/,Ig=/^\s*#each\s+([\s\S]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([\s\S]+)\))?\s*$/,Wg=/^\s*#snippet\s+(\w+)(?:\s*\(([\s\S]*)\))?\s*$/,Dg=/^\s*:(?:then|catch)\s+([A-Za-z_$][\w$]*)\s*$/;Jg=/^(?:node:|(?:fs|path|os|crypto|http|https|net|tls|stream|child_process|worker_threads|dns|cluster|better-sqlite3|sqlite3|pg|mysql2|mongodb|redis|ioredis)$)/;Oi=new Map,sd=new Map;xd=[],Zg=2e3,rd=new WeakMap,id=new WeakMap;tm=(()=>{try{return String(te.statSync(Ni(import.meta.url)).mtimeMs)}catch{return"noid"}})(),zr=(()=>{try{let e=z.join(md.tmpdir(),"rosefc-compile-cache");return te.mkdirSync(e,{recursive:!0}),e}catch{return null}})(),nm=0;Cd=new Set(["img","br","hr","input","meta","link","source","wbr"]),ld=/^[ \t]*export\s+(?:(const|let|var)|(?:async\s+)?function)\s+(\w+)/gm;lm=new Set("(,=:[!&|?{};+-*%<>~^".split(""));dm=new Set(["true","false","null","undefined","NaN","Infinity"]);pm=!0;Cm=new Set(["if","each","boundary","island","await","snippet"]),dd=new Map;Ll=0,Bl=!1,Il="",Wl={},Do=new Set,Dl=new Set,zl=null,Fi="";Bm=/<img\b(?:[^<>]|\{[^{}]*\})*>/g,Im={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon"},Wm=4096,Dm=16384;pd=new Map;Jm=new Set(["checked","disabled","readonly","required","selected","multiple","autofocus","open"]);Ii="import { state, setState, persistState, $data, hasState, isSeeded, markSeeded, esc, refresh, onMount, onCleanup, $effect, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, $udp, $tcp, $listen, $websocket, $mqtt, parseLoRaWAN, ActionError, $actionError, $actionErrorOrThrow, $actionPending, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound, aggregate, loader, encodeSdui, decodeSdui } from './runtime.js';",Gm=Ii.replace(/^import\s*\{/,"").replace(/\}\s*from[\s\S]*$/,"").split(",").map(e=>e.trim()).filter(Boolean);Nd=`const __slot = (sl, name, pairs) => {
|
|
1620
1620
|
const fn = sl[name];
|
|
1621
1621
|
if (typeof fn !== 'function') return null;
|
|
1622
1622
|
const o = {};
|
|
@@ -1654,8 +1654,8 @@ const __rhreg = (prefix, fn) => {
|
|
|
1654
1654
|
|
|
1655
1655
|
import { start, postForm } from '/client.js';
|
|
1656
1656
|
|
|
1657
|
-
for (const el of document.querySelectorAll('[data-
|
|
1658
|
-
const route = el.getAttribute('data-
|
|
1657
|
+
for (const el of document.querySelectorAll('[data-rosefc]')) {
|
|
1658
|
+
const route = el.getAttribute('data-rosefc');
|
|
1659
1659
|
const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
|
|
1660
1660
|
const parsed = new DOMParser().parseFromString(doc, 'text/html');
|
|
1661
1661
|
// A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
|
|
@@ -1667,8 +1667,8 @@ for (const el of document.querySelectorAll('[data-rosefd]')) {
|
|
|
1667
1667
|
if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
|
|
1668
1668
|
}
|
|
1669
1669
|
}
|
|
1670
|
-
// start() resumes from #
|
|
1671
|
-
const state = parsed.getElementById('
|
|
1670
|
+
// start() resumes from #__rosefc_state (zero hydration), so the state
|
|
1671
|
+
const state = parsed.getElementById('__rosefc_state');
|
|
1672
1672
|
if (state) el.appendChild(state);
|
|
1673
1673
|
|
|
1674
1674
|
const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
|
|
@@ -1679,7 +1679,7 @@ for (const el of document.querySelectorAll('[data-rosefd]')) {
|
|
|
1679
1679
|
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
1680
1680
|
if (!a || !el.contains(a)) return;
|
|
1681
1681
|
e.preventDefault();
|
|
1682
|
-
el.setAttribute('data-
|
|
1682
|
+
el.setAttribute('data-rosefc', a.getAttribute('href'));
|
|
1683
1683
|
start(el, a.getAttribute('href'), false);
|
|
1684
1684
|
});
|
|
1685
1685
|
// Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
|
|
@@ -1688,15 +1688,15 @@ for (const el of document.querySelectorAll('[data-rosefd]')) {
|
|
|
1688
1688
|
if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
|
|
1689
1689
|
if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
1690
1690
|
e.preventDefault();
|
|
1691
|
-
postForm(new FormData(f), el, el.getAttribute('data-
|
|
1691
|
+
postForm(new FormData(f), el, el.getAttribute('data-rosefc'));
|
|
1692
1692
|
});
|
|
1693
1693
|
}
|
|
1694
|
-
`,Nl=new Map,gd=null});import*as Is from"fs";import*as qr from"path";import*as Bd from"esbuild";import{createHash as Fd}from"crypto";function Xo(e){Id=e==="split",zi=e==="sliced"}function Zl(e,t){Gl=e.trim(),Ql=t.trim(),Ur=null}function Ld(){let e=ey;return Gl!==""&&(e=e.replace("connect-src 'self'",`connect-src 'self' ${Gl}`)),Ql!==""&&(e=e.replace("img-src 'self' data: https://fastly.picsum.photos",`img-src 'self' data: https://fastly.picsum.photos ${Ql}`)),e}function Ws(e,t=Kl){if(Id)return null;let n=zi&&e?qr.join(t,"slices",`${e}.js`):qr.join(t,"client.js");try{let s=Is.statSync(n);if(zi&&e){let r=Pd.get(e+"\0"+t);if(r&&r.mtimeMs===s.mtimeMs)return r.source;let i=Is.readFileSync(n,"utf-8");return Pd.set(e+"\0"+t,{mtimeMs:s.mtimeMs,source:i}),i}return(!Wi||Wi.for!==t||Wi.mtimeMs!==s.mtimeMs)&&(Wi={for:t,mtimeMs:s.mtimeMs,source:Is.readFileSync(n,"utf-8")}),Wi.source}catch{return zi&&e?Ws(null,t):null}}function Zo(){try{let e=qr.join(Kl,"client.js"),t=Is.statSync(e);return(!qo||qo.mtimeMs!==t.mtimeMs)&&(qo={mtimeMs:t.mtimeMs,v:Br(Is.readFileSync(e))}),qo.v}catch{return""}}function Wd(){let e=Zo();return e?`/client.js?v=${e}`:"/client.js"}function Hi(){let e=qr.join(Kl,"styles.css");try{let t=Is.statSync(e);return(!Go||Go.mtimeMs!==t.mtimeMs)&&(Go={mtimeMs:t.mtimeMs,source:Is.readFileSync(e,"utf-8")}),Go.source}catch{return""}}function Dd(){if(Di===null)if(globalThis.
|
|
1694
|
+
`,Nl=new Map,gd=null});import*as Is from"fs";import*as qr from"path";import*as Bd from"esbuild";import{createHash as Fd}from"crypto";function Xo(e){Id=e==="split",zi=e==="sliced"}function Zl(e,t){Gl=e.trim(),Ql=t.trim(),Ur=null}function Ld(){let e=ey;return Gl!==""&&(e=e.replace("connect-src 'self'",`connect-src 'self' ${Gl}`)),Ql!==""&&(e=e.replace("img-src 'self' data: https://fastly.picsum.photos",`img-src 'self' data: https://fastly.picsum.photos ${Ql}`)),e}function Ws(e,t=Kl){if(Id)return null;let n=zi&&e?qr.join(t,"slices",`${e}.js`):qr.join(t,"client.js");try{let s=Is.statSync(n);if(zi&&e){let r=Pd.get(e+"\0"+t);if(r&&r.mtimeMs===s.mtimeMs)return r.source;let i=Is.readFileSync(n,"utf-8");return Pd.set(e+"\0"+t,{mtimeMs:s.mtimeMs,source:i}),i}return(!Wi||Wi.for!==t||Wi.mtimeMs!==s.mtimeMs)&&(Wi={for:t,mtimeMs:s.mtimeMs,source:Is.readFileSync(n,"utf-8")}),Wi.source}catch{return zi&&e?Ws(null,t):null}}function Zo(){try{let e=qr.join(Kl,"client.js"),t=Is.statSync(e);return(!qo||qo.mtimeMs!==t.mtimeMs)&&(qo={mtimeMs:t.mtimeMs,v:Br(Is.readFileSync(e))}),qo.v}catch{return""}}function Wd(){let e=Zo();return e?`/client.js?v=${e}`:"/client.js"}function Hi(){let e=qr.join(Kl,"styles.css");try{let t=Is.statSync(e);return(!Go||Go.mtimeMs!==t.mtimeMs)&&(Go={mtimeMs:t.mtimeMs,source:Is.readFileSync(e,"utf-8")}),Go.source}catch{return""}}function Dd(){if(Di===null)if(globalThis.__ROSEFC_SKIP_MINIFY)Di=ql;else try{Di=Bd.transformSync(ql,{minify:!0}).code}catch{Di=ql}return Di}function zd(){let e=Zo();return(Qo===null||Qo.v!==e)&&(Qo={v:e,s:`
|
|
1695
1695
|
import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '${Wd()}';
|
|
1696
1696
|
${Dd()}`}),Qo.s}function Hd(e){if(Ko!==null&&Ko.for===e)return Ko.out;let t=/\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(e),n=e,s="";t&&(n=e.slice(0,t.index)+e.slice(t.index+t[0].length),s=t[1].split(",").map(i=>{let o=i.split(" as ").map(a=>a.trim());return o.length===1||o[0]===o[1]?"":o[0]&&o[1]?`var ${o[1]} = ${o[0]};`:""}).join(""));let r=`
|
|
1697
1697
|
${n}
|
|
1698
1698
|
${s}
|
|
1699
|
-
${Dd()}`;return Ko={for:e,out:r},r}function Vi(){let e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Gr(e,t=""){let n={...ty};if(t)return n["Content-Security-Policy"]=`script-src 'nonce-${t}' 'strict-dynamic'; ${Ld()}`,n;if(!Ur||Ur.for!==e||Ur.v!==(e?"":Zo())){let s=e?`'sha256-${Fd("sha256").update(Hd(e),"utf-8").digest("base64")}'${zi?" 'self'":""}`:`'self' 'sha256-${Fd("sha256").update(zd(),"utf-8").digest("base64")}'`;Ur={for:e,v:e?"":Zo(),value:`script-src ${s}; ${Ld()}`}}return n["Content-Security-Policy"]=Ur.value,n}function ny(e){let t=new Map,n=[],s=new Map,r=(i,o)=>{t.has(i)||(t.set(i,o),n.push(i))};for(let i of e){for(let o of i.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi))r("title",o[0]);for(let o of i.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)){let a=o[1].toLowerCase();if(a==="title")continue;let c=o[2],d=m=>{let b=c.match(new RegExp(`\\s${m}=(?:"([^"]*)"|'([^']*)')`,"i"));return b?b[1]??b[2]:null},u=c.match(/\sid=(?:"([^"]*)"|'([^']*)')/i),l=d("name"),p=d("property"),f=d("rel"),h=d("charset"),g;l!==null?g=`${a}:${l}`:p!==null?g=`${a}:${p}`:f!==null?g=`${a}:${f}${sy(f,d)}`:h!==null?g=`${a}:${h}`:u?g=`${a}:${u[1]??u[2]}`:(g=`${a}:#${s.get(a)??0}`,s.set(a,(s.get(a)??0)+1)),g=g.replace(/"/g,"");let y=o[0].replace(/^<\w+/,m=>`${m} data-
|
|
1699
|
+
${Dd()}`;return Ko={for:e,out:r},r}function Vi(){let e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Gr(e,t=""){let n={...ty};if(t)return n["Content-Security-Policy"]=`script-src 'nonce-${t}' 'strict-dynamic'; ${Ld()}`,n;if(!Ur||Ur.for!==e||Ur.v!==(e?"":Zo())){let s=e?`'sha256-${Fd("sha256").update(Hd(e),"utf-8").digest("base64")}'${zi?" 'self'":""}`:`'self' 'sha256-${Fd("sha256").update(zd(),"utf-8").digest("base64")}'`;Ur={for:e,v:e?"":Zo(),value:`script-src ${s}; ${Ld()}`}}return n["Content-Security-Policy"]=Ur.value,n}function ny(e){let t=new Map,n=[],s=new Map,r=(i,o)=>{t.has(i)||(t.set(i,o),n.push(i))};for(let i of e){for(let o of i.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi))r("title",o[0]);for(let o of i.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)){let a=o[1].toLowerCase();if(a==="title")continue;let c=o[2],d=m=>{let b=c.match(new RegExp(`\\s${m}=(?:"([^"]*)"|'([^']*)')`,"i"));return b?b[1]??b[2]:null},u=c.match(/\sid=(?:"([^"]*)"|'([^']*)')/i),l=d("name"),p=d("property"),f=d("rel"),h=d("charset"),g;l!==null?g=`${a}:${l}`:p!==null?g=`${a}:${p}`:f!==null?g=`${a}:${f}${sy(f,d)}`:h!==null?g=`${a}:${h}`:u?g=`${a}:${u[1]??u[2]}`:(g=`${a}:#${s.get(a)??0}`,s.set(a,(s.get(a)??0)+1)),g=g.replace(/"/g,"");let y=o[0].replace(/^<\w+/,m=>`${m} data-rosefc-head="${g}"`);r(g,y)}}return n.map(i=>t.get(i)).join(`
|
|
1700
1700
|
`)}function sy(e,t){return/(^|\s)canonical(\s|$)/i.test(e)?"":`@${t("href")??t("type")??t("as")??""}`}function Ji(e,t=""){let n=t?` nonce="${t}"`:"";if(e)return`<script type="module"${n}>${Hd(e)}</script>`;let s=Wd();return`${`<link rel="modulepreload" href="${s}" crossorigin>`}
|
|
1701
1701
|
<script type="module"${n} src="${s}" fetchpriority="high"></script>
|
|
1702
1702
|
<script type="module"${n}>${zd()}</script>`}function Yo(e=Hi(),t="en",n="",s=!0){let r=e?`
|
|
@@ -1707,14 +1707,14 @@ ${Dd()}`;return Ko={for:e,out:r},r}function Vi(){let e=new Uint8Array(16);crypto
|
|
|
1707
1707
|
<head>
|
|
1708
1708
|
<meta charset="UTF-8">
|
|
1709
1709
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1710
|
-
<title>
|
|
1710
|
+
<title>Rosefc</title>${i}${r}
|
|
1711
1711
|
${Vd}
|
|
1712
1712
|
</head>
|
|
1713
|
-
<body>${o}`}function Xl(e,t,n,s=[],r=Hi(),i=!0,o="en",a="",c="",d=!0){let u=ny(s),l=c?u.replace(/<script\b([^>]*)>/gi,(S,C)=>/\bnonce=/.test(C)?S:`<script${C} nonce="${c}">`):u,p=` lang="${o}"${a?` dir="${a}"`:""}`,f="",h=l.replace(/<(html|body)\b([^>]*)>/gi,(S,C,x)=>{let A=x.replace(/\s*data-
|
|
1713
|
+
<body>${o}`}function Xl(e,t,n,s=[],r=Hi(),i=!0,o="en",a="",c="",d=!0){let u=ny(s),l=c?u.replace(/<script\b([^>]*)>/gi,(S,C)=>/\bnonce=/.test(C)?S:`<script${C} nonce="${c}">`):u,p=` lang="${o}"${a?` dir="${a}"`:""}`,f="",h=l.replace(/<(html|body)\b([^>]*)>/gi,(S,C,x)=>{let A=x.replace(/\s*data-rosefc-head="[^"]*"/,"");return C==="html"?p=A:f=A,""}),g=/<title>/i.test(u)?"":"<title>Rosefc</title>",y=/rel=["']?icon/i.test(u)?"":`
|
|
1714
1714
|
${Vd}`,m=h?`
|
|
1715
1715
|
${h}`:"",b=r?`
|
|
1716
1716
|
<style>${r}</style>`:"",$=t.replace(/</g,"\\u003c"),w=i?`
|
|
1717
|
-
<script type="application/json" id="
|
|
1717
|
+
<script type="application/json" id="__rosefc_state">${$}</script>
|
|
1718
1718
|
${Ji(n,c)}`:"",v=i&&d?'<div id="app">':"",_=i&&d?"</div>":"",k=i&&d?`
|
|
1719
1719
|
<style>${Ud}</style>`:"";return`<!DOCTYPE html>
|
|
1720
1720
|
<html${p}>
|
|
@@ -1754,7 +1754,7 @@ if (!__app) {
|
|
|
1754
1754
|
function __saveScroll() {
|
|
1755
1755
|
try {
|
|
1756
1756
|
const s = history.state || {};
|
|
1757
|
-
history.replaceState(Object.assign({}, s, {
|
|
1757
|
+
history.replaceState(Object.assign({}, s, { __rosefcScroll: window.scrollY }), '');
|
|
1758
1758
|
} catch (e) { /* history state unavailable (file:// edge): best effort */ }
|
|
1759
1759
|
}
|
|
1760
1760
|
function __navigate(pathname, restore) {
|
|
@@ -1763,7 +1763,7 @@ function __navigate(pathname, restore) {
|
|
|
1763
1763
|
if (restore) {
|
|
1764
1764
|
// back/forward: restore the entry's scroll (top when it has none)
|
|
1765
1765
|
const s = history.state || {};
|
|
1766
|
-
const y = typeof s.
|
|
1766
|
+
const y = typeof s.__rosefcScroll === 'number' ? s.__rosefcScroll : 0;
|
|
1767
1767
|
return Promise.resolve(p).then(() => { window.scrollTo(0, y); }, () => { window.scrollTo(0, y); });
|
|
1768
1768
|
}
|
|
1769
1769
|
// a fresh navigation starts at the top, like a full page load
|
|
@@ -1787,7 +1787,7 @@ document.addEventListener('click', (e) => {
|
|
|
1787
1787
|
});
|
|
1788
1788
|
// Prefetch the target route's full render (including $data) on hover, keyboard
|
|
1789
1789
|
// focus, or touch - the click that follows paints from cache: no await, no
|
|
1790
|
-
// request. Other frameworks prefetch data only;
|
|
1790
|
+
// request. Other frameworks prefetch data only; Rosefc prefetches the render
|
|
1791
1791
|
// because the inlined bundle already contains every route.
|
|
1792
1792
|
function __prefetchHandler(e) {
|
|
1793
1793
|
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
@@ -1837,20 +1837,20 @@ document.addEventListener('submit', (e) => {
|
|
|
1837
1837
|
// running page. Both are DIRECT references (no wrapper arrow): the names take
|
|
1838
1838
|
// no arguments, so the call is identical and every document that carries the
|
|
1839
1839
|
// bundle pays eleven bytes for the pair instead of forty.
|
|
1840
|
-
window.
|
|
1840
|
+
window.__rosefc = { state: serializeState, prefetch: prefetchStats };
|
|
1841
1841
|
// initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
|
|
1842
1842
|
// If the document was rendered for a DIFFERENT route (a static-file server's
|
|
1843
1843
|
// SPA fallback serves index.html for unknown paths), adopt nothing - let the
|
|
1844
1844
|
// client router render the requested route from scratch.
|
|
1845
|
-
const __st = document.getElementById('
|
|
1845
|
+
const __st = document.getElementById('__rosefc_state');
|
|
1846
1846
|
let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
|
|
1847
1847
|
// The dev server's reload bridge hands the pre-reload signal graph back inside
|
|
1848
|
-
// the next document (window.
|
|
1848
|
+
// the next document (window.__rosefc_resume). The resumed values win over the
|
|
1849
1849
|
// fresh render's, but the ROUTE stays the one the server just rendered - and
|
|
1850
1850
|
// the route renders client-side from the bundle rather than adopting the SSR
|
|
1851
1851
|
// DOM, because a resumed list can be longer than the document's rows and
|
|
1852
1852
|
// adoption could not add them. Absent in every non-dev document.
|
|
1853
|
-
const __resumed = window.
|
|
1853
|
+
const __resumed = window.__rosefc_resume ? JSON.parse(window.__rosefc_resume) : null;
|
|
1854
1854
|
if (__resumed) {
|
|
1855
1855
|
const __route = __state.__route;
|
|
1856
1856
|
__state = Object.assign(__state, __resumed);
|
|
@@ -1870,7 +1870,7 @@ if (__state.__notFound) {
|
|
|
1870
1870
|
// layout): defer the initial wire() until the browser is idle so the SSR
|
|
1871
1871
|
// paint is interactive-to-paint without blocking on the event wiring. Falls
|
|
1872
1872
|
// back to eager wiring where requestIdleCallback is unavailable.
|
|
1873
|
-
if (window.
|
|
1873
|
+
if (window.__rosefcLazy && typeof requestIdleCallback === 'function') {
|
|
1874
1874
|
requestIdleCallback(() => start(__app, window.location.pathname, true));
|
|
1875
1875
|
} else {
|
|
1876
1876
|
start(__app, window.location.pathname, true);
|
|
@@ -1898,10 +1898,10 @@ ${s.join(`
|
|
|
1898
1898
|
`}function Zr(e,t,n=[]){let r=e.replace(/\(([^()]*)\)\s*=>\s*(?:[^(),]|\([^()]*\))*/g,"ARROW").replace(/\b([A-Za-z_$][\w$]*)\s*=>\s*[^,)]*/g,"ARROW").replace(/'(?:[^'\\]|\\.)*'/g,"''").replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/([{,]\s*)[A-Za-z_$][\w$]*\s*:/g,"$1").replace(/\.\s*[A-Za-z_$][\w$]*/g,".").replace(/\[[^[\]]*?\bfor\b[^[\]]*?\bin\b[^[\]]*?\]/g,o=>{let a=o.lastIndexOf(" in ");if(a<0)return"COMP";let c=o.slice(a+4,o.lastIndexOf("]")),d=c.search(/\bif\b/);return`[COMP in ${d<0?c:c.slice(0,d)}]`}),i=new Set([...n,"true","false","null","undefined","True","False","None","Math","Date","JSON","Object","Array","map","filter","reduce","ARROW","COMP","VAR","enumerate","functools","in","if","else","not","and","or","lambda","is","query","store","kv","cookies","actionError","actionPending","sessionCookie","t","state","persist","derived","data"]);for(let o of r.matchAll(/\b([A-Za-z_$][\w$]*)\b/g))if(!t.has(o[1])&&!i.has(o[1]))return o[1];return null}function St(e){let t=[],n=s=>{for(let r of s)if(!(!r||typeof r!="object")){if(r.kind==="element"&&String(r.tag).toLowerCase()==="form"){let i=(r.attrs??[]).find(d=>d.name==="on:submit"),o=i&&i.value&&i.value.kind==="expr"?i.value.code.trim():"",a=[],c=d=>{for(let u of d??[])if(!(!u||typeof u!="object")){if(u.kind==="element"&&["input","textarea","select"].includes(String(u.tag).toLowerCase())){let l=(u.attrs??[]).find(f=>f.name==="name"),p=l&&l.value&&l.value.kind==="text"?l.value.text.trim():"";p&&/^[A-Za-z_$][\w$]*$/.test(p)&&a.push(p)}c(u.children??[]),u.kind==="if"&&(u.branches??[]).forEach(l=>c(l.children??[])),(u.kind==="each"||u.kind==="block")&&c(u.children??[])}};c(r.children??[]),(o||a.length)&&t.push({submit:o,fields:a})}n(r.children??[]),r.kind==="if"&&(r.branches??[]).forEach(i=>n(i.children??[])),(r.kind==="each"||r.kind==="block")&&n(r.children??[]),r.kind==="await"&&(n(r.pending??[]),n(r.then??[]),n(r.catch??[]))}};return n(e),t}function An(e,t){return e.some(n=>n.fields.includes(t))?t:null}function rn(e,t){let n=e;for(let s of e.matchAll(/(?:\$setState|__set)\s*\(\s*(['"])([^'"]*)\1\s*,/g)){let r=s.index??0,i=r+s[0].indexOf("("),o=Wn(e,i);if(o<0)continue;let a=xr(e.slice(r+s[0].length,o).trim());if(!a||a.params.length!==1)continue;let c=t(s[2],a.params[0],a.body);if(c===null)continue;let d=o+1;e[d]===";"&&d++;let u=e.slice(r,d);n=n.replace(u,()=>c+";")}return n}function ec(e,t,n){let s="",r=0,i=0;for(;i<e.length;){let o=e[i];if(o==="/"&&e[i+1]==="/"){let c=e.indexOf(`
|
|
1899
1899
|
`,i);i=c<0?e.length:c;continue}if(o==="/"&&e[i+1]==="*"){let c=e.indexOf("*/",i+2);i=c<0?e.length:c+2;continue}if(o==="#"&&(i===0||e[i-1]===`
|
|
1900
1900
|
`)){let c=e.indexOf(`
|
|
1901
|
-
`,i);i=c<0?e.length:c;continue}if(o==='"'||o==="'"||o==="`"){let c=i+1;for(;c<e.length&&e[c]!==o;){if(e[c]==="\\"){c+=2;continue}if(o==="`"&&e[c]==="$"&&e[c+1]==="{"){let d=1;for(c+=2;c<e.length&&d>0&&(e[c]==="{"?d++:e[c]==="}"&&d--,d!==0);)c++;continue}c++}i=c+1;continue}t.lastIndex=i;let a=t.exec(e);if(a&&a.index===i){s+=e.slice(r,i)+n(a,i),i=Math.max(i+1,t.lastIndex),r=i;continue}i++}return s+=e.slice(r),s}function Qn(e,t,n){let s=e;for(let r of e.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)\s*\.\s*(push|unshift|splice)\s*\(/g)){let i=r[1],o=r[2];if(!t(i))continue;let c=(r.index??0)+r[0].length-1,d=Wn(e,c);if(d<0)continue;let u=er(e.slice(c+1,d)).map(b=>b.trim()),l=e.slice(r.index??0,d+1);if(o==="splice"){let b=u[0]??"0",$=u[1]??"1",w=`$setState('${i}', ${i}().slice(0, ${b}).concat(${i}().slice((${b}) + (${$}))))`,v=e.slice(d+1),_=new RegExp(`^\\s*;?\\s*set[A-Z][\\w$]*\\s*\\(\\s*${i}\\s*\\(\\s*\\)\\s*\\)\\s*;?`).exec(v),k=_?d+1+_[0].length:d+1;s=s.replace(e.slice(r.index??0,k),w);continue}let p=u[0]??"",f=o==="push"?`[...${i}(), ${p}]`:`[${p}, ...${i}()]`,h=e.slice(d+1),y=new RegExp(`^\\s*;?\\s*set[A-Z][\\w$]*\\s*\\(\\s*${i}\\s*\\(\\s*\\)\\s*\\)\\s*;?`).exec(h),m=y?d+1+y[0].length:d+1;s=s.replace(e.slice(r.index??0,m),`$setState('${i}', ${f})`)}return s}function Kn(e,t,n){let s=e;for(let r of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let i=r[1],o=t(i);if(!o)continue;let a=r.index??0,c=a+r[0].length-1,d=Wn(e,c);if(d<0)continue;let u=e.slice(c+1,d).trim();if(xr(u)||u.includes("...")||!/\.(?:map|filter|reduce|find|some|concat)\s*\(/.test(u))continue;let l=n(o,u);if(l===null)continue;let p=d+1;e[p]===";"&&p++,s=s.replace(e.slice(a,p),()=>l)}return s}function on(e,t){let n=e;for(let s of e.matchAll(/(?:\$setState|__set)\s*\(\s*(['"])([^'"]*)\1\s*,/g)){let r=s.index??0,i=r+s[0].indexOf("("),o=Wn(e,i);if(o<0)continue;let a=e.slice(r+s[0].length,o).trim();if(xr(a)||a.includes("...")||!/\.(map|filter|reduce|find|some|concat)\s*\(/.test(a))continue;let c=t(s[2],a);if(c===null)continue;let d=o+1;e[d]===";"&&d++,n=n.replace(e.slice(r,d),()=>c)}return n}function dp(e){let t=e;for(let n of e.matchAll(/(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$store\s*\(/g)){let s=n[1],r=(n.index??0)+n[0].length-1,i=Wn(e,r);if(i<0)continue;let o=er(e.slice(r+1,i)),a=(o.length>=2?o[1]:o[0])?.trim()??"";a&&(t=t.replace(new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\.\\s*get\\s*\\(\\s*\\)`,"g"),`(${a})`))}return t}function pp(e){let t=e;for(let n of e.matchAll(/(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$store\s*\(\s*(['"])([^'"]*)\2\s*,/g)){let s=n[1],r=n[3],i=new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\.\\s*update\\s*\\(`,"g");t=t.replace(i,`$setState('${r}', `)}return t}function tr(e){let t=(e.attrs??[]).find(n=>n.name==="type");return!!t&&t.value&&t.value.kind==="text"&&t.value.text.trim()==="submit"}function an(e){let t=[];for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$persist\b(?:<[^>]*>)?\s*\(/g))t.push(n[1]);return t}function Cn(e){let t=[];for(let n of e.matchAll(/font-family\s*:\s*([^;}]+)/g))for(let s of n[1].split(",")){let r=s.trim().replace(/^['"]|['"]$/g,"");!r||fp.has(r.toLowerCase())||t.includes(r)||t.push(r)}return t}function Mt(e){let t=op(e,"src","content");if(!ip(t))return null;let n;try{n=Io(t)}catch{return null}for(let s of Object.values(n))for(let r of s)delete r.body;return n}function ln(e){let t=[];for(let n of e.matchAll(/\bglobalThis\s*\.\s*(
|
|
1901
|
+
`,i);i=c<0?e.length:c;continue}if(o==='"'||o==="'"||o==="`"){let c=i+1;for(;c<e.length&&e[c]!==o;){if(e[c]==="\\"){c+=2;continue}if(o==="`"&&e[c]==="$"&&e[c+1]==="{"){let d=1;for(c+=2;c<e.length&&d>0&&(e[c]==="{"?d++:e[c]==="}"&&d--,d!==0);)c++;continue}c++}i=c+1;continue}t.lastIndex=i;let a=t.exec(e);if(a&&a.index===i){s+=e.slice(r,i)+n(a,i),i=Math.max(i+1,t.lastIndex),r=i;continue}i++}return s+=e.slice(r),s}function Qn(e,t,n){let s=e;for(let r of e.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)\s*\.\s*(push|unshift|splice)\s*\(/g)){let i=r[1],o=r[2];if(!t(i))continue;let c=(r.index??0)+r[0].length-1,d=Wn(e,c);if(d<0)continue;let u=er(e.slice(c+1,d)).map(b=>b.trim()),l=e.slice(r.index??0,d+1);if(o==="splice"){let b=u[0]??"0",$=u[1]??"1",w=`$setState('${i}', ${i}().slice(0, ${b}).concat(${i}().slice((${b}) + (${$}))))`,v=e.slice(d+1),_=new RegExp(`^\\s*;?\\s*set[A-Z][\\w$]*\\s*\\(\\s*${i}\\s*\\(\\s*\\)\\s*\\)\\s*;?`).exec(v),k=_?d+1+_[0].length:d+1;s=s.replace(e.slice(r.index??0,k),w);continue}let p=u[0]??"",f=o==="push"?`[...${i}(), ${p}]`:`[${p}, ...${i}()]`,h=e.slice(d+1),y=new RegExp(`^\\s*;?\\s*set[A-Z][\\w$]*\\s*\\(\\s*${i}\\s*\\(\\s*\\)\\s*\\)\\s*;?`).exec(h),m=y?d+1+y[0].length:d+1;s=s.replace(e.slice(r.index??0,m),`$setState('${i}', ${f})`)}return s}function Kn(e,t,n){let s=e;for(let r of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let i=r[1],o=t(i);if(!o)continue;let a=r.index??0,c=a+r[0].length-1,d=Wn(e,c);if(d<0)continue;let u=e.slice(c+1,d).trim();if(xr(u)||u.includes("...")||!/\.(?:map|filter|reduce|find|some|concat)\s*\(/.test(u))continue;let l=n(o,u);if(l===null)continue;let p=d+1;e[p]===";"&&p++,s=s.replace(e.slice(a,p),()=>l)}return s}function on(e,t){let n=e;for(let s of e.matchAll(/(?:\$setState|__set)\s*\(\s*(['"])([^'"]*)\1\s*,/g)){let r=s.index??0,i=r+s[0].indexOf("("),o=Wn(e,i);if(o<0)continue;let a=e.slice(r+s[0].length,o).trim();if(xr(a)||a.includes("...")||!/\.(map|filter|reduce|find|some|concat)\s*\(/.test(a))continue;let c=t(s[2],a);if(c===null)continue;let d=o+1;e[d]===";"&&d++,n=n.replace(e.slice(r,d),()=>c)}return n}function dp(e){let t=e;for(let n of e.matchAll(/(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$store\s*\(/g)){let s=n[1],r=(n.index??0)+n[0].length-1,i=Wn(e,r);if(i<0)continue;let o=er(e.slice(r+1,i)),a=(o.length>=2?o[1]:o[0])?.trim()??"";a&&(t=t.replace(new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\.\\s*get\\s*\\(\\s*\\)`,"g"),`(${a})`))}return t}function pp(e){let t=e;for(let n of e.matchAll(/(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$store\s*\(\s*(['"])([^'"]*)\2\s*,/g)){let s=n[1],r=n[3],i=new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\.\\s*update\\s*\\(`,"g");t=t.replace(i,`$setState('${r}', `)}return t}function tr(e){let t=(e.attrs??[]).find(n=>n.name==="type");return!!t&&t.value&&t.value.kind==="text"&&t.value.text.trim()==="submit"}function an(e){let t=[];for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$persist\b(?:<[^>]*>)?\s*\(/g))t.push(n[1]);return t}function Cn(e){let t=[];for(let n of e.matchAll(/font-family\s*:\s*([^;}]+)/g))for(let s of n[1].split(",")){let r=s.trim().replace(/^['"]|['"]$/g,"");!r||fp.has(r.toLowerCase())||t.includes(r)||t.push(r)}return t}function Mt(e){let t=op(e,"src","content");if(!ip(t))return null;let n;try{n=Io(t)}catch{return null}for(let s of Object.values(n))for(let r of s)delete r.body;return n}function ln(e){let t=[];for(let n of e.matchAll(/\bglobalThis\s*\.\s*(__rosefcContent|__rosefcExtras|__rosefcKvApi)\b/g))t.includes(n[1])||t.push(n[1]);return t}function jn(e,t){return e.replace(/globalThis\s*\.\s*(?:__rosefcContent|__rosefcExtras|__rosefcKvApi)\s*(?:\.\s*[A-Za-z_$][\w$]*)?\s*(?:\((?:[^()]|\([^()]*\))*\))?(?:\s*\.\s*[A-Za-z_$][\w$]*)*/g,t)}function Oe(e,t,n,s){let r=i=>{let o=i.indexOf("(");return i.slice(o+1,i.lastIndexOf(")"))};return e.replace(/globalThis\s*\.\s*__rosefcContent\s*\.\s*list\s*\((?:[^()]|\([^()]*\))*\)/g,i=>`${t}(${r(i)})`).replace(/globalThis\s*\.\s*__rosefcContent\s*\.\s*get\s*\((?:[^()]|\([^()]*\))*\)/g,i=>{let o=er(r(i));return`${n}(${o.slice(0,2).join(", ")})`}).replace(/globalThis\s*\.\s*__rosefcContent\s*\.\s*rss\s*\((?:[^()]|\([^()]*\))*\)/g,s)}function ys(e,t,n=()=>!1){let s=new Set(["null","undefined","true","false","this","new","typeof","void"]),r=/(^|[^$\w.!=<>&|?+\-*/%])([A-Za-z_$][\w$]*)\s*\(\s*\)\s*\?([^?:]*):/g;return e.replace(r,(i,o,a,c)=>n(a)?`${o}${t(`${a}()`)} ?${c}:`:i).replace(/(^|[^$\w.!=<>&|?+\-*/%])([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\?([^?:]*):/g,(i,o,a,c,d)=>{if(s.has(a.trim())||/\s*\(/.test(c.slice(0,1)))return i;let u=e.slice(0,d+o.length).replace(/\s+$/,"");return/[=!<>&|+\-*/%]$/.test(u)?i:`${o}${t(a.trim())} ?${c}:`})}function cn(e){let t=[];for(let n of e.matchAll(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*globalThis\s*\.\s*__rosefcContent\s*\.\s*(?:list|get)\s*\(/gm))t.includes(n[1])||t.push(n[1]);return t}function nr(e){for(let t of e.split(",")){let n=t.trim().replace(/^['"]|['"]$/g,"").toLowerCase();if(n==="serif"||n==="ui-serif")return"serif";if(n==="monospace"||n==="ui-monospace")return"monospace";if(n==="sans-serif"||n==="sans"||n==="system-ui"||n==="ui-sans-serif")return"sans-serif"}return null}function hp(e,t,n=96*1024){let s=[],r=[];return{css:e.replace(/@font-face\s*\{([^}]*)\}/g,(o,a)=>{let c=/font-family\s*:\s*([^;}]+)/.exec(a)?.[1],d=c?c.trim().replace(/^['"]|['"]$/g,""):"",u=/url\(\s*['"]?([^'")\s]+)['"]?\s*\)/.exec(a)?.[1];if(!u||/^data:/i.test(u))return o;let l=u.startsWith("/")?u.slice(1):u.replace(/^\.?\//,""),p=op(t,l);if(!ip(p))return r.push({family:d,file:l,reason:"not in public/"}),o;let f=vy(p).size;if(f>n)return r.push({family:d,file:l,reason:`${Math.round(f/1024)} KB over the ${Math.round(n/1024)} KB inline limit`}),o;let h=wy(p).toString("base64"),g=/\.woff2$/i.test(l)?"font/woff2":/\.woff$/i.test(l)?"font/woff":/\.otf$/i.test(l)?"font/otf":"font/ttf";return s.push(d),o.replace(/url\(\s*['"]?[^'")\s]+['"]?\s*\)/,`url(data:${g};base64,${h})`)}),inlined:s,skipped:r}}function Zn(e){let t=[];for(let n of e.matchAll(/@font-face\s*\{([^}]*)\}/g)){let s=/font-family\s*:\s*([^;}]+)/.exec(n[1])?.[1],r=/url\(\s*['"]?([^'")\s]+)['"]?\s*\)/.exec(n[1])?.[1];if(!s||!r)continue;let i=s.trim().replace(/^['"]|['"]$/g,""),o=r.startsWith("/")?r:"/"+r.replace(/^\.?\//,"");i&&!fp.has(i.toLowerCase())&&t.push({family:i,file:o})}return t}function un(e){let t=e.trim();if(!t)return!1;for(;;){let n=t;if(t=t.replace(/\bPromise\s*\.\s*(?:resolve|reject)\s*\(([^()]*)\)/g,(s,r)=>`(${r.trim()})`),t=t.replace(/new\s+Error\(([^()]*)\)/g,(s,r)=>`(${r.trim()})`),t===n)break}return!/\b[A-Za-z_$][\w$]*\s*\(/.test(t)&&!/\b[A-Za-z_$][\w$]*\s*\./.test(t)&&!/^[A-Za-z_$][\w$]*$/.test(t)}function bs(e){return/^\([^)]*\)\s*=>/.test(e)||/^function\b/.test(e)?`(${e})()`:e}function $s(e){let t=[];for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$kv\b(?:<[^>]*>)?\s*\(/g)){let s=n.index+n[0].length-1,r=lp(e,s);if(r===null)continue;let i=er(r);if(!i.length)continue;let o=i.length>1&&i[1].trim()||"300";t.push({name:n[1],fn:i[0].trim(),ttl:o})}return t}function oa(e){let t=[],n=0;for(;;){let s=e.indexOf("$effect",n);if(s<0)break;if(/[A-Za-z0-9_$.]/.test(e[s-1]??"")){n=s+7;continue}let r=s+7;for(;r<e.length&&/\s/.test(e[r]);)r++;if(e[r]!=="("){n=s+7;continue}let i=ap(e,r);if(i<0){n=s+7;continue}let o=e.slice(r+1,i).trim();n=i+1,o&&t.push({arg:o,body:Oy(o),call:/^[A-Za-z_$][\w$]*$/.test(o)?o:null})}return t}function Oy(e){let t=e.replace(/^\s*async\s+/,""),n=/^\s*(?:function\s*(?:[A-Za-z_$][\w$]*\s*)?)?\(([^()]*)\)\s*(?::[^=>]*)?(?:=>)?\s*\{([\s\S]*)\}$/.exec(t);return n||(n=/^\s*(?:function\s*)?([A-Za-z_$][\w$]*)\s*(?::[^=>]*)?=>\s*\{([\s\S]*)\}$/.exec(t),n)||(n=/^\s*(?:function\s*[A-Za-z_$][\w$]*\s*)?\(([^()]*)\)\s*(?::[^=>]*)?=>\s*([\s\S]+)$/.exec(t),n)||(n=/^\s*(?:function\s*)?([A-Za-z_$][\w$]*)\s*(?::[^=>]*)?=>\s*([\s\S]+)$/.exec(t),n&&n[2].trim()!==t.replace(/^\s*async\s+/,"").trim())?n[2].trim():null}function gp(e,t){return`${e}: ${t} $effect ${t===1?"body does":"bodies do"} not run on this platform - a field an effect maintains keeps its initial value (a $derived of the same inputs is live)`}var ia,fp,hn=De(()=>{"use strict";jl();gs();ia=/[A-Za-z0-9_$]/;fp=new Set(["serif","sans-serif","sans","monospace","system-ui","ui-sans-serif","ui-serif","ui-monospace","cursive","fantasy","inherit","initial","unset"])});function Ce(e,t="<template>",n){let s=[],i=Po(e,n??"web",s).replace(/<!--[\s\S]*?-->/g,""),o=y=>{let b=new RegExp(`<${y}(\\s[^>]*)?>([\\s\\S]*?)<\\/${y}>`).exec(i);return b?(i=i.slice(0,b.index)+i.slice(b.index+b[0].length),b[2]):null},a=vr(i)??o("script");a!==null&&(i=i.replace(/<script(\s[^>]*)?>[\s\S]*?<\/script>/,""));let c=o("head"),d=[];for(let y=/<style(\s[^>]*)?>([\s\S]*?)<\/style>/.exec(i);y;y=/<style(\s[^>]*)?>([\s\S]*?)<\/style>/.exec(i))d.push(y[2]),i=i.slice(0,y.index)+i.slice(y.index+y[0].length);let u=c;if(u)for(;;){let y=/<style(\s[^>]*)?>([\s\S]*?)<\/style>/.exec(u);if(!y)break;d.push(y[2]),u=u.slice(0,y.index)+u.slice(y.index+y[0].length)}let l=new Set(Bu(a)),p=No(a);if(p)throw new ee("E-STATE",`${t}: ${p} is a $derived value and is written here - a $derived is read-only`,{file:t,hint:`make ${p} a $state, or derive a different name from it`});if(l.size){let y=m=>l.has(m);i=Zs(i,y),a=a===null?null:Zs(a,y)}i=Lo(i,n??"web",s);let f=Ny(i,t,s,n),h=zy(f,s,t),g=a===null?null:pp(dp(a));return{template:i,script:g,style:d.length?d.join(`
|
|
1902
1902
|
`):null,head:u,nodes:h,warnings:s}}function Ny(e,t="<template>",n=[],s){let r=new tc(e,t,n,s),i=r.parseNodes({type:"eof"});return r.term.type!=="eof"&&n.push(`${t}: unexpected ${My(r.term)} at the end of the template`),i}function My(e){return e.type==="elementClose"?`</${e.tag}>`:e.type==="blockClose"?`{/${e.name}}`:e.type==="blockBranch"?`{:${e.head}}`:"the end"}function mp(e){if(e==="")return{kind:"text",text:""};if(!e.includes("{"))return{kind:"text",text:e};let t=[],n=0;for(;n<e.length;){let s=e.indexOf("{",n);if(s<0){n<e.length&&t.push({kind:"text",value:e.slice(n)});break}s>n&&t.push({kind:"text",value:e.slice(n,s)});let r=Ds(e,s);if(!r){t.push({kind:"text",value:e.slice(s)});break}let i=e.slice(s+1,r.contentEnd).trim();i&&t.push({kind:"expr",value:i}),n=r.end}return t.length===1&&t[0].kind==="expr"?{kind:"expr",code:t[0].value}:t.every(s=>s.kind==="text")?{kind:"text",text:e}:{kind:"mixed",parts:t}}function Ds(e,t){if(e[t]!=="{")return null;let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){let i=Ly(e,s);if(i<0)return null;s=i;continue}if(r==="`"){let i=By(e,s);if(i<0)return null;s=i;continue}if(r==="/"&&e[s+1]==="/"){let i=e.indexOf(`
|
|
1903
1903
|
`,s);if(i<0)return null;s=i;continue}if(r==="/"&&e[s+1]==="*"){let i=e.indexOf("*/",s+2);if(i<0)return null;s=i+1;continue}if(r==="{")n++;else if(r==="}"&&(n--,n===0))return{contentEnd:s,end:s+1}}return null}function Ly(e,t){let n=e[t];for(let s=t+1;s<e.length;s++){if(e[s]==="\\"){s++;continue}if(e[s]===n)return s}return-1}function By(e,t){for(let n=t+1;n<e.length;n++){if(e[n]==="\\"){n++;continue}if(e[n]==="`")return n;if(e[n]==="$"&&e[n+1]==="{"){let s=Ds(e,n+1);if(!s)return-1;n=s.end-1}}return-1}function Iy(e){let t=0;for(let n=0;n<e.length-3;n++){let s=e[n];if(s==="("||s==="["||s==="{")t++;else if(s===")"||s==="]"||s==="}")t--;else if(t===0&&/\s/.test(s)&&e.slice(n+1,n+3)==="as"&&/\s/.test(e[n+3]??""))return n+1}return-1}function Wy(e){let t=0;for(let n=0;n<e.length;n++){let s=e[n];if(s==="("||s==="["||s==="{")t++;else if(s===")"||s==="]"||s==="}")t--;else if(s===","&&t===0)return n}return-1}function Dy(e,t){let n=0;for(let s=0;s<t;s++){let r=e[s];r==="("||r==="["||r==="{"?n++:(r===")"||r==="]"||r==="}")&&n--}return n===0}function zy(e,t,n="<template>"){let s=new Map,r=o=>{for(let a of o)a.kind==="snippet"?(s.set(a.name,a),r(a.children)):a.kind==="element"?r(a.children):a.kind==="if"?a.branches.forEach(c=>r(c.children)):a.kind==="each"||a.kind==="block"?(r(a.children),a.fallback&&r(a.fallback)):a.kind==="await"&&(r(a.pending),r(a.then),r(a.catch))};if(r(e),!s.size&&!ws(e))return e;let i=(o,a)=>{let c=[];for(let d of o)if(d.kind!=="snippet"){if(d.kind==="render"){let u=Hy(d.code);if(!u){t.push(`${n}: {@render ${d.code}} is not a call - dropped`);continue}let l=s.get(u.name);if(!l){t.push(`${n}: {@render ${u.name}(...)} names no snippet in this file - dropped`);continue}if(a>16){t.push(`${n}: {#snippet ${u.name}} expands recursively - stopped at depth 16`);continue}let p=l.params.split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean),f=new Map;p.forEach((h,g)=>f.set(h,u.args[g]??"undefined")),c.push(...i(Xn(l.children,f),a+1));continue}if(d.kind==="element"){c.push({...d,children:i(d.children,a)});continue}if(d.kind==="if"){c.push({...d,branches:d.branches.map(u=>({...u,children:i(u.children,a)}))});continue}if(d.kind==="each"){c.push({...d,children:i(d.children,a),fallback:d.fallback?i(d.fallback,a):void 0});continue}if(d.kind==="block"){c.push({...d,children:i(d.children,a),fallback:d.fallback?i(d.fallback,a):void 0});continue}if(d.kind==="await"){c.push({...d,pending:i(d.pending,a),then:i(d.then,a),catch:i(d.catch,a)});continue}if(d.kind==="const"){c.push({...d,code:Se(d.code,new Map)});continue}c.push(d)}return c};return i(e,0)}function ws(e){for(let t of e)if(t.kind==="render"||t.kind==="element"&&ws(t.children)||t.kind==="if"&&t.branches.some(n=>ws(n.children))||t.kind==="each"&&(ws(t.children)||t.fallback&&ws(t.fallback))||t.kind==="block"&&(ws(t.children)||t.fallback&&ws(t.fallback))||t.kind==="await"&&(ws(t.pending)||ws(t.then)||ws(t.catch)))return!0;return!1}function Hy(e){let t=/^\s*([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(e);return t?{name:t[1],args:Vy(t[2])}:null}function Vy(e){let t=[],n=0,s="",r=0;for(let i=0;i<=e.length;i++){let o=e[i];if(s){if(o==="\\"){i++;continue}o===s&&(s="");continue}if(o==='"'||o==="'"||o==="`"){s=o;continue}if(o==="("||o==="["||o==="{"?n++:(o===")"||o==="]"||o==="}")&&n--,o===","&&n===0||i===e.length){let a=e.slice(r,i).trim();t.push(a),r=i+1}}return t}function Se(e,t){if(!t||!t.size)return e;let n="",s=0;for(;s<e.length;){let r=e[s];if(r==='"'||r==="'"||r==="`"){let i=r,o=s+1;for(;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]===i)break}n+=e.slice(s,Math.min(o+1,e.length)),s=o+1;continue}if(/[A-Za-z_$]/.test(r)){let i=s+1;for(;i<e.length&&/[\w$]/.test(e[i]);)i++;let o=e.slice(s,i),c=n.replace(/\s+$/,"").slice(-1)===".";n+=c?o:t.get(o)??o,s=i;continue}n+=r,s++}return n}function Xn(e,t){return e.map(n=>{switch(n.kind){case"expr":return{...n,code:Se(n.code,t)};case"html":return{...n,code:Se(n.code,t)};case"const":return{...n,code:Se(n.code,t)};case"text":return n;case"mixed":return{...n,parts:n.parts.map(s=>s.kind==="expr"?{kind:"expr",value:Se(s.value,t)}:s)};case"element":return{...n,attrs:n.attrs.map(s=>({...s,value:s.value.kind==="expr"?{kind:"expr",code:Se(s.value.code,t)}:s.value.kind==="mixed"?{kind:"mixed",parts:s.value.parts.map(r=>r.kind==="expr"?{kind:"expr",value:Se(r.value,t)}:r)}:s.value})),children:Xn(n.children,t)};case"if":return{...n,branches:n.branches.map(s=>({cond:s.cond?Se(s.cond,t):null,children:Xn(s.children,t)}))};case"each":return{...n,items:Se(n.items,t),key:n.key?Se(n.key,t):void 0,children:Xn(n.children,t),fallback:n.fallback?Xn(n.fallback,t):void 0};case"await":return{...n,expr:Se(n.expr,t),pending:Xn(n.pending,t),then:Xn(n.then,t),catch:Xn(n.catch,t)};case"block":return{...n,children:Xn(n.children,t),fallback:n.fallback?Xn(n.fallback,t):void 0};case"snippet":return n;case"render":return{...n,code:Se(n.code,t)};case"slot":return n}})}function Ft(e){let t={hasDefault:!1,named:[]},n=s=>{for(let r of s){if(r.kind!=="element"){r.kind==="if"?r.branches.forEach(i=>n(i.children)):r.kind==="each"||r.kind==="block"?(n(r.children),r.fallback&&n(r.fallback)):r.kind==="await"&&(n(r.pending),n(r.then),n(r.catch));continue}if(r.tag==="slot"){let i=r.attrs.find(a=>a.name==="name"),o=i&&i.value.kind==="text"?i.value.text:"";!o||o==="default"?t.hasDefault=!0:t.named.some(a=>a.name===o)||t.named.push({name:o,props:r.attrs.filter(a=>a.name!=="name"&&a.value.kind==="expr").map(a=>a.name)})}n(r.children)}};return n(e),t}function Pt(e){let t=[],n=new Map;for(let s of e){if(s.kind!=="element"){t.push(s);continue}let r=s.attrs.find(a=>a.name==="slot"),i=r&&r.value.kind==="text"?r.value.text:"";if(!i){t.push(s);continue}let o=n.get(i)??[];o.push({...s,attrs:s.attrs.filter(a=>a.name!=="slot")}),n.set(i,o)}return{defaultNodes:t,named:n}}function st(e,t){let n=null,s=r=>{for(let i of r){if(n)return;if(i.kind!=="element"){i.kind==="if"?i.branches.forEach(o=>s(o.children)):i.kind==="each"||i.kind==="block"?(s(i.children),i.fallback&&s(i.fallback)):i.kind==="await"&&(s(i.pending),s(i.then),s(i.catch));continue}if(i.tag==="slot"){let o=i.attrs.find(d=>d.name==="name"),a=o&&o.value.kind==="text"?o.value.text:"";if(t==="default"?!a||a==="default":a===t){n=i.children;return}}s(i.children)}};return s(e),n??[]}function Lt(e,t,n){if(!t.length)return e;let s=new Map;for(let r of t)s.set(r,n(r));return Xn(e,s)}function aa(e,t){let n=null,s=r=>{for(let i of r){if(n)return;if(i.kind!=="element"){i.kind==="if"?i.branches.forEach(o=>s(o.children)):i.kind==="each"||i.kind==="block"?(s(i.children),i.fallback&&s(i.fallback)):i.kind==="await"&&(s(i.pending),s(i.then),s(i.catch));continue}if(i.tag==="slot"){let o=i.attrs.find(d=>d.name==="name"),a=o&&o.value.kind==="text"?o.value.text:"";if(t==="default"?!a||a==="default":a===t){n=i;return}}s(i.children)}};return s(e),n}function Jy(e,t){let n=e.indexOf("(",t);if(n<0)return null;let s=0;for(let r=n;r<e.length;r++){let i=e[r];if(i==='"'||i==="'"||i==="`"){let o=i;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"&&r++,r++;continue}if(i==="(")s++;else if(i===")"&&(s--,s===0))return{arg:e.slice(n+1,r),end:r+1}}return null}function Bt(e){let t=e.trim();for(t=t.replace(/new\s+Error\(([^()]*)\)/g,(n,s)=>`(${s.trim()})`);;){let n=!1,s=/\bPromise\s*\.\s*(resolve|reject)\s*\(/g,r;for(;r=s.exec(t);){let i=Jy(t,r.index+r[0].length-1);if(!i)continue;let o=r[1]==="resolve"?`(${i.arg.trim()})`:`roseThrow(${i.arg.trim()})`;t=t.slice(0,r.index)+o+t.slice(i.end),n=!0,s.lastIndex=r.index+o.length}if(!n)break}return t}function Ct(e,t){if(!t)return e;let n=r=>r.replace(new RegExp(`\\b${t}\\s*\\.\\s*message\\b`,"g"),t),s=r=>r.map(i=>{switch(i.kind){case"expr":return{...i,code:n(i.code)};case"mixed":return{...i,parts:i.parts.map(o=>o.kind==="expr"?{kind:"expr",value:n(o.value)}:o)};case"html":return{...i,code:n(i.code)};case"const":return{...i,code:n(i.code)};case"element":return{...i,attrs:i.attrs.map(o=>o.value.kind==="expr"?{...o,value:{kind:"expr",code:n(o.value.code)}}:o.value.kind==="mixed"?{...o,value:{kind:"mixed",parts:o.value.parts.map(a=>a.kind==="expr"?{kind:"expr",value:n(a.value)}:a)}}:o),children:s(i.children)};case"if":return{...i,branches:i.branches.map(o=>({...o,cond:o.cond?n(o.cond):null,children:s(o.children)}))};case"each":return{...i,items:n(i.items),children:s(i.children),fallback:i.fallback?s(i.fallback):void 0};case"await":return{...i,expr:n(i.expr),pending:s(i.pending),then:s(i.then),catch:s(i.catch)};case"block":return{...i,children:s(i.children),fallback:i.fallback?s(i.fallback):void 0};default:return i}});return s(e)}function _t(e,t){let n=new Map;if(!e)return n;for(let s of e.matchAll(/(?:^|\n)[ \t]*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)){let r=s[1],i=s[2].trim();if(!(t.has(r)||n.has(r))){if(/\$query\s*\(/.test(i)){n.set(r,i);continue}/^(['"`]|-?\d|true|false|null|\[|\{)/.test(i)&&n.set(r,i)}}return n}function Je(e,t){return t.size?Xn(e,t):e}function ze(e){return"on"+e.charAt(0).toUpperCase()+e.slice(1)+"Change"}function It(e){let t=new Map;for(let n of e.attrs){let s=/^bind:(value|checked|group|open)$/.exec(n.name);!s||n.value.kind!=="expr"||t.set(s[1],n.value.code.trim())}return t}function gn(e,t){let n=new Set(t),s=[],r=i=>{for(let o of i){if(o.kind!=="element"){o.kind==="if"?o.branches.forEach(a=>r(a.children)):o.kind==="each"||o.kind==="block"?(r(o.children),o.fallback&&r(o.fallback)):o.kind==="await"&&(r(o.pending),r(o.then),r(o.catch));continue}if(o.tag==="input"||o.tag==="textarea"||o.tag==="select")for(let a of o.attrs){if(!(a.name==="value"||a.name.startsWith("bind:"))||a.value.kind!=="expr")continue;let d=a.value.code.trim();n.has(d)&&!s.includes(d)&&s.push(d)}r(o.children)}};return r(e),s}var Fy,Py,tc,vs=De(()=>{"use strict";kn();Mo();Oo();hn();Cl();Fy=new Set(["if","each","await","boundary","key","island","defer","snippet","ifdef","ifndef"]),Py=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),tc=class{constructor(t,n,s,r){this.src=t;this.file=n;this.warnings=s;this.platform=r}i=0;term={type:"eof"};parseNodes(t){let n=[];for(;this.i<this.src.length;){let s=this.i;if(this.src.startsWith("{:",s)){let o=Ds(this.src,s);if(!o)break;let a=this.src.slice(s+2,o.contentEnd).trim();return this.i=o.end,this.term={type:"blockBranch",name:a.split(/\s+/)[0]||"",head:a},n}if(this.src.startsWith("{/",s)){let o=Ds(this.src,s);if(!o)break;let a=this.src.slice(s+2,o.contentEnd).trim();return this.i=o.end,this.term={type:"blockClose",name:a},n}if(this.src.startsWith("{#",s)){let o=this.parseBlock();o&&n.push(o);continue}if(this.src.startsWith("{@",s)){let o=this.parseAt();o&&n.push(o);continue}if(this.src.startsWith("<!--",s)){let o=this.src.indexOf("-->",s+4);this.i=o<0?this.src.length:o+3;continue}if(this.src.startsWith("</",s)){let o=/^<\/\s*([A-Za-z][\w:.-]*)\s*>/.exec(this.src.slice(s));if(!o){this.warnings.push(`${this.file}: malformed closing tag at ${s}`),this.i=s+2;continue}return this.i=s+o[0].length,this.term={type:"elementClose",tag:o[1]},n}if(this.src[s]==="<"&&/[A-Za-z]/.test(this.src[s+1]??"")){let o=this.parseElement();o&&(o.kind==="element"&&o.tag.toLowerCase()==="template"&&o.attrs.length===0?n.push(...o.children):n.push(o));continue}if(this.src[s]==="{"){let o=Ds(this.src,s);if(!o){this.warnings.push(`${this.file}: unbalanced "{" at ${s}`);break}let a=this.src.slice(s+1,o.contentEnd).trim();this.i=o.end,a&&n.push({kind:"expr",code:a});continue}let r=this.src.length;for(let o=s+1;o<this.src.length;o++){let a=this.src[o];if(a==="<"&&/[A-Za-z/!]/.test(this.src[o+1]??"")){r=o;break}if(a==="{"){r=o;break}}let i=this.src.slice(s,r);i&&n.push({kind:"text",value:i}),this.i=r}return this.term={type:"eof"},n}parseElement(){let t=/^<([A-Za-z][\w:.-]*)/.exec(this.src.slice(this.i));if(!t)return this.i++,null;let n=t[1],s=this.i+t[0].length,r=[],i=!1;for(;;){for(;/\s/.test(this.src[s]??"");)s++;if(this.src.startsWith("/>",s)){i=!0,s+=2;break}if(this.src[s]===">"){s++;break}if(s>=this.src.length){this.warnings.push(`${this.file}: unterminated tag <${n}>`);break}if(this.src[s]==="{"){let u=Ds(this.src,s);if(!u)break;this.warnings.push(`${this.file}: attribute spread is not supported by the exporter - <${n}${this.src.slice(s,u.end)}>`),s=u.end;continue}let a=/^[^\s=/>]+/.exec(this.src.slice(s));if(!a){s++;continue}let c=a[0];for(s+=c.length;/\s/.test(this.src[s]??"");)s++;if(this.src[s]!=="="){r.push({name:c,value:{kind:"none"}});continue}for(s++;/\s/.test(this.src[s]??"");)s++;let d=this.src[s];if(d==='"'||d==="'"){let u=this.src.indexOf(d,s+1),l=u<0?this.src.slice(s+1):this.src.slice(s+1,u);r.push({name:c,value:mp(l)}),s=u<0?this.src.length:u+1}else if(d==="{"){let u=Ds(this.src,s);if(!u)break;let l=this.src.slice(s+1,u.contentEnd).trim();r.push({name:c,value:{kind:"expr",code:l}}),s=u.end}else{let u=/^[^\s>]+/.exec(this.src.slice(s)),l=u?u[0]:"";r.push({name:c,value:mp(l)}),s+=l.length}}if(this.i=s,i||Py.has(n.toLowerCase()))return{kind:"element",tag:n,attrs:r,children:[],selfClosing:!0};let o=this.parseNodes({type:"elementClose",tag:n});return this.term.type==="elementClose"&&(this.term={type:"eof"}),{kind:"element",tag:n,attrs:r,children:o,selfClosing:!1}}parseBlock(){let t=Ds(this.src,this.i);if(!t)return null;let n=this.src.slice(this.i+2,t.contentEnd).trim();this.i=t.end;let s=(n.split(/\s+/)[0]||"").toLowerCase(),r=n.slice(s.length).trim();if(!Fy.has(s))return this.warnings.push(`${this.file}: unknown block {#${n}} - skipped`),this.skipToBlockClose(s),null;switch(s){case"if":return this.parseIf(r);case"each":return this.parseEach(r);case"await":return this.parseAwait(r);case"boundary":case"key":case"island":case"defer":{let i=this.parseNodes({type:"blockClose",name:s}),o;return this.term.type==="blockBranch"&&(o=this.parseNodes({type:"blockClose",name:s})),this.term.type==="blockClose"&&(this.term={type:"eof"}),{kind:"block",name:s,head:r,children:i,fallback:o}}case"snippet":{let i=/^(\w+)\s*(\(([\s\S]*)\))?$/.exec(r),o=this.parseNodes({type:"blockClose",name:s});return this.term.type==="blockClose"&&(this.term={type:"eof"}),i?{kind:"snippet",name:i[1],params:i[3]??"",children:o}:(this.warnings.push(`${this.file}: malformed {#snippet ${r}} - skipped`),null)}}return null}skipToBlockClose(t){let n=new RegExp(`\\{/${t}\\}`,"g");n.lastIndex=this.i;let s=n.exec(this.src);this.i=s?s.index+s[0].length:this.src.length}parseIf(t){let n=[{cond:t.trim(),children:[]}],s=n[0];for(;s.children=this.parseNodes({type:"blockClose",name:"if"}),this.term.type==="blockBranch";){let r=this.term.head.trim();if(/^else\s+if\b/.test(r)){s={cond:r.replace(/^else\s+if\s+/,""),children:[]},n.push(s);continue}if(/^else\b/.test(r)){s={cond:null,children:[]},n.push(s);continue}this.warnings.push(`${this.file}: unexpected {:${r}} inside {#if} - ignored`);break}return this.term.type==="blockClose"&&(this.term={type:"eof"}),{kind:"if",branches:n}}parseEach(t){let n=Iy(t);if(n<0)return this.warnings.push(`${this.file}: {#each ${t}} has no "as" binding - skipped`),this.skipToBlockClose("each"),{kind:"each",items:t,binding:"_item",children:[]};let s=t.slice(0,n).trim(),r=t.slice(n+2).trim(),i,o=/\(([\s\S]*)\)\s*$/.exec(r);o&&Dy(r,o.index)&&(i=o[1].trim(),r=r.slice(0,o.index).trim());let a=r,c,d=Wy(r);d>=0&&(a=r.slice(0,d).trim(),c=r.slice(d+1).trim()||void 0);let u=this.parseNodes({type:"blockClose",name:"each"}),l;return this.term.type==="blockBranch"&&(l=this.parseNodes({type:"blockClose",name:"each"})),this.term.type==="blockClose"&&(this.term={type:"eof"}),{kind:"each",items:s,binding:a,index:c,key:i,children:u,fallback:l}}parseAwait(t){let n={kind:"await",expr:t.trim(),pending:[],then:[],catch:[]},s="pending";for(;;){let r=this.parseNodes({type:"blockClose",name:"await"});if(s==="pending"?n.pending=r:s==="then"?n.then=r:n.catch=r,this.term.type!=="blockBranch")break;let i=this.term.head.trim(),o=/^then\b\s*(.*)$/.exec(i),a=/^catch\b\s*(.*)$/.exec(i);if(o){s="then",o[1]&&(n.thenName=o[1]);continue}if(a){s="catch",a[1]&&(n.catchName=a[1]);continue}this.warnings.push(`${this.file}: unexpected {:${i}} inside {#await} - ignored`);break}return this.term.type==="blockClose"&&(this.term={type:"eof"}),n}parseAt(){let t=Ds(this.src,this.i);if(!t)return null;let n=this.src.slice(this.i+2,t.contentEnd).trim();if(this.i=t.end,/^html\b/.test(n))return{kind:"html",code:n.replace(/^html\s*/,"")};if(/^render\b/.test(n))return{kind:"render",code:n.replace(/^render\s*/,"")};if(/^const\b/.test(n)){let s=/^const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]*)$/.exec(n);return s?{kind:"const",name:s[1],code:s[2]}:(this.warnings.push(`${this.file}: malformed {@const ${n}} - skipped`),null)}return null}}});function Uy(e,t=[]){let n=Dn(e,t);return n||(/\bnew\s+[A-Za-z_$]/.test(e)?"a `new` expression":/\bFormData\s*\(/.test(e)?"FormData":/\bdocument\s*\.|\bwindow\s*\.|\blocalStorage\b/.test(e)?"the DOM":/\?\?=?/.test(e)?"nullish coalescing":/\?\./.test(e)?"optional chaining":/\.\.\./.test(e)?"spread":/`/.test(e)?"a template literal":/\bawait\s+/.test(e)?"await":/\bfor\s*\(|\bwhile\s*\(|\bswitch\s*\(/.test(e)?"a loop or switch":/\b(?:const|let|var)\s+[A-Za-z_$]/.test(e)?"a variable declaration":null)}function jt(e,t,n){let s=e.trim();if(!s)return{params:[],stmts:[],reason:"an empty handler",ref:null};if(/^[A-Za-z_$][\w$]*$/.test(s)&&!n.has(s))return{params:[],stmts:[],reason:null,ref:s};let r=[],i=s,o=qy(s);if(o&&(r=Gy(o.params),i=o.body.trim()),i.startsWith("{")){let d=la(i,0);if(d===i.length-1)i=i.slice(1,d).trim();else return{params:r,stmts:[],reason:"an unbalanced handler body",ref:null}}if(!i)return{params:r,stmts:[],reason:"an empty handler body",ref:null};let a=t.refuses?t.refuses(i,r):Uy(i,r);if(a)return{params:r,stmts:[],reason:a,ref:null};let c=[];for(let d of Qy(i)){let u=Ky(d,t,n);u.trim()&&c.push(u.trim())}return c.length?{params:r,stmts:c,reason:null,ref:null}:{params:r,stmts:[],reason:"no statements in the handler body",ref:null}}function sr(e,t="__h"){let n=e.size,s=`${t}${n}`;for(;e.has(s);)s=`${t}${++n}`;return e.add(s),s}function qy(e){let t=/^([A-Za-z_$][\w$]*)\s*=>\s*([\s\S]*)$/.exec(e);if(t)return{params:t[1],body:t[2]};if(!e.startsWith("("))return null;let n=la(e,0);if(n<0)return null;let s=e.slice(n+1);return/^\s*=>\s*/.test(s)?{params:e.slice(1,n),body:s.replace(/^\s*=>\s*/,"")}:null}function Gy(e){let t=[];for(let n of yp(e,",")){let s=n.trim();if(!s)continue;let r=/^([A-Za-z_$][\w$]*)/.exec(s.replace(/^[{[]|[\]}]$/g,""));r&&t.push(r[1])}return t}function Qy(e){let t=[],n=0,s=0,r="";for(let i=0;i<e.length;i++){let o=e[i];if(r){o==="\\"?i++:o===r&&(r="");continue}if(o==='"'||o==="'"||o==="`"){r=o;continue}o==="("||o==="["||o==="{"?s++:o===")"||o==="]"||o==="}"?s--:s===0&&(o===";"||o===`
|
|
1904
|
-
`)&&(t.push(e.slice(n,i)),n=i+1)}return t.push(e.slice(n)),t.map(i=>i.trim()).filter(Boolean)}function yp(e,t){let n=[],s=0,r=0,i="";for(let o=0;o<e.length;o++){let a=e[o];if(i){a==="\\"?o++:a===i&&(i="");continue}if(a==='"'||a==="'"||a==="`"){i=a;continue}a==="("||a==="["||a==="{"?r++:a===")"||a==="]"||a==="}"?r--:r===0&&a===t&&(n.push(e.slice(s,o)),s=o+1)}return n.push(e.slice(s)),n}function la(e,t){let n=0,s="";for(let r=t;r<e.length;r++){let i=e[r];if(s){i==="\\"?r++:i===s&&(s="");continue}if(i==='"'||i==="'"||i==="`"){s=i;continue}if(i==="("||i==="["||i==="{")n++;else if((i===")"||i==="]"||i==="}")&&(n--,n===0))return r}return-1}function Ky(e,t,n){let s=e;for(let r=0;r<64;r++){let i=Zy(s,n);if(i!==s){s=i;continue}let o=Yy(s,t);if(o!==s){s=o;continue}break}return t.expr(s)}function Zy(e,t){let n=/\$(setState|action)\s*\(/.exec(e);if(n&&n.index!==void 0){let i=n.index+n[0].length-1,o=la(e,i);if(o>0){let a=yp(e.slice(i+1,o),","),c=Xy(a[0]??"");if(c!==null){let d=n[1]==="setState"?"S":"A",u=a.slice(1).join(",").trim();return e.slice(0,n.index)+nc(d,c,u)+e.slice(o+1)}}}let s=/\brefresh\s*\(\s*\)/.exec(e);if(s)return e.slice(0,s.index)+nc("R","","")+e.slice(s.index+s[0].length);let r=/\b([A-Za-z_$][\w$]*)\s*\.\s*(set|update)\s*\(/.exec(e);if(r&&t.has(r[1])){let i=r.index+r[0].length-1,o=la(e,i);if(o>0){let a=e.slice(i+1,o).trim(),c=r[2]==="set"?"S":"U";return e.slice(0,r.index)+nc(c,r[1],a)+e.slice(o+1)}}return e}function nc(e,t,n){return`${Ss}${e}${Ss}${JSON.stringify(t)}${Ss}${n}${Ss}`}function Dn(e,t){for(let n of t)if(new RegExp(`\\b${n}\\b`).test(e))return`the event object (${n})`;return null}function Xy(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2]:/^[A-Za-z_$][\w$]*$/.test(t)?t:null}function Yy(e,t){let n=new RegExp(`${Ss}([SUAR])${Ss}("(?:[^"\\\\]|\\\\.)*"|[^${Ss}]+)${Ss}([^${Ss}]*)${Ss}`,"g");return e.replace(n,(s,r,i,o)=>{let a=i;try{a=JSON.parse(i)}catch{}switch(r){case"S":return t.set(String(a),t.expr(o));case"U":return t.update?t.update(String(a),t.expr(o)):`/*
|
|
1904
|
+
`)&&(t.push(e.slice(n,i)),n=i+1)}return t.push(e.slice(n)),t.map(i=>i.trim()).filter(Boolean)}function yp(e,t){let n=[],s=0,r=0,i="";for(let o=0;o<e.length;o++){let a=e[o];if(i){a==="\\"?o++:a===i&&(i="");continue}if(a==='"'||a==="'"||a==="`"){i=a;continue}a==="("||a==="["||a==="{"?r++:a===")"||a==="]"||a==="}"?r--:r===0&&a===t&&(n.push(e.slice(s,o)),s=o+1)}return n.push(e.slice(s)),n}function la(e,t){let n=0,s="";for(let r=t;r<e.length;r++){let i=e[r];if(s){i==="\\"?r++:i===s&&(s="");continue}if(i==='"'||i==="'"||i==="`"){s=i;continue}if(i==="("||i==="["||i==="{")n++;else if((i===")"||i==="]"||i==="}")&&(n--,n===0))return r}return-1}function Ky(e,t,n){let s=e;for(let r=0;r<64;r++){let i=Zy(s,n);if(i!==s){s=i;continue}let o=Yy(s,t);if(o!==s){s=o;continue}break}return t.expr(s)}function Zy(e,t){let n=/\$(setState|action)\s*\(/.exec(e);if(n&&n.index!==void 0){let i=n.index+n[0].length-1,o=la(e,i);if(o>0){let a=yp(e.slice(i+1,o),","),c=Xy(a[0]??"");if(c!==null){let d=n[1]==="setState"?"S":"A",u=a.slice(1).join(",").trim();return e.slice(0,n.index)+nc(d,c,u)+e.slice(o+1)}}}let s=/\brefresh\s*\(\s*\)/.exec(e);if(s)return e.slice(0,s.index)+nc("R","","")+e.slice(s.index+s[0].length);let r=/\b([A-Za-z_$][\w$]*)\s*\.\s*(set|update)\s*\(/.exec(e);if(r&&t.has(r[1])){let i=r.index+r[0].length-1,o=la(e,i);if(o>0){let a=e.slice(i+1,o).trim(),c=r[2]==="set"?"S":"U";return e.slice(0,r.index)+nc(c,r[1],a)+e.slice(o+1)}}return e}function nc(e,t,n){return`${Ss}${e}${Ss}${JSON.stringify(t)}${Ss}${n}${Ss}`}function Dn(e,t){for(let n of t)if(new RegExp(`\\b${n}\\b`).test(e))return`the event object (${n})`;return null}function Xy(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2]:/^[A-Za-z_$][\w$]*$/.test(t)?t:null}function Yy(e,t){let n=new RegExp(`${Ss}([SUAR])${Ss}("(?:[^"\\\\]|\\\\.)*"|[^${Ss}]+)${Ss}([^${Ss}]*)${Ss}`,"g");return e.replace(n,(s,r,i,o)=>{let a=i;try{a=JSON.parse(i)}catch{}switch(r){case"S":return t.set(String(a),t.expr(o));case"U":return t.update?t.update(String(a),t.expr(o)):`/* rosefc: ${a}.update() has no equivalent here */`;case"A":return t.action(String(a),t.expr(o));default:return t.refresh()}})}var Ss,_s=De(()=>{"use strict";Ss=""});function eb(e,t,n){switch(e.op){case"move":return{op:"move",x:e.x+t,y:e.y+n};case"line":return{op:"line",x:e.x+t,y:e.y+n};case"curve":return{op:"curve",c1x:e.c1x+t,c1y:e.c1y+n,c2x:e.c2x+t,c2y:e.c2y+n,x:e.x+t,y:e.y+n};case"close":return e}}function Wt(e){if(!/<svg[\s>]/.test(e))return{shape:null,reason:"not an SVG file"};for(let[h,g]of[[/<text[\s>]/,"a <text> element"],[/<mask[\s>]/,"a mask"],[/<filter[\s>]/,"a filter"],[/<image[\s>]/,"an embedded image"],[/<svg[^>]*\stransform=/,"a transformed <svg>"],[/\bstroke(?:-width)?=/,"a stroke"]])if(h.test(e))return{shape:null,reason:g};let t=/viewBox\s*=\s*"([^"]*)"/.exec(e);if(!t)return{shape:null,reason:"no viewBox"};let n=t[1].trim().split(/[\s,]+/).map(Number);if(n.length!==4||n.some(h=>!Number.isFinite(h)))return{shape:null,reason:"an unreadable viewBox"};let s=n[2]-n[0],r=n[3]-n[1];if(!(s>0)||!(r>0))return{shape:null,reason:"a degenerate viewBox"};let i=new Map;for(let h of e.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g))for(let g of h[1].matchAll(/\.([A-Za-z_][\w-]*)\s*\{([^}]*)\}/g)){let y=/fill\s*:\s*([^;}]+)/.exec(g[2]);y&&i.set(g[1],sc(y[1].trim()))}let o=new Map,a=/<(linear|radial)Gradient\b([^>]*)>([\s\S]*?)<\/\1Gradient>/g;for(let h of e.matchAll(a)){let g=/\bid\s*=\s*"([^"]*)"/.exec(h[2])?.[1];if(!g)continue;let y=h[2],m=[];for(let $ of h[3].matchAll(/<stop\b([^>]*)\/?>/g)){let w=Number(/\boffset\s*=\s*"([^"]*)"/.exec($[1])?.[1]??/stop-offset\s*:\s*([\d.]+)/.exec($[1])?.[1]??0),v=/stop-color\s*=\s*"([^"]*)"/.exec($[1])?.[1]??/stop-color\s*:\s*([^;}]+)/.exec($[1])?.[1];v&&m.push({offset:Number.isFinite(w)?w:0,color:sc(v)})}if(!m.length)continue;let b=$=>{let w=$.exec(y),v=w?Number(w[1]):NaN;return Number.isFinite(v)?v:0};if(h[1]==="radial"){let $=b(/cx\s*=\s*"([^"]*)"/),w=b(/cy\s*=\s*"([^"]*)"/),v=b(/r\s*=\s*"([^"]*)"/);o.set(g,{type:"radial",x1:$,y1:w,x2:$,y2:w,r:v||1,stops:m})}else{let $=b(/x1\s*=\s*"([^"]*)"/),w=b(/y1\s*=\s*"([^"]*)"/),v=b(/x2\s*=\s*"([^"]*)"/),_=b(/y2\s*=\s*"([^"]*)"/);o.set(g,{type:"linear",x1:$,y1:w,x2:v,y2:_,r:0,stops:m})}}let c=h=>{if(h==="none")return null;let g=/url\(\s*#([^)]+)\s*\)/.exec(h);if(g){let y=o.get(g[1]);if(y)return{fill:y.stops[0].color,gradient:y}}return{fill:sc(h)}},d=new Map,u=h=>{let g=/\bclass\s*=\s*"([^"]*)"/.exec(h)?.[1]??"";for(let m of g.split(/\s+/))if(m&&i.has(m))return{fill:i.get(m)};let y=/\bfill\s*=\s*"([^"]*)"/.exec(h)?.[1];return y?c(y):null},l=h=>/\bd\s*=\s*"([^"]*)"/.exec(h)?.[1]??/\bd\s*=\s*'([^']*)'/.exec(h)?.[1]??null,p=e;for(let h of e.matchAll(/<defs[^>]*>([\s\S]*?)<\/defs>/g)){for(let g of h[1].matchAll(/<path\b([^>]*)\/?>/g)){let y=/\bid\s*=\s*"([^"]*)"/.exec(g[1])?.[1],m=l(g[1]);if(y&&m&&m.trim()){let b=bp(m);if(b){let $=u(g[1]);d.set(y,{ops:b,fill:$?.fill??"#000000",gradient:$?.gradient})}}}p=p.replace(h[0],"")}let f=[];for(let h of p.matchAll(/<path\b([^>]*)\/?>/g)){let g=h[1],y=l(g);if(!y||!y.trim())continue;let m=bp(y);if(!m)return{shape:null,reason:`a path with an unreadable "d" (${y.slice(0,24)}...)`};if(m.length){let b=u(g);f.push({fill:b?.fill??"#000000",gradient:b?.gradient,ops:m})}}for(let h of p.matchAll(/<use\b([^>]*)\/?>/g)){let g=h[1],y=/\bhref\s*=\s*"#?([^"]*)"/.exec(g)?.[1]??/\bhref\s*=\s*'#?([^']*)'/.exec(g)?.[1],m=y?d.get(y):void 0;if(!m)continue;let b=Number(/\bx\s*=\s*"([^"]*)"/.exec(g)?.[1]??0)||0,$=Number(/\by\s*=\s*"([^"]*)"/.exec(g)?.[1]??0)||0,w=b||$?m.ops.map(C=>eb(C,b,$)):m.ops,v=/\bfill\s*=\s*"([^"]*)"/.exec(g)?.[1],_=v?c(v):null,k=_?.fill??m.fill,S=_?.gradient??m.gradient;w.length&&f.push({fill:k,gradient:S,ops:w})}return f.length?{shape:{viewBox:[n[0],n[1],n[2],n[3]],subPaths:f},reason:null}:{shape:null,reason:"no drawable <path> elements"}}function sc(e){let t=e.trim().toLowerCase();if(/^#[0-9a-f]{6}$/.test(t))return t;if(/^#[0-9a-f]{3}$/.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`;let n=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(t);return n?`#${n.slice(1).map(r=>Number(r).toString(16).padStart(2,"0")).join("")}`:{black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",gray:"#808080",grey:"#808080"}[t]??"#000000"}function bp(e){let t=tb(e);if(!t)return null;let n=[],s=0,r=0,i=0,o=0,a=0,c=0,d=!1,u="",l=0,p=()=>{for(;l<t.length&&t[l]===" ";)l++;if(l>=t.length)return null;let f=Number(t[l]);return Number.isFinite(f)?(l++,f):null};for(;l<t.length;){for(;l<t.length&&t[l]===" ";)l++;if(l>=t.length)break;let f=t[l];if(/[A-Za-z]/.test(f))l++,u=f;else{if(!u)return null;f=u.toUpperCase()==="M"?u==="M"?"L":"l":u}let h=f===f.toLowerCase();switch(f.toUpperCase()){case"M":{let g=p(),y=p();if(g===null||y===null)return null;s=h?s+g:g,r=h?r+y:y,i=s,o=r,n.push({op:"move",x:s,y:r}),d=!1;break}case"L":{let g=p(),y=p();if(g===null||y===null)return null;s=h?s+g:g,r=h?r+y:y,n.push({op:"line",x:s,y:r}),d=!1;break}case"H":{let g=p();if(g===null)return null;s=h?s+g:g,n.push({op:"line",x:s,y:r}),d=!1;break}case"V":{let g=p();if(g===null)return null;r=h?r+g:g,n.push({op:"line",x:s,y:r}),d=!1;break}case"C":{let g=p(),y=p(),m=p(),b=p(),$=p(),w=p();if([g,y,m,b,$,w].some(C=>C===null))return null;let v=h?s+g:g,_=h?r+y:y,k=h?s+m:m,S=h?r+b:b;s=h?s+$:$,r=h?r+w:w,n.push({op:"curve",c1x:v,c1y:_,c2x:k,c2y:S,x:s,y:r}),a=k,c=S,d=!0;break}case"S":{let g=p(),y=p(),m=p(),b=p();if([g,y,m,b].some(k=>k===null))return null;let $=d?2*s-a:s,w=d?2*r-c:r,v=h?s+g:g,_=h?r+y:y;s=h?s+m:m,r=h?r+b:b,n.push({op:"curve",c1x:$,c1y:w,c2x:v,c2y:_,x:s,y:r}),a=v,c=_,d=!0;break}case"Q":{let g=p(),y=p(),m=p(),b=p();if([g,y,m,b].some(v=>v===null))return null;let $=h?s+g:g,w=h?r+y:y;s=h?s+m:m,r=h?r+b:b,n.push({op:"curve",c1x:s+2/3*($-s),c1y:r+2/3*(w-r),c2x:$+2/3*(s-$),c2y:w+2/3*(r-w),x:s,y:r}),a=$,c=w,d=!0;break}case"T":{let g=p(),y=p();if(g===null||y===null)return null;let m=d?2*s-a:s,b=d?2*r-c:r;s=h?s+g:g,r=h?r+y:y,n.push({op:"curve",c1x:s+2/3*(m-s),c1y:r+2/3*(b-r),c2x:m+2/3*(s-m),c2y:b+2/3*(r-b),x:s,y:r}),a=m,c=b,d=!0;break}case"Z":{s=i,r=o,n.push({op:"close"}),d=!1;break}default:return null}}return n.length?n:null}function tb(e){let t=[],n=0;for(;n<e.length;){let s=e[n];if(s===" "||s===","||s===`
|
|
1905
1905
|
`||s===" "||s==="\r"){t.length&&t[t.length-1]!==" "&&t.push(" "),n++;continue}if(/[A-Za-z]/.test(s)){t.push(s),n++;continue}let r=n;(e[r]==="+"||e[r]==="-")&&r++;let i=0;for(;r<e.length&&(/[0-9]/.test(e[r])||e[r]==="."&&i===0&&++i);)r++;if(r<e.length&&(e[r]==="e"||e[r]==="E")){let o=r+1;if((e[o]==="+"||e[o]==="-")&&o++,o<e.length&&/[0-9]/.test(e[o]))for(r=o;r<e.length&&/[0-9]/.test(e[r]);)r++}if(r===n||r===n+1&&(e[n]==="+"||e[n]==="-"))return null;t.push(e.slice(n,r)),n=r}return t}function Rr(e,t=2){let n=s=>{let r=Number(s.toFixed(t));return String(r===0?0:r)};return e.map(s=>{switch(s.op){case"move":return`M${n(s.x)},${n(s.y)}`;case"line":return`L${n(s.x)},${n(s.y)}`;case"curve":return`C${n(s.c1x)},${n(s.c1y)} ${n(s.c2x)},${n(s.c2y)} ${n(s.x)},${n(s.y)}`;case"close":return"Z"}}).join(" ")}function nb(e){return`#ff${e.slice(1)}`}function $p(e){return`0xff${e.slice(1).toUpperCase()}`}function wp(e){let t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,s=parseInt(e.slice(5,7),16)/255,r=i=>i.toFixed(4).replace(/0+$/,"").replace(/\.$/,".0");return`Color(red: ${r(t)}, green: ${r(n)}, blue: ${r(s)})`}function vp(e){return`#FF${e.slice(1).toUpperCase()}`}function Sp(e){let t=e.subPaths.map(n=>` <path
|
|
1906
1906
|
android:fillColor="${nb(n.fill)}"
|
|
1907
1907
|
android:pathData="${Rr(n.ops)}"/>`).join(`
|
|
@@ -1913,32 +1913,32 @@ ${s.join(`
|
|
|
1913
1913
|
android:viewportHeight="${e.viewBox[3]}">
|
|
1914
1914
|
${t}
|
|
1915
1915
|
</vector>
|
|
1916
|
-
`}var xs=De(()=>{"use strict"});function sb(e){let t=[],n=0,s=null,r="";for(let i=0;i<e.length;i++){let o=e[i];if(s){r+=o,o===s&&e[i-1]!=="\\"&&(s=null);continue}if(o==='"'||o==="'"||o==="`"){s=o,r+=o;continue}if(o==="("||o==="["||o==="{"){n++,r+=o;continue}if(o===")"||o==="]"||o==="}"){n--,r+=o;continue}if(o===","&&n===0){t.push(r),r="";continue}r+=o}return t.push(r),t.map(i=>i.trim()).filter(Boolean)}function rb(e){let t=0,n=null;for(let s=0;s<e.length;s++){let r=e[s];if(n){r===n&&e[s-1]!=="\\"&&(n=null);continue}if(r==='"'||r==="'"||r==="`"){n=r;continue}if(r==="("||r==="["||r==="{")t++;else if(r===")"||r==="]"||r==="}")t--;else if(r===":"&&t===0)return s}return-1}function Ki(e){let t=(e??"").trim();if(t.length<2||t[0]!=="{"||t[t.length-1]!=="}")return null;let n=t.slice(1,-1).trim(),s=[];if(!n)return s;for(let r of sb(n)){if(r.startsWith("...")||r.startsWith("["))return null;let i=rb(r);if(i<0){if(!/^[A-Za-z_$][\w$]*$/.test(r))return null;s.push({key:r,value:r});continue}let o=r.slice(0,i).trim(),a=/^(['"])([\s\S]*)\1$/.exec(o),c=a?a[2]:o;if(!/^[A-Za-z_$][\w$-]*$/.test(c))return null;let d=r.slice(i+1).trim();if(!d)return null;s.push({key:c,value:d})}return s}function ac(e){let t=e.trim();if(t==="true")return!0;if(t==="false"||t==="null"||t==="undefined")return!1;if(/^-?(\d+\.?\d*|\.\d+)$/.test(t))return Number(t)!==0;let n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2].length>0:null}function lc(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2]:/^-?(\d+\.?\d*|\.\d+)(px|rem|em|%|vh|vw|deg)?$/.test(t)?t:t==="null"||t==="undefined"||t==="false"?"":null}function Qi(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function ib(e){let t=Ki(e);if(!t)return{statics:[],dynamic:[e]};let n=[],s=[];for(let r of t){let i=ac(r.value);if(i===!0)n.push(r.key);else{if(i===!1)continue;s.push(`(${r.value}) ? '${r.key}' : ''`)}}return{statics:n,dynamic:s}}function zs(e){let t=e.trim().toLowerCase();if(!t||t==="currentcolor"||t==="inherit"||t==="initial"||t==="unset"||t==="none"||t.startsWith("var("))return null;let n=ob[t];if(n)return n;let s=/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);if(s){let o=s[1];return o.length===3||o.length===4?"#"+o.split("").map(c=>c+c).join("").toLowerCase():"#"+o.toLowerCase()}let r=/^rgba?\(([^)]+)\)$/.exec(t);if(r){let o=r[1].split(/[,/\s]+/).filter(Boolean);if(o.length<3)return null;let a=p=>p.endsWith("%")?Math.round(Number(p.slice(0,-1))/100*255):Math.round(Number(p)),c=a(o[0]),d=a(o[1]),u=a(o[2]);if(![c,d,u].every(p=>Number.isFinite(p)))return null;let l=p=>Math.max(0,Math.min(255,p)).toString(16).padStart(2,"0");if(o.length>=4&&o[3]!==void 0){let p=o[3],f=p.endsWith("%")?Number(p.slice(0,-1))/100:Number(p);return Number.isFinite(f)?`#${l(c)}${l(d)}${l(u)}${l(Math.round(Math.max(0,Math.min(1,f))*255))}`:`#${l(c)}${l(d)}${l(u)}`}return`#${l(c)}${l(d)}${l(u)}`}let i=/^hsla?\(([^)]+)\)$/.exec(t);if(i){let o=i[1].split(/[,/\s]+/).filter(Boolean);if(o.length<3)return null;let a=(Number(o[0])%360+360)%360,c=Number(o[1].endsWith("%")?o[1].slice(0,-1):o[1])/100,d=Number(o[2].endsWith("%")?o[2].slice(0,-1):o[2])/100;if(![a,c,d].every($=>Number.isFinite($)))return null;let u=(1-Math.abs(2*d-1))*c,l=u*(1-Math.abs(a/60%2-1)),p=d-u/2,f=Math.floor(a/60)%6,h=[[u,l,0],[l,u,0],[0,u,l],[0,l,u],[l,0,u],[u,0,l]],[g,y,m]=h[f],b=$=>Math.round(($+p)*255).toString(16).padStart(2,"0");return`#${b(g)}${b(y)}${b(m)}`}return null}function ca(e){let t=ft(e);return t&&t.u==="px"?t.n:null}function ft(e,t=16){let n=e.trim().toLowerCase();if(!n)return null;if(n==="auto")return{n:0,u:"auto"};if(n==="0"||n==="0px")return{n:0,u:"px"};let s=/^(-?\d*\.?\d+)(px|%|rem|em|vw|vh)?$/.exec(n);if(!s)return null;let r=Number(s[1]);if(!Number.isFinite(r))return null;switch(s[2]){case"%":return{n:r,u:"%"};case"rem":case"em":return{n:Math.round(r*t*10)/10,u:"px"};case"vw":return{n:Math.round(r*3.9*10)/10,u:"px"};case"vh":return{n:Math.round(r*8.44*10)/10,u:"px"};default:return{n:r,u:"px"}}}function rc(e,t=16){let n=e.map(i=>ft(i,t));if(n.some(i=>i===null))return null;let s=n,r=i=>i.u==="%"?Math.round(i.n/100*390):i.n;if(s.length===1){let i=r(s[0]);return[i,i,i,i]}if(s.length===2){let i=r(s[0]),o=r(s[1]);return[i,o,i,o]}if(s.length===3){let i=r(s[0]),o=r(s[1]),a=r(s[2]);return[i,o,a,o]}return s.length>=4?[r(s[0]),r(s[1]),r(s[2]),r(s[3])]:null}function Xr(e){let t=[],n=0,s=0,r=e;for(let o=0;o<r.length;o++){let a=r[o];a==="("?n++:a===")"?n--:a===";"&&n===0&&(i(r.slice(s,o)),s=o+1)}i(r.slice(s));function i(o){let a=o.indexOf(":");if(a<0)return;let c=o.slice(0,a).trim().toLowerCase(),d=o.slice(a+1).trim().replace(/\s*!important\s*$/i,"");c&&d&&t.push({prop:c,value:d})}return t}function as(e){let t=[],n=0,s=null,r="";for(let i=0;i<e.length;i++){let o=e[i];if(s){r+=o,o===s&&e[i-1]!=="\\"&&(s=null);continue}if(o==='"'||o==="'"){s=o,r+=o;continue}if(o==="("){n++,r+=o;continue}if(o===")"){n=Math.max(0,n-1),r+=o;continue}if(/\s/.test(o)&&n===0){r&&t.push(r),r="";continue}r+=o}return r&&t.push(r),t}function cc(e,t,n,s){let r=n.trim();switch(t){case"color":{let i=zs(r);return i&&(e.color=i),!0}case"font-size":{let i=ft(r);return i&&i.u!=="auto"&&(e.fontSize=i.n),!0}case"font-weight":{if(/^bold$/i.test(r))e.fontWeight=700;else if(/^bolder$/i.test(r))e.fontWeight=800;else if(/^lighter$/i.test(r))e.fontWeight=300;else{let i=Number(r);Number.isFinite(i)&&(e.fontWeight=i)}return!0}case"font-family":{let i=0,o=null,a="";for(let d=0;d<r.length;d++){let u=r[d];if(o){a+=u,u===o&&r[d-1]!=="\\"&&(o=null);continue}if(u==='"'||u==="'"){o=u,a+=u;continue}if(u==="("&&i++,u===")"&&(i=Math.max(0,i-1)),u===","&&i===0)break;a+=u}let c=a.trim().replace(/^['"]|['"]$/g,"");return c&&!/^(inherit|initial|unset)$/i.test(c)&&(e.fontFamily=c),!0}case"font-style":return e.italic=/italic|oblique/i.test(r),!0;case"line-height":{if(/^\d*\.?\d+$/.test(r))return e.lineHeight=Number(r),!0;let i=ft(r,e.fontSize??16);return i&&e.fontSize&&(e.lineHeight=Math.round(i.n/e.fontSize*100)/100),!0}case"letter-spacing":{let i=ft(r);return i&&(e.letterSpacing=i.n),!0}case"text-align":return/^left$|^start$/i.test(r)?e.textAlign="left":/^center$/i.test(r)?e.textAlign="center":/^right$|^end$/i.test(r)?e.textAlign="right":/^justify$/i.test(r)&&(e.textAlign="justify"),!0;case"text-transform":return/^uppercase$/i.test(r)?e.textTransform="uppercase":/^lowercase$/i.test(r)?e.textTransform="lowercase":/^capitalize$/i.test(r)&&(e.textTransform="capitalize"),!0;case"text-decoration":return/underline/i.test(r)&&(e.underline=!0),/line-through/i.test(r)&&(e.strike=!0),!0;case"text-decoration-line":return/underline/i.test(r)&&(e.underline=!0),/line-through/i.test(r)&&(e.strike=!0),!0;case"background":case"background-color":{if(/gradient\(/i.test(r)){let o=ab(r);return o&&(e.gradient=o),!0}let i=zs(r);return i&&(e.background=i),!0}case"padding":{let i=rc(as(r));return i&&(e.padding=i),!0}case"padding-top":return rr(e.padding??[0,0,0,0],0,r,i=>e.padding=i),!0;case"padding-right":return rr(e.padding??[0,0,0,0],1,r,i=>e.padding=i),!0;case"padding-bottom":return rr(e.padding??[0,0,0,0],2,r,i=>e.padding=i),!0;case"padding-left":return rr(e.padding??[0,0,0,0],3,r,i=>e.padding=i),!0;case"margin":{let i=rc(as(r));return i&&(e.margin=i),!0}case"margin-top":return rr(e.margin??[0,0,0,0],0,r,i=>e.margin=i),!0;case"margin-right":return rr(e.margin??[0,0,0,0],1,r,i=>e.margin=i),!0;case"margin-bottom":return rr(e.margin??[0,0,0,0],2,r,i=>e.margin=i),!0;case"margin-left":return rr(e.margin??[0,0,0,0],3,r,i=>e.margin=i),!0;case"gap":case"grid-gap":{let i=ft(as(r)[0]);return i&&(e.gap=i.n),!0}case"row-gap":{let i=ft(r);return i&&(e.gap=e.gap??i.n),!0}case"column-gap":{let i=ft(r);return i&&(e.gap=i.n),!0}case"border":{let i=as(r),o=i.find(u=>/^\d/.test(u)),a=i.find(u=>/^(solid|dashed|dotted)$/i.test(u)),c=i.find(u=>zs(u)!==null);if(o){let u=ft(o);u&&(e.borderWidth=[u.n,u.n,u.n,u.n])}a?e.borderStyle=a.toLowerCase():o&&(e.borderStyle="solid");let d=c?zs(c):null;return d&&(e.borderColor=d),!0}case"border-top":return ua(e,"top",r),!0;case"border-right":return ua(e,"right",r),!0;case"border-bottom":return ua(e,"bottom",r),!0;case"border-left":return ua(e,"left",r),!0;case"border-width":{let i=rc(as(r));return i&&(e.borderWidth=i),!0}case"border-color":{let i=zs(r);return i&&(e.borderColor=i),!0}case"border-style":return/^(solid|dashed|dotted)$/i.test(r)&&(e.borderStyle=r.toLowerCase()),!0;case"border-radius":{let i=as(r).map(o=>ft(o)).filter(o=>o!==null).map(o=>o.n);return i.length===1?e.radius=[i[0],i[0],i[0],i[0]]:i.length===2?e.radius=[i[0],i[1],i[0],i[1]]:i.length===3?e.radius=[i[0],i[1],i[2],i[1]]:i.length>=4&&(e.radius=[i[0],i[1],i[2],i[3]]),!0}case"box-shadow":{let i=lb(r);return i&&(e.shadow=i),!0}case"opacity":{let i=Number(r);return Number.isFinite(i)&&(e.opacity=Math.max(0,Math.min(1,i))),!0}case"display":return/^flex$/i.test(r)||/^inline-flex$/i.test(r)?e.display="flex":/^none$/i.test(r)?e.display="none":/^inline-block$/i.test(r)?e.display="inline-block":/^inline$/i.test(r)?e.display="inline":/^block$/i.test(r)?e.display="block":/^grid$/i.test(r)&&(e.display="flex",e.direction=e.direction??"row",e.wrap=!0,s?.add("grid")),!0;case"flex-direction":return/^row/i.test(r)?e.direction="row":/^column/i.test(r)&&(e.direction="column"),!0;case"flex-wrap":return e.wrap=/wrap/i.test(r),!0;case"justify-content":return/flex-start|^start$|^left$/i.test(r)?e.justify="start":/center/i.test(r)?e.justify="center":/flex-end|^end$|^right$/i.test(r)?e.justify="end":/space-between/i.test(r)?e.justify="between":/space-around/i.test(r)?e.justify="around":/space-evenly/i.test(r)&&(e.justify="evenly"),!0;case"align-items":return e.align=_p(r),!0;case"align-self":{let i=_p(r);return i&&(e.alignSelf=i),!0}case"align-content":return!0;case"flex":{let i=as(r),o=Number(i[0]);if(Number.isFinite(o)&&(e.grow=o),i.length>=2&&/^\d/.test(i[1])&&(e.shrink=Number(i[1])),i.length>=3){let a=ft(i[2]);a&&(e.basis=a)}return!0}case"flex-grow":{let i=Number(r);return Number.isFinite(i)&&(e.grow=i),!0}case"flex-shrink":{let i=Number(r);return Number.isFinite(i)&&(e.shrink=i),!0}case"flex-basis":{let i=ft(r);return i&&(e.basis=i),!0}case"width":{let i=ft(r);return i&&(e.width=i),!0}case"height":{let i=ft(r);return i&&(e.height=i),!0}case"min-width":{let i=ft(r);return i&&(e.minWidth=i),!0}case"max-width":{let i=ft(r);return i&&(e.maxWidth=i),!0}case"min-height":{let i=ft(r);return i&&(e.minHeight=i),!0}case"max-height":{let i=ft(r);return i&&(e.maxHeight=i),!0}case"overflow":case"overflow-x":case"overflow-y":return/auto|scroll/i.test(r)?e.overflow="scroll":e.overflow=/hidden/i.test(r)?"hidden":"visible",!0;case"position":return/^(absolute|fixed)$/i.test(r)&&(e.position=r.toLowerCase()),!0;case"top":{let i=ca(r);return i!==null&&(e.insetTop=i),!0}case"right":{let i=ca(r);return i!==null&&(e.insetRight=i),!0}case"bottom":{let i=ca(r);return i!==null&&(e.insetBottom=i),!0}case"left":{let i=ca(r);return i!==null&&(e.insetLeft=i),!0}case"z-index":{let i=Number(r);return Number.isFinite(i)&&(e.zIndex=i),!0}case"cursor":return e.cursor=r,!0;case"visibility":return!0;default:return!1}}function rr(e,t,n,s){let r=ft(n);if(!r)return;let i=[e[0],e[1],e[2],e[3]];i[t]=r.u==="%"?Math.round(r.n/100*390):r.n,s(i)}function ua(e,t,n){let s=as(n),r={top:0,right:1,bottom:2,left:3}[t],i=s.find(c=>/^\d/.test(c));if(i){let c=ft(i);if(c){let d=e.borderWidth??[0,0,0,0],u=[d[0],d[1],d[2],d[3]];u[r]=c.n,e.borderWidth=u}}let o=s.find(c=>/^(solid|dashed|dotted)$/i.test(c));o&&(e.borderStyle=o.toLowerCase());let a=s.map(c=>zs(c)).find(c=>c!==null);a&&(e.borderColor=a)}function _p(e){if(/flex-start|^start$|^self-start$/i.test(e))return"start";if(/center/i.test(e))return"center";if(/flex-end|^end$|^self-end$/i.test(e))return"end";if(/stretch/i.test(e))return"stretch"}function ab(e){let t=/^(linear|radial)-gradient\(([\s\S]*)\)$/.exec(e.trim());if(!t)return null;let n=t[2],s=180,r=as(n),i=n;if(r[0]&&/^(to|[-\d.])/.test(r[0])){let c=r.shift();if(i=r.join(" "),c.startsWith("to")){let d=c.slice(2).trim();s={top:0,right:90,bottom:180,left:270,"top right":45,"right bottom":135,"bottom left":225,"left top":315}[d]??180}else{let d=Number(c.replace(/(deg|turn|rad)$/,""));Number.isFinite(d)&&(s=c.endsWith("turn")?d*360:c.endsWith("rad")?d*180/Math.PI:d)}}let o=[],a=0;for(let c of i.split(",")){let d=as(c.trim());if(!d.length)continue;let u=zs(d[0]);if(!u)continue;let l=a,p=d[1]?ft(d[1]):null;p&&p.u==="%"&&(l=p.n),o.push({at:l,color:u}),a=Math.min(100,l+50)}return o.length<2?null:{angle:s,stops:o}}function lb(e){let t=as(e);if(!t.length)return null;let n=t.findIndex(i=>zs(i)!==null),s=t.filter((i,o)=>o!==n&&/^-?[\d.]/.test(i)).map(i=>ft(i)).filter(i=>i!==null).map(i=>i.n);if(!s.length)return null;let r=n>=0?zs(t[n]):"#00000040";return{x:s[0]??0,y:s[1]??s[0]??0,blur:s[2]??0,spread:s[3]??0,color:r}}function ub(e){let t=cb.exec(e);if(!t||!t[1]&&!t[2]&&!t[3])return null;let n={classes:[],attrs:[],unsupported:[]};t[1]&&t[1]!=="*"&&(n.tag=t[1].toLowerCase());for(let s of t[2].match(/[.#][\w-]+/g)??[])s[0]==="."?n.classes.push(s.slice(1)):n.id=s.slice(1);for(let s of t[3].match(/\[[^\]]+\]/g)??[]){let r=s.slice(1,-1),i=/^([\w-]+)\s*(\^=|\$=|\*=|~=|=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+))$/.exec(r);i&&n.attrs.push({name:i[1].toLowerCase(),op:i[2],value:(i[3]??i[4]??i[5]??"").toLowerCase()})}return n}function db(e){let t=e.trim();if(!t||t.startsWith("@")||t.includes("::"))return null;let n=[],s="",r=null;for(let c=0;c<t.length;c++){let d=t[c];if(d===">"||d==="+"){let u=s.trim();u&&n.push({text:u,comb:r}),r=d===">"?"child":"descendant",s="";continue}if(/\s/.test(d)){let u=s.trim();u&&(n.push({text:u,comb:r}),r="descendant",s="");continue}s+=d}let i=s.trim();if(i&&n.push({text:i,comb:r}),!n.length)return null;let o=[],a=[];for(let c of n){let d=c.text.indexOf(":"),u=c.text;if(d>=0){let f=c.text.slice(d);if(u=c.text.slice(0,d),!/^(?:hover|focus|active)$/i.test(f)&&/^:not\(/i.test(f))return null}let l=ub(u);if(!l)return null;let p=f=>f.slice(d);d>=0&&/^(?:hover|focus|active)$/i.test(c.text.slice(d))?l.unsupported.push(p(c.text)):d>=0&&!/^:not\(/i.test(p(c.text))&&l.unsupported.push(p(c.text).replace(/\(.*$/,"")),o.push(l),c.comb&&o.length>1&&a.push(c.comb)}return{parts:o,combinators:a}}function pb(e){let t=0;for(let n of e)t+=n.classes.length*10+(n.id?100:0)+(n.tag?1:0)+n.attrs.length*10;return t}function fb(e,t=!1,n=!1,s=!1){if(t)return{model:{},hover:ic(e)};if(n)return{model:{},focus:ic(e)};if(s)return{model:{},active:ic(e)};let r={},i,o,a;for(let c of Xr(e)){let d=/^:hover\b/.test(c.prop),u=/^:focus\b/.test(c.prop),l=/^:active\b/.test(c.prop),p=d?c.prop.replace(/^:hover\s*/,""):u?c.prop.replace(/^:focus\s*/,""):l?c.prop.replace(/^:active\s*/,""):c.prop,f=d?i??={}:u?o??={}:l?a??={}:r;cc(f,p,c.value)}return{model:r,hover:i,focus:o,active:a}}function ic(e){let t={};for(let n of Xr(e))cc(t,n.prop,n.value);return t}function Te(e){let t=[],n=[],s=e.replace(/\/\*[\s\S]*?\*\//g,""),r=0,i=[],o=[],a=0,c="",d=(p,f,h)=>{for(let g of p.split(",")){let y=g.trim();if(!y)continue;let m=db(y);if(!m){t.push(`selector "${y}" is outside the engine's subset - the rule is skipped`);continue}let b=m.parts[m.parts.length-1],$=m.parts.flatMap(S=>S.unsupported).filter(S=>S!==":hover"&&S!==":focus"&&S!==":active");if($.length){t.push(`selector "${y}" uses ${[...new Set($)].join(", ")} - a native tree cannot test it, so the rule is skipped (it would otherwise style every match)`);continue}let{model:w,hover:v,focus:_,active:k}=fb(f,b.unsupported.includes(":hover"),b.unsupported.includes(":focus"),b.unsupported.includes(":active"));n.push({selector:y,parts:m.parts,combinators:m.combinators,model:w,hover:v,focus:_,active:k,specificity:pb(m.parts),order:r++,media:h?{...h}:void 0})}},u=p=>{let f=p.trim();if(a>0){i.push({sel:f,skip:!0,pushedMedia:!1}),a++;return}if(f.startsWith("@")){if(f.startsWith("@media")){let h=hb(f,t);i.push({sel:f,skip:!1,pushedMedia:!0}),o.push(h);return}if(f.startsWith("@supports")){i.push({sel:f,skip:!1,pushedMedia:!0}),o.push({});return}i.push({sel:f,skip:!0,pushedMedia:!1}),a++;return}i.push({sel:f,skip:!1,pushedMedia:!1})},l=p=>{let f=i.pop();if(!f){c="";return}if(f.skip){a=Math.max(0,a-1),c="";return}let h=o[o.length-1];f.pushedMedia&&o.pop(),!f.sel.startsWith("@")&&f.sel&&d(f.sel,p,h),c=""};for(let p=0;p<s.length;p++){let f=s[p];if(f==="{"){u(c),c="";continue}if(f==="}"){l(c),c="";continue}c+=f}return c.trim()&&i.length&&!i[i.length-1].sel.startsWith("@")&&t.push(`selector "${c.trim()}" has no block - the rule is skipped`),{rules:n,warnings:t}}function hb(e,t){let n=/\(\s*min-width\s*:\s*([\d.]+)(px)?\s*\)/.exec(e),s=/\(\s*max-width\s*:\s*([\d.]+)(px)?\s*\)/.exec(e),r=/\((?!\s*(?:min|max)-width)[^)]*\)/.exec(e);if(r&&t.push(`@media ${r[0]} has no native meaning - only the width guard is honoured`),n||s){let i={};return n&&(i.min=Number(n[1])),s&&(i.max=Number(s[1])),i}return t.push(`@media "${e.slice(0,44)}" has no min/max-width guard - the rule is applied at every width`),{}}function oc(e,t){if(e.tag&&e.tag!==t.tag||e.id&&e.id!==t.id)return!1;for(let n of e.classes)if(!t.classes.includes(n))return!1;for(let n of e.attrs){let s=n.name==="class"?t.classes.join(" "):n.name==="id"?t.id??"":"";if(n.name!=="class"&&n.name!=="id")return!1;let r=s.toLowerCase();if(n.op==="="&&r!==n.value||n.op==="~="&&!r.split(/\s+/).includes(n.value)||n.op==="*="&&!r.includes(n.value)||n.op==="^="&&!r.startsWith(n.value)||n.op==="$="&&!r.endsWith(n.value))return!1}return!0}function gb(e,t,n){let s=e.parts;if(!s.length||!oc(s[s.length-1],t))return!1;if(s.length===1)return!0;let r=n.length-1;for(let i=s.length-2;i>=0;i--){if((e.combinators[i]??"descendant")==="child"){if(r<0||!oc(s[i],n[r]))return!1;r--;continue}for(;r>=0&&!oc(s[i],n[r]);)r--;if(r<0)return!1;r--}return!0}function yb(e){let t=mb[e];return t?{...t}:null}function fe(e,t){if(!e)return{...t??{}};if(!t)return{...e};let n={...e};for(let s of Object.keys(t)){let r=t[s];r!==void 0&&(n[s]=r)}return n}function rt(e,t,n=[],s={}){let r=s.viewport??0,i=e.rules.filter(u=>u.media&&(u.media.min!==void 0||u.media.max!==void 0)&&(r<=0||u.media.min!==void 0&&r<u.media.min||u.media.max!==void 0&&r>u.media.max)?!1:gb(u,t,n));i.sort((u,l)=>u.specificity-l.specificity||u.order-l.order);let o=yb(t.tag)??{},a=null,c=null,d=null;for(let u of i)o=fe(o,u.model),u.hover&&(a=fe(a,u.hover)),u.focus&&(c=fe(c,u.focus)),u.active&&(d=fe(d,u.active));return{model:o,hover:a,focus:c,active:d}}function da(e){let t={};for(let n of Xr(e))cc(t,n.prop,n.value);return t}function ir(e,t,n=bb){return e?.direction?e.direction:pa(e)||n.has(t.toLowerCase())?"row":"column"}function pa(e){return e?e.display==="flex"||e.direction!==void 0||e.justify!==void 0||e.align!==void 0||e.wrap!==void 0||e.gap!==void 0:!1}function bt(e){let t=[],n=[],s=[],r=null,i=[],o=null,a=d=>{let u=ib(d);t.push(...u.statics),n.push(...u.dynamic)};for(let d of e.attrs){let u=d.name.toLowerCase();if(u==="class"){if(d.value.kind==="text")t.push(...(d.value.text??"").split(/\s+/).filter(Boolean));else if(d.value.kind==="expr")a(d.value.code??"");else if(d.value.kind==="mixed"&&d.value.parts){let l="";for(let p of d.value.parts)p.kind==="text"?l+=p.value:(l.trim()&&t.push(...l.split(/\s+/).filter(Boolean)),l="",a(p.value));l.trim()&&t.push(...l.split(/\s+/).filter(Boolean))}continue}if(u.startsWith("class:")){n.push(`(${d.value.kind==="expr"?d.value.code:"false"}) ? '${d.name.slice(6)}' : ''`);continue}if(u==="style"){if(d.value.kind==="text")r=da(d.value.text??""),i=Xr(d.value.text??"").map(l=>`${l.prop}: ${l.value}`);else if(d.value.kind==="expr"){let l=Ki(d.value.code??"");if(l){let p="";for(let f of l){let h=lc(f.value);h===null?s.push({prop:Qi(f.key),code:f.value}):h&&(p+=`${Qi(f.key)}: ${h}; `)}if(p){r=fe(r,da(p));for(let f of Xr(p))i.push(`${f.prop}: ${f.value}`)}}else o=d.value.code??""}else if(d.value.kind==="mixed"&&d.value.parts){let l="";for(let p of d.value.parts)p.kind==="text"&&(l+=p.value);r=da(l),i=Xr(l).map(p=>`${p.prop}: ${p.value}`)}continue}if(u.startsWith("style:")){let l=d.name.slice(6);d.value.kind==="expr"?s.push({prop:l,code:d.value.code??""}):d.value.kind==="text"&&(r=fe(r,da(`${l}: ${d.value.text}`)));continue}}let c=n.length>0||s.length>0;return{staticClasses:t,inlineStyle:r,inlineDecls:i,dynamicClassExprs:n,dynamicStyle:s,opaqueStyle:o,hasDynamic:c}}function fa(e,t,n){if(!e.trim())return;let s=e;for(;;){let i=s.search(/@supports\b/);if(i<0)break;let o=s.indexOf("{",i);if(o<0){s=s.slice(0,i);break}let a=1,c=o+1;for(;c<s.length&&a>0;)s[c]==="{"?a++:s[c]==="}"&&a--,c++;s=s.slice(0,i)+s.slice(c)}let r=Te(s);for(let i of r.warnings)n.push(`${t}: ${i}`);for(let i of r.rules){if(i.media){n.push(`${t}: "${i.selector}" is behind a @media guard - this target honours no width guard, the rule is dropped or applied unconditionally`);continue}if(i.hover!==void 0||i.parts.some(o=>o.unsupported.includes(":hover"))){n.push(`${t}: selector "${i.selector}" has a :hover half - this target has no hover state, the rule is dropped`);continue}/^\.([\w-]+)$/.test(i.selector.trim())||n.push(`${t}: selector "${i.selector}" is not a single class - only .class rules compile here, the rule is dropped`)}for(let i of e.matchAll(/@(?:-[\w]+-)?keyframes\s+([\w-]+)/g))n.push(`${t}: @keyframes "${i[1]}" - this target has no CSS animation, the keyframes are dropped`);/@supports\b/.test(e)&&n.push(`${t}: an @supports block has no feature tests here - it is dropped`)}function Tt(e){return e?Object.keys(e).length===0:!0}var ob,cb,mb,bb,ks=De(()=>{"use strict";ob={transparent:"#00000000",black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",yellow:"#ffff00",orange:"#ffa500",purple:"#800080",pink:"#ffc0cb",grey:"#808080",gray:"#808080",silver:"#c0c0c0",gold:"#ffd700",navy:"#000080",teal:"#008080",olive:"#808000",maroon:"#800000",aqua:"#00ffff",lime:"#00ff00",cyan:"#00ffff",magenta:"#ff00ff",brown:"#a52a2a",crimson:"#dc143c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",violet:"#ee82ee",indigo:"#4b0082",khaki:"#f0e68c",lavender:"#e6e6fa",beige:"#f5f5dc",ivory:"#fffff0",snow:"#fffafa",mistyrose:"#ffe4e1",seashell:"#fff5ee",skyblue:"#87ceeb",slategray:"#708099",darkgreen:"#006400",darkblue:"#00008b",darkred:"#8b0000",darkgray:"#a9a9a9",lightgray:"#d3d3d3",lightblue:"#add8e6",lightgreen:"#90ee90",lightyellow:"#ffffe0",dimgray:"#696969",whitesmoke:"#f5f5f5",ghostwhite:"#f8f8ff",floralwhite:"#fffaf0",honeydew:"#f0fff0",mintcream:"#f5fffa",aliceblue:"#f0f8ff",azure:"#f0ffff",bisque:"#ffe4c4",burlywood:"#deb887",chartreuse:"#7fff00",chocolate:"#d2691e",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",gainsboro:"#dcdcdc",hotpink:"#ff69b4",indianred:"#cd5c5c",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",mediumblue:"#0000cd",mediumseagreen:"#3cb371",midnightblue:"#191970",orchid:"#da70d6",palegreen:"#98fb98",peachpuff:"#ffdab9",peru:"#cd853f",plum:"#dda0dd",royalblue:"#4169e1",saddlebrown:"#8b4513",sandybrown:"#f4a460",seagreen:"#2e8b57",sienna:"#a0522d",steelblue:"#4682b4",tan:"#d2b48c",thistle:"#d8bfd8",turquoise:"#40e0d0",wheat:"#f5deb3",yellowgreen:"#9acd32",rebeccapurple:"#663399"};cb=/^([A-Za-z][\w-]*|\*)?((?:[.#][\w-]+)*)((?:\[[^\]]+\])*)/;mb={h1:{fontSize:32,fontWeight:700},h2:{fontSize:24,fontWeight:700},h3:{fontSize:19,fontWeight:700},h4:{fontSize:16,fontWeight:700},h5:{fontSize:13,fontWeight:700},h6:{fontSize:11,fontWeight:700}};bb=new Set});function wb(e){return $b[e]}function xt(e){let t=new Set;for(let n of e)if(!(!n||!n.includes("useNative")))for(let s of n.matchAll(/(^|[^\w$.])useNative\s*\(\s*(['"])([^'"]*)\2/g))t.add(s[3]);return xp.filter(n=>t.has(n))}function kp(e,t){let n=uc[e].dependencies??{},s=[];for(let r of t){let i=n[r];i&&!s.includes(i)&&s.push(i)}return s}function ha(e,t){let n=uc[e].manifest??{},s=[];for(let r of t)for(let i of n[r]??[])s.includes(i)||s.push(i);return s}function Dt(e,t){let n=(e??"").trim();if(!n)return"{}";let s=n.match(/^\{([\s\S]*)\}$/);if(!s)return null;let r=[];for(let i of s[1].split(",")){let o=i.trim();if(!o)continue;let a=o.match(/^([A-Za-z_$][\w$]*)\s*:\s*([\s\S]+)$/);if(!a)return null;let c=t==="quoted"?`'${a[1]}'`:a[1];r.push(`${c}: ${a[2].trim()}`)}return r.length?`{ ${r.join(", ")} }`:"{}"}function vb(e,t){let n=0,s="";for(let r=t;r<e.length;r++){let i=e[r];if(s){i==="\\"?r++:i===s&&(s="");continue}if(i==='"'||i==="'"||i==="`"){s=i;continue}if(i==="("||i==="["||i==="{")n++;else if((i===")"||i==="]"||i==="}")&&(n--,n===0))return r}return-1}function zt(e,t){if(!e||!e.includes("useNative"))return{code:e,used:[]};let n=uc[t.target],s=wb(t.target),r=t.file?`${t.file}: `:"",i=new Set,o="",a=0;for(;;){let c=e.indexOf("useNative",a);if(c<0){o+=e.slice(a);break}if(/[A-Za-z0-9_$.]/.test(e[c-1]??"")){o+=e.slice(a,c+9),a=c+9;continue}let d=c+9;for(;d<e.length&&/\s/.test(e[d]);)d++;if(e[d]!=="("){o+=e.slice(a,c+9),a=c+9;continue}let u=vb(e,d);if(u<0){o+=e.slice(a,c+9),a=c+9;continue}let l=e.slice(d+1,u).trim(),p=l.match(/^(['"])([^'"]*)\1/),f=p?p[2]:"";if(o+=e.slice(a,c),!p||!xp.includes(f))t.warn(`${r}useNative('${f||"\u2026"}') is not a known capability - ${s} emits ${t.empty}`),o+=t.empty;else if(n.capabilities.includes(f)){let h=f;i.add(h);let g=l.slice(p[0].length).replace(/^\s*,\s*/,""),y=t.options(g);y===null&&t.warn(`${r}useNative('${h}') options ${g.trim().slice(0,40)} are not a flat object literal - ${s} uses the platform defaults`),o+=`${n.helper}('${h}', ${y??"{}"})`}else{let h=n.platform[f];t.warn(`${r}useNative('${f}') has no ${s} equivalent${h?` (nearest platform API: ${h})`:""} - emits ${t.empty}`),o+=t.empty}a=u+1}return{code:o,used:[...i]}}var xp,Zi,uc,$b,ls=De(()=>{"use strict";xp=["camera","geolocation","clipboard-read","clipboard-write","share"],Zi=["camera","geolocation","clipboard-read","clipboard-write"],uc={weapp:{helper:"__rosefdNative",capabilities:Zi,platform:{camera:"wx.chooseMedia",geolocation:"wx.getLocation","clipboard-read":"wx.getClipboardData","clipboard-write":"wx.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},qq:{helper:"__rosefdNative",capabilities:Zi,platform:{camera:"qq.chooseMedia",geolocation:"qq.getLocation","clipboard-read":"qq.getClipboardData","clipboard-write":"qq.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},alipay:{helper:"__rosefdNative",capabilities:Zi,platform:{camera:"my.chooseImage",geolocation:"my.getLocation","clipboard-read":"my.getClipboard","clipboard-write":"my.setClipboard"},manifest:{geolocation:["location"]}},baidu:{helper:"__rosefdNative",capabilities:Zi,platform:{camera:"swan.chooseImage",geolocation:"swan.getLocation","clipboard-read":"swan.getClipboardData","clipboard-write":"swan.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},toutiao:{helper:"__rosefdNative",capabilities:Zi,platform:{camera:"tt.chooseImage",geolocation:"tt.getLocation","clipboard-read":"tt.getClipboardData","clipboard-write":"tt.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},flutter:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],dependencies:{camera:"image_picker",geolocation:"geolocator",share:"share_plus"},platform:{camera:"image_picker",geolocation:"geolocator","clipboard-read":"Clipboard.getData","clipboard-write":"Clipboard.setData",share:"share_plus"}},arkts:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"@ohos.multimedia.camera / photoAccessHelper",geolocation:"@ohos.geoLocationManager","clipboard-read":"@ohos.pasteboard","clipboard-write":"@ohos.pasteboard",share:"@ohos.app.ability.wantAgent"},manifest:{camera:["ohos.permission.CAMERA"],geolocation:["ohos.permission.LOCATION","ohos.permission.APPROXIMATELY_LOCATION"]}},android:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"ActivityResultContracts.TakePicture",geolocation:"FusedLocationProviderClient","clipboard-read":"ClipboardManager","clipboard-write":"ClipboardManager",share:"Intent.ACTION_SEND"}},xcode:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"UIImagePickerController",geolocation:"CLLocationManager","clipboard-read":"UIPasteboard","clipboard-write":"UIPasteboard",share:"UIActivityViewController"}},electron:{helper:"useNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"navigator.mediaDevices.getUserMedia",geolocation:"navigator.geolocation","clipboard-read":"navigator.clipboard.readText","clipboard-write":"navigator.clipboard.writeText",share:"navigator.share"}},python:{helper:"rose_native",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"tkinter.filedialog",geolocation:"no Tk API (an app needs an OS/web location service)","clipboard-read":"tkinter.clipboard_get","clipboard-write":"tkinter.clipboard_append",share:"webbrowser.open"}},dotnet:{helper:"RoseKit.RoseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"OpenFileDialog",geolocation:"GeoCoordinateWatcher (a package - not in the box for net8.0)","clipboard-read":"Clipboard.GetText","clipboard-write":"Clipboard.SetText",share:"Process.Start"}},java:{helper:"RoseKit.roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"no capture API (java.awt.Robot / third-party webcam lib)",geolocation:"no JDK API (third-party library)","clipboard-read":"Toolkit.getSystemClipboard","clipboard-write":"Toolkit.getSystemClipboard",share:"Desktop.browse"}},cpp:{helper:"rose_native",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"QFileDialog",geolocation:"QGeoPositionInfoSource","clipboard-read":"QClipboard","clipboard-write":"QClipboard",share:"QDesktopServices::openUrl"}}},$b={weapp:"WeChat",qq:"QQ",alipay:"Alipay",baidu:"Baidu",toutiao:"Douyin",flutter:"Flutter",android:"Android",arkts:"HarmonyOS ArkTS",xcode:"Xcode/SwiftUI",electron:"Electron",python:"Python/Tkinter",dotnet:".NET/WPF",java:"Java/Swing",cpp:"C++/Qt"}});import*as ue from"node:fs";import*as le from"node:path";import{transformSync as Ap}from"esbuild";function zn(e,t){return e.endsWith("-")?`${e}${t}`:`${e}:${t}`}function kb(e,t,n){let s=Cp[e];if(!s)return"";let r=[];s.transform&&r.push(`transform: ${s.transform};`),s.filter&&r.push(`filter: ${s.filter};`),r.push(`opacity: ${s.opacity};`);let i=[];return s.transform&&i.push("transform: none;"),s.filter&&i.push("filter: none;"),i.push("opacity: 1;"),[`@keyframes rf-in-${e} { from { ${r.join(" ")} } to { ${i.join(" ")} } }`,`.rf-in-${e} { animation-name: rf-in-${e}; animation-duration: ${t}ms; animation-delay: ${n}ms; animation-timing-function: ease; animation-fill-mode: both; }`].join(`
|
|
1917
|
-
`)}async function jp(e){let t=wa[e.target],n=e.warnings,s=e.projectRoot,r=le.join(e.outDir,t.dir),i=le.join(s,"src","pages"),o=Mt(s),a=o!==null,[c,d]=await Promise.all([Ye(s),Ke(s)]),u=new Map;for(let v of c){if(le.basename(v)!=="_layout.rose")continue;let _=le.dirname(le.relative(i,v)).replace(/\\/g,"/"),k=Ce(await ue.promises.readFile(v,"utf8"),v,e.target);n.push(...k.warnings),u.set(_==="."?"":_,{file:v,nodes:k.nodes,script:k.script,style:k.style})}let l=[];for(let v of c){let _=le.relative(i,v).replace(/\\/g,"/"),k=_.replace(/\.rose$/,""),S=le.basename(k);if(S==="_layout"||S==="404"||S==="_notfound"||S==="500"||S==="_middleware"||k==="api"||k.startsWith("api/"))continue;let C=Ce(await ue.promises.readFile(v,"utf8"),v,e.target);n.push(...C.warnings);let x=[],A=_.split("/").slice(0,-1);for(let R=A.length;R>=0;R--){let T=u.get(A.slice(0,R).join("/"));T&&x.push(T)}l.push({file:v,route:Tb(k),name:Eb(k),scope:Ob(_),nodes:C.nodes,script:C.script,style:C.style,title:Nb(C.head),layoutChain:x})}let p=[];for(let v of d){let _=Ce(await ue.promises.readFile(v,"utf8"),v,e.target);n.push(..._.warnings),p.push({file:v,name:le.basename(v,".rose"),scope:le.relative(le.join(s,"src","components"),v).replace(/\\/g,"/").replace(/\.rose$/,""),nodes:_.nodes,script:_.script,style:_.style})}await ue.promises.rm(r,{recursive:!0,force:!0}),await ue.promises.mkdir(le.join(r,"utils"),{recursive:!0}),await ue.promises.writeFile(le.join(r,"utils","
|
|
1916
|
+
`}var xs=De(()=>{"use strict"});function sb(e){let t=[],n=0,s=null,r="";for(let i=0;i<e.length;i++){let o=e[i];if(s){r+=o,o===s&&e[i-1]!=="\\"&&(s=null);continue}if(o==='"'||o==="'"||o==="`"){s=o,r+=o;continue}if(o==="("||o==="["||o==="{"){n++,r+=o;continue}if(o===")"||o==="]"||o==="}"){n--,r+=o;continue}if(o===","&&n===0){t.push(r),r="";continue}r+=o}return t.push(r),t.map(i=>i.trim()).filter(Boolean)}function rb(e){let t=0,n=null;for(let s=0;s<e.length;s++){let r=e[s];if(n){r===n&&e[s-1]!=="\\"&&(n=null);continue}if(r==='"'||r==="'"||r==="`"){n=r;continue}if(r==="("||r==="["||r==="{")t++;else if(r===")"||r==="]"||r==="}")t--;else if(r===":"&&t===0)return s}return-1}function Ki(e){let t=(e??"").trim();if(t.length<2||t[0]!=="{"||t[t.length-1]!=="}")return null;let n=t.slice(1,-1).trim(),s=[];if(!n)return s;for(let r of sb(n)){if(r.startsWith("...")||r.startsWith("["))return null;let i=rb(r);if(i<0){if(!/^[A-Za-z_$][\w$]*$/.test(r))return null;s.push({key:r,value:r});continue}let o=r.slice(0,i).trim(),a=/^(['"])([\s\S]*)\1$/.exec(o),c=a?a[2]:o;if(!/^[A-Za-z_$][\w$-]*$/.test(c))return null;let d=r.slice(i+1).trim();if(!d)return null;s.push({key:c,value:d})}return s}function ac(e){let t=e.trim();if(t==="true")return!0;if(t==="false"||t==="null"||t==="undefined")return!1;if(/^-?(\d+\.?\d*|\.\d+)$/.test(t))return Number(t)!==0;let n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2].length>0:null}function lc(e){let t=e.trim(),n=/^(['"])([\s\S]*)\1$/.exec(t);return n?n[2]:/^-?(\d+\.?\d*|\.\d+)(px|rem|em|%|vh|vw|deg)?$/.test(t)?t:t==="null"||t==="undefined"||t==="false"?"":null}function Qi(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function ib(e){let t=Ki(e);if(!t)return{statics:[],dynamic:[e]};let n=[],s=[];for(let r of t){let i=ac(r.value);if(i===!0)n.push(r.key);else{if(i===!1)continue;s.push(`(${r.value}) ? '${r.key}' : ''`)}}return{statics:n,dynamic:s}}function zs(e){let t=e.trim().toLowerCase();if(!t||t==="currentcolor"||t==="inherit"||t==="initial"||t==="unset"||t==="none"||t.startsWith("var("))return null;let n=ob[t];if(n)return n;let s=/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);if(s){let o=s[1];return o.length===3||o.length===4?"#"+o.split("").map(c=>c+c).join("").toLowerCase():"#"+o.toLowerCase()}let r=/^rgba?\(([^)]+)\)$/.exec(t);if(r){let o=r[1].split(/[,/\s]+/).filter(Boolean);if(o.length<3)return null;let a=p=>p.endsWith("%")?Math.round(Number(p.slice(0,-1))/100*255):Math.round(Number(p)),c=a(o[0]),d=a(o[1]),u=a(o[2]);if(![c,d,u].every(p=>Number.isFinite(p)))return null;let l=p=>Math.max(0,Math.min(255,p)).toString(16).padStart(2,"0");if(o.length>=4&&o[3]!==void 0){let p=o[3],f=p.endsWith("%")?Number(p.slice(0,-1))/100:Number(p);return Number.isFinite(f)?`#${l(c)}${l(d)}${l(u)}${l(Math.round(Math.max(0,Math.min(1,f))*255))}`:`#${l(c)}${l(d)}${l(u)}`}return`#${l(c)}${l(d)}${l(u)}`}let i=/^hsla?\(([^)]+)\)$/.exec(t);if(i){let o=i[1].split(/[,/\s]+/).filter(Boolean);if(o.length<3)return null;let a=(Number(o[0])%360+360)%360,c=Number(o[1].endsWith("%")?o[1].slice(0,-1):o[1])/100,d=Number(o[2].endsWith("%")?o[2].slice(0,-1):o[2])/100;if(![a,c,d].every($=>Number.isFinite($)))return null;let u=(1-Math.abs(2*d-1))*c,l=u*(1-Math.abs(a/60%2-1)),p=d-u/2,f=Math.floor(a/60)%6,h=[[u,l,0],[l,u,0],[0,u,l],[0,l,u],[l,0,u],[u,0,l]],[g,y,m]=h[f],b=$=>Math.round(($+p)*255).toString(16).padStart(2,"0");return`#${b(g)}${b(y)}${b(m)}`}return null}function ca(e){let t=ft(e);return t&&t.u==="px"?t.n:null}function ft(e,t=16){let n=e.trim().toLowerCase();if(!n)return null;if(n==="auto")return{n:0,u:"auto"};if(n==="0"||n==="0px")return{n:0,u:"px"};let s=/^(-?\d*\.?\d+)(px|%|rem|em|vw|vh)?$/.exec(n);if(!s)return null;let r=Number(s[1]);if(!Number.isFinite(r))return null;switch(s[2]){case"%":return{n:r,u:"%"};case"rem":case"em":return{n:Math.round(r*t*10)/10,u:"px"};case"vw":return{n:Math.round(r*3.9*10)/10,u:"px"};case"vh":return{n:Math.round(r*8.44*10)/10,u:"px"};default:return{n:r,u:"px"}}}function rc(e,t=16){let n=e.map(i=>ft(i,t));if(n.some(i=>i===null))return null;let s=n,r=i=>i.u==="%"?Math.round(i.n/100*390):i.n;if(s.length===1){let i=r(s[0]);return[i,i,i,i]}if(s.length===2){let i=r(s[0]),o=r(s[1]);return[i,o,i,o]}if(s.length===3){let i=r(s[0]),o=r(s[1]),a=r(s[2]);return[i,o,a,o]}return s.length>=4?[r(s[0]),r(s[1]),r(s[2]),r(s[3])]:null}function Xr(e){let t=[],n=0,s=0,r=e;for(let o=0;o<r.length;o++){let a=r[o];a==="("?n++:a===")"?n--:a===";"&&n===0&&(i(r.slice(s,o)),s=o+1)}i(r.slice(s));function i(o){let a=o.indexOf(":");if(a<0)return;let c=o.slice(0,a).trim().toLowerCase(),d=o.slice(a+1).trim().replace(/\s*!important\s*$/i,"");c&&d&&t.push({prop:c,value:d})}return t}function as(e){let t=[],n=0,s=null,r="";for(let i=0;i<e.length;i++){let o=e[i];if(s){r+=o,o===s&&e[i-1]!=="\\"&&(s=null);continue}if(o==='"'||o==="'"){s=o,r+=o;continue}if(o==="("){n++,r+=o;continue}if(o===")"){n=Math.max(0,n-1),r+=o;continue}if(/\s/.test(o)&&n===0){r&&t.push(r),r="";continue}r+=o}return r&&t.push(r),t}function cc(e,t,n,s){let r=n.trim();switch(t){case"color":{let i=zs(r);return i&&(e.color=i),!0}case"font-size":{let i=ft(r);return i&&i.u!=="auto"&&(e.fontSize=i.n),!0}case"font-weight":{if(/^bold$/i.test(r))e.fontWeight=700;else if(/^bolder$/i.test(r))e.fontWeight=800;else if(/^lighter$/i.test(r))e.fontWeight=300;else{let i=Number(r);Number.isFinite(i)&&(e.fontWeight=i)}return!0}case"font-family":{let i=0,o=null,a="";for(let d=0;d<r.length;d++){let u=r[d];if(o){a+=u,u===o&&r[d-1]!=="\\"&&(o=null);continue}if(u==='"'||u==="'"){o=u,a+=u;continue}if(u==="("&&i++,u===")"&&(i=Math.max(0,i-1)),u===","&&i===0)break;a+=u}let c=a.trim().replace(/^['"]|['"]$/g,"");return c&&!/^(inherit|initial|unset)$/i.test(c)&&(e.fontFamily=c),!0}case"font-style":return e.italic=/italic|oblique/i.test(r),!0;case"line-height":{if(/^\d*\.?\d+$/.test(r))return e.lineHeight=Number(r),!0;let i=ft(r,e.fontSize??16);return i&&e.fontSize&&(e.lineHeight=Math.round(i.n/e.fontSize*100)/100),!0}case"letter-spacing":{let i=ft(r);return i&&(e.letterSpacing=i.n),!0}case"text-align":return/^left$|^start$/i.test(r)?e.textAlign="left":/^center$/i.test(r)?e.textAlign="center":/^right$|^end$/i.test(r)?e.textAlign="right":/^justify$/i.test(r)&&(e.textAlign="justify"),!0;case"text-transform":return/^uppercase$/i.test(r)?e.textTransform="uppercase":/^lowercase$/i.test(r)?e.textTransform="lowercase":/^capitalize$/i.test(r)&&(e.textTransform="capitalize"),!0;case"text-decoration":return/underline/i.test(r)&&(e.underline=!0),/line-through/i.test(r)&&(e.strike=!0),!0;case"text-decoration-line":return/underline/i.test(r)&&(e.underline=!0),/line-through/i.test(r)&&(e.strike=!0),!0;case"background":case"background-color":{if(/gradient\(/i.test(r)){let o=ab(r);return o&&(e.gradient=o),!0}let i=zs(r);return i&&(e.background=i),!0}case"padding":{let i=rc(as(r));return i&&(e.padding=i),!0}case"padding-top":return rr(e.padding??[0,0,0,0],0,r,i=>e.padding=i),!0;case"padding-right":return rr(e.padding??[0,0,0,0],1,r,i=>e.padding=i),!0;case"padding-bottom":return rr(e.padding??[0,0,0,0],2,r,i=>e.padding=i),!0;case"padding-left":return rr(e.padding??[0,0,0,0],3,r,i=>e.padding=i),!0;case"margin":{let i=rc(as(r));return i&&(e.margin=i),!0}case"margin-top":return rr(e.margin??[0,0,0,0],0,r,i=>e.margin=i),!0;case"margin-right":return rr(e.margin??[0,0,0,0],1,r,i=>e.margin=i),!0;case"margin-bottom":return rr(e.margin??[0,0,0,0],2,r,i=>e.margin=i),!0;case"margin-left":return rr(e.margin??[0,0,0,0],3,r,i=>e.margin=i),!0;case"gap":case"grid-gap":{let i=ft(as(r)[0]);return i&&(e.gap=i.n),!0}case"row-gap":{let i=ft(r);return i&&(e.gap=e.gap??i.n),!0}case"column-gap":{let i=ft(r);return i&&(e.gap=i.n),!0}case"border":{let i=as(r),o=i.find(u=>/^\d/.test(u)),a=i.find(u=>/^(solid|dashed|dotted)$/i.test(u)),c=i.find(u=>zs(u)!==null);if(o){let u=ft(o);u&&(e.borderWidth=[u.n,u.n,u.n,u.n])}a?e.borderStyle=a.toLowerCase():o&&(e.borderStyle="solid");let d=c?zs(c):null;return d&&(e.borderColor=d),!0}case"border-top":return ua(e,"top",r),!0;case"border-right":return ua(e,"right",r),!0;case"border-bottom":return ua(e,"bottom",r),!0;case"border-left":return ua(e,"left",r),!0;case"border-width":{let i=rc(as(r));return i&&(e.borderWidth=i),!0}case"border-color":{let i=zs(r);return i&&(e.borderColor=i),!0}case"border-style":return/^(solid|dashed|dotted)$/i.test(r)&&(e.borderStyle=r.toLowerCase()),!0;case"border-radius":{let i=as(r).map(o=>ft(o)).filter(o=>o!==null).map(o=>o.n);return i.length===1?e.radius=[i[0],i[0],i[0],i[0]]:i.length===2?e.radius=[i[0],i[1],i[0],i[1]]:i.length===3?e.radius=[i[0],i[1],i[2],i[1]]:i.length>=4&&(e.radius=[i[0],i[1],i[2],i[3]]),!0}case"box-shadow":{let i=lb(r);return i&&(e.shadow=i),!0}case"opacity":{let i=Number(r);return Number.isFinite(i)&&(e.opacity=Math.max(0,Math.min(1,i))),!0}case"display":return/^flex$/i.test(r)||/^inline-flex$/i.test(r)?e.display="flex":/^none$/i.test(r)?e.display="none":/^inline-block$/i.test(r)?e.display="inline-block":/^inline$/i.test(r)?e.display="inline":/^block$/i.test(r)?e.display="block":/^grid$/i.test(r)&&(e.display="flex",e.direction=e.direction??"row",e.wrap=!0,s?.add("grid")),!0;case"flex-direction":return/^row/i.test(r)?e.direction="row":/^column/i.test(r)&&(e.direction="column"),!0;case"flex-wrap":return e.wrap=/wrap/i.test(r),!0;case"justify-content":return/flex-start|^start$|^left$/i.test(r)?e.justify="start":/center/i.test(r)?e.justify="center":/flex-end|^end$|^right$/i.test(r)?e.justify="end":/space-between/i.test(r)?e.justify="between":/space-around/i.test(r)?e.justify="around":/space-evenly/i.test(r)&&(e.justify="evenly"),!0;case"align-items":return e.align=_p(r),!0;case"align-self":{let i=_p(r);return i&&(e.alignSelf=i),!0}case"align-content":return!0;case"flex":{let i=as(r),o=Number(i[0]);if(Number.isFinite(o)&&(e.grow=o),i.length>=2&&/^\d/.test(i[1])&&(e.shrink=Number(i[1])),i.length>=3){let a=ft(i[2]);a&&(e.basis=a)}return!0}case"flex-grow":{let i=Number(r);return Number.isFinite(i)&&(e.grow=i),!0}case"flex-shrink":{let i=Number(r);return Number.isFinite(i)&&(e.shrink=i),!0}case"flex-basis":{let i=ft(r);return i&&(e.basis=i),!0}case"width":{let i=ft(r);return i&&(e.width=i),!0}case"height":{let i=ft(r);return i&&(e.height=i),!0}case"min-width":{let i=ft(r);return i&&(e.minWidth=i),!0}case"max-width":{let i=ft(r);return i&&(e.maxWidth=i),!0}case"min-height":{let i=ft(r);return i&&(e.minHeight=i),!0}case"max-height":{let i=ft(r);return i&&(e.maxHeight=i),!0}case"overflow":case"overflow-x":case"overflow-y":return/auto|scroll/i.test(r)?e.overflow="scroll":e.overflow=/hidden/i.test(r)?"hidden":"visible",!0;case"position":return/^(absolute|fixed)$/i.test(r)&&(e.position=r.toLowerCase()),!0;case"top":{let i=ca(r);return i!==null&&(e.insetTop=i),!0}case"right":{let i=ca(r);return i!==null&&(e.insetRight=i),!0}case"bottom":{let i=ca(r);return i!==null&&(e.insetBottom=i),!0}case"left":{let i=ca(r);return i!==null&&(e.insetLeft=i),!0}case"z-index":{let i=Number(r);return Number.isFinite(i)&&(e.zIndex=i),!0}case"cursor":return e.cursor=r,!0;case"visibility":return!0;default:return!1}}function rr(e,t,n,s){let r=ft(n);if(!r)return;let i=[e[0],e[1],e[2],e[3]];i[t]=r.u==="%"?Math.round(r.n/100*390):r.n,s(i)}function ua(e,t,n){let s=as(n),r={top:0,right:1,bottom:2,left:3}[t],i=s.find(c=>/^\d/.test(c));if(i){let c=ft(i);if(c){let d=e.borderWidth??[0,0,0,0],u=[d[0],d[1],d[2],d[3]];u[r]=c.n,e.borderWidth=u}}let o=s.find(c=>/^(solid|dashed|dotted)$/i.test(c));o&&(e.borderStyle=o.toLowerCase());let a=s.map(c=>zs(c)).find(c=>c!==null);a&&(e.borderColor=a)}function _p(e){if(/flex-start|^start$|^self-start$/i.test(e))return"start";if(/center/i.test(e))return"center";if(/flex-end|^end$|^self-end$/i.test(e))return"end";if(/stretch/i.test(e))return"stretch"}function ab(e){let t=/^(linear|radial)-gradient\(([\s\S]*)\)$/.exec(e.trim());if(!t)return null;let n=t[2],s=180,r=as(n),i=n;if(r[0]&&/^(to|[-\d.])/.test(r[0])){let c=r.shift();if(i=r.join(" "),c.startsWith("to")){let d=c.slice(2).trim();s={top:0,right:90,bottom:180,left:270,"top right":45,"right bottom":135,"bottom left":225,"left top":315}[d]??180}else{let d=Number(c.replace(/(deg|turn|rad)$/,""));Number.isFinite(d)&&(s=c.endsWith("turn")?d*360:c.endsWith("rad")?d*180/Math.PI:d)}}let o=[],a=0;for(let c of i.split(",")){let d=as(c.trim());if(!d.length)continue;let u=zs(d[0]);if(!u)continue;let l=a,p=d[1]?ft(d[1]):null;p&&p.u==="%"&&(l=p.n),o.push({at:l,color:u}),a=Math.min(100,l+50)}return o.length<2?null:{angle:s,stops:o}}function lb(e){let t=as(e);if(!t.length)return null;let n=t.findIndex(i=>zs(i)!==null),s=t.filter((i,o)=>o!==n&&/^-?[\d.]/.test(i)).map(i=>ft(i)).filter(i=>i!==null).map(i=>i.n);if(!s.length)return null;let r=n>=0?zs(t[n]):"#00000040";return{x:s[0]??0,y:s[1]??s[0]??0,blur:s[2]??0,spread:s[3]??0,color:r}}function ub(e){let t=cb.exec(e);if(!t||!t[1]&&!t[2]&&!t[3])return null;let n={classes:[],attrs:[],unsupported:[]};t[1]&&t[1]!=="*"&&(n.tag=t[1].toLowerCase());for(let s of t[2].match(/[.#][\w-]+/g)??[])s[0]==="."?n.classes.push(s.slice(1)):n.id=s.slice(1);for(let s of t[3].match(/\[[^\]]+\]/g)??[]){let r=s.slice(1,-1),i=/^([\w-]+)\s*(\^=|\$=|\*=|~=|=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+))$/.exec(r);i&&n.attrs.push({name:i[1].toLowerCase(),op:i[2],value:(i[3]??i[4]??i[5]??"").toLowerCase()})}return n}function db(e){let t=e.trim();if(!t||t.startsWith("@")||t.includes("::"))return null;let n=[],s="",r=null;for(let c=0;c<t.length;c++){let d=t[c];if(d===">"||d==="+"){let u=s.trim();u&&n.push({text:u,comb:r}),r=d===">"?"child":"descendant",s="";continue}if(/\s/.test(d)){let u=s.trim();u&&(n.push({text:u,comb:r}),r="descendant",s="");continue}s+=d}let i=s.trim();if(i&&n.push({text:i,comb:r}),!n.length)return null;let o=[],a=[];for(let c of n){let d=c.text.indexOf(":"),u=c.text;if(d>=0){let f=c.text.slice(d);if(u=c.text.slice(0,d),!/^(?:hover|focus|active)$/i.test(f)&&/^:not\(/i.test(f))return null}let l=ub(u);if(!l)return null;let p=f=>f.slice(d);d>=0&&/^(?:hover|focus|active)$/i.test(c.text.slice(d))?l.unsupported.push(p(c.text)):d>=0&&!/^:not\(/i.test(p(c.text))&&l.unsupported.push(p(c.text).replace(/\(.*$/,"")),o.push(l),c.comb&&o.length>1&&a.push(c.comb)}return{parts:o,combinators:a}}function pb(e){let t=0;for(let n of e)t+=n.classes.length*10+(n.id?100:0)+(n.tag?1:0)+n.attrs.length*10;return t}function fb(e,t=!1,n=!1,s=!1){if(t)return{model:{},hover:ic(e)};if(n)return{model:{},focus:ic(e)};if(s)return{model:{},active:ic(e)};let r={},i,o,a;for(let c of Xr(e)){let d=/^:hover\b/.test(c.prop),u=/^:focus\b/.test(c.prop),l=/^:active\b/.test(c.prop),p=d?c.prop.replace(/^:hover\s*/,""):u?c.prop.replace(/^:focus\s*/,""):l?c.prop.replace(/^:active\s*/,""):c.prop,f=d?i??={}:u?o??={}:l?a??={}:r;cc(f,p,c.value)}return{model:r,hover:i,focus:o,active:a}}function ic(e){let t={};for(let n of Xr(e))cc(t,n.prop,n.value);return t}function Te(e){let t=[],n=[],s=e.replace(/\/\*[\s\S]*?\*\//g,""),r=0,i=[],o=[],a=0,c="",d=(p,f,h)=>{for(let g of p.split(",")){let y=g.trim();if(!y)continue;let m=db(y);if(!m){t.push(`selector "${y}" is outside the engine's subset - the rule is skipped`);continue}let b=m.parts[m.parts.length-1],$=m.parts.flatMap(S=>S.unsupported).filter(S=>S!==":hover"&&S!==":focus"&&S!==":active");if($.length){t.push(`selector "${y}" uses ${[...new Set($)].join(", ")} - a native tree cannot test it, so the rule is skipped (it would otherwise style every match)`);continue}let{model:w,hover:v,focus:_,active:k}=fb(f,b.unsupported.includes(":hover"),b.unsupported.includes(":focus"),b.unsupported.includes(":active"));n.push({selector:y,parts:m.parts,combinators:m.combinators,model:w,hover:v,focus:_,active:k,specificity:pb(m.parts),order:r++,media:h?{...h}:void 0})}},u=p=>{let f=p.trim();if(a>0){i.push({sel:f,skip:!0,pushedMedia:!1}),a++;return}if(f.startsWith("@")){if(f.startsWith("@media")){let h=hb(f,t);i.push({sel:f,skip:!1,pushedMedia:!0}),o.push(h);return}if(f.startsWith("@supports")){i.push({sel:f,skip:!1,pushedMedia:!0}),o.push({});return}i.push({sel:f,skip:!0,pushedMedia:!1}),a++;return}i.push({sel:f,skip:!1,pushedMedia:!1})},l=p=>{let f=i.pop();if(!f){c="";return}if(f.skip){a=Math.max(0,a-1),c="";return}let h=o[o.length-1];f.pushedMedia&&o.pop(),!f.sel.startsWith("@")&&f.sel&&d(f.sel,p,h),c=""};for(let p=0;p<s.length;p++){let f=s[p];if(f==="{"){u(c),c="";continue}if(f==="}"){l(c),c="";continue}c+=f}return c.trim()&&i.length&&!i[i.length-1].sel.startsWith("@")&&t.push(`selector "${c.trim()}" has no block - the rule is skipped`),{rules:n,warnings:t}}function hb(e,t){let n=/\(\s*min-width\s*:\s*([\d.]+)(px)?\s*\)/.exec(e),s=/\(\s*max-width\s*:\s*([\d.]+)(px)?\s*\)/.exec(e),r=/\((?!\s*(?:min|max)-width)[^)]*\)/.exec(e);if(r&&t.push(`@media ${r[0]} has no native meaning - only the width guard is honoured`),n||s){let i={};return n&&(i.min=Number(n[1])),s&&(i.max=Number(s[1])),i}return t.push(`@media "${e.slice(0,44)}" has no min/max-width guard - the rule is applied at every width`),{}}function oc(e,t){if(e.tag&&e.tag!==t.tag||e.id&&e.id!==t.id)return!1;for(let n of e.classes)if(!t.classes.includes(n))return!1;for(let n of e.attrs){let s=n.name==="class"?t.classes.join(" "):n.name==="id"?t.id??"":"";if(n.name!=="class"&&n.name!=="id")return!1;let r=s.toLowerCase();if(n.op==="="&&r!==n.value||n.op==="~="&&!r.split(/\s+/).includes(n.value)||n.op==="*="&&!r.includes(n.value)||n.op==="^="&&!r.startsWith(n.value)||n.op==="$="&&!r.endsWith(n.value))return!1}return!0}function gb(e,t,n){let s=e.parts;if(!s.length||!oc(s[s.length-1],t))return!1;if(s.length===1)return!0;let r=n.length-1;for(let i=s.length-2;i>=0;i--){if((e.combinators[i]??"descendant")==="child"){if(r<0||!oc(s[i],n[r]))return!1;r--;continue}for(;r>=0&&!oc(s[i],n[r]);)r--;if(r<0)return!1;r--}return!0}function yb(e){let t=mb[e];return t?{...t}:null}function fe(e,t){if(!e)return{...t??{}};if(!t)return{...e};let n={...e};for(let s of Object.keys(t)){let r=t[s];r!==void 0&&(n[s]=r)}return n}function rt(e,t,n=[],s={}){let r=s.viewport??0,i=e.rules.filter(u=>u.media&&(u.media.min!==void 0||u.media.max!==void 0)&&(r<=0||u.media.min!==void 0&&r<u.media.min||u.media.max!==void 0&&r>u.media.max)?!1:gb(u,t,n));i.sort((u,l)=>u.specificity-l.specificity||u.order-l.order);let o=yb(t.tag)??{},a=null,c=null,d=null;for(let u of i)o=fe(o,u.model),u.hover&&(a=fe(a,u.hover)),u.focus&&(c=fe(c,u.focus)),u.active&&(d=fe(d,u.active));return{model:o,hover:a,focus:c,active:d}}function da(e){let t={};for(let n of Xr(e))cc(t,n.prop,n.value);return t}function ir(e,t,n=bb){return e?.direction?e.direction:pa(e)||n.has(t.toLowerCase())?"row":"column"}function pa(e){return e?e.display==="flex"||e.direction!==void 0||e.justify!==void 0||e.align!==void 0||e.wrap!==void 0||e.gap!==void 0:!1}function bt(e){let t=[],n=[],s=[],r=null,i=[],o=null,a=d=>{let u=ib(d);t.push(...u.statics),n.push(...u.dynamic)};for(let d of e.attrs){let u=d.name.toLowerCase();if(u==="class"){if(d.value.kind==="text")t.push(...(d.value.text??"").split(/\s+/).filter(Boolean));else if(d.value.kind==="expr")a(d.value.code??"");else if(d.value.kind==="mixed"&&d.value.parts){let l="";for(let p of d.value.parts)p.kind==="text"?l+=p.value:(l.trim()&&t.push(...l.split(/\s+/).filter(Boolean)),l="",a(p.value));l.trim()&&t.push(...l.split(/\s+/).filter(Boolean))}continue}if(u.startsWith("class:")){n.push(`(${d.value.kind==="expr"?d.value.code:"false"}) ? '${d.name.slice(6)}' : ''`);continue}if(u==="style"){if(d.value.kind==="text")r=da(d.value.text??""),i=Xr(d.value.text??"").map(l=>`${l.prop}: ${l.value}`);else if(d.value.kind==="expr"){let l=Ki(d.value.code??"");if(l){let p="";for(let f of l){let h=lc(f.value);h===null?s.push({prop:Qi(f.key),code:f.value}):h&&(p+=`${Qi(f.key)}: ${h}; `)}if(p){r=fe(r,da(p));for(let f of Xr(p))i.push(`${f.prop}: ${f.value}`)}}else o=d.value.code??""}else if(d.value.kind==="mixed"&&d.value.parts){let l="";for(let p of d.value.parts)p.kind==="text"&&(l+=p.value);r=da(l),i=Xr(l).map(p=>`${p.prop}: ${p.value}`)}continue}if(u.startsWith("style:")){let l=d.name.slice(6);d.value.kind==="expr"?s.push({prop:l,code:d.value.code??""}):d.value.kind==="text"&&(r=fe(r,da(`${l}: ${d.value.text}`)));continue}}let c=n.length>0||s.length>0;return{staticClasses:t,inlineStyle:r,inlineDecls:i,dynamicClassExprs:n,dynamicStyle:s,opaqueStyle:o,hasDynamic:c}}function fa(e,t,n){if(!e.trim())return;let s=e;for(;;){let i=s.search(/@supports\b/);if(i<0)break;let o=s.indexOf("{",i);if(o<0){s=s.slice(0,i);break}let a=1,c=o+1;for(;c<s.length&&a>0;)s[c]==="{"?a++:s[c]==="}"&&a--,c++;s=s.slice(0,i)+s.slice(c)}let r=Te(s);for(let i of r.warnings)n.push(`${t}: ${i}`);for(let i of r.rules){if(i.media){n.push(`${t}: "${i.selector}" is behind a @media guard - this target honours no width guard, the rule is dropped or applied unconditionally`);continue}if(i.hover!==void 0||i.parts.some(o=>o.unsupported.includes(":hover"))){n.push(`${t}: selector "${i.selector}" has a :hover half - this target has no hover state, the rule is dropped`);continue}/^\.([\w-]+)$/.test(i.selector.trim())||n.push(`${t}: selector "${i.selector}" is not a single class - only .class rules compile here, the rule is dropped`)}for(let i of e.matchAll(/@(?:-[\w]+-)?keyframes\s+([\w-]+)/g))n.push(`${t}: @keyframes "${i[1]}" - this target has no CSS animation, the keyframes are dropped`);/@supports\b/.test(e)&&n.push(`${t}: an @supports block has no feature tests here - it is dropped`)}function Tt(e){return e?Object.keys(e).length===0:!0}var ob,cb,mb,bb,ks=De(()=>{"use strict";ob={transparent:"#00000000",black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",yellow:"#ffff00",orange:"#ffa500",purple:"#800080",pink:"#ffc0cb",grey:"#808080",gray:"#808080",silver:"#c0c0c0",gold:"#ffd700",navy:"#000080",teal:"#008080",olive:"#808000",maroon:"#800000",aqua:"#00ffff",lime:"#00ff00",cyan:"#00ffff",magenta:"#ff00ff",brown:"#a52a2a",crimson:"#dc143c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",violet:"#ee82ee",indigo:"#4b0082",khaki:"#f0e68c",lavender:"#e6e6fa",beige:"#f5f5dc",ivory:"#fffff0",snow:"#fffafa",mistyrose:"#ffe4e1",seashell:"#fff5ee",skyblue:"#87ceeb",slategray:"#708099",darkgreen:"#006400",darkblue:"#00008b",darkred:"#8b0000",darkgray:"#a9a9a9",lightgray:"#d3d3d3",lightblue:"#add8e6",lightgreen:"#90ee90",lightyellow:"#ffffe0",dimgray:"#696969",whitesmoke:"#f5f5f5",ghostwhite:"#f8f8ff",floralwhite:"#fffaf0",honeydew:"#f0fff0",mintcream:"#f5fffa",aliceblue:"#f0f8ff",azure:"#f0ffff",bisque:"#ffe4c4",burlywood:"#deb887",chartreuse:"#7fff00",chocolate:"#d2691e",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",gainsboro:"#dcdcdc",hotpink:"#ff69b4",indianred:"#cd5c5c",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",mediumblue:"#0000cd",mediumseagreen:"#3cb371",midnightblue:"#191970",orchid:"#da70d6",palegreen:"#98fb98",peachpuff:"#ffdab9",peru:"#cd853f",plum:"#dda0dd",royalblue:"#4169e1",saddlebrown:"#8b4513",sandybrown:"#f4a460",seagreen:"#2e8b57",sienna:"#a0522d",steelblue:"#4682b4",tan:"#d2b48c",thistle:"#d8bfd8",turquoise:"#40e0d0",wheat:"#f5deb3",yellowgreen:"#9acd32",rebeccapurple:"#663399"};cb=/^([A-Za-z][\w-]*|\*)?((?:[.#][\w-]+)*)((?:\[[^\]]+\])*)/;mb={h1:{fontSize:32,fontWeight:700},h2:{fontSize:24,fontWeight:700},h3:{fontSize:19,fontWeight:700},h4:{fontSize:16,fontWeight:700},h5:{fontSize:13,fontWeight:700},h6:{fontSize:11,fontWeight:700}};bb=new Set});function wb(e){return $b[e]}function xt(e){let t=new Set;for(let n of e)if(!(!n||!n.includes("useNative")))for(let s of n.matchAll(/(^|[^\w$.])useNative\s*\(\s*(['"])([^'"]*)\2/g))t.add(s[3]);return xp.filter(n=>t.has(n))}function kp(e,t){let n=uc[e].dependencies??{},s=[];for(let r of t){let i=n[r];i&&!s.includes(i)&&s.push(i)}return s}function ha(e,t){let n=uc[e].manifest??{},s=[];for(let r of t)for(let i of n[r]??[])s.includes(i)||s.push(i);return s}function Dt(e,t){let n=(e??"").trim();if(!n)return"{}";let s=n.match(/^\{([\s\S]*)\}$/);if(!s)return null;let r=[];for(let i of s[1].split(",")){let o=i.trim();if(!o)continue;let a=o.match(/^([A-Za-z_$][\w$]*)\s*:\s*([\s\S]+)$/);if(!a)return null;let c=t==="quoted"?`'${a[1]}'`:a[1];r.push(`${c}: ${a[2].trim()}`)}return r.length?`{ ${r.join(", ")} }`:"{}"}function vb(e,t){let n=0,s="";for(let r=t;r<e.length;r++){let i=e[r];if(s){i==="\\"?r++:i===s&&(s="");continue}if(i==='"'||i==="'"||i==="`"){s=i;continue}if(i==="("||i==="["||i==="{")n++;else if((i===")"||i==="]"||i==="}")&&(n--,n===0))return r}return-1}function zt(e,t){if(!e||!e.includes("useNative"))return{code:e,used:[]};let n=uc[t.target],s=wb(t.target),r=t.file?`${t.file}: `:"",i=new Set,o="",a=0;for(;;){let c=e.indexOf("useNative",a);if(c<0){o+=e.slice(a);break}if(/[A-Za-z0-9_$.]/.test(e[c-1]??"")){o+=e.slice(a,c+9),a=c+9;continue}let d=c+9;for(;d<e.length&&/\s/.test(e[d]);)d++;if(e[d]!=="("){o+=e.slice(a,c+9),a=c+9;continue}let u=vb(e,d);if(u<0){o+=e.slice(a,c+9),a=c+9;continue}let l=e.slice(d+1,u).trim(),p=l.match(/^(['"])([^'"]*)\1/),f=p?p[2]:"";if(o+=e.slice(a,c),!p||!xp.includes(f))t.warn(`${r}useNative('${f||"\u2026"}') is not a known capability - ${s} emits ${t.empty}`),o+=t.empty;else if(n.capabilities.includes(f)){let h=f;i.add(h);let g=l.slice(p[0].length).replace(/^\s*,\s*/,""),y=t.options(g);y===null&&t.warn(`${r}useNative('${h}') options ${g.trim().slice(0,40)} are not a flat object literal - ${s} uses the platform defaults`),o+=`${n.helper}('${h}', ${y??"{}"})`}else{let h=n.platform[f];t.warn(`${r}useNative('${f}') has no ${s} equivalent${h?` (nearest platform API: ${h})`:""} - emits ${t.empty}`),o+=t.empty}a=u+1}return{code:o,used:[...i]}}var xp,Zi,uc,$b,ls=De(()=>{"use strict";xp=["camera","geolocation","clipboard-read","clipboard-write","share"],Zi=["camera","geolocation","clipboard-read","clipboard-write"],uc={weapp:{helper:"__rosefcNative",capabilities:Zi,platform:{camera:"wx.chooseMedia",geolocation:"wx.getLocation","clipboard-read":"wx.getClipboardData","clipboard-write":"wx.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},qq:{helper:"__rosefcNative",capabilities:Zi,platform:{camera:"qq.chooseMedia",geolocation:"qq.getLocation","clipboard-read":"qq.getClipboardData","clipboard-write":"qq.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},alipay:{helper:"__rosefcNative",capabilities:Zi,platform:{camera:"my.chooseImage",geolocation:"my.getLocation","clipboard-read":"my.getClipboard","clipboard-write":"my.setClipboard"},manifest:{geolocation:["location"]}},baidu:{helper:"__rosefcNative",capabilities:Zi,platform:{camera:"swan.chooseImage",geolocation:"swan.getLocation","clipboard-read":"swan.getClipboardData","clipboard-write":"swan.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},toutiao:{helper:"__rosefcNative",capabilities:Zi,platform:{camera:"tt.chooseImage",geolocation:"tt.getLocation","clipboard-read":"tt.getClipboardData","clipboard-write":"tt.setClipboardData"},manifest:{geolocation:["scope.userLocation"]}},flutter:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],dependencies:{camera:"image_picker",geolocation:"geolocator",share:"share_plus"},platform:{camera:"image_picker",geolocation:"geolocator","clipboard-read":"Clipboard.getData","clipboard-write":"Clipboard.setData",share:"share_plus"}},arkts:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"@ohos.multimedia.camera / photoAccessHelper",geolocation:"@ohos.geoLocationManager","clipboard-read":"@ohos.pasteboard","clipboard-write":"@ohos.pasteboard",share:"@ohos.app.ability.wantAgent"},manifest:{camera:["ohos.permission.CAMERA"],geolocation:["ohos.permission.LOCATION","ohos.permission.APPROXIMATELY_LOCATION"]}},android:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"ActivityResultContracts.TakePicture",geolocation:"FusedLocationProviderClient","clipboard-read":"ClipboardManager","clipboard-write":"ClipboardManager",share:"Intent.ACTION_SEND"}},xcode:{helper:"roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"UIImagePickerController",geolocation:"CLLocationManager","clipboard-read":"UIPasteboard","clipboard-write":"UIPasteboard",share:"UIActivityViewController"}},electron:{helper:"useNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"navigator.mediaDevices.getUserMedia",geolocation:"navigator.geolocation","clipboard-read":"navigator.clipboard.readText","clipboard-write":"navigator.clipboard.writeText",share:"navigator.share"}},python:{helper:"rose_native",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"tkinter.filedialog",geolocation:"no Tk API (an app needs an OS/web location service)","clipboard-read":"tkinter.clipboard_get","clipboard-write":"tkinter.clipboard_append",share:"webbrowser.open"}},dotnet:{helper:"RoseKit.RoseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"OpenFileDialog",geolocation:"GeoCoordinateWatcher (a package - not in the box for net8.0)","clipboard-read":"Clipboard.GetText","clipboard-write":"Clipboard.SetText",share:"Process.Start"}},java:{helper:"RoseKit.roseNative",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"no capture API (java.awt.Robot / third-party webcam lib)",geolocation:"no JDK API (third-party library)","clipboard-read":"Toolkit.getSystemClipboard","clipboard-write":"Toolkit.getSystemClipboard",share:"Desktop.browse"}},cpp:{helper:"rose_native",capabilities:["camera","geolocation","clipboard-read","clipboard-write","share"],platform:{camera:"QFileDialog",geolocation:"QGeoPositionInfoSource","clipboard-read":"QClipboard","clipboard-write":"QClipboard",share:"QDesktopServices::openUrl"}}},$b={weapp:"WeChat",qq:"QQ",alipay:"Alipay",baidu:"Baidu",toutiao:"Douyin",flutter:"Flutter",android:"Android",arkts:"HarmonyOS ArkTS",xcode:"Xcode/SwiftUI",electron:"Electron",python:"Python/Tkinter",dotnet:".NET/WPF",java:"Java/Swing",cpp:"C++/Qt"}});import*as ue from"node:fs";import*as le from"node:path";import{transformSync as Ap}from"esbuild";function zn(e,t){return e.endsWith("-")?`${e}${t}`:`${e}:${t}`}function kb(e,t,n){let s=Cp[e];if(!s)return"";let r=[];s.transform&&r.push(`transform: ${s.transform};`),s.filter&&r.push(`filter: ${s.filter};`),r.push(`opacity: ${s.opacity};`);let i=[];return s.transform&&i.push("transform: none;"),s.filter&&i.push("filter: none;"),i.push("opacity: 1;"),[`@keyframes rf-in-${e} { from { ${r.join(" ")} } to { ${i.join(" ")} } }`,`.rf-in-${e} { animation-name: rf-in-${e}; animation-duration: ${t}ms; animation-delay: ${n}ms; animation-timing-function: ease; animation-fill-mode: both; }`].join(`
|
|
1917
|
+
`)}async function jp(e){let t=wa[e.target],n=e.warnings,s=e.projectRoot,r=le.join(e.outDir,t.dir),i=le.join(s,"src","pages"),o=Mt(s),a=o!==null,[c,d]=await Promise.all([Ye(s),Ke(s)]),u=new Map;for(let v of c){if(le.basename(v)!=="_layout.rose")continue;let _=le.dirname(le.relative(i,v)).replace(/\\/g,"/"),k=Ce(await ue.promises.readFile(v,"utf8"),v,e.target);n.push(...k.warnings),u.set(_==="."?"":_,{file:v,nodes:k.nodes,script:k.script,style:k.style})}let l=[];for(let v of c){let _=le.relative(i,v).replace(/\\/g,"/"),k=_.replace(/\.rose$/,""),S=le.basename(k);if(S==="_layout"||S==="404"||S==="_notfound"||S==="500"||S==="_middleware"||k==="api"||k.startsWith("api/"))continue;let C=Ce(await ue.promises.readFile(v,"utf8"),v,e.target);n.push(...C.warnings);let x=[],A=_.split("/").slice(0,-1);for(let R=A.length;R>=0;R--){let T=u.get(A.slice(0,R).join("/"));T&&x.push(T)}l.push({file:v,route:Tb(k),name:Eb(k),scope:Ob(_),nodes:C.nodes,script:C.script,style:C.style,title:Nb(C.head),layoutChain:x})}let p=[];for(let v of d){let _=Ce(await ue.promises.readFile(v,"utf8"),v,e.target);n.push(..._.warnings),p.push({file:v,name:le.basename(v,".rose"),scope:le.relative(le.join(s,"src","components"),v).replace(/\\/g,"/").replace(/\.rose$/,""),nodes:_.nodes,script:_.script,style:_.style})}await ue.promises.rm(r,{recursive:!0,force:!0}),await ue.promises.mkdir(le.join(r,"utils"),{recursive:!0}),await ue.promises.writeFile(le.join(r,"utils","rosefc.js"),Yb,"utf8");let f=await Cb(s,r,n);f.cloud?e.cloud===void 0&&(e.cloud=!0):e.cloud&&(n.push(`${t.dir}: --cloud requested but the project ships no services/user.js - emitted the plain HTTP bootstrap`),e.cloud=!1),f.cloud&&e.cloud&&n.push(`${t.dir}: shipped the project cloud assets (cloudfunctions/, services/, utils/) - deploy the functions in DevTools before previewing`);let h=le.join(s,"public");if(ue.existsSync(h)){let v=async(_,k)=>{for(let S of await ue.promises.readdir(_,{withFileTypes:!0})){let C=le.join(_,S.name),x=k?k+"/"+S.name:S.name;if(S.isDirectory()){await v(C,x);continue}if(/\.svg$/i.test(S.name)){let R=Wt(await ue.promises.readFile(C,"utf8"));R.shape?pc.set("/"+x,R.shape):n.push(`${t.dir}: ${x} uses ${R.reason??"an unsupported feature"} - skipped`);continue}if(!/\.(png|jpe?g|webp|gif)$/i.test(S.name))continue;let A=le.join(r,x);await ue.promises.mkdir(le.dirname(A),{recursive:!0}),await ue.promises.copyFile(C,A)}};await v(h,"")}let g=new Map,y=new Map;for(let v of p){let _=$a(v.name);g.set(_,`/components/${v.name}/${v.name}`),y.set(v.name,v),await Ib(r,s,t,e.target,v,y,n)}let m={};for(let v of l)m[v.route]=`pages/${v.name}/${v.name}`;let b=new Set;try{let v=le.join(s,"rosefc.mp.json");if(ue.existsSync(v)){let _=JSON.parse((ue.readFileSync(v,"utf8")||"").replace(/^\uFEFF/,""));for(let k of _?.tabBar?.list??[])k&&typeof k.pagePath=="string"&&b.add(k.pagePath)}}catch{}await ue.promises.writeFile(le.join(r,"utils","rosefc-routes.js"),`// Generated by rosefc export: web route -> exported page path (+tab set).
|
|
1918
1918
|
module.exports = `+JSON.stringify(m,null,2)+`;
|
|
1919
1919
|
module.exports.__tabs = `+JSON.stringify([...b])+`;
|
|
1920
1920
|
`,"utf8");let $=[];for(let v of l){let _=Mb(v.nodes,v.layoutChain),k=[v.style,...v.layoutChain.map(S=>S.style)].filter(S=>!!S).join(`
|
|
1921
|
-
`);await Pb(r,s,t,e.target,v,_,k,g,y,n,a),$.push(`pages/${v.name}/${v.name}`)}let w=ha(e.target,xt([...l.map(v=>v.script),...p.map(v=>v.script)]));if(await ue.promises.writeFile(le.join(r,"app.json"),JSON.stringify({pages:$,window:{navigationBarTitleText:"
|
|
1921
|
+
`);await Pb(r,s,t,e.target,v,_,k,g,y,n,a),$.push(`pages/${v.name}/${v.name}`)}let w=ha(e.target,xt([...l.map(v=>v.script),...p.map(v=>v.script)]));if(await ue.promises.writeFile(le.join(r,"app.json"),JSON.stringify({pages:$,window:{navigationBarTitleText:"Rosefc",navigationBarBackgroundColor:"#ffffff",navigationBarTextStyle:"black"},...w.length?{permission:Object.fromEntries(w.map(v=>[v,{desc:"Rosefc uses this to answer a useNative() call"}]))}:{}},null,2)+`
|
|
1922
1922
|
`,"utf8"),a&&(await ue.promises.mkdir(le.join(r,"data"),{recursive:!0}),await ue.promises.writeFile(le.join(r,"data","content.json"),JSON.stringify(o),"utf8")),e.seed&&Object.keys(e.seed).length&&(await ue.promises.mkdir(le.join(r,"data"),{recursive:!0}),await ue.promises.writeFile(le.join(r,"data","seed.json"),JSON.stringify(e.seed),"utf8")),await ue.promises.writeFile(le.join(r,"app."+t.style),Bb+`
|
|
1923
1923
|
`+Lb(ke)+`page { background: #ffffff; }
|
|
1924
|
-
`,"utf8"),e.target==="weapp"){let v="touristappid",_="
|
|
1925
|
-
`,"utf8"),v!=="touristappid"&&n.push(`weapp: project.config.json carries the project's own appid (${v}) - real-device preview and cloud work`)}return await ue.promises.writeFile(le.join(r,"app.js"),Ab(e),"utf8"),await ue.promises.writeFile(le.join(r,"README.md"),jb(e.target,$.length,[...g.keys()].length,e.apiBase??"",e.warnings),"utf8"),{pages:$,components:[...g.keys()]}}function Ab(e){if(e.cloud){let t=e.cloudEnv?JSON.stringify(e.cloudEnv):"wx.cloud.DYNAMIC_CURRENT_ENV";return["// WeChat Cloud Development bootstrap + auto login (original app.js contract).","const userService = require('./services/user');","","App({"," globalData: {"," cloudEnvId: "+(e.cloudEnv?JSON.stringify(e.cloudEnv):"''")+","," isLogin: false,"," userInfo: null,"," },",""," onLaunch() {"," this.initCloud();"," this.autoLogin()"," .then((u) => console.log('auto login ok', u && u.nickName))"," .catch((err) => console.log('auto login failed', err));"," },",""," initCloud() {"," if (!wx.cloud) {",' console.error("base library too old for cloud (need 2.2.3+)");'," return;"," }"," wx.cloud.init({"," env: "+t+","," traceUser: true,"," });"," },",""," autoLogin() {"," const cached = wx.getStorageSync('userInfo');"," return userService.getCurrentUser()"," .then((user) => user || userService.createUser())"," .catch((err) => {"," if (cached && cached._id) return cached;"," throw err;"," })"," .then((user) => {"," wx.setStorageSync('userInfo', user);"," this.globalData.isLogin = true;"," this.globalData.userInfo = user;"," return user;"," });"," },",""," getUserInfo(options) {"," options = options || {};"," if (options.refresh) {"," wx.removeStorageSync('userInfo');"," return this.autoLogin();"," }"," if (this.globalData.isLogin && this.globalData.userInfo) {"," return Promise.resolve(this.globalData.userInfo);"," }"," return this.autoLogin();"," },",""," setUserInfo(userInfo) {"," this.globalData.userInfo = userInfo;"," this.globalData.isLogin = true;"," wx.setStorageSync('userInfo', userInfo);"," },",""," logout() {"," wx.removeStorageSync('userInfo');"," this.globalData.isLogin = false;"," this.globalData.userInfo = null;"," },","});","","const { setApiBase } = require('./utils/
|
|
1926
|
-
`)}return["const { setApiBase } = require('./utils/
|
|
1927
|
-
`)}async function Cb(e,t,n){let s=le.join(e,"cloudfunctions"),r=le.join(e,"services"),i=le.join(e,"utils"),o=ue.existsSync(le.join(e,"services","user.js"));if(ue.existsSync(s)&&await ue.promises.cp(s,le.join(t,"cloudfunctions"),{recursive:!0}),ue.existsSync(r)&&await ue.promises.cp(r,le.join(t,"services"),{recursive:!0}),ue.existsSync(i))for(let c of await ue.promises.readdir(i,{withFileTypes:!0})){if(c.name==="
|
|
1924
|
+
`,"utf8"),e.target==="weapp"){let v="touristappid",_="rosefc-export",k="",S=C=>{try{if(!ue.existsSync(C))return;let x=(ue.readFileSync(C,"utf8")||"").replace(/^\uFEFF/,""),A=JSON.parse(x);typeof A.appid=="string"&&/^wx[0-9a-f]{16}$/i.test(A.appid)&&(v=A.appid),typeof A.projectname=="string"&&A.projectname.trim()&&(_=A.projectname.trim()),typeof A.cloudEnv=="string"&&A.cloudEnv.trim()&&(k=A.cloudEnv.trim())}catch{}};S(le.join(s,"project.config.json")),S(le.join(s,"project.private.config.json"));try{let C=le.join(s,"rosefc.mp.json");if(ue.existsSync(C)){let x=JSON.parse((ue.readFileSync(C,"utf8")||"").replace(/^\uFEFF/,""));typeof x.appid=="string"&&/^wx[0-9a-f]{16}$/i.test(x.appid)&&(v=x.appid),typeof x.projectname=="string"&&x.projectname.trim()&&(_=x.projectname.trim()),typeof x.cloudEnv=="string"&&x.cloudEnv.trim()&&(k=x.cloudEnv.trim())}}catch{}k&&!e.cloudEnv&&(e.cloudEnv=k),await ue.promises.writeFile(le.join(r,"project.config.json"),JSON.stringify({description:"Rosefc - exported mini program",compileType:"miniprogram",miniprogramRoot:"./",setting:{urlCheck:!1,es6:!0,postcss:!0,minified:!0},...e.cloud?{cloudfunctionRoot:"cloudfunctions/"}:{},appid:v,projectname:_},null,2)+`
|
|
1925
|
+
`,"utf8"),v!=="touristappid"&&n.push(`weapp: project.config.json carries the project's own appid (${v}) - real-device preview and cloud work`)}return await ue.promises.writeFile(le.join(r,"app.js"),Ab(e),"utf8"),await ue.promises.writeFile(le.join(r,"README.md"),jb(e.target,$.length,[...g.keys()].length,e.apiBase??"",e.warnings),"utf8"),{pages:$,components:[...g.keys()]}}function Ab(e){if(e.cloud){let t=e.cloudEnv?JSON.stringify(e.cloudEnv):"wx.cloud.DYNAMIC_CURRENT_ENV";return["// WeChat Cloud Development bootstrap + auto login (original app.js contract).","const userService = require('./services/user');","","App({"," globalData: {"," cloudEnvId: "+(e.cloudEnv?JSON.stringify(e.cloudEnv):"''")+","," isLogin: false,"," userInfo: null,"," },",""," onLaunch() {"," this.initCloud();"," this.autoLogin()"," .then((u) => console.log('auto login ok', u && u.nickName))"," .catch((err) => console.log('auto login failed', err));"," },",""," initCloud() {"," if (!wx.cloud) {",' console.error("base library too old for cloud (need 2.2.3+)");'," return;"," }"," wx.cloud.init({"," env: "+t+","," traceUser: true,"," });"," },",""," autoLogin() {"," const cached = wx.getStorageSync('userInfo');"," return userService.getCurrentUser()"," .then((user) => user || userService.createUser())"," .catch((err) => {"," if (cached && cached._id) return cached;"," throw err;"," })"," .then((user) => {"," wx.setStorageSync('userInfo', user);"," this.globalData.isLogin = true;"," this.globalData.userInfo = user;"," return user;"," });"," },",""," getUserInfo(options) {"," options = options || {};"," if (options.refresh) {"," wx.removeStorageSync('userInfo');"," return this.autoLogin();"," }"," if (this.globalData.isLogin && this.globalData.userInfo) {"," return Promise.resolve(this.globalData.userInfo);"," }"," return this.autoLogin();"," },",""," setUserInfo(userInfo) {"," this.globalData.userInfo = userInfo;"," this.globalData.isLogin = true;"," wx.setStorageSync('userInfo', userInfo);"," },",""," logout() {"," wx.removeStorageSync('userInfo');"," this.globalData.isLogin = false;"," this.globalData.userInfo = null;"," },","});","","const { setApiBase } = require('./utils/rosefc.js');","setApiBase("+JSON.stringify(e.apiBase||"")+");",""].join(`
|
|
1926
|
+
`)}return["const { setApiBase } = require('./utils/rosefc.js');","","setApiBase("+JSON.stringify(e.apiBase||"")+");","","App({});",""].join(`
|
|
1927
|
+
`)}async function Cb(e,t,n){let s=le.join(e,"cloudfunctions"),r=le.join(e,"services"),i=le.join(e,"utils"),o=ue.existsSync(le.join(e,"services","user.js"));if(ue.existsSync(s)&&await ue.promises.cp(s,le.join(t,"cloudfunctions"),{recursive:!0}),ue.existsSync(r)&&await ue.promises.cp(r,le.join(t,"services"),{recursive:!0}),ue.existsSync(i))for(let c of await ue.promises.readdir(i,{withFileTypes:!0})){if(c.name==="rosefc.js")continue;let d=le.join(i,c.name),u=le.join(t,"utils",c.name);c.isDirectory()?await ue.promises.cp(d,u,{recursive:!0}):await ue.promises.copyFile(d,u)}let a=le.join(e,"src");if(ue.existsSync(a)){let c=async(d,u)=>{for(let l of await ue.promises.readdir(d,{withFileTypes:!0})){if(l.name==="node_modules"||l.name.startsWith("."))continue;let p=le.join(d,l.name),f=u?u+"/"+l.name:l.name;if(l.isDirectory()){await c(p,f);continue}let h=le.join(t,"src",f);if(await ue.promises.mkdir(le.dirname(h),{recursive:!0}),l.name.endsWith(".ts")){let g=await ue.promises.readFile(p,"utf8");try{let y=Ap(g,{loader:"ts",format:"cjs",target:"es2020"}).code;if(!/\bmodule\.exports\b/.test(y)){let m=[...g.matchAll(/^export\s+(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/gm)].map(b=>b[1]);m.length&&(y+=`
|
|
1928
1928
|
module.exports = { `+m.join(", ")+` };
|
|
1929
|
-
`)}await ue.promises.writeFile(h.replace(/[.]ts$/,".js"),y,"utf8")}catch(y){n.push("src/"+f+" did not transpile ("+(y instanceof Error?y.message:String(y))+")")}}else/[.](js|cjs|json|wxml|wxss|png|jpe?g|svg)$/i.test(l.name)&&await ue.promises.copyFile(p,h)}};await c(a,"")}return{cloud:o}}function jb(e,t,n,s,r){let i=e==="weapp"?"WeChat DevTools":e==="qq"?"QQ DevTools":e==="alipay"?"Alipay DevTools":e==="baidu"?"Baidu DevTools":"ByteDance DevTools",o=wa[e].tpl;return`#
|
|
1929
|
+
`)}await ue.promises.writeFile(h.replace(/[.]ts$/,".js"),y,"utf8")}catch(y){n.push("src/"+f+" did not transpile ("+(y instanceof Error?y.message:String(y))+")")}}else/[.](js|cjs|json|wxml|wxss|png|jpe?g|svg)$/i.test(l.name)&&await ue.promises.copyFile(p,h)}};await c(a,"")}return{cloud:o}}function jb(e,t,n,s,r){let i=e==="weapp"?"WeChat DevTools":e==="qq"?"QQ DevTools":e==="alipay"?"Alipay DevTools":e==="baidu"?"Baidu DevTools":"ByteDance DevTools",o=wa[e].tpl;return`# Rosefc -> ${e} mini-program
|
|
1930
1930
|
|
|
1931
|
-
Generated by \`
|
|
1931
|
+
Generated by \`rosefc export ${e}\` from the project's \`.rose\` pages.
|
|
1932
1932
|
|
|
1933
1933
|
- ${t} page(s), ${n} component(s)
|
|
1934
1934
|
- Open this folder in ${i} and preview on a device/simulator
|
|
1935
|
-
- Server: \`
|
|
1936
|
-
\`utils/
|
|
1935
|
+
- Server: \`rosefc export ${e} --api <base>\` writes the base URL into
|
|
1936
|
+
\`utils/rosefc.js\`. Current: \`${s||"(unset)"}\`
|
|
1937
1937
|
|
|
1938
|
-
A page is one .${o} + .js + .json trio; the runtime kit in \`utils/
|
|
1938
|
+
A page is one .${o} + .js + .json trio; the runtime kit in \`utils/rosefc.js\`
|
|
1939
1939
|
speaks the same data channel and server-action protocol as the web build, and a
|
|
1940
1940
|
page's \`$persist\` / \`$kv\` fields are backed by the platform's storage.
|
|
1941
|
-
${Nt(r)}`}function Tb(e){return"/"+e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n).join("/")}function Eb(e){return e.split("/").map(t=>t==="index"?"index":t.startsWith("[")&&t.endsWith("]")?"param-"+t.slice(1,-1).replace(/[^\w]/g,""):t.replace(/[^\w-]/g,"-")).join("-")}function Ob(e){return e.replace(/\.rose$/,"")}function Nb(e){if(!e)return"";let t=/<title>([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/\{[^}]*\}/g,"").trim():""}function Mb(e,t){let n=e;for(let s of t)n=Fb(s.nodes,n);return n}function Fb(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"&&!r.attrs.some(i=>i.name==="name")?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}function Tp(e,t,n){let s={state:[],actions:[]};if(!e)return s;for(let i of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|derived|data|kv|persist)\b(?:<[^>]*>)?\s*\(/g))s.state.push({name:i[1],kind:i[2]});try{s.actions=Qe(e).actions.map(i=>i.name)}catch{}s.actions.length&&t.push(`${n}: ${s.actions.length} server action(s) become HTTP calls: ${s.actions.join(", ")}`);let r=s.state.filter(i=>i.kind==="data");return r.length&&t.push(`${n}: ${r.length} $data field(s) start null and load from GET /
|
|
1941
|
+
${Nt(r)}`}function Tb(e){return"/"+e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n).join("/")}function Eb(e){return e.split("/").map(t=>t==="index"?"index":t.startsWith("[")&&t.endsWith("]")?"param-"+t.slice(1,-1).replace(/[^\w]/g,""):t.replace(/[^\w-]/g,"-")).join("-")}function Ob(e){return e.replace(/\.rose$/,"")}function Nb(e){if(!e)return"";let t=/<title>([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/\{[^}]*\}/g,"").trim():""}function Mb(e,t){let n=e;for(let s of t)n=Fb(s.nodes,n);return n}function Fb(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"&&!r.attrs.some(i=>i.name==="name")?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}function Tp(e,t,n){let s={state:[],actions:[]};if(!e)return s;for(let i of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|derived|data|kv|persist)\b(?:<[^>]*>)?\s*\(/g))s.state.push({name:i[1],kind:i[2]});try{s.actions=Qe(e).actions.map(i=>i.name)}catch{}s.actions.length&&t.push(`${n}: ${s.actions.length} server action(s) become HTTP calls: ${s.actions.join(", ")}`);let r=s.state.filter(i=>i.kind==="data");return r.length&&t.push(`${n}: ${r.length} $data field(s) start null and load from GET /__rosefc/data (${r.map(i=>i.name).join(", ")})`),s}async function Pb(e,t,n,s,r,i,o,a,c,d,u){let l=le.join(e,"pages",r.name);await ue.promises.mkdir(l,{recursive:!0});let f=[...[...r.layoutChain].reverse().map(_=>_.script).filter(_=>!!_),r.script??""].filter(_=>_.trim()).join(`
|
|
1942
1942
|
`),h=Tp(f,d,r.file),g=new ya(d,r.file);g.target=s,g.stateNames=new Set(h.state.map(_=>_.name)),g.pageAction=h.actions[0]??null,g.contentBaked=u,g.scriptConsts=_t(r.script,g.stateNames);for(let _ of(o??"").matchAll(/([.\w-]+):hover\b/g))g.hoverSelectors.add(_[1]);for(let _ of(o??"").matchAll(/([.\w-]+):active\b/g))g.hoverSelectors.add(_[1]);let y=mn(i,g,n,a,c),m={};for(let _ of g.usedComponents){let k=a.get(_);k?m[_]=k:g.warnings.push(`${g.file}: <${_}> is used but no exported component provides it`)}let b=`<view class="${va(r.scope)}">
|
|
1943
1943
|
${y}
|
|
1944
1944
|
</view>`;await ue.promises.writeFile(le.join(l,r.name+"."+n.tpl),b+`
|
|
@@ -1955,9 +1955,9 @@ ${l}
|
|
|
1955
1955
|
</view>`;await ue.promises.writeFile(le.join(a,r.name+"."+n.tpl),f+`
|
|
1956
1956
|
`,"utf8"),await ue.promises.writeFile(le.join(a,r.name+".json"),JSON.stringify({component:!0},null,2)+`
|
|
1957
1957
|
`,"utf8"),await ue.promises.writeFile(le.join(a,r.name+"."+n.style),Np(hc(r.style??"",r.scope),t,o,r.file),"utf8");let h=p.map(S=>`${S.name}: ${Wb(S.init)}`).join(`,
|
|
1958
|
-
`),g=new Set(d.state.map(S=>S.name)),y=[];for(let S of d.state){if(S.kind==="derived"||S.kind==="data"){y.push(` ${S.name}: null,`);continue}let C=ma(r.script??"",S.name,S.kind);Op(C)?y.push(` ${S.name}: ${C},`):y.push(` ${S.name}: null,`)}for(let S of c.awaits)y.push(` ${S.done}: false,`,` ${S.value}: null,`,` ${S.err}: null,`,` ${S.failed}: false,`);for(let S of c.boundaryFlags)y.push(` ${S.field}: true,`);for(let S of c.deferred)y.push(` ${S.name}: false,`);let m=[...c.inlineHandlers.entries()].map(([S,C])=>{let x=jt(S,Mp(g),g);if(x.reason||!x.stmts.length)return c.warnings.push(`${c.file}: an inline handler (${S.slice(0,40)}...) is not translated (${x.reason??"empty"})`),` function ${C}(e) { /*
|
|
1959
|
-
`)}return S.trigger?` ${S.name}: function (e) { this.setData({ ${S.state}: e.detail.value }); this.triggerEvent(${JSON.stringify(S.trigger)}, e.detail.value); },`:S.kind==="value"||S.kind==="radio"?` ${S.name}: function (e) { this.__set(${JSON.stringify(S.state)}, e.detail.value); },`:` ${S.name}: function (e) {},`}),...[...c.namedHandlers.values()].map(S=>` ${S}: function (e) { return this.
|
|
1960
|
-
`);await ue.promises.writeFile(le.join(a,r.name+"."+n.js),[v,"","Component({"," properties: {",` ${h}`," },"," data: {",...y," },"," lifetimes: {"," attached() {"," this.
|
|
1958
|
+
`),g=new Set(d.state.map(S=>S.name)),y=[];for(let S of d.state){if(S.kind==="derived"||S.kind==="data"){y.push(` ${S.name}: null,`);continue}let C=ma(r.script??"",S.name,S.kind);Op(C)?y.push(` ${S.name}: ${C},`):y.push(` ${S.name}: null,`)}for(let S of c.awaits)y.push(` ${S.done}: false,`,` ${S.value}: null,`,` ${S.err}: null,`,` ${S.failed}: false,`);for(let S of c.boundaryFlags)y.push(` ${S.field}: true,`);for(let S of c.deferred)y.push(` ${S.name}: false,`);let m=[...c.inlineHandlers.entries()].map(([S,C])=>{let x=jt(S,Mp(g),g);if(x.reason||!x.stmts.length)return c.warnings.push(`${c.file}: an inline handler (${S.slice(0,40)}...) is not translated (${x.reason??"empty"})`),` function ${C}(e) { /* rosefc: handler not translated */ }`;let R=(c.inlineLoops.get(C)??[]).length?" const __ds = __domEvent(e).target.dataset || {}; const __loop = function (n) { return __ds[n]; };":"";return` function ${C}(e) {${R} return ((${x.params.join(", ")}) => { ${x.stmts.map(T=>`${T};`).join(" ")} })(__domEvent(e)); }`}),b=[...c.namedHandlers.entries()].map(([S,C])=>` function ${C}(e) { return ${S}(__domEvent(e)); }`),{body:$}=await Fp(r.script??"",d,c),w=["__rosefcNative","__rosefcConfirm","__rosefcAlert","__rosefcPrompt","__rosefcOpen"].filter(S=>new RegExp(`\\b${S}\\s*\\(`).test($)),v=`const { roseThrow, getApiBase${w.length?", "+w.join(", "):""} } = require('../../utils/rosefc.js');`,_=[" const __comp = this;"," const state = this.data;"," const __computed = {};"," const __effects = [];"," const __setState = function (k, v) { __comp.setData({ [k]: v }); };"," const __set = __setState;"," const __domEvent = function (e) {"," const detail = (e && e.detail) || {};"," const current = (e && e.currentTarget) || {};",' const values = typeof detail.value === "object" && detail.value !== null ? detail.value : { value: detail.value };'," return {"," type: e && e.type,"," detail: detail,"," preventDefault: function () {},"," stopPropagation: function () {},"," target: Object.assign({}, values, { dataset: current.dataset || {} }),"," currentTarget: current,"," };"," };",Pp($.trim(),2),...m,...b,...[...c.computed.entries()].map(([S,C])=>` __computed.${S} = function () { return (${Ar(ei(C,g))}); };`)," return {",...[...c.inlineHandlers.values(),...c.namedHandlers.values()].map(S=>` ${S}: ${S},`)," __computed: __computed,"," __effects: __effects,"," };"],k=[...c.bindHandlers.map(S=>{if(S.trigger&&S.kind==="checkboxBool")return` ${S.name}: function (e) { var v = (e.detail.value || []).length > 0; this.setData({ ${S.state}: v }); this.triggerEvent(${JSON.stringify(S.trigger)}, v); },`;if(S.trigger&&S.kind==="checkboxGroup"){let C=JSON.stringify(S.values??[]);return[` ${S.name}: function (e) {`,` var own = ${C};`,` var cur = this.data.${S.state} || [];`," var next = (e.detail.value || []).concat(cur.filter(function (x) { return own.indexOf(x) === -1; }));",` this.setData({ ${S.state}: next }); this.triggerEvent(${JSON.stringify(S.trigger)}, next);`," },"].join(`
|
|
1959
|
+
`)}return S.trigger?` ${S.name}: function (e) { this.setData({ ${S.state}: e.detail.value }); this.triggerEvent(${JSON.stringify(S.trigger)}, e.detail.value); },`:S.kind==="value"||S.kind==="radio"?` ${S.name}: function (e) { this.__set(${JSON.stringify(S.state)}, e.detail.value); },`:` ${S.name}: function (e) {},`}),...[...c.namedHandlers.values()].map(S=>` ${S}: function (e) { return this.__rosefcDefs.${S}(__domEvent(e)); },`),...[...c.inlineHandlers.values()].map(S=>` ${S}: function (e) { return this.__rosefcDefs.${S}(e); },`)," __rosefcSync() {"," const defs = this.__rosefcDefs || {};"," const computed = defs.__computed || {};"," const patch = {};"," for (const k of Object.keys(computed)) {"," try { patch[k] = computed[k].call(this); } catch (err) { console.warn('rosefc: computed ' + k + ' failed', err); }"," }"," if (Object.keys(patch).length) this.setData(patch);"," },"].join(`
|
|
1960
|
+
`);await ue.promises.writeFile(le.join(a,r.name+"."+n.js),[v,"","Component({"," properties: {",` ${h}`," },"," data: {",...y," },"," lifetimes: {"," attached() {"," this.__rosefcDefs = (function () {",..._," })();"," this.__rosefcSync();"," },"," },"," methods: {",...k.split(`
|
|
1961
1961
|
`)," },","});",""].join(`
|
|
1962
1962
|
`),"utf8")}function Wb(e){let t=e.trim();return t?/^-?\d+(?:\.\d+)?$/.test(t)?`{ type: Number, value: ${t} }`:/^(true|false)$/.test(t)?`{ type: Boolean, value: ${t} }`:/^\[/.test(t)?`{ type: Array, value: ${t} }`:/^\{/.test(t)?`{ type: Object, value: ${t} }`:/^['"\`]/.test(t)?`{ type: String, value: ${t} }`:"{ type: String, value: '' }":"{ type: String, value: '' }"}function Db(e,t,n,s){let r=e.type==="radial"?`c.createRadialGradient(${s(e.x1*t)}, ${s(e.y1*n)}, 0, ${s(e.x2*t)}, ${s(e.y2*n)}, ${s(e.r*t)})`:`c.createLinearGradient(${s(e.x1*t)}, ${s(e.y1*n)}, ${s(e.x2*t)}, ${s(e.y2*n)})`;return` ${e.stops.map(o=>`${r}.addColorStop(${o.offset}, '${o.color}');`).join(`
|
|
1963
1963
|
`)}
|
|
@@ -1982,9 +1982,9 @@ ${a}
|
|
|
1982
1982
|
`);return t.trim()?t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\{\{/g,"{{"):""}function Tn(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<")}function Np(e,t,n,s){let{css:r,skipped:i}=hp(e,le.join(t,"public"));for(let o of i)n.push(`${s}: font-family '${o.family}' could not be inlined (${o.reason}) - the mini-program will render the system default`);return r}function hc(e,t){if(!e.trim())return"";let n="."+va(t),s=c=>{let d=c.trim();if(!d)return d;if(d.startsWith(":global("))return d.replace(/^:global\(([\s\S]*)\)$/,"$1");if(d.startsWith("@")||/^(from|to|\d+%)$/.test(d)||d==="page"||d.startsWith("page ")||d.startsWith("page:"))return d;let l=d.replace(/([.\w-]+):active\b/g,(p,f)=>`${f}.${fc(f)}`).replace(/([.\w-]+):hover\b/g,(p,f)=>`${f}.${ba(f)}`).replace(/(^|[\s>+~,(])(h[1-6]|p|strong|b|em|i|small|code|pre|abbr|cite|q|s|u|sub|sup|mark|time|label|ul|ol|li|dl|dt|dd|blockquote|hr|section|main|article|header|footer|nav|aside|figure|figcaption|details|summary|fieldset|legend)\b(?![\w-])/g,(p,f,h)=>`${f}.rose-${h}`);return`${n} ${l}`},r=e.replace(/\/\*[\s\S]*?\*\//g,""),i=[],o="",a=0;for(;a<r.length;){let c=r[a];if(c==="{"){let d=1,u=a+1;for(;u<r.length&&d>0;)r[u]==="{"?d++:r[u]==="}"&&d--,u++;let l=r.slice(a+1,d>0?u:u-1),p=o.trim();if(o="",p.startsWith("@")){let f=/^@(?:-[\w]+-)?keyframes\b/.test(p)||/^@font-face\b/.test(p);i.push(`${p} {${f?l:hc(l,t).trimEnd()}}`)}else if(p){let f=l.replace(/(-?[\d.]+)rem\b/g,(h,g)=>`${Math.round(Number(g)*16*10)/10}px`);i.push(`${p.split(",").map(s).join(", ")} {${f}}`)}a=u;continue}c==="}"?o="":c!==`
|
|
1983
1983
|
`&&c!=="\r"&&(o+=c),a++}return i.length?i.join(`
|
|
1984
1984
|
`)+`
|
|
1985
|
-
`:""}function va(e){return"rose-"+e.replace(/[^\w-]/g,"-")}async function Kb(e,t,n,s,r){let i=new Set(t.state.map(x=>x.name)),o=/function\s+onPullDownRefresh/.test(s),a=t.state.filter(x=>x.kind==="persist").map(x=>x.name),c=$s(s).filter(x=>i.has(x.name)),d=[],u=[];for(let x of t.state){if(x.kind==="derived"){d.push(` ${x.name}: null,`);continue}if(x.kind==="data"){d.push(` ${x.name}: null,`);continue}let A=ma(s,x.name,x.kind);Op(A)?d.push(` ${x.name}: ${A},`):(d.push(` ${x.name}: null,`),u.push({name:x.name,init:A}))}for(let x of n.awaits)d.push(` ${x.done}: false,`),d.push(` ${x.value}: null,`),d.push(` ${x.err}: null,`),d.push(` ${x.failed}: false,`);for(let x of n.boundaryFlags)d.push(` ${x.field}: true,`);for(let x of n.deferred)d.push(` ${x.name}: false,`);let l=[];for(let x of t.state){if(x.kind!=="derived")continue;let A=Zb(s,x.name);if(A===null){n.warnings.push(`${n.file}: the $derived '${x.name}' expression could not be read back, so the field stays null on this platform`);continue}l.push(` __computed.${x.name} = function () { return (${Ar(ei(A,i))}); };`)}let p=[...n.computed.entries()].map(([x,A])=>` __computed.${x} = function () { return (${Ar(ei(A,i))}); };`),f=[...l,...p],h=[...n.inlineHandlers.entries()].map(([x,A])=>{let R=jt(x,Mp(i),i);if(R.reason||!R.stmts.length)return n.warnings.push(`${n.file}: an inline handler (${x.slice(0,40)}...) is not translated (${R.reason??"empty"})`),` function ${A}(e) { /*
|
|
1986
|
-
`)})],{body:$,names:w}=await Fp(s,t,n),v=new Set(t.state.map(x=>x.name)),k=Xb($,x=>{let A=ei(Ar(x),v);return Zs(A,R=>v.has(R),(R,T)=>xl(R,T).replace(/^\$setState/,"__setState"))}),S=[...new Set([...w,...n.inlineHandlers.values(),...n.namedHandlers.values()])].map(x=>` ${x}: ${x},`);return[`const { rosePage, roseThrow, getApiBase${n.kitImports.length?", "+n.kitImports.join(", "):""} } = require('../../utils/
|
|
1987
|
-
`)}function ma(e,t,n){if(n==="kv")return"null";let r=new RegExp(`\\b(?:let|const|var)\\s+${Yr(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$${n}\\b(?:<[^>]*>)?\\s*\\(`).exec(e);if(!r)return"null";let i=r.index+r[0].length-1,o=Sa(e,i);if(o<0)return"null";let a=e.slice(i+1,o).trim();return Ar(a)||"null"}function Zb(e,t){let s=new RegExp(`\\b(?:let|const|var)\\s+${Yr(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$derived\\b(?:<[^>]*>)?\\s*\\(`).exec(e);if(!s)return null;let r=s.index+s[0].length-1,i=Sa(e,r);return i<0?null:e.slice(r+1,i).trim()||null}function Xb(e,t){if(!e||!e.includes("$effect"))return e;let n="",s=0;for(;;){let r=e.indexOf("$effect",s);if(r<0){n+=e.slice(s);break}if(/[A-Za-z0-9_$.]/.test(e[r-1]??"")){n+=e.slice(s,r+7),s=r+7;continue}let i=r+7;for(;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]!=="("){n+=e.slice(s,r+7),s=r+7;continue}let o=Sa(e,i);if(o<0){n+=e.slice(s,r+7),s=r+7;continue}let a=e.slice(i+1,o);t&&(a=t(a)),n+=`${e.slice(s,r)}__effects.push(${a})`,s=o+1}return n}function Sa(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return s}return-1}function ei(e,t){let n=e.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(s,r)=>t.has(r)?`state.${r}`:s);return Gt(n,s=>t.has(s),s=>`state.${s}`)}function Mp(e){return{expr:t=>ei(t,e),set:(t,n)=>`__setState('${t}', ${n})`,action:(t,n)=>`__action('${t}'${n?`, ${n}`:""})`,refresh:()=>"__refresh()",refuses:()=>null}}function Ar(e){return e.replace(/\$(?:derived|state|data|kv|persist)\b(?:<[^>]*>)?\s*\(/g,"(").replace(/\$actionPending\s*\(\s*\)/g,"false").replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null").replace(/\$query\s*\(\s*\)/g,"__page.__query").replace(/\$(?:store|cookies|sessionCookie)\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"{}").replace(/\bonMount\s*\(/g,"__mount(").replace(/\bonCleanup\s*\(/g,"__cleanup(").replace(/\brefresh\s*\(\s*\)/g,"__refresh()").replace(/\$setState\s*\(/g,"__setState(").replace(/\$action\s*\(/g,"__action(").replace(/\$t\s*\(/g,"__t(")}async function Fp(e,t,n){if(!e.trim())return{body:"",names:[]};let s=e.replace(/^\s*import\s+([\s\S]*?)\s+from\s*['"](\.[^'"]*)['"]\s*;?\s*$/gm,(o,a,c)=>{let d=String(a).trim(),u="require("+JSON.stringify(c)+")",l=d.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(l)return"const "+l[1]+" = "+u+";";let p=d.match(/^\{([\s\S]*)\}$/);return p?"const {"+p[1].replace(/\bas\s+([A-Za-z_$][\w$]*)/g,": $1")+"} = "+u+";":/^[A-Za-z_$][\w$]*$/.test(d)?"const "+d+" = "+u+";":"const __mod = "+u+";"}).replace(/^\s*import\s+['"]([^'"]*)['"]\s*;?\s*$/gm,(o,a)=>a.startsWith(".")?"require("+JSON.stringify(a)+");":(n.warnings.push(`${n.file}: side-effect import is not resolvable in a mini program - dropped (${a})`),"")).replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,o=>(n.warnings.push(`${n.file}: package import is not resolvable in a mini program - dropped (${o.trim().slice(0,60)})`),""));s=s.replace(/\blocation\.href\s*=\s*([^;\n]+);?/g,"
|
|
1985
|
+
`:""}function va(e){return"rose-"+e.replace(/[^\w-]/g,"-")}async function Kb(e,t,n,s,r){let i=new Set(t.state.map(x=>x.name)),o=/function\s+onPullDownRefresh/.test(s),a=t.state.filter(x=>x.kind==="persist").map(x=>x.name),c=$s(s).filter(x=>i.has(x.name)),d=[],u=[];for(let x of t.state){if(x.kind==="derived"){d.push(` ${x.name}: null,`);continue}if(x.kind==="data"){d.push(` ${x.name}: null,`);continue}let A=ma(s,x.name,x.kind);Op(A)?d.push(` ${x.name}: ${A},`):(d.push(` ${x.name}: null,`),u.push({name:x.name,init:A}))}for(let x of n.awaits)d.push(` ${x.done}: false,`),d.push(` ${x.value}: null,`),d.push(` ${x.err}: null,`),d.push(` ${x.failed}: false,`);for(let x of n.boundaryFlags)d.push(` ${x.field}: true,`);for(let x of n.deferred)d.push(` ${x.name}: false,`);let l=[];for(let x of t.state){if(x.kind!=="derived")continue;let A=Zb(s,x.name);if(A===null){n.warnings.push(`${n.file}: the $derived '${x.name}' expression could not be read back, so the field stays null on this platform`);continue}l.push(` __computed.${x.name} = function () { return (${Ar(ei(A,i))}); };`)}let p=[...n.computed.entries()].map(([x,A])=>` __computed.${x} = function () { return (${Ar(ei(A,i))}); };`),f=[...l,...p],h=[...n.inlineHandlers.entries()].map(([x,A])=>{let R=jt(x,Mp(i),i);if(R.reason||!R.stmts.length)return n.warnings.push(`${n.file}: an inline handler (${x.slice(0,40)}...) is not translated (${R.reason??"empty"})`),` function ${A}(e) { /* rosefc: handler not translated */ }`;let M=(n.inlineLoops.get(A)??[]).length?" const __ds = __domEvent(e).target.dataset || {}; const __loop = function (n) { return __ds[n]; };":"";return` function ${A}(e) {${M} return ((${R.params.join(", ")}) => { ${R.stmts.map(F=>`${F};`).join(" ")} })(__domEvent(e)); }`}),g=[...n.namedHandlers.entries()].map(([x,A])=>` function ${A}(e) { return ${x}(__domEvent(e)); }`),y=u.map(x=>` __data[${JSON.stringify(x.name)}] = (${x.init});`);for(let[x,A]of n.pickers){let R=ma(s,x,"state"),T=A.values.findIndex(M=>R.includes("'"+M+"'")||R.includes('"'+M+'"'));d.push(" __sel_"+x+": "+(T>0?T:0)+",")}for(let[x,A]of n.groupOptions){let R=ma(s,x,"state").replace(/^\[/,"").replace(/\]$/,"");for(let T of A){let M=R.includes("'"+T+"'")||R.includes('"'+T+'"');d.push(" __"+x+"_"+T.replace(/[^A-Za-z0-9]/g,"_")+": "+(M?"true":"false")+",")}}let b=[...n.propChanges.map(x=>` ${x.name}: function (e) { this.__set(${JSON.stringify(x.state)}, e.detail); },`),...n.bindHandlers.map(x=>{if(x.kind==="formGet")return` ${x.name}: function (e) { __rosefcNavigate(${JSON.stringify(x.action??"")}, (e && e.detail && e.detail.value) || {}); },`;if(x.trigger)return` ${x.name}: function (e) { this.setData({ ${x.state}: e.detail.value }); this.triggerEvent(${JSON.stringify(x.trigger)}, e.detail.value); },`;if(x.kind==="value")return` ${x.name}: function (e) { this.__set(${JSON.stringify(x.state)}, e.detail.value); },`;if(x.kind==="radio")return` ${x.name}: function (e) { this.__set(${JSON.stringify(x.state)}, e.detail.value); },`;if(x.kind==="picker")return` ${x.name}: function (e) { var index = Number(e.detail.value) || 0; this.__set(${JSON.stringify(x.state)}, ${JSON.stringify(x.values)}[index]); this.setData({ __sel_${x.state}: index }); },`;if(x.kind==="checkboxBool")return` ${x.name}: function (e) { this.__set(${JSON.stringify(x.state)}, (e.detail.value || []).length > 0); },`;let A=JSON.stringify(x.values??[]);return[` ${x.name}: function (e) {`," var next = e.detail.value || [];",` this.__set(${JSON.stringify(x.state)}, next);`,` ${A}.forEach(function () {});`," var flags = {};",` ${A}.forEach(function (value) { flags['__' + ${JSON.stringify(x.state)} + '_' + String(value).replace(/[^A-Za-z0-9]/g, '_')] = next.indexOf(value) !== -1; });`," this.setData(flags);"," },"].join(`
|
|
1986
|
+
`)})],{body:$,names:w}=await Fp(s,t,n),v=new Set(t.state.map(x=>x.name)),k=Xb($,x=>{let A=ei(Ar(x),v);return Zs(A,R=>v.has(R),(R,T)=>xl(R,T).replace(/^\$setState/,"__setState"))}),S=[...new Set([...w,...n.inlineHandlers.values(),...n.namedHandlers.values()])].map(x=>` ${x}: ${x},`);return[`const { rosePage, roseThrow, getApiBase${n.kitImports.length?", "+n.kitImports.join(", "):""} } = require('../../utils/rosefc.js');`,...r?["const __content = require('../../data/content.json');"]:[],"","// The .rose <script> block, transformed: state declarations became `data`,","// state getters became `state.x` reads, setters became setData calls.","const definitions = function () {"," const state = this.data;"," const __page = this;"," const __computed = {};"," const __effects = [];"," const __data = {};"," const __setState = function (k, v) { __page.__set(k, v); };"," const __set = __setState;"," const __action = function (n, e) { return __page.__runAction(n, e); };"," var __ROUTES = require('../../utils/rosefc-routes.js');"," const __rosefcNavigate = function (target, fields) {"," var q = Object.keys(fields || {}).filter(function (k) { return fields[k] !== undefined && fields[k] !== null && fields[k] !== ''; })"," .map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(String(fields[k])); }).join('&');"," var url = q ? target + (target.indexOf('?') === -1 ? '?' : '&') + q : target;"," var api = (typeof wx !== 'undefined' && wx.navigateTo) ? wx"," : (typeof my !== 'undefined' && my.navigateTo) ? my"," : (typeof swan !== 'undefined' && swan.navigateTo) ? swan"," : (typeof tt !== 'undefined' && tt.navigateTo) ? tt : null;"," if (!api) return;"," // Web-shaped target -> package path: /postDetail/p1 matches the"," // /postDetail/:id pattern in the route table and lands on"," // pages/postDetail-param-id/postDetail-param-id?id=p1. Static routes"," // pass through unchanged. Without this the three-step degrade (navigateTo"," // -> switchTab -> reLaunch) fails three times on a package path that does"," // not exist and the tap does nothing at all."," if (target.charAt(0) === '/' && target.indexOf('.html') < 0 && !/^\\/pages\\//.test(target)) {"," var pathOnly = target.split('?')[0];"," var query = target.indexOf('?') >= 0 ? target.slice(target.indexOf('?') + 1) : '';"," var best = null;"," var segParams = null;"," for (var pattern in __ROUTES) {"," var pp = pattern.split('/');"," var tp = pathOnly.split('/');"," if (pp.length !== tp.length) continue;"," var ok = true;"," var segs = [];"," for (var i = 0; i < pp.length; i++) {"," if (pp[i].charAt(0) === ':') { segs.push([pp[i].slice(1), tp[i]]); continue; }"," if (pp[i] !== tp[i]) { ok = false; break; }"," }"," if (ok) { best = __ROUTES[pattern]; segParams = segs; break; }"," }"," if (best) {"," // Dynamic segments ride as query params: /postDetail/p1 becomes"," // ?id=p1, and the kit seeds state.id from options in onLoad. Without"," // this the target page opened EMPTY (the param lived only in the"," // path, WeChat only hands launch options the query string) - the"," // tap looked dead even though navigation happened."," var extra = [];"," if (segParams) {"," for (var s = 0; s < segParams.length; s++) {"," extra.push(encodeURIComponent(segParams[s][0]) + '=' + encodeURIComponent(segParams[s][1]));"," }"," }"," var qsAll = extra.concat(query ? [query] : []);"," url = '/' + best + (qsAll.length ? '?' + qsAll.join('&') : '');"," }"," }",' // A tab page refuses navigateTo ("can not navigateTo a tabbar page"),'," // so the jump degrades: switchTab first (query dropped - the platform"," // contract), then reLaunch as the last resort. Bare-string targets"," // (location.href rewrites) pass as { url }."," // Tab pages go straight to switchTab: a navigateTo at a tabbar page"," // always fails and only litters the console; url here is already the"," // resolved package path, and the tab set is keyed by package path."," var bare = url.split('?')[0];"," var isTab = (__ROUTES.__tabs || []).indexOf(bare.replace(/^\\//, '')) >= 0;"," if (isTab && api.switchTab) {"," api.switchTab({ url: url });"," return;"," }"," api.navigateTo({"," url: url,"," fail: function () {"," api.switchTab ? api.switchTab({ url: url, fail: function () {"," if (api.reLaunch) api.reLaunch({ url: url, fail: function (e) {"," console.warn('[rosefc] navigate failed after 3 steps:', url, e);"," if (api.showToast) api.showToast({ title: '\u9875\u9762\u8DF3\u8F6C\u5931\u8D25', icon: 'none' });"," } }); else {"," console.warn('[rosefc] navigate failed:', url);"," }"," } })"," : (api.reLaunch && api.reLaunch({ url: url }));"," },"," });"," };"," const __mount = function (fn) { __page.__mount(fn); };"," const __cleanup = function (fn) { __page.__cleanup(fn); };"," const __refresh = function () { return __page.__loadData(); };"," const __t = function (k) { return __page.__t(k); };"," const __domEvent = function (e) {"," const detail = (e && e.detail) || {};",' const rawValue = typeof detail.value === "string" ? detail.value : undefined;'," const values = rawValue !== undefined ? { value: rawValue } : (detail.value || {});"," const current = (e && e.currentTarget) || {};"," return {"," type: e && e.type,"," detail: detail,"," preventDefault: function () {},"," stopPropagation: function () {},"," target: Object.assign({}, values, {"," value: values.value !== undefined ? values.value : current.value,"," dataset: current.dataset || {},"," __values: values,"," reset: function () {},"," }),"," currentTarget: current,"," };"," };",Pp(k.trim(),2),...h,...g,...f,...y,...n.vectorDrawJs," return {",...S," __computed: __computed,",' __pullDown: typeof onPullDownRefresh === "function" ? onPullDownRefresh : null,'," __effects: __effects,"," __computedBoundary: "+JSON.stringify(Object.fromEntries(n.computedBoundary))+","," __data: __data,"," };","};","","Page(rosePage(definitions, {",` route: ${JSON.stringify(e.route)},`,` scope: ${JSON.stringify(va(e.scope))},`,` __hasData: ${/\$data\s*\(/.test(s)},`,` __hasPullDown: ${o},`," data: {",...d," },",...b,...n.awaits.length?[` awaits: [${n.awaits.map(x=>`{ expr: ${x.expr} }`).join(", ")}],`]:[],...a.length?[` persist: ${JSON.stringify(a)},`]:[],...c.length?[` kv: [${c.map(x=>`{ name: ${JSON.stringify(x.name)}, fn: function () { return (${bs(x.fn)}); }, ttl: ${x.ttl} }`).join(", ")}],`]:[],...r?[" content: __content,"]:[],...n.deferred.length?[` defers: [${n.deferred.map(x=>`{ name: ${JSON.stringify(x.name)}, hold: ${x.hold} }`).join(", ")}],`]:[],"}));",""].join(`
|
|
1987
|
+
`)}function ma(e,t,n){if(n==="kv")return"null";let r=new RegExp(`\\b(?:let|const|var)\\s+${Yr(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$${n}\\b(?:<[^>]*>)?\\s*\\(`).exec(e);if(!r)return"null";let i=r.index+r[0].length-1,o=Sa(e,i);if(o<0)return"null";let a=e.slice(i+1,o).trim();return Ar(a)||"null"}function Zb(e,t){let s=new RegExp(`\\b(?:let|const|var)\\s+${Yr(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$derived\\b(?:<[^>]*>)?\\s*\\(`).exec(e);if(!s)return null;let r=s.index+s[0].length-1,i=Sa(e,r);return i<0?null:e.slice(r+1,i).trim()||null}function Xb(e,t){if(!e||!e.includes("$effect"))return e;let n="",s=0;for(;;){let r=e.indexOf("$effect",s);if(r<0){n+=e.slice(s);break}if(/[A-Za-z0-9_$.]/.test(e[r-1]??"")){n+=e.slice(s,r+7),s=r+7;continue}let i=r+7;for(;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]!=="("){n+=e.slice(s,r+7),s=r+7;continue}let o=Sa(e,i);if(o<0){n+=e.slice(s,r+7),s=r+7;continue}let a=e.slice(i+1,o);t&&(a=t(a)),n+=`${e.slice(s,r)}__effects.push(${a})`,s=o+1}return n}function Sa(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return s}return-1}function ei(e,t){let n=e.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(s,r)=>t.has(r)?`state.${r}`:s);return Gt(n,s=>t.has(s),s=>`state.${s}`)}function Mp(e){return{expr:t=>ei(t,e),set:(t,n)=>`__setState('${t}', ${n})`,action:(t,n)=>`__action('${t}'${n?`, ${n}`:""})`,refresh:()=>"__refresh()",refuses:()=>null}}function Ar(e){return e.replace(/\$(?:derived|state|data|kv|persist)\b(?:<[^>]*>)?\s*\(/g,"(").replace(/\$actionPending\s*\(\s*\)/g,"false").replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null").replace(/\$query\s*\(\s*\)/g,"__page.__query").replace(/\$(?:store|cookies|sessionCookie)\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"{}").replace(/\bonMount\s*\(/g,"__mount(").replace(/\bonCleanup\s*\(/g,"__cleanup(").replace(/\brefresh\s*\(\s*\)/g,"__refresh()").replace(/\$setState\s*\(/g,"__setState(").replace(/\$action\s*\(/g,"__action(").replace(/\$t\s*\(/g,"__t(")}async function Fp(e,t,n){if(!e.trim())return{body:"",names:[]};let s=e.replace(/^\s*import\s+([\s\S]*?)\s+from\s*['"](\.[^'"]*)['"]\s*;?\s*$/gm,(o,a,c)=>{let d=String(a).trim(),u="require("+JSON.stringify(c)+")",l=d.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(l)return"const "+l[1]+" = "+u+";";let p=d.match(/^\{([\s\S]*)\}$/);return p?"const {"+p[1].replace(/\bas\s+([A-Za-z_$][\w$]*)/g,": $1")+"} = "+u+";":/^[A-Za-z_$][\w$]*$/.test(d)?"const "+d+" = "+u+";":"const __mod = "+u+";"}).replace(/^\s*import\s+['"]([^'"]*)['"]\s*;?\s*$/gm,(o,a)=>a.startsWith(".")?"require("+JSON.stringify(a)+");":(n.warnings.push(`${n.file}: side-effect import is not resolvable in a mini program - dropped (${a})`),"")).replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,o=>(n.warnings.push(`${n.file}: package import is not resolvable in a mini program - dropped (${o.trim().slice(0,60)})`),""));s=s.replace(/\blocation\.href\s*=\s*([^;\n]+);?/g,"__rosefcNavigate($1);").replace(/\blocation\.(?:assign|replace)\s*\(([^)]*)\)\s*;?/g,"__rosefcNavigate($1);").replace(/\bwindow\.open\s*\?\.\s*\(([^)]*)\)/g,"__rosefcOpen($1)").replace(/\bwindow\.open\s*\(([^)]*)\)/g,"__rosefcOpen($1)").replace(/\bconfirm\s*\(/g,"__rosefcConfirm(").replace(/\balert\s*\(/g,"__rosefcAlert(").replace(/\bprompt\s*\(/g,"__rosefcPrompt("),s=zt(s,{target:n.target,options:o=>Dt(o,"bare"),empty:"null",file:n.file,warn:o=>n.warnings.push(o)}).code,n.kitImports=["__rosefcNative","__rosefcConfirm","__rosefcAlert","__rosefcPrompt","__rosefcOpen"].filter(o=>new RegExp(`\\b${o}\\s*\\(`).test(s));try{s=Ap(s,{loader:"ts",format:"esm",target:"es2020"}).code}catch(o){n.warnings.push(`${n.file}: the script did not parse as TypeScript - emitted raw (${o instanceof Error?o.message:String(o)})`)}for(let o of t.actions){let a=new RegExp(`\\b(async\\s+)?function\\s+${Yr(o)}\\s*\\(`,"g");s=s.replace(a,(c,d)=>`function __server_${o}(`),s=s.replace(new RegExp(`\\bconst\\s+${Yr(o)}\\s*=`,"g"),`const __server_${o} =`),s+=`
|
|
1988
1988
|
function ${o}(e) { return __action(${JSON.stringify(o)}, e); }
|
|
1989
1989
|
`}s=s.replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+(?=(?:async\s+)?(?:function|const|let|var|class)\b)/gm,"");for(let o of t.state){let c=new RegExp(`\\b(?:let|const|var)\\s+${Yr(o.name)}\\s*(?::[^=;\\n]*)?=\\s*\\$${o.kind}\\b(?:<[^>]*>)?\\s*\\(`).exec(s);if(!c)continue;let d=c.index+c[0].length-1,u=Sa(s,d);u<0||(s=s.slice(0,c.index)+s.slice(u+1).replace(/^;/,""))}s=s.replace(/^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=;\n]*)?=\s*\$store\s*\([^;]*\)\s*;?\s*$/gm,""),s=Ot(s),s=Ar(s);let r=new Set(t.state.map(o=>o.name));s=ei(s,r);for(let o of t.state){let a=o.name[0].toUpperCase()+o.name.slice(1);s=s.replace(new RegExp(`\\bset${Yr(a)}\\s*\\(`,"g"),`__setState(${JSON.stringify(o.name)}, `)}let i=new Set;for(let o of s.matchAll(/^(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/gm))i.add(o[1].replace(/^__server_/,""));for(let o of s.matchAll(/^const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function|\([^)]*\)\s*=>)/gm))o[1].startsWith("__server_")||i.add(o[1]);return{body:s,names:[...i]}}function Yr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pp(e,t){let n=" ".repeat(t);return e.split(`
|
|
1990
1990
|
`).map(s=>s.trim()?n+s:s).join(`
|
|
@@ -2012,10 +2012,10 @@ function ${o}(e) { return __action(${JSON.stringify(o)}, e); }
|
|
|
2012
2012
|
.rose-ul, .rose-ol { margin: 16px 0; padding-left: 40px; }
|
|
2013
2013
|
.rose-li { display: block; }
|
|
2014
2014
|
.rose-ul .rose-li::before { content: '\u2022 '; margin-right: 4px; }
|
|
2015
|
-
.rose-ol { counter-reset:
|
|
2016
|
-
.rose-ol .rose-li::before { counter-increment:
|
|
2015
|
+
.rose-ol { counter-reset: rosefc-ol; }
|
|
2016
|
+
.rose-ol .rose-li::before { counter-increment: rosefc-ol; content: counter(rosefc-ol) '. '; margin-right: 4px; }
|
|
2017
2017
|
`;Ub=new Set(["id","name","slot","placeholder","value","maxlength","disabled","title","mode","decoded","src","url","open-type","hover-class","bindinput","bindchange","type","confirm-type","placeholder-class","placeholder-style","range","range-key","start","end","fields","custom-item","indicator-style","indicator-class","item-style"]);Yb=`/**
|
|
2018
|
-
*
|
|
2018
|
+
* Rosefc - the exported mini-program runtime.
|
|
2019
2019
|
*
|
|
2020
2020
|
* The web runtime adopts SSR DOM and patches markers; a mini program owns its
|
|
2021
2021
|
* own renderer, so this kit is the small remainder that still has to exist:
|
|
@@ -2067,13 +2067,13 @@ function applyPatch(page, patch) {
|
|
|
2067
2067
|
/// wx.showToast / wx.showModal with an editable field, and fall back to the
|
|
2068
2068
|
/// browser globals when the page also runs on the web (the same file keeps
|
|
2069
2069
|
/// working in a dev-server preview of the export).
|
|
2070
|
-
function
|
|
2070
|
+
function __rosefcDialogApi() {
|
|
2071
2071
|
if (typeof wx !== 'undefined' && wx.showModal) return wx;
|
|
2072
2072
|
if (typeof my !== 'undefined' && my.confirm) return my;
|
|
2073
2073
|
return null;
|
|
2074
2074
|
}
|
|
2075
|
-
function
|
|
2076
|
-
const api =
|
|
2075
|
+
function __rosefcConfirm(message) {
|
|
2076
|
+
const api = __rosefcDialogApi();
|
|
2077
2077
|
if (!api) return Promise.resolve(typeof confirm === 'function' ? confirm(message) : false);
|
|
2078
2078
|
return new Promise(function (resolve) {
|
|
2079
2079
|
api.showModal({
|
|
@@ -2084,8 +2084,8 @@ function __rosefdConfirm(message) {
|
|
|
2084
2084
|
});
|
|
2085
2085
|
});
|
|
2086
2086
|
}
|
|
2087
|
-
function
|
|
2088
|
-
const api =
|
|
2087
|
+
function __rosefcAlert(message) {
|
|
2088
|
+
const api = __rosefcDialogApi();
|
|
2089
2089
|
if (!api) { if (typeof alert === 'function') alert(message); return Promise.resolve(); }
|
|
2090
2090
|
return new Promise(function (resolve) {
|
|
2091
2091
|
wx.showToast({ title: String(message), icon: 'none', complete: function () { resolve(); } });
|
|
@@ -2098,7 +2098,7 @@ function __rosefdAlert(message) {
|
|
|
2098
2098
|
* URL falls back to a clipboard copy with a toast (there is no browser tab to
|
|
2099
2099
|
* open, and doing nothing silently is worse than saying so).
|
|
2100
2100
|
*/
|
|
2101
|
-
function
|
|
2101
|
+
function __rosefcOpen(url, target) {
|
|
2102
2102
|
const src = String(url == null ? '' : url);
|
|
2103
2103
|
if (!src) return;
|
|
2104
2104
|
if (typeof wx !== 'undefined' && wx.previewImage) {
|
|
@@ -2109,8 +2109,8 @@ function __rosefdOpen(url, target) {
|
|
|
2109
2109
|
wx.setClipboardData({ data: src, success: function () { wx.showToast({ title: '\u94FE\u63A5\u5DF2\u590D\u5236', icon: 'none' }); } });
|
|
2110
2110
|
}
|
|
2111
2111
|
}
|
|
2112
|
-
function
|
|
2113
|
-
const api =
|
|
2112
|
+
function __rosefcPrompt(message, defaultValue) {
|
|
2113
|
+
const api = __rosefcDialogApi();
|
|
2114
2114
|
if (!api) return Promise.resolve(typeof prompt === 'function' ? prompt(message, defaultValue) : null);
|
|
2115
2115
|
return new Promise(function (resolve) {
|
|
2116
2116
|
wx.showModal({
|
|
@@ -2134,7 +2134,7 @@ function __rosefdPrompt(message, defaultValue) {
|
|
|
2134
2134
|
/// geolocation -> { latitude, longitude }, or null
|
|
2135
2135
|
/// clipboard-read -> the clipboard text ('' when empty)
|
|
2136
2136
|
/// clipboard-write -> true once written
|
|
2137
|
-
function
|
|
2137
|
+
function __rosefcNativeApi() {
|
|
2138
2138
|
if (typeof wx !== 'undefined' && wx.chooseMedia) return wx;
|
|
2139
2139
|
if (typeof qq !== 'undefined' && qq.chooseMedia) return qq;
|
|
2140
2140
|
if (typeof tt !== 'undefined' && tt.chooseImage) return tt;
|
|
@@ -2142,9 +2142,9 @@ function __rosefdNativeApi() {
|
|
|
2142
2142
|
if (typeof my !== 'undefined' && my.chooseImage) return my;
|
|
2143
2143
|
return null;
|
|
2144
2144
|
}
|
|
2145
|
-
function
|
|
2145
|
+
function __rosefcNative(capability, options) {
|
|
2146
2146
|
var opts = options || {};
|
|
2147
|
-
var api =
|
|
2147
|
+
var api = __rosefcNativeApi();
|
|
2148
2148
|
if (!api) return Promise.resolve(null);
|
|
2149
2149
|
if (capability === 'camera') {
|
|
2150
2150
|
return new Promise(function (resolve) {
|
|
@@ -2235,11 +2235,11 @@ function installFormData() {
|
|
|
2235
2235
|
};
|
|
2236
2236
|
}
|
|
2237
2237
|
|
|
2238
|
-
///
|
|
2238
|
+
/// __rosefcContent is a server-side bridge over the markdown collections. The
|
|
2239
2239
|
/// export bakes them into data/content.json, so a mini program reads the real
|
|
2240
2240
|
/// collections instead of throwing a ReferenceError on the first access.
|
|
2241
2241
|
function installContentBridge(collections) {
|
|
2242
|
-
if (typeof globalThis.
|
|
2242
|
+
if (typeof globalThis.__rosefcContent !== 'undefined') return;
|
|
2243
2243
|
if (!collections || typeof collections !== 'object') return;
|
|
2244
2244
|
const index = {};
|
|
2245
2245
|
for (const coll of Object.keys(collections)) {
|
|
@@ -2248,7 +2248,7 @@ function installContentBridge(collections) {
|
|
|
2248
2248
|
index[coll] = {};
|
|
2249
2249
|
for (const entry of entries) index[coll][entry.slug] = entry;
|
|
2250
2250
|
}
|
|
2251
|
-
globalThis.
|
|
2251
|
+
globalThis.__rosefcContent = {
|
|
2252
2252
|
list: function (coll) { const e = collections[coll]; return Array.isArray(e) ? e.slice() : []; },
|
|
2253
2253
|
get: function (coll, slug) { return (index[coll] && index[coll][slug]) || null; },
|
|
2254
2254
|
rss: function () { return ''; }
|
|
@@ -2263,7 +2263,7 @@ function installContentBridge(collections) {
|
|
|
2263
2263
|
* this shadow field instead.
|
|
2264
2264
|
*/
|
|
2265
2265
|
function routeOf(self, fallback) {
|
|
2266
|
-
return self.
|
|
2266
|
+
return self.__rosefcRoute || self.route || fallback || '';
|
|
2267
2267
|
}
|
|
2268
2268
|
|
|
2269
2269
|
function rosePage(definitions, def) {
|
|
@@ -2274,7 +2274,7 @@ function rosePage(definitions, def) {
|
|
|
2274
2274
|
page.__awaitDefs = def.awaits || [];
|
|
2275
2275
|
page.__persist = def.persist || [];
|
|
2276
2276
|
page.__kvDefs = def.kv || [];
|
|
2277
|
-
// Baked collections: a page that reads
|
|
2277
|
+
// Baked collections: a page that reads __rosefcContent gets the real data
|
|
2278
2278
|
// instead of an unresolved global.
|
|
2279
2279
|
if (def.content) installContentBridge(def.content);
|
|
2280
2280
|
page.__defers = def.defers || [];
|
|
@@ -2291,7 +2291,7 @@ function rosePage(definitions, def) {
|
|
|
2291
2291
|
page.onShareAppMessage = function () {
|
|
2292
2292
|
// The fallback is the app's own name, never a hard-coded product
|
|
2293
2293
|
// string: an app-specific literal here leaked into every project.
|
|
2294
|
-
return { title: (this.data && this.data.__shareTitle) || (def.window && def.window.navigationBarTitleText) || '
|
|
2294
|
+
return { title: (this.data && this.data.__shareTitle) || (def.window && def.window.navigationBarTitleText) || 'Rosefc', path: '/' + routeOf(this, def.route) };
|
|
2295
2295
|
};
|
|
2296
2296
|
}
|
|
2297
2297
|
// Pull-to-refresh: a page opts in by exporting an onPullDownRefresh handler.
|
|
@@ -2328,7 +2328,7 @@ function rosePage(definitions, def) {
|
|
|
2328
2328
|
this.data[k] = value;
|
|
2329
2329
|
}
|
|
2330
2330
|
catch (err) {
|
|
2331
|
-
console.warn('
|
|
2331
|
+
console.warn('rosefc: computed ' + k + ' failed', err);
|
|
2332
2332
|
// A computed inside a {#boundary} flips that boundary to its fallback.
|
|
2333
2333
|
const bnd = this.__computedBoundary[k];
|
|
2334
2334
|
if (bnd) patch[bnd] = false;
|
|
@@ -2355,15 +2355,15 @@ function rosePage(definitions, def) {
|
|
|
2355
2355
|
self.__effectDirty = false;
|
|
2356
2356
|
for (let i = 0; i < list.length; i++) {
|
|
2357
2357
|
if (passes > 0 && typeof self.__effectCleanups[i] === 'function') {
|
|
2358
|
-
try { self.__effectCleanups[i].call(self); } catch (err) { console.warn('
|
|
2358
|
+
try { self.__effectCleanups[i].call(self); } catch (err) { console.warn('rosefc: effect cleanup failed', err); }
|
|
2359
2359
|
}
|
|
2360
2360
|
try {
|
|
2361
2361
|
const done = list[i].call(self);
|
|
2362
2362
|
if (typeof done === 'function') self.__effectCleanups[i] = done;
|
|
2363
|
-
} catch (err) { console.warn('
|
|
2363
|
+
} catch (err) { console.warn('rosefc: $effect failed', err); }
|
|
2364
2364
|
}
|
|
2365
2365
|
} while (self.__effectDirty && ++passes < 8);
|
|
2366
|
-
if (self.__effectDirty) console.warn('
|
|
2366
|
+
if (self.__effectDirty) console.warn('rosefc: $effect never settled (a loop of 8 passes) - check that the effect does not write state it also reads');
|
|
2367
2367
|
} finally {
|
|
2368
2368
|
self.__effectRunning = false;
|
|
2369
2369
|
self.__effectDirty = false;
|
|
@@ -2381,7 +2381,7 @@ function rosePage(definitions, def) {
|
|
|
2381
2381
|
this.setData(patch);
|
|
2382
2382
|
// A $persist field survives a reload through the mini program's storage.
|
|
2383
2383
|
if (this.__persist && this.__persist.indexOf(key) !== -1) {
|
|
2384
|
-
try { wx.setStorageSync('
|
|
2384
|
+
try { wx.setStorageSync('rosefc:' + key, value); } catch (err) { console.warn('rosefc: persist write failed', err); }
|
|
2385
2385
|
}
|
|
2386
2386
|
this.__sync();
|
|
2387
2387
|
};
|
|
@@ -2394,9 +2394,9 @@ function rosePage(definitions, def) {
|
|
|
2394
2394
|
page.__runAction = function (name, extra) {
|
|
2395
2395
|
const self = this;
|
|
2396
2396
|
const api = requestApi();
|
|
2397
|
-
if (!api) { console.warn('
|
|
2397
|
+
if (!api) { console.warn('rosefc: no request API on this platform'); return Promise.resolve(); }
|
|
2398
2398
|
if (!apiBase) {
|
|
2399
|
-
console.warn('
|
|
2399
|
+
console.warn('rosefc: no apiBase configured - server action "' + name + '" cannot run');
|
|
2400
2400
|
return Promise.resolve();
|
|
2401
2401
|
}
|
|
2402
2402
|
// A submit event carries the form's fields in e.detail.value; without them
|
|
@@ -2415,7 +2415,7 @@ function rosePage(definitions, def) {
|
|
|
2415
2415
|
header: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
2416
2416
|
data: body,
|
|
2417
2417
|
success: (res) => { applyPatch(self, res.data && res.data.state ? res.data.state : res.data); resolve(res); },
|
|
2418
|
-
fail: (err) => { console.warn('
|
|
2418
|
+
fail: (err) => { console.warn('rosefc: action "' + name + '" failed', err); resolve(err); },
|
|
2419
2419
|
});
|
|
2420
2420
|
});
|
|
2421
2421
|
};
|
|
@@ -2427,15 +2427,15 @@ function rosePage(definitions, def) {
|
|
|
2427
2427
|
const api = requestApi();
|
|
2428
2428
|
if (!api) return Promise.resolve();
|
|
2429
2429
|
if (!apiBase) {
|
|
2430
|
-
console.warn("[
|
|
2430
|
+
console.warn("[rosefc] no apiBase for " + routeOf(self, def.route) + " - pages using an HTTP $data channel need: rosefc export weapp . --api <base>");
|
|
2431
2431
|
return Promise.resolve();
|
|
2432
2432
|
}
|
|
2433
2433
|
return new Promise((resolve) => {
|
|
2434
2434
|
api.request({
|
|
2435
|
-
url: apiBase + "/
|
|
2435
|
+
url: apiBase + "/__rosefc/data?path=" + encodeURIComponent(routeOf(self, def.route)),
|
|
2436
2436
|
method: "GET",
|
|
2437
2437
|
success: (res) => { applyPatch(self, res.data && res.data.state ? res.data.state : res.data); resolve(res); },
|
|
2438
|
-
fail: (err) => { console.warn("
|
|
2438
|
+
fail: (err) => { console.warn("rosefc: $data channel failed", err); resolve(err); },
|
|
2439
2439
|
});
|
|
2440
2440
|
});
|
|
2441
2441
|
};
|
|
@@ -2446,7 +2446,7 @@ function rosePage(definitions, def) {
|
|
|
2446
2446
|
// rebuilt from the launch options (options.id for pages/postDetail-param-id),
|
|
2447
2447
|
// the same work renderPageIsolated does on the web (setState per segment).
|
|
2448
2448
|
// Two jobs, both previously missing: (1) self.route stayed the ':id'
|
|
2449
|
-
// placeholder, so every action POST and /
|
|
2449
|
+
// placeholder, so every action POST and /__rosefc/data request carried a
|
|
2450
2450
|
// literal ':id' the server could never match to real data; (2) a $state
|
|
2451
2451
|
// named like the segment was never seeded, so the page could not even know
|
|
2452
2452
|
// its own param without an explicit launch-parameters read.
|
|
@@ -2465,7 +2465,7 @@ function rosePage(definitions, def) {
|
|
|
2465
2465
|
}
|
|
2466
2466
|
}
|
|
2467
2467
|
}
|
|
2468
|
-
if (real !== def.route) this.
|
|
2468
|
+
if (real !== def.route) this.__rosefcRoute = real;
|
|
2469
2469
|
if (Object.keys(seeded).length) {
|
|
2470
2470
|
for (const k of Object.keys(seeded)) this.data[k] = seeded[k];
|
|
2471
2471
|
this.setData(seeded);
|
|
@@ -2493,7 +2493,7 @@ function rosePage(definitions, def) {
|
|
|
2493
2493
|
const restored = {};
|
|
2494
2494
|
for (const key of this.__persist) {
|
|
2495
2495
|
let saved;
|
|
2496
|
-
try { saved = wx.getStorageSync('
|
|
2496
|
+
try { saved = wx.getStorageSync('rosefc:' + key); } catch (err) { saved = ''; }
|
|
2497
2497
|
if (saved !== '' && saved !== undefined && saved !== null) restored[key] = saved;
|
|
2498
2498
|
}
|
|
2499
2499
|
if (Object.keys(restored).length) { Object.assign(this.data, restored); this.setData(restored); this.__sync(); }
|
|
@@ -2526,7 +2526,7 @@ function rosePage(definitions, def) {
|
|
|
2526
2526
|
const patch = {};
|
|
2527
2527
|
for (let i = 0; i < list.length; i++) {
|
|
2528
2528
|
const spec = list[i];
|
|
2529
|
-
const storeKey = '
|
|
2529
|
+
const storeKey = 'rosefc:kv:' + spec.name;
|
|
2530
2530
|
let cached = null;
|
|
2531
2531
|
try { cached = wx.getStorageSync(storeKey); } catch (err) { cached = null; }
|
|
2532
2532
|
if (cached && typeof cached === 'object' && cached.value !== undefined && now - cached.at < spec.ttl * 1000) {
|
|
@@ -2534,7 +2534,7 @@ function rosePage(definitions, def) {
|
|
|
2534
2534
|
continue;
|
|
2535
2535
|
}
|
|
2536
2536
|
let value;
|
|
2537
|
-
try { value = spec.fn.call(self); } catch (err) { console.warn('
|
|
2537
|
+
try { value = spec.fn.call(self); } catch (err) { console.warn('rosefc: $kv ' + spec.name + ' failed', err); continue; }
|
|
2538
2538
|
try { wx.setStorageSync(storeKey, { value: value, at: now }); } catch (err) { /* a full quota just skips the memo */ }
|
|
2539
2539
|
patch[spec.name] = value;
|
|
2540
2540
|
}
|
|
@@ -2578,27 +2578,27 @@ function rosePage(definitions, def) {
|
|
|
2578
2578
|
if (list.length) this.__sync();
|
|
2579
2579
|
};
|
|
2580
2580
|
page.onReady = function () {
|
|
2581
|
-
for (const fn of this.__mounts) { try { fn.call(this); } catch (err) { console.warn('
|
|
2581
|
+
for (const fn of this.__mounts) { try { fn.call(this); } catch (err) { console.warn('rosefc: mount failed', err); } }
|
|
2582
2582
|
this.__mounts.length = 0;
|
|
2583
2583
|
};
|
|
2584
2584
|
page.onUnload = function () {
|
|
2585
|
-
for (const fn of this.__cleanups) { try { fn.call(this); } catch (err) { console.warn('
|
|
2585
|
+
for (const fn of this.__cleanups) { try { fn.call(this); } catch (err) { console.warn('rosefc: cleanup failed', err); } }
|
|
2586
2586
|
this.__cleanups.length = 0;
|
|
2587
2587
|
// Effects are still registered when the page goes away, and their return
|
|
2588
2588
|
// values are the only dispose hooks the author has: a timer or a socket
|
|
2589
2589
|
// started in an effect body leaks to the next page instance otherwise.
|
|
2590
|
-
for (const fn of this.__effectCleanups) { if (typeof fn === 'function') { try { fn.call(this); } catch (err) { console.warn('
|
|
2590
|
+
for (const fn of this.__effectCleanups) { if (typeof fn === 'function') { try { fn.call(this); } catch (err) { console.warn('rosefc: effect cleanup failed', err); } } }
|
|
2591
2591
|
this.__effectCleanups.length = 0;
|
|
2592
2592
|
this.__effects.length = 0;
|
|
2593
2593
|
};
|
|
2594
2594
|
return page;
|
|
2595
2595
|
}
|
|
2596
2596
|
|
|
2597
|
-
module.exports = { rosePage, setApiBase, getApiBase, installFormData, roseThrow,
|
|
2598
|
-
`});import*as Hs from"node:fs";import*as Rs from"node:path";import{fileURLToPath as e$}from"node:url";function n$(){for(let e of["../../deploy/native","../deploy/native"]){let t=e$(new URL(e,import.meta.url));if(Hs.existsSync(t))return t}return null}async function ti(e,t,n){let s=t$[e],r=n$();if(!r)return n.push(`${s.label}: deploy templates are not shipped beside this build - the CI workflow is skipped (copy deploy/native/ by hand)`),[];let i=[],o=async(a,c,d)=>{let u=Rs.join(r,a);if(!Hs.existsSync(u)){n.push(`${s.label}: deploy template ${a} is missing - that file is skipped`);return}let l=await Hs.promises.readFile(u,"utf8");d&&(l=d(l)),await Hs.promises.mkdir(Rs.dirname(c),{recursive:!0}),await Hs.promises.writeFile(c,l,"utf8"),i.push(Rs.relative(t,c).replace(/\\/g,"/"))};if(await o(s.workflow,Rs.join(t,".github","workflows",s.workflow)),await o(s.deployMd,Rs.join(t,"DEPLOY.md")),e==="xcode"){let a=Rs.join(t,"
|
|
2597
|
+
module.exports = { rosePage, setApiBase, getApiBase, installFormData, roseThrow, __rosefcConfirm, __rosefcAlert, __rosefcPrompt, __rosefcOpen, __rosefcNative };
|
|
2598
|
+
`});import*as Hs from"node:fs";import*as Rs from"node:path";import{fileURLToPath as e$}from"node:url";function n$(){for(let e of["../../deploy/native","../deploy/native"]){let t=e$(new URL(e,import.meta.url));if(Hs.existsSync(t))return t}return null}async function ti(e,t,n){let s=t$[e],r=n$();if(!r)return n.push(`${s.label}: deploy templates are not shipped beside this build - the CI workflow is skipped (copy deploy/native/ by hand)`),[];let i=[],o=async(a,c,d)=>{let u=Rs.join(r,a);if(!Hs.existsSync(u)){n.push(`${s.label}: deploy template ${a} is missing - that file is skipped`);return}let l=await Hs.promises.readFile(u,"utf8");d&&(l=d(l)),await Hs.promises.mkdir(Rs.dirname(c),{recursive:!0}),await Hs.promises.writeFile(c,l,"utf8"),i.push(Rs.relative(t,c).replace(/\\/g,"/"))};if(await o(s.workflow,Rs.join(t,".github","workflows",s.workflow)),await o(s.deployMd,Rs.join(t,"DEPLOY.md")),e==="xcode"){let a=Rs.join(t,"RosefcApp.xcodeproj","project.pbxproj"),c=Hs.existsSync(a)?/^\t\t([0-9A-F]{24}) \/\* RosefcApp \*\/ = \{\n\t+isa = PBXNativeTarget;/m.exec(await Hs.promises.readFile(a,"utf8"))?.[1]:void 0;c?await o("RosefcApp.xcscheme",Rs.join(t,"RosefcApp.xcodeproj","xcshareddata","xcschemes","RosefcApp.xcscheme"),d=>d.replaceAll("__ROSEFC_TARGET_ID__",c)):n.push("xcode: the RosefcApp target id could not be read from project.pbxproj - the shared scheme is skipped (Xcode creates one when the project is opened)")}return i}var t$,_a=De(()=>{"use strict";t$={android:{workflow:"android.yml",deployMd:"android.DEPLOY.md",label:"android"},xcode:{workflow:"ios.yml",deployMd:"ios.DEPLOY.md",label:"xcode"},flutter:{workflow:"flutter.yml",deployMd:"flutter.DEPLOY.md",label:"flutter"}}});import*as at from"node:fs";import*as Le from"node:path";import{transformSync as s$}from"esbuild";async function o$(e,t,n){let s=new Map,r=Le.join(e,"public");if(!at.existsSync(r))return s;await at.promises.mkdir(t,{recursive:!0});for(let i of await at.promises.readdir(r,{withFileTypes:!0})){if(/\.svg$/i.test(i.name)){let o=Wt(await at.promises.readFile(Le.join(r,i.name),"utf8"));o.shape?Sc.set("/"+i.name,{shape:o.shape,name:"rose"+or(i.name.replace(/\.[^.]+$/,""))+"Vector"}):n.push(`flutter: ${i.name} uses ${o.reason??"an unsupported feature"} - skipped`);continue}if(/\.(woff2?|ttf|otf)$/i.test(i.name)){let o=Le.join(t,"..","fonts");await at.promises.mkdir(o,{recursive:!0}),await at.promises.copyFile(Le.join(r,i.name),Le.join(o,i.name)),s.set("/"+i.name,"assets/fonts/"+i.name);continue}/\.(png|jpe?g|webp)$/i.test(i.name)&&(await at.promises.copyFile(Le.join(r,i.name),Le.join(t,i.name)),s.set("/"+i.name,"assets/images/"+i.name))}return s}async function zp(e){let t=e.warnings,n=e.projectRoot,s=Le.join(e.outDir,"flutter");Ra=new Map;let r=Le.join(n,"src","pages"),[i,o]=await Promise.all([Ye(n),Ke(n)]),a=new Map;for(let b of i){if(Le.basename(b)!=="_layout.rose")continue;let $=Le.dirname(Le.relative(r,b)).replace(/\\/g,"/"),w=Ce(await at.promises.readFile(b,"utf8"),b,"flutter");t.push(...w.warnings),a.set($==="."?"":$,{nodes:w.nodes,script:w.script,style:w.style})}let c=[];for(let b of i){let $=Le.relative(r,b).replace(/\\/g,"/"),w=$.replace(/\.rose$/,""),v=Le.basename(w);if(v==="_layout"||v==="404"||v==="_notfound"||v==="500"||v==="_middleware"||w==="api"||w.startsWith("api/"))continue;let _=Ce(await at.promises.readFile(b,"utf8"),b,"flutter");t.push(..._.warnings);let k=[],S=$.split("/").slice(0,-1);for(let T=S.length;T>=0;T--){let M=a.get(S.slice(0,T).join("/"));M&&k.push(M)}let C=_.nodes;for(let T of k)C=c$(T.nodes,C);let x=[...k.map(T=>T.script).filter(T=>!!T),_.script??""].filter(T=>T.trim()),A=[_.style,...k.map(T=>T.style)].filter(T=>!!T).join(`
|
|
2599
2599
|
`),R=or(w.replace(/\[([^\]]+)\]/g,"Param$1").replace(/[^\w]/g,"_"));c.push({file:b,route:a$(w),className:R,fileName:ka(w.replace(/\[([^\]]+)\]/g,"param_$1").replace(/[^\w-]/g,"_")),nodes:C,script:x.join(`
|
|
2600
2600
|
`),style:A,params:[...w.matchAll(/\[([^\]]+)\]/g)].map(T=>T[1]),title:l$(_.head)})}let d=[];for(let b of o){let $=Ce(await at.promises.readFile(b,"utf8"),b,"flutter");t.push(...$.warnings);let w=Le.basename(b,".rose");d.push({file:b,name:w,className:or(w),nodes:$.nodes,script:$.script,style:$.style??"",slots:Ft($.nodes)})}await at.promises.rm(s,{recursive:!0,force:!0}),await at.promises.mkdir(Le.join(s,"lib","pages"),{recursive:!0}),await at.promises.mkdir(Le.join(s,"lib","components"),{recursive:!0});let u=[...c.flatMap(b=>gc(b.style??"",t,b.fileName)),...d.flatMap(b=>gc(b.style??"",t,b.name)),gc(ke,t)],l=new Set;for(let b of u)for(let $ of b.hoverKeys)l.add($);let p=new Set;for(let b of u)for(let $ of b.focusKeys)p.add($);let f=new Set;for(let b of u)for(let $ of b.activeKeys)f.add($);let h=u.flatMap(b=>b.rules),g=[...c.map(b=>b.style??""),...d.map(b=>b.style??""),ke].join(`
|
|
2601
|
-
`),y=Mt(n),m=xt([...c.map(b=>b.script),...d.map(b=>b.script)]);bc=await o$(n,Le.join(s,"assets","images"),t),await at.promises.writeFile(Le.join(s,"lib","styles.dart"),f$(h,Ra),"utf8"),await at.promises.writeFile(Le.join(s,"lib","
|
|
2601
|
+
`),y=Mt(n),m=xt([...c.map(b=>b.script),...d.map(b=>b.script)]);bc=await o$(n,Le.join(s,"assets","images"),t),await at.promises.writeFile(Le.join(s,"lib","styles.dart"),f$(h,Ra),"utf8"),await at.promises.writeFile(Le.join(s,"lib","rosefc.dart"),h$(e.apiBase??"",y,m),"utf8"),await at.promises.writeFile(Le.join(s,"lib","vectors.dart"),g$(),"utf8"),await at.promises.writeFile(Le.join(s,"pubspec.yaml"),m$(c,[...bc.values()].filter(b=>!/\.(woff2?|ttf|otf)$/i.test(b)),Zn(g),kp("flutter",m)),"utf8"),await at.promises.writeFile(Le.join(s,"README.md"),b$(e.apiBase??"",c.length,d.length,t),"utf8");for(let b of d)await at.promises.writeFile(Le.join(s,"lib","components",ka(b.name)+".dart"),v$(b,t),"utf8");for(let b of c)await at.promises.writeFile(Le.join(s,"lib","pages",b.fileName+".dart"),w$(b,d,t,y,l,p,f),"utf8");return await at.promises.writeFile(Le.join(s,"lib","main.dart"),$$(c,d),"utf8"),await ti("flutter",s,t),{pages:c.map(b=>`lib/pages/${b.fileName}.dart`),components:d.map(b=>`lib/components/${ka(b.name)}.dart`)}}function a$(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function l$(e){if(!e)return"";let t=/<title>([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/\{[^}]*\}/g,"").trim():""}function c$(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}function gc(e,t,n){if(!e.trim())return{rules:[],hoverKeys:new Set,focusKeys:new Set,activeKeys:new Set};let s=Te(e);for(let l of s.warnings)t.push(`flutter: ${l}`);let r=new Map,i=[],o=[];for(let l of s.rules){let p=l.parts[l.parts.length-1];if(l.hover&&p.classes.length)for(let f of p.classes){let h=n?`__hover_${f}__${n}`:`__hover_${f}`;r.set(h,fe(r.get(h)??null,l.hover))}if(l.focus&&p.classes.length&&i.push({last:p,focus:l.focus}),l.active&&p.classes.length&&o.push({last:p,active:l.active}),p.unsupported.includes(":hover")&&!l.hover&&t.push(`flutter: :hover has no Flutter equivalent on "${l.selector}" - dropped`),!(l.media&&(l.media.min!==void 0||l.media.max!==void 0)&&(l.media.min!==void 0&&wc<l.media.min||l.media.max!==void 0&&wc>l.media.max))){if(!p.classes.length&&p.tag){Ra.set(p.tag,fe(Ra.get(p.tag)??null,l.model));continue}for(let f of p.classes){let h=n?`${f}__${n}`:f;r.set(h,fe(r.get(h)??null,l.model))}}}for(let l of i)for(let p of l.last.classes){let f=n?`__focus_${p}__${n}`:`__focus_${p}`,h=n?`${p}__${n}`:p,g=l.focus.borderColor&&!l.focus.borderWidth?{...l.focus,borderWidth:r.get(h)?.borderWidth??l.focus.borderWidth}:l.focus;r.set(f,fe(r.get(f)??null,g))}for(let l of o)for(let p of l.last.classes){let f=n?`__active_${p}__${n}`:`__active_${p}`,h=n?`${p}__${n}`:p,g=l.active.borderColor&&!l.active.borderWidth?{...l.active,borderWidth:r.get(h)?.borderWidth??l.active.borderWidth}:l.active;r.set(f,fe(r.get(f)??null,g))}for(let l of Cn(e))Zn(e).some(p=>p.family===l)||t.push(`flutter: font-family '${l}' has no @font-face - the Flutter default is used`);let a=[...r.entries()].map(([l,p])=>({className:l,model:p})),c=new Set;for(let l of s.rules){let p=l.parts[l.parts.length-1];if(l.hover)for(let f of p.classes)c.add(n?`__hover_${f}__${n}`:`__hover_${f}`)}let d=new Set;for(let l of i)for(let p of l.last.classes)d.add(n?`__focus_${p}__${n}`:`__focus_${p}`);let u=new Set;for(let l of o)for(let p of l.last.classes)u.add(n?`__active_${p}__${n}`:`__active_${p}`);return{rules:a,hoverKeys:c,focusKeys:d,activeKeys:u}}function He(e){return String(Math.round(e*100)/100)}function to(e){let t=e.replace("#","").toUpperCase();return`Color(0x${t.length===8?t:"FF"+t})`}function Bp(e){return`EdgeInsets.fromLTRB(${He(e[3])}, ${He(e[0])}, ${He(e[1])}, ${He(e[2])})`}function u$(e){return e[0]===e[1]&&e[1]===e[2]&&e[2]===e[3]?`BorderRadius.circular(${He(e[0])})`:`BorderRadius.only(topLeft: Radius.circular(${He(e[0])}), topRight: Radius.circular(${He(e[1])}), bottomRight: Radius.circular(${He(e[2])}), bottomLeft: Radius.circular(${He(e[3])}))`}function d$(e){return`BoxShadow(color: ${to(e.color)}, offset: Offset(${He(e.x)}, ${He(e.y)}), blurRadius: ${He(e.blur)}, spreadRadius: ${He(e.spread)})`}function p$(e){if(!e.borderWidth||!e.borderColor)return null;let t=e.borderWidth,n=to(e.borderColor);if(t[0]===t[1]&&t[1]===t[2]&&t[2]===t[3])return t[0]>0?`Border.all(color: ${n}, width: ${He(t[0])})`:null;let r=[],i=[["top",t[0]],["right",t[1]],["bottom",t[2]],["left",t[3]]];for(let[o,a]of i)a>0&&r.push(`${o}: BorderSide(color: ${n}, width: ${He(a)})`);return r.length?`Border(${r.join(", ")})`:null}function ni(e){if(!(!e||e.u==="auto"))return e.u==="%"?Math.round(e.n/100*390*10)/10:e.n}function $c(e){let t=[];e.color&&t.push(`color: ${to(e.color)}`),e.fontSize!==void 0&&t.push(`fontSize: ${He(e.fontSize)}`),e.fontWeight!==void 0&&t.push(`weight: ${e.fontWeight}`),e.fontFamily&&t.push(`fontFamily: ${JSON.stringify(e.fontFamily)}`),e.italic&&t.push("italic: true"),e.letterSpacing!==void 0&&t.push(`letterSpacing: ${He(e.letterSpacing)}`),e.lineHeight!==void 0&&t.push(`lineHeight: ${He(e.lineHeight)}`),e.textAlign&&t.push(`align: '${e.textAlign}'`),e.textTransform&&t.push(`transform: '${e.textTransform}'`),e.underline&&t.push("underline: true"),e.strike&&t.push("strike: true"),e.background&&t.push(`background: ${to(e.background)}`),e.gradient&&e.gradient.stops.length>=2&&(t.push(`gradient: <Color>[${e.gradient.stops.map(r=>to(r.color)).join(", ")}]`),t.push(`gradientAngle: ${He(e.gradient.angle)}`)),e.padding&&t.push(`padding: ${Bp(e.padding)}`),e.margin&&t.push(`margin: ${Bp(e.margin)}`),e.gap!==void 0&&t.push(`gap: ${He(e.gap)}`);let n=p$(e);n&&t.push(`border: ${n}`),e.radius&&t.push(`radius: ${u$(e.radius)}`),e.shadow&&t.push(`shadow: ${d$(e.shadow)}`),e.opacity!==void 0&&t.push(`opacity: ${He(e.opacity)}`),e.direction?t.push(`direction: '${e.direction}'`):pa(e)&&t.push("direction: 'row'"),e.wrap&&t.push("wrap: true"),e.justify&&t.push(`justify: '${e.justify}'`),e.align&&t.push(`items: '${e.align}'`),e.alignSelf&&t.push(`selfAlign: '${e.alignSelf}'`),e.grow!==void 0&&t.push(`grow: ${He(e.grow)}`),e.shrink!==void 0&&t.push(`shrink: ${He(e.shrink)}`);let s=[["width",ni(e.width)],["height",ni(e.height)],["minWidth",ni(e.minWidth)],["maxWidth",ni(e.maxWidth)],["minHeight",ni(e.minHeight)],["maxHeight",ni(e.maxHeight)]];for(let[r,i]of s)i!==void 0&&t.push(`${r}: ${He(i)}`);return e.display==="none"&&t.push("hidden: true"),e.position&&(t.push("absolute: true"),e.insetLeft!==void 0&&t.push(`insetLeft: ${He(e.insetLeft)}`),e.insetTop!==void 0&&t.push(`insetTop: ${He(e.insetTop)}`),e.insetRight!==void 0&&t.push(`insetRight: ${He(e.insetRight)}`),e.insetBottom!==void 0&&t.push(`insetBottom: ${He(e.insetBottom)}`)),e.overflow==="scroll"&&t.push("scrolls: true"),t}function f$(e,t){let n=e.map(r=>{let i=$c(r.model);return` '${r.className}': RoseStyle(${i.join(", ")}),`}),s=[...t.entries()].map(([r,i])=>{let o=$c(i);return` '${r}': RoseStyle(${o.join(", ")}),`});return`import 'package:flutter/material.dart';
|
|
2602
2602
|
|
|
2603
2603
|
/// The compiled style classes of the project, as a runtime model.
|
|
2604
2604
|
///
|
|
@@ -3131,8 +3131,8 @@ Widget roseHtml(String html) {
|
|
|
3131
3131
|
}import 'dart:convert';
|
|
3132
3132
|
import 'dart:io';
|
|
3133
3133
|
|
|
3134
|
-
/// Base URL of the deployed
|
|
3135
|
-
const String
|
|
3134
|
+
/// Base URL of the deployed Rosefc server (rosefc export --api).
|
|
3135
|
+
const String rosefcApiBase = ${s};
|
|
3136
3136
|
|
|
3137
3137
|
/// The {#await} reject branch: a promise that never resolves, it throws.
|
|
3138
3138
|
Never roseThrow(Object e) => throw e is Exception ? e : Exception(e.toString());
|
|
@@ -3150,20 +3150,20 @@ List<Widget> roseBoundary(List<Widget> Function() build, List<Widget> fallback)
|
|
|
3150
3150
|
|
|
3151
3151
|
/// $persist storage: one JSON file beside the app, so a persisted field survives
|
|
3152
3152
|
/// a restart exactly as localStorage does on the web.
|
|
3153
|
-
final Map<String, dynamic>
|
|
3153
|
+
final Map<String, dynamic> __rosefcStore = () {
|
|
3154
3154
|
try {
|
|
3155
|
-
final f = File('.
|
|
3155
|
+
final f = File('.rosefc-state.json');
|
|
3156
3156
|
if (f.existsSync()) return Map<String, dynamic>.from(jsonDecode(f.readAsStringSync()) as Map);
|
|
3157
3157
|
} catch (_) {}
|
|
3158
3158
|
return <String, dynamic>{};
|
|
3159
3159
|
}();
|
|
3160
3160
|
|
|
3161
|
-
dynamic
|
|
3161
|
+
dynamic rosefcLoad(String key) => __rosefcStore[key];
|
|
3162
3162
|
|
|
3163
|
-
void
|
|
3164
|
-
|
|
3163
|
+
void rosefcSave(String key, dynamic value) {
|
|
3164
|
+
__rosefcStore[key] = value;
|
|
3165
3165
|
try {
|
|
3166
|
-
File('.
|
|
3166
|
+
File('.rosefc-state.json').writeAsStringSync(jsonEncode(__rosefcStore));
|
|
3167
3167
|
} catch (_) {}
|
|
3168
3168
|
}
|
|
3169
3169
|
|
|
@@ -3217,24 +3217,24 @@ dynamic roseIndex(dynamic value, dynamic index) {
|
|
|
3217
3217
|
/// A kv memo: the value is computed at most once per TTL window, and the window
|
|
3218
3218
|
/// survives a restart - the client-side stand-in for the server-side memo the
|
|
3219
3219
|
/// web build uses (where the server computes and ships the value in the state).
|
|
3220
|
-
T
|
|
3221
|
-
final entry =
|
|
3220
|
+
T rosefcKv<T>(String name, T Function() compute, int ttlSeconds) {
|
|
3221
|
+
final entry = rosefcLoad('rosefc:kv:' + name);
|
|
3222
3222
|
final now = DateTime.now().millisecondsSinceEpoch;
|
|
3223
3223
|
if (entry is Map && entry['at'] is int && now - (entry['at'] as int) < ttlSeconds * 1000 && entry.containsKey('value')) {
|
|
3224
3224
|
return entry['value'] as T;
|
|
3225
3225
|
}
|
|
3226
3226
|
final value = compute();
|
|
3227
|
-
|
|
3227
|
+
rosefcSave('rosefc:kv:' + name, <String, dynamic>{'value': value, 'at': now});
|
|
3228
3228
|
return value;
|
|
3229
3229
|
}
|
|
3230
3230
|
|
|
3231
3231
|
/// The JSON half of a render: the state the page's $data produced.
|
|
3232
|
-
/// Same contract the mini-program target uses (/
|
|
3233
|
-
Future<Map<String, dynamic>>
|
|
3234
|
-
if (
|
|
3232
|
+
/// Same contract the mini-program target uses (/__rosefc/data).
|
|
3233
|
+
Future<Map<String, dynamic>> rosefcData(String route) async {
|
|
3234
|
+
if (rosefcApiBase.isEmpty) return <String, dynamic>{};
|
|
3235
3235
|
final client = HttpClient();
|
|
3236
3236
|
try {
|
|
3237
|
-
final uri = Uri.parse('$
|
|
3237
|
+
final uri = Uri.parse('$rosefcApiBase/__rosefc/data?path=\${Uri.encodeComponent(route)}');
|
|
3238
3238
|
final req = await client.getUrl(uri);
|
|
3239
3239
|
final res = await req.close();
|
|
3240
3240
|
final body = await res.transform(utf8.decoder).join();
|
|
@@ -3257,11 +3257,11 @@ Future<Map<String, dynamic>> rosefdData(String route) async {
|
|
|
3257
3257
|
/// The optional fields map is the submitting form's inputs by name: the action
|
|
3258
3258
|
/// reads them with form.get() on the server, so a form that posted only the
|
|
3259
3259
|
/// action name would hand the action empty strings for every field.
|
|
3260
|
-
Future<Map<String, dynamic>>
|
|
3261
|
-
if (
|
|
3260
|
+
Future<Map<String, dynamic>> rosefcAction(String route, String name, [Map<String, dynamic>? fields]) async {
|
|
3261
|
+
if (rosefcApiBase.isEmpty) return <String, dynamic>{};
|
|
3262
3262
|
final client = HttpClient();
|
|
3263
3263
|
try {
|
|
3264
|
-
final uri = Uri.parse('$
|
|
3264
|
+
final uri = Uri.parse('$rosefcApiBase$route');
|
|
3265
3265
|
final req = await client.postUrl(uri);
|
|
3266
3266
|
req.headers.contentType = ContentType('application', 'x-www-form-urlencoded');
|
|
3267
3267
|
const __body = StringBuffer('__action=\${Uri.encodeComponent(name)}');
|
|
@@ -3331,13 +3331,13 @@ class RoseSvgPainter extends CustomPainter {
|
|
|
3331
3331
|
}
|
|
3332
3332
|
|
|
3333
3333
|
/// Router helpers: the generated routes are named by their .rose path.
|
|
3334
|
-
Route<dynamic>
|
|
3334
|
+
Route<dynamic> rosefcOnUnknownRoute(RouteSettings settings) {
|
|
3335
3335
|
return MaterialPageRoute(
|
|
3336
3336
|
settings: settings,
|
|
3337
3337
|
builder: (_) => const Scaffold(body: Center(child: Text('404 - no such route'))),
|
|
3338
3338
|
);
|
|
3339
3339
|
}
|
|
3340
|
-
${o}`}function g$(){let e=n=>String(Number(n.toFixed(2)));return`// Vector assets, generated from public/*.svg by
|
|
3340
|
+
${o}`}function g$(){let e=n=>String(Number(n.toFixed(2)));return`// Vector assets, generated from public/*.svg by rosefc export flutter.
|
|
3341
3341
|
// Rows: 0 = move, 1 = line, 2 = cubic, 3 = close; fills[i] fills subpath i.
|
|
3342
3342
|
|
|
3343
3343
|
${[...Sc.entries()].map(([n,{shape:s,name:r}])=>{let i=s.subPaths.flatMap(a=>a.ops.map(c=>{switch(c.op){case"move":return` const [0, ${e(c.x)}, ${e(c.y)}],`;case"line":return` const [1, ${e(c.x)}, ${e(c.y)}],`;case"curve":return` const [2, ${e(c.c1x)}, ${e(c.c1y)}, ${e(c.c2x)}, ${e(c.c2y)}, ${e(c.x)}, ${e(c.y)}],`;case"close":return" const [3],"}})).join(`
|
|
@@ -3350,7 +3350,7 @@ const double ${r}VbWidth = ${e(s.viewBox[2]-s.viewBox[0])};
|
|
|
3350
3350
|
const double ${r}VbHeight = ${e(s.viewBox[3]-s.viewBox[1])};`}).join(`
|
|
3351
3351
|
|
|
3352
3352
|
`)||"// no vector assets in this export"}
|
|
3353
|
-
`}function m$(e,t=[],n=[],s=[]){let r="
|
|
3353
|
+
`}function m$(e,t=[],n=[],s=[]){let r="rosefc_app",i=n.length?` fonts:
|
|
3354
3354
|
`+n.map(a=>` - family: ${a.family}
|
|
3355
3355
|
fonts:
|
|
3356
3356
|
- asset: assets/fonts/${a.file.split("/").pop()}`).join(`
|
|
@@ -3358,7 +3358,7 @@ const double ${r}VbHeight = ${e(s.viewBox[3]-s.viewBox[1])};`}).join(`
|
|
|
3358
3358
|
`:"",o=s.length?s.map(a=>` ${a}: "${y$[a]??"any"}"`).join(`
|
|
3359
3359
|
`)+`
|
|
3360
3360
|
`:"";return`name: ${r}
|
|
3361
|
-
description: A
|
|
3361
|
+
description: A Rosefc app, exported with rosefc export flutter.
|
|
3362
3362
|
publish_to: none
|
|
3363
3363
|
version: 1.0.0
|
|
3364
3364
|
environment:
|
|
@@ -3371,15 +3371,15 @@ ${o}flutter:
|
|
|
3371
3371
|
${t.length?` assets:
|
|
3372
3372
|
`+t.map(a=>" - "+a).join(`
|
|
3373
3373
|
`)+`
|
|
3374
|
-
`:""}${i}# ${e.length} page(s) were generated from .rose files by
|
|
3375
|
-
`}function b$(e,t,n,s){return`#
|
|
3374
|
+
`:""}${i}# ${e.length} page(s) were generated from .rose files by rosefc export.
|
|
3375
|
+
`}function b$(e,t,n,s){return`# Rosefc -> Flutter
|
|
3376
3376
|
|
|
3377
|
-
Generated by \`
|
|
3377
|
+
Generated by \`rosefc export flutter\` from the project's \`.rose\` pages.
|
|
3378
3378
|
|
|
3379
3379
|
- ${t} page(s), ${n} component(s)
|
|
3380
3380
|
- Run: \`flutter pub get && flutter run\`
|
|
3381
|
-
- Server: \`
|
|
3382
|
-
\`lib/
|
|
3381
|
+
- Server: \`rosefc export flutter --api <base>\` writes the base URL into
|
|
3382
|
+
\`lib/rosefc.dart\` (data channel + server actions). Current: \`${e||"(unset)"}\`
|
|
3383
3383
|
|
|
3384
3384
|
The output has no third-party dependencies: \`dart:io\` HTTP for the data
|
|
3385
3385
|
channel and the action POST, Material widgets for the view tree. A construct
|
|
@@ -3392,7 +3392,7 @@ ${Nt(s)}`}function $$(e,t){let n=e.map(i=>`import 'pages/${i.fileName}.dart';`).
|
|
|
3392
3392
|
}`}).join(`
|
|
3393
3393
|
`);return`import 'package:flutter/material.dart';
|
|
3394
3394
|
${n}
|
|
3395
|
-
import '
|
|
3395
|
+
import 'rosefc.dart';
|
|
3396
3396
|
import 'vectors.dart';
|
|
3397
3397
|
|
|
3398
3398
|
void main() => runApp(const RoseApp());
|
|
@@ -3403,7 +3403,7 @@ class RoseApp extends StatelessWidget {
|
|
|
3403
3403
|
@override
|
|
3404
3404
|
Widget build(BuildContext context) {
|
|
3405
3405
|
return MaterialApp(
|
|
3406
|
-
title: '
|
|
3406
|
+
title: 'Rosefc',
|
|
3407
3407
|
theme: ThemeData(useMaterial3: true, colorSchemeSeed: const Color(0xFFE91E63)),
|
|
3408
3408
|
initialRoute: '/',
|
|
3409
3409
|
routes: {
|
|
@@ -3412,12 +3412,12 @@ ${s}
|
|
|
3412
3412
|
onGenerateRoute: (settings) {
|
|
3413
3413
|
final routeName = settings.name ?? '/';
|
|
3414
3414
|
${r||" // no dynamic routes in this app"}
|
|
3415
|
-
return
|
|
3415
|
+
return rosefcOnUnknownRoute(settings);
|
|
3416
3416
|
},
|
|
3417
3417
|
);
|
|
3418
3418
|
}
|
|
3419
3419
|
}
|
|
3420
|
-
`}function w$(e,t,n,s,r=new Set,i=new Set,o=new Set){let a=E$(e.script),c=ln(e.script??"");for(let R of c)n.push(s?`flutter: ${R} reads the content collections, baked into the kit at export time`:`flutter: ${R} is a server-side bridge - a native build has no content collections, so it resolves empty`);let d=c.length?s?Oe(e.script??"","roseContentList","roseContentGet","[]"):jn(e.script??"","[]"):e.script,u=St(e.nodes).flatMap(R=>R.fields),p=$s(e.script??"").filter(R=>new Set([...a.state.map(T=>T.name),...a.data]).has(R.name)).map(R=>` setState(() { ${R.name} =
|
|
3420
|
+
`}function w$(e,t,n,s,r=new Set,i=new Set,o=new Set){let a=E$(e.script),c=ln(e.script??"");for(let R of c)n.push(s?`flutter: ${R} reads the content collections, baked into the kit at export time`:`flutter: ${R} is a server-side bridge - a native build has no content collections, so it resolves empty`);let d=c.length?s?Oe(e.script??"","roseContentList","roseContentGet","[]"):jn(e.script??"","[]"):e.script,u=St(e.nodes).flatMap(R=>R.fields),p=$s(e.script??"").filter(R=>new Set([...a.state.map(T=>T.name),...a.data]).has(R.name)).map(R=>` setState(() { ${R.name} = rosefcKv(${JSON.stringify(R.name)}, () => (${bs(R.fn)}), ${R.ttl}); });`).join(`
|
|
3421
3421
|
`),f=new Set,h=[...j$(d),...s&&c.length?cn(e.script??"").map(R=>{let T=new RegExp(`(?:const|let|var)\\s+${R}\\s*(?::[^=;\\n]*)?=`).exec(e.script??""),M=T?e.script.slice(T.index+T[0].length).split(`
|
|
3422
3422
|
`)[0].trim().replace(/;\s*$/,""):"[]";return{name:R,init:Oe(M,"roseContentList","roseContentGet","[]")}}):[]],g=new Set(h.map(R=>R.name)),y={warnings:n,file:e.fileName,components:t,styleClasses:f,inText:!1,stateNames:new Set([...a.state.map(R=>R.name),...a.derived.map(R=>R.name)]),mapBinds:new Set(h.map(R=>R.name)),inline:new Map,awaits:[],deferred:[],scriptConsts:_t(e.script,new Set([...a.state.map(R=>R.name),...a.derived.map(R=>R.name)])),componentProps:new Set,forms:St(e.nodes),formSubmit:null,pageAction:S$(e.script),sheet:Te([e.style,ke].filter(R=>R&&R.trim()).join(`
|
|
3423
3423
|
`)),scope:e.fileName,ancestors:[],hoverKeys:r,focusKeys:i,activeKeys:o},m=es(e.nodes,y),b=O$(e.script,a,e.fileName,e.route,n,u,g),$=[...y.inline.entries()].map(([R,T])=>{let M=jt(R,N$(y),y.stateNames);if(M.reason||!M.stmts.length)return n.push(`flutter: ${e.fileName}: an inline handler (${R.slice(0,40)}) is not translated (${M.reason??"empty"}) - method ${T} is empty`),` void ${T}() {}`;let F=M.stmts.map(I=>/[};]\s*$/.test(I)?I:I+";").join(`
|
|
@@ -3430,8 +3430,8 @@ ${F.split(`
|
|
|
3430
3430
|
`),v=e.params.length?` final Map<String, String> params;
|
|
3431
3431
|
const ${e.className}({super.key, this.params = const {}});
|
|
3432
3432
|
`:` const ${e.className}({super.key});
|
|
3433
|
-
`,_=["import 'package:flutter/material.dart';","import '../
|
|
3434
|
-
`),k=new Set(an(e.script??"")),S=a.state.map(R=>{let T=R.init||"null";if(k.has(R.name))return` dynamic ${R.name} =
|
|
3433
|
+
`,_=["import 'package:flutter/material.dart';","import '../rosefc.dart';","import '../vectors.dart';","import '../styles.dart';",...t.map(R=>`import '../components/${ka(R.name)}.dart';`)].join(`
|
|
3434
|
+
`),k=new Set(an(e.script??"")),S=a.state.map(R=>{let T=R.init||"null";if(k.has(R.name))return` dynamic ${R.name} = rosefcLoad(${JSON.stringify("rosefc:"+R.name)}) ?? ${xa(T,g)};`;let M=/^[A-Za-z_$][\w$]*/.exec(T)?.[0]??"";return/^[A-Za-z_$][\w$]*(\.[\w$]+)*$/.test(T)&&!/^(true|false|null|this)$/.test(T)&&!g.has(M)?(n.push(`flutter: ${e.fileName}: the initial value of "${R.name}" reads module-level state (${T}) - it has no widget scope, so it starts null and the data channel/server state is the source`),` dynamic ${R.name} = null;`):` dynamic ${R.name} = ${xa(T,g)};`}).join(`
|
|
3435
3435
|
`),C=h.map(R=>R.init.startsWith("roseContentList(")?` List<dynamic> ${R.name} = ${R.init};`:R.init.startsWith("roseContentGet(")?` dynamic ${R.name} = ${R.init};`:` dynamic ${R.name} = ${xa(R.init)};`).join(`
|
|
3436
3436
|
`),x=a.derived.map(R=>` dynamic get ${R.name} => ${Qt(R.expr,new Set([...a.state.map(T=>T.name),...a.derived.map(T=>T.name)]),y.mapBinds)};`).join(`
|
|
3437
3437
|
`),A=a.data.map(R=>` ${R.name} = __data['${R.name}'];`).join(`
|
|
@@ -3499,7 +3499,7 @@ ${p}
|
|
|
3499
3499
|
}
|
|
3500
3500
|
|
|
3501
3501
|
Future<void> __loadData() async {
|
|
3502
|
-
final patch = await
|
|
3502
|
+
final patch = await rosefcData('${e.route}');
|
|
3503
3503
|
if (!mounted || patch.isEmpty) return;
|
|
3504
3504
|
setState(() {
|
|
3505
3505
|
__data = patch;
|
|
@@ -3536,11 +3536,11 @@ ${a.state.map(R=>` case '${R.name}': ${R.name} = value; break;`).join(`
|
|
|
3536
3536
|
});
|
|
3537
3537
|
// A $persist field is mirrored into the on-disk store, so it survives a
|
|
3538
3538
|
// restart exactly as localStorage does on the web.
|
|
3539
|
-
if (const [${[...k].map(R=>JSON.stringify(R)).join(", ")}].contains(key))
|
|
3539
|
+
if (const [${[...k].map(R=>JSON.stringify(R)).join(", ")}].contains(key)) rosefcSave('rosefc:' + key, value);
|
|
3540
3540
|
}
|
|
3541
3541
|
|
|
3542
3542
|
Future<void> __runAction(String name) async {
|
|
3543
|
-
final patch = await
|
|
3543
|
+
final patch = await rosefcAction('${e.route}', name, __formFields());
|
|
3544
3544
|
if (!mounted || patch.isEmpty) return;
|
|
3545
3545
|
patch.forEach((key, value) { __set(key, value); });
|
|
3546
3546
|
}
|
|
@@ -3557,7 +3557,7 @@ ${w}
|
|
|
3557
3557
|
@override
|
|
3558
3558
|
Widget build(BuildContext context) {
|
|
3559
3559
|
return Scaffold(
|
|
3560
|
-
appBar: AppBar(title: const Text(${JSON.stringify(e.route==="/"?"
|
|
3560
|
+
appBar: AppBar(title: const Text(${JSON.stringify(e.route==="/"?"Rosefc":e.route)})),
|
|
3561
3561
|
body: SingleChildScrollView(
|
|
3562
3562
|
padding: const EdgeInsets.all(16),
|
|
3563
3563
|
child: ${m},
|
|
@@ -3580,13 +3580,13 @@ ${o.join(`
|
|
|
3580
3580
|
}
|
|
3581
3581
|
}
|
|
3582
3582
|
`}function S$(e){if(!e)return null;try{return Qe(e).actions[0]?.name??null}catch{return null}}function ri(e,t){let n=t.constExprs;if(!n||n.size===0)return e;let s=e;for(let[r,i]of n)s=s.replace(new RegExp(`(?<![\\w$.])${r.replace(/[$]/g,"\\$&")}(?![\\w$])`,"g"),`(${i})`);return s}function es(e,t){let n=ii(e,t);return n.length===0?"const SizedBox.shrink()":n.length===1?n[0]:`Column(crossAxisAlignment: CrossAxisAlignment.start, children: [${n.join(", ")}])`}function ii(e,t){let n=[];for(let s of e){if(s.kind==="text"){let r=s.value.replace(/\s+/g," ").trim();r&&n.push(`Text(${JSON.stringify(r)})`);continue}if(s.kind==="expr"){n.push(`Text('\${${Qt(ri(s.code,t),t.stateNames,t.mapBinds)}}')`);continue}if(s.kind==="html"){n.push(`roseHtml(${Qt(ri(s.code,t),t.stateNames,t.mapBinds)})`);continue}if(s.kind==="const"){let r=t.constExprs??new Map;t.constExprs||(t.constExprs=r),r.set(s.name,Qt(ri(s.code,t),t.stateNames,t.mapBinds));continue}if(s.kind==="render"){t.warnings.push(`flutter: {@render ${s.code}} is not expanded yet - renders nothing`);continue}if(s.kind==="snippet"){t.warnings.push(`flutter: {#snippet ${s.name}} is emitted where declared (no call-site expansion yet)`),n.push(...ii(s.children,t));continue}if(s.kind==="if"){let r=s.branches[0],i=s.branches.find(d=>d.cond===null),o=Qt(ri(r.cond??"false",t),t.stateNames,t.mapBinds),a=es(r.children,t),c=i?es(i.children,t):"const SizedBox.shrink()";n.push(`(${o}) ? ${a} : ${c}`);continue}if(s.kind==="each"){let r=/^[A-Za-z_$][\w$]*$/.test(s.binding)?s.binding:"item",i=Qt(ri(s.items,t),t.stateNames,t.mapBinds),o={...t,mapBinds:new Set([...t.mapBinds,r])},a=es(s.children,o);n.push(`Column(crossAxisAlignment: CrossAxisAlignment.start, children: (${i} as List).map((dynamic ${r}) => ${a}).toList())`);continue}if(s.kind==="await"){let r=t.awaits.length,i=`__await${r}Done`,o=`__await${r}Value`,a=`__await${r}Err`,c=Qt(Se(Bt(s.expr),t.scriptConsts),t.stateNames,t.mapBinds);un(s.expr)||t.warnings.push(`${t.file}: the {#await} head is a promise this target cannot await - the then branch renders only for Promise.resolve/reject literals`),t.awaits.push({done:i,value:o,err:a,expr:c});let d=new Map;s.thenName&&d.set(s.thenName,o);let u=new Map;s.catchName&&u.set(s.catchName,a);let l=Je(Ct(s.then,s.catchName??""),d),p=Je(Ct(s.catch,s.catchName??""),u);n.push(`${i} ? (${a} != null ? ${es(p,t)} : ${es(l,t)}) : ${es(s.pending,t)}`);continue}if(s.kind==="block"){if(s.name==="boundary"){let r=ii(s.children,t),i=s.fallback&&s.fallback.length?ii(s.fallback,t):["const Text('This section failed to render.')"];n.push(`...roseBoundary(() => [${r.join(", ")}], [${i.join(", ")}])`);continue}if(s.name==="defer"){let r=Number(/hold\s*=\s*(\d+)/.exec(String(s.head??""))?.[1]??"0"),i=`__defer${t.deferred.length}`;t.deferred.push({name:i,hold:Number.isFinite(r)?r:0}),n.push(`${i} ? ${es(s.children,t)} : const SizedBox.shrink()`);continue}n.push(...ii(s.children,t));continue}if(s.kind==="slot"){t.warnings.push("flutter: <slot> inside a component needs the children parameter - slot skipped");continue}if(s.kind==="element"){n.push(_$(s,t));continue}}return n}function _$(e,t){let n=bt(e),s=x$(e,n,t);t.ancestors.push({tag:e.tag.toLowerCase(),classes:n.staticClasses});try{return k$(e,t,n,s)}finally{t.ancestors.pop()}}function x$(e,t,n){for(let p of t.staticClasses)n.styleClasses.add(p);let s=t.staticClasses,r=rt(n.sheet,{tag:e.tag.toLowerCase(),classes:s},n.ancestors,{viewport:wc}).model,i=fe(r,t.inlineStyle),o=null;for(let p of s){let f=`__hover_${p}__${n.scope}`;if(n.hoverKeys?.has(f)){o=f;break}}let a=null;for(let p of s){let f=`__focus_${p}__${n.scope}`;if(n.focusKeys?.has(f)){a=f;break}}let c=null;for(let p of s){let f=`__active_${p}__${n.scope}`;if(n.activeKeys?.has(f)){c=f;break}}if(!t.hasDynamic&&s.length===1&&!t.inlineStyle){let p=[...o?[`, if (__hover.contains('${o}')) '${o}'`]:[],...a?[`, if (__focus.contains('${a}')) '${a}'`]:[],...c?[`, if (__active.contains('${c}')) '${c}'`]:[]].join("");return{expr:`roseResolve(${p?`<String>['${s[0]}'${p}]`:`const <String>['${s[0]}']`}, '${n.scope}', '${e.tag.toLowerCase()}')`,model:i,hoverKey:o,focusKey:a,activeKey:c}}let d=[...s.map(p=>`'${p}'`),...t.dynamicClassExprs.map(p=>Qt(p,n.stateNames,n.mapBinds))],u=d.every(p=>p.startsWith("'"))&&!o&&!a&&!c;o&&d.push(`if (__hover.contains('${o}')) '${o}'`),a&&d.push(`if (__focus.contains('${a}')) '${a}'`),c&&d.push(`if (__active.contains('${c}')) '${c}'`);let l=[`${u?"const ":""}<String>[${d.join(", ")}]`,`'${n.scope}'`];if(t.inlineStyle&&l.push(`inline: RoseStyle(${$c(t.inlineStyle).join(", ")})`),t.dynamicStyle.length){let p=t.dynamicStyle.map(f=>`'${f.prop}': ${Qt(f.code,n.stateNames,n.mapBinds)}`).join(", ");l.push(`props: <String, dynamic>{${p}}`)}return{expr:`roseResolve(${l.join(", ")}, '${e.tag.toLowerCase()}')`,model:i,hoverKey:o,focusKey:a,activeKey:c}}function k$(e,t,n,s){let r=e.tag.toLowerCase(),i=s.expr,o=s.model;if(r==="slot"){let g=e.attrs.find($=>$.name==="name"),y=g&&g.value.kind==="text"?g.value.text:"";if(!y||y==="default")return"slotDefault";let m=e.attrs.filter($=>$.name!=="name"&&$.value.kind==="expr").map($=>`'${$.name}': ${Qt($.value.code,t.stateNames,t.mapBinds)}`).join(", "),b=es(e.children,t);return`slot${or(y)} != null ? slot${or(y)}!({${m}}) : ${b}`}let a=t.components.find(g=>g.name.toLowerCase()===r);if(a){let y=[...It(e).entries()].map(([v,_])=>`${vc(v)}: ${si({name:v,value:{kind:"expr",code:_}},t)}, ${ze(v)}: (v) => __set('${_}', v)`),m=e.attrs.filter(v=>v.name!=="class"&&!/^bind:(value|checked|group|open)$/.test(v.name)).map(v=>`${vc(v.name)}: ${si(v,t)}`).join(", "),b=Pt(e.children),$=[];if(a.slots.hasDefault){let v=b.defaultNodes.length?b.defaultNodes:st(a.nodes,"default");$.push(`slotDefault: ${es(v,t)}`)}for(let v of a.slots.named){let _=b.named.get(v.name)??st(a.nodes,v.name),k=Lt(_,v.props,S=>`props['${S}']`);$.push(`slot${or(v.name)}: (props) => ${es(k,t)}`)}let w=[m,...y,...$].filter(Boolean).join(", ");return`${a.className}(${w})`}if(r==="progress"){let g=e.attrs.find(w=>w.name==="value"),y=e.attrs.find(w=>w.name==="max"),m=g&&g.value.kind==="expr"?Qt(g.value.code,t.stateNames,t.mapBinds):g&&g.value.kind==="text"?g.value.text:"0",b=y&&y.value.kind==="text"?y.value.text:"100",$=`LinearProgressIndicator(value: (${m}).toDouble() / (${b}).toDouble())`;return i?`roseBox(${i}, ${$})`:$}if(r==="video"){let g=e.attrs.find($=>$.name==="src"),y=g&&g.value.kind==="text"?g.value.text:"",m=i?`roseBox(${i}, `:"",b=i?")":"";return`${m}Container(padding: const EdgeInsets.all(8), child: Text('\u{1F3AC} ${y.replace(/'/g,"\\'")}', style: const TextStyle(fontSize: 12, color: Colors.grey)))${b}`}if(r==="audio"){let g=e.attrs.find($=>$.name==="src"),y=g&&g.value.kind==="text"?g.value.text:"",m=i?`roseBox(${i}, `:"",b=i?")":"";return`${m}Container(padding: const EdgeInsets.all(8), child: Text('\u{1F50A} ${y.replace(/'/g,"\\'")}', style: const TextStyle(fontSize: 12, color: Colors.grey)))${b}`}if(r==="img"){let g=e.attrs.find($=>$.name==="src"),y=g&&g.value.kind==="text"?g.value.text:"";if(!y)return"const SizedBox.shrink()";let m="",b=bc.get(y);if(b){let $=e.attrs.find(_=>_.name==="width"),w=e.attrs.find(_=>_.name==="height"),v=[$?`width: ${$.value.kind==="text"?$.value.text:48}.0`:"",w?`height: ${w.value.kind==="text"?w.value.text:48}.0`:""].filter(Boolean).join(", ");m=`Image.asset('${b}', fit: BoxFit.contain${v?", "+v:""})`}else{let $=Sc.get(y);if($){let w=e.attrs.find(S=>S.name==="width"),v=e.attrs.find(S=>S.name==="height"),_=w&&w.value.kind==="text"&&Number(w.value.text)||72,k=v&&v.value.kind==="text"&&Number(v.value.text)||72;m=`SizedBox(width: ${_}.0, height: ${k}.0, child: CustomPaint(painter: RoseSvgPainter(ops: ${$.name}Ops, fills: ${$.name}Fills, vbWidth: ${$.name}VbWidth, vbHeight: ${$.name}VbHeight)))`}else/^data:/.test(y)?(t.warnings.push("flutter: an inlined data-URI image has no Bundle asset - add it to pubspec assets"),m="const Icon(Icons.image)"):m=`Image.network('${y.replace(/'/g,"\\'")}', fit: BoxFit.contain)`}return i?`roseBox(${i}, ${m})`:m}if(r==="a"){let g=e.attrs.find(w=>w.name==="href"),y=g?si(g,t):"''",m=e.children.map(w=>w.kind==="text"?w.value.replace(/\s+/g," "):w.kind==="expr"?`\${${Qt(w.code,t.stateNames,t.mapBinds)}}`:"").join("").trim(),b=i?`roseText(${JSON.stringify(m||"")}, ${i})`:`Text(${JSON.stringify(m||"")})`,$=`InkWell(onTap: () => Navigator.pushNamed(context, ${y}.toString()), child: ${b})`;return i?`roseBox(${i}, ${$})`:$}if(r==="input"||r==="textarea"){let g=e.attrs.find(O=>O.name==="placeholder"),y=g?si(g,t):"''",m=e.attrs.find(O=>O.name==="type"),b=m&&m.value.kind==="text"?m.value.text:"text",$=e.attrs.find(O=>O.name==="bind:checked"),w=e.attrs.find(O=>O.name==="bind:group"),v=e.attrs.find(O=>O.name==="bind:value"),_=O=>O&&O.value.kind==="expr"&&t.stateNames.has(O.value.code.trim())?O.value.code.trim():"",k=e.attrs.find(O=>O.name==="value"),S=k?k.value.kind==="text"?JSON.stringify(k.value.text):si(k,t):"true";if(b==="checkbox"){let O=_(w),P=_($);return O?`Checkbox(value: ((${O} as List).contains(${S})), onChanged: (checked) { final list = List.of(${O} as List); if (checked) { list.add(${S}); } else { list.remove(${S}); } __set('${O}', list); })`:P?`Checkbox(value: ${P} == true, onChanged: (value) => __set('${P}', value ?? false))`:"Checkbox(value: false, onChanged: null)"}if(b==="radio"){let O=_(w);return O?`Radio<dynamic>(value: ${S}, groupValue: ${O}, onChanged: (value) => __set('${O}', value))`:"const SizedBox.shrink()"}let C=O=>t.componentProps.has(O)?`(value) => ${ze(O)}?.call(value)`:null,x=null,A=e.attrs.find(O=>O.name==="name"),R=A&&A.value.kind==="text"?A.value.text.trim():"",T=R?An(t.forms,R):null;if(!v&&T&&(x=`(value) => __set('${T}', value)`),v&&v.value.kind==="expr"){let O=v.value.code.trim();x=C(O)??`(value) => __set('${O}', value)`}else{let O=k&&k.value.kind==="expr"?k.value.code.trim():"",P=O?C(O):null;P&&(x=P)}let M=r==="textarea"?4:1;if(b==="range"){let O=e.attrs.find(re=>re.name==="min"),P=e.attrs.find(re=>re.name==="max"),j=(re,xe)=>re&&re.value.kind==="text"?re.value.text:re&&re.value.kind==="expr"?si(re,t):xe,B=j(O,"0"),U=j(P,"100"),ce=v&&v.value.kind==="expr"?v.value.code.trim():"",N=ce?`(__set('${ce}', value))`:"null",W=ce||j(k,B);return`roseSlider(${i??"null"}, ${W}, ${B}, ${U}, ${N})`}let F=`roseInputField(${i??"null"}, ${y}.toString(), ${x??"null"}, lines: ${M})`,I=s.focusKey?`Focus(onFocusChange: (v) => __setFocus('${s.focusKey}', v), child: ${F})`:F;return s.activeKey&&(I=`Listener(onPointerDown: (e) => __setActive('${s.activeKey}', true), onPointerUp: (e) => __setActive('${s.activeKey}', false), onPointerCancel: (e) => __setActive('${s.activeKey}', false), child: ${I})`),I}if(r==="button"){let g=e.attrs.find(v=>v.name==="on:click"||v.name==="on:submit"),y=g&&g.value.kind==="expr"?A$(g.value.code.trim(),t):"null";!g&&tr(e)&&t.pageAction&&(y=`() => __runAction('${t.pageAction}')`);let m=e.children.map(v=>v.kind==="text"?v.value.replace(/\s+/g," "):v.kind==="expr"?`\${${Qt(v.code,t.stateNames,t.mapBinds)}}`:"").join("").trim(),b=i?`roseText(${JSON.stringify(m||"Button")}, ${i})`:`Text(${JSON.stringify(m||"Button")})`,$=`ElevatedButton(onPressed: ${y}, child: ${b})`,w=i?`roseBox(${i}, ${$})`:$;return s.focusKey&&(w=`Focus(onFocusChange: (v) => __setFocus('${s.focusKey}', v), child: ${w})`),s.hoverKey&&(w=`MouseRegion(onEnter: (e) => __setHover('${s.hoverKey}', true), onExit: (e) => __setHover('${s.hoverKey}', false), child: ${w})`),s.activeKey&&(w=`Listener(onPointerDown: (e) => __setActive('${s.activeKey}', true), onPointerUp: (e) => __setActive('${s.activeKey}', false), onPointerCancel: (e) => __setActive('${s.activeKey}', false), child: ${w})`),w}if(r==="select"){let g=e.attrs.find(S=>S.name==="bind:value"),y=g&&g.value.kind==="expr"&&t.stateNames.has(g.value.code.trim())?g.value.code.trim():"",m=e.children.filter(S=>S.kind==="element"&&S.tag.toLowerCase()==="option").map(S=>{let C=S.children.filter(T=>T.kind==="text").map(T=>T.value.trim()).join(""),x=S.attrs.find(T=>T.name==="value"),A=x&&x.value.kind==="text"?x.value.text:C,R=bt(S).staticClasses;for(let T of R)t.styleClasses.add(T);return{label:C,value:A,cls:R}}),b=S=>S.length===1?`roseResolve(const <String>['${S[0]}'], '${t.scope}', 'option')`:S.length?`roseResolve(const <String>[${S.map(C=>`'${C}'`).join(", ")}], '${t.scope}', 'option')`:null,$=(S,C)=>{let x=b(C);return x?`roseText(${JSON.stringify(S)}, ${x})`:`Text(${JSON.stringify(S)})`},w=m.map(S=>`DropdownMenuItem<String>(value: ${JSON.stringify(S.value)}, child: ${$(S.label,S.cls)})`).join(", "),v=y?`onChanged: (value) => __set('${y}', value)`:"onChanged: null",_=y?`value: ${y}?.toString()`:"value: null";if(e.attrs.some(S=>S.name==="multiple"))return`Wrap(children: [${m.map(C=>`Row(children: [Checkbox(value: ((${y} as List).contains(${JSON.stringify(C.value)})), onChanged: (checked) { final list = List.of(${y} as List); if (checked) { list.add(${JSON.stringify(C.value)}); } else { list.remove(${JSON.stringify(C.value)}); } __set('${y}', list); }), ${$(C.label,C.cls)}])`).join(", ")}])`;let k=`DropdownButton<String>(items: <DropdownMenuItem<String>>[${w}], ${v}, ${_})`;return i?`roseBox(${i}, ${k})`:k}if(r==="hr")return"const Divider()";if(r==="br")return"const SizedBox(height: 12)";if(o.display==="none")return"const SizedBox.shrink()";let c=pa(o),d=ii(e.children,t),u=r$[r]==="Text"&&!e.children.some(g=>g.kind==="element");if(u&&i&&d.every(g=>g.startsWith("Text("))){let g=/^h[1-6]$/.test(r)?`, base: const TextStyle(fontSize: ${Ip[r]}, fontWeight: FontWeight.bold)`:"",y=`roseText(${R$(e.children,t)}, ${i}${g})`;return c?`roseBox(${i}, roseFlex(${i}, [${y}]))`:`roseBox(${i}, ${y})`}let l;if(!i&&u&&d.every(g=>g.startsWith("Text("))?l=d.length===1?d[0]:`Row(mainAxisSize: MainAxisSize.min, children: [${d.join(", ")}])`:d.length===0?l="const SizedBox.shrink()":d.length===1?l=d[0]:c?l=`roseFlex(${i}, [${d.join(", ")}])`:l=`${i$.has(r)?"Row(crossAxisAlignment: CrossAxisAlignment.center":"Column(crossAxisAlignment: CrossAxisAlignment.start"}, children: [${d.join(", ")}])`,!i)return u&&/^h[1-6]$/.test(r)?`Container(child: DefaultTextStyle(style: const TextStyle(fontSize: ${Ip[r]}, fontWeight: FontWeight.bold), child: ${l}))`:l;c&&!l.startsWith("roseFlex(")&&(l=`roseFlex(${i}, [${l}])`);let p=`roseBox(${i}, ${l})`,f=s.focusKey?`Focus(onFocusChange: (v) => __setFocus('${s.focusKey}', v), child: ${p})`:p,h=s.hoverKey?`MouseRegion(onEnter: (e) => __setHover('${s.hoverKey}', true), onExit: (e) => __setHover('${s.hoverKey}', false), child: ${f})`:f;return s.activeKey?`Listener(onPointerDown: (e) => __setActive('${s.activeKey}', true), onPointerUp: (e) => __setActive('${s.activeKey}', false), onPointerCancel: (e) => __setActive('${s.activeKey}', false), child: ${h})`:h}function R$(e,t){let n="";for(let s of e)s.kind==="text"?n+=s.value.replace(/\s+/g," ").replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\$/g,"\\$"):s.kind==="expr"&&(n+="${"+Qt(ri(s.code,t),t.stateNames,t.mapBinds)+"}");return"'"+n+"'"}function A$(e,t){if(!e)return"null";if(/^[A-Za-z_$][\w$]*$/.test(e))return e;let n=t.inline.get(e);if(n)return n;let s=`__h${t.inline.size}`;return t.inline.set(e,s),s}function si(e,t){return e.value.kind==="expr"?Qt(e.value.code??"",t.stateNames,t.mapBinds):e.value.kind==="text"?JSON.stringify(e.value.text??""):(t.warnings.push("flutter: a mixed attribute value is read as an empty string"),"''")}function Qt(e,t=new Set,n=new Set){let s=Oe(e.trim(),"roseContentList","roseContentGet","[]");if(s=s.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(r,i)=>`(__params[${JSON.stringify(i)}] ?? '')`),s=s.replace(/\$query\s*\(\s*\)/g,"__params"),/`/.test(s)||/\?\./.test(s)||/\?\?/.test(s)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(s)||/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(s)){let r=G(s,{...Aa,read:i=>i},new Set);if(r!==null)return r}return s=s.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),s=s.replace(/\$actionPending\s*\(\s*\)/g,"false"),s=s.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,'"$2"'),s=s.replace(/\$(?:store|cookies|sessionCookie)\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),s=s.replace(/\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,(r,i,o)=>n.has(i)?`${i}['${o}']`:r),s=s.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(r,i)=>t.has(i)||Wp(i)?Wp(i)?r:i:r),s=s.replace(/===/g,"==").replace(/!==/g,"!="),s=s.replace(/\bundefined\b/g,"null"),s=s.replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g,(r,i,o)=>`${i}'${o}':`),s=nn(s,C$),s=pt(s,r=>`(${r}).toString()`),s}function xa(e,t=new Set){if(/\.(map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(e)){let n=G(e,Aa,new Set);if(n!==null)return n}return Qt(e,new Set,t)}function Wp(e){return/^(if|for|while|switch|catch|function|return|typeof|new|await|async|true|false|null|undefined|this|super)$/.test(e)}function vc(e){return e.replace(/[-_]([a-z0-9])/gi,(t,n)=>n.toUpperCase())}function or(e){let t=vc(e);return t.charAt(0).toUpperCase()+t.slice(1)}function ka(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^\w]/g,"_").toLowerCase()}function j$(e){let t=[];for(let n of e.matchAll(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^\n;]+)/gm)){let s=n[1],r=n[2].trim();/^\$(?:state|derived|data|kv|persist)\b/.test(r)||/^([\[{'"`]|-?\d|true|false|null)/.test(r)&&T$(r)&&t.push({name:s,init:r})}return t}function T$(e){let t=0;for(let n=0;n<e.length;n++){let s=e[n];if(s==='"'||s==="'"){for(n++;n<e.length&&e[n]!==s;n++)e[n]==="\\"&&n++;continue}if(s==="("||s==="["||s==="{")t++;else if((s===")"||s==="]"||s==="}")&&(t--,t<0))return!1}return t===0}function E$(e){let t={state:[],derived:[],data:[]};if(!e.trim())return t;for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|persist|kv)\b(?:<[^>]*>)?\s*\(/g)){let s=(n.index??0)+n[0].length-1;t.state.push({name:n[1],init:n[2]==="kv"?"null":Dp(e,s)})}for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$derived\b(?:<[^>]*>)?\s*\(/g)){let s=(n.index??0)+n[0].length-1;t.derived.push({name:n[1],expr:Dp(e,s)})}for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$data\b(?:<[^>]*>)?\s*\(/g))t.data.push({name:n[1]});return t}function Dp(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return e.slice(t+1,s).trim()}return""}function O$(e,t,n,s,r,i=[],o=new Set){if(!e.trim())return{methods:"",mounts:[]};let a=e.replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,"").replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,"");try{a=s$(a,{loader:"ts",format:"esm",target:"es2020"}).code}catch{r.push("flutter: the script did not parse as TypeScript - handlers are stubs")}for(let p of[...t.state.map(f=>f.name),...t.derived.map(f=>f.name),...t.data.map(f=>f.name)]){let h=new RegExp(`\\b(?:let|const|var)\\s+${eo(p)}\\s*(?::[^=;\\n]*)?=\\s*\\$(?:state|derived|data|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(a);if(!h)continue;let g=h.index+h[0].length-1,y=yc(a,g);y<0||(a=a.slice(0,h.index)+a.slice(y+1).replace(/^;/,""))}let c=[];try{c=Qe(e).actions.map(p=>p.name)}catch{}let d=[];for(let p of c)a=a.replace(new RegExp(`\\b(?:async\\s+)?function\\s+${eo(p)}\\s*\\(`,"g"),`function __server_${p}(`),a=a.replace(new RegExp(`\\bconst\\s+${eo(p)}\\s*=`,"g"),`const __server_${p} =`),d.push(` Future<void> ${p}() async {
|
|
3583
|
-
final patch = await
|
|
3583
|
+
final patch = await rosefcAction('${s}', '${p}'${i.length?", __formFields()":""});
|
|
3584
3584
|
if (!mounted || patch.isEmpty) return;
|
|
3585
3585
|
patch.forEach((key, value) { __set(key, value); });
|
|
3586
3586
|
}`);for(let p of t.state){a=a.replace(new RegExp(`\\b${eo(p.name)}\\s*\\(\\s*\\)`,"g"),p.name);let f=p.name[0].toUpperCase()+p.name.slice(1);a=a.replace(new RegExp(`\\bset${eo(f)}\\s*\\(`,"g"),`__set('${p.name}', `)}a=a.replace(/\$setState\s*\(/g,"__set(").replace(/\$action\s*\(/g,"__runAction(").replace(/\bonMount\s*\(\s*(?:\(\)\s*=>|function\s*\(\s*\))\s*/g,"__onMount(").replace(/\bonCleanup\s*\(\s*(?:\(\)\s*=>|function\s*\(\s*\))\s*/g,"__onCleanup(").replace(/\brefresh\s*\(\s*\)/g,"__loadData()").replace(/^\s*export\s+(?=(?:async\s+)?(?:function|const|let|var|class)\b)/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"");let u=[];for(let p of a.matchAll(/^(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/gm)){let f=p[1];if(f.startsWith("__"))continue;let h=p.index+p[0].length-1,g=yc(a,h);if(g<0)continue;let y=a.slice(h+1,g),m=p[0].includes("async")?"Future<void>":"dynamic",b=p[0].includes("async")?" async":"",$=p[2].split(",").map(v=>v.trim()).filter(Boolean).map(v=>{let[_,k]=v.split(":").map(C=>C.trim());return`${k&&/^(string|number|boolean|dynamic|any)$/i.test(k)?"dynamic":k||"dynamic"} ${_}`}).join(", "),w=mc(y,n,r,o);u.push(` ${m} ${f}(${$})${b} ${w}`)}let l=[];for(let p of a.matchAll(/__onMount\s*\(/g)){let f=p.index+p[0].length-1,h=yc(a,f);if(h<0)continue;let y=a.slice(f+1,h).trim().replace(/^\(\s*\)\s*=>\s*/,"").replace(/^function\s*\(\s*\)\s*/,"").trim();y.startsWith("{")&&y.endsWith("}")?l.push(mc(y.slice(1,-1),n,r,o)):l.push(`${mc(y,n,r,o).replace(/^\{/,"").replace(/\}$/,"")}`)}return{methods:[...u,...d].join(`
|
|
3587
3587
|
|
|
3588
3588
|
`),mounts:l}}function N$(e){return{expr:t=>Qt(t,e.stateNames,e.mapBinds),set:(t,n)=>`__set('${t}', ${n})`,update:(t,n)=>`__set('${t}', (${n})(${t}))`,action:t=>`__runAction('${t}')`,refresh:()=>"__loadData()"}}function Yi(e){if(!/^"[\s\S]*"$/.test(e))return e;let t;try{t=JSON.parse(e)}catch{return e}return`'${t.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\$/g,"\\$").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function mc(e,t,n,s=new Set){e=Ot(e),e=tn(e),e=zt(e,{target:"flutter",options:o=>Dt(o,"quoted"),empty:"null",file:t,warn:o=>n.push(`flutter: ${o}`)}).code,e=sn(e),e=rn(e,(o,a,c)=>{let d=G(c,Aa,new Set([a]));if(d===null)return null;let u=`${o}`;return`__set('${o}', ${d})`.replace(new RegExp(`\\b${a}\\b`,"g"),u)}),e=on(e,(o,a)=>{let c=G(a,Aa,new Set);return c===null?null:`__set('${o}', ${c})`});let r=[[/new\s+FormData|FormData\(/,"FormData"],[/\$\{/,"a template literal"],[/\bnew\s+[A-Z]/,"new"],[/\?\./,"optional chaining"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bconsole\./,"console"]];for(let[o,a]of r)if(o.test(e))return n.push(`flutter: ${t}: a handler body uses ${a}, which has no Dart equivalent - emitted as a commented stub`),`{
|
|
3589
|
-
//
|
|
3589
|
+
// rosefc: handler body not translated (uses ${a}).
|
|
3590
3590
|
return null;
|
|
3591
3591
|
}`;let i=e.trim();return i=i.replace(/\bconsole\.log\(/g,"debugPrint("),i=i.replace(/\btrue\b/g,"true").replace(/\bfalse\b/g,"false"),i=i.replace(/===/g,"==").replace(/!==/g,"!="),i=i.replace(/\bnull\b/g,"null").replace(/\bundefined\b/g,"null"),i=i.replace(/\bString\(/g,"("),i=i.replace(/\bMath\./g,"math."),i=i.replace(/\$formRead\(\s*(['"])([^'"]*)\1\s*\)/g,(o,a,c)=>c),i=i.replace(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,"var $1 ="),i=Rn(i,o=>`${o}.isNotEmpty`),i=pt(i,o=>`(${o}).toString()`),s.size&&(i=i.replace(/\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,(o,a,c)=>s.has(a)?`${a}['${c}']`:o)),`{
|
|
3592
3592
|
${i.replace(/^/gm," ")}
|
|
@@ -3594,7 +3594,7 @@ ${i.replace(/^/gm," ")}
|
|
|
3594
3594
|
`),C=[];for(let x of($.script??"").matchAll(/import\s+\w+\s+from\s+['"][^'"]*\/(\w+)\.rose['"]/g))C.push(x[1]);c.push({route:B$(m),name:sw(m.replace(/\[([^\]]+)\]/g,"param_$1").replace(/[^\w-]/g,"_")),nodes:_,script:k.join(`
|
|
3595
3595
|
`),style:S,params:[...m.matchAll(/\[([^\]]+)\]/g)].map(x=>x[1]),title:I$($.head),components:C})}let d=[];for(let g of o){let y=Ce(await Ht.promises.readFile(g,"utf8"),g,"python");t.push(...y.warnings),d.push({file:g,name:it.basename(g,".rose"),nodes:y.nodes,script:y.script,style:y.style})}d.length&&t.push(`python: ${d.length} component(s) are inlined at their call site (Tk has no component boundary)`);let u=Mt(n),l=xt([...c.map(g=>g.script),...d.map(g=>g.script)]);await Ht.promises.rm(s,{recursive:!0,force:!0}),await Ht.promises.mkdir(it.join(s,"pages"),{recursive:!0}),Qp=await L$(n,it.join(s,"assets"),t);let p=d.map(g=>g.style??"").join(`
|
|
3596
3596
|
`),f=[...c.flatMap(g=>Vp([g.style,p].filter(y=>y&&y.trim()).join(`
|
|
3597
|
-
`),t,g.name)),...Vp(ke,t)],h=new Map(f.filter(g=>g.className.startsWith("__hover_")).map(g=>[g.className,g.model]));await Ht.promises.writeFile(it.join(s,"styles.py"),z$(f),"utf8"),await Ht.promises.writeFile(it.join(s,"
|
|
3597
|
+
`),t,g.name)),...Vp(ke,t)],h=new Map(f.filter(g=>g.className.startsWith("__hover_")).map(g=>[g.className,g.model]));await Ht.promises.writeFile(it.join(s,"styles.py"),z$(f),"utf8"),await Ht.promises.writeFile(it.join(s,"rosefc.py"),H$(e.apiBase??"",u,l),"utf8"),await Ht.promises.writeFile(it.join(s,"pages","__init__.py"),"","utf8");for(let g of c)await Ht.promises.writeFile(it.join(s,"pages",g.name+".py"),U$(g,d,t,u,p,h),"utf8");return await Ht.promises.writeFile(it.join(s,"app.py"),J$(c),"utf8"),await Ht.promises.writeFile(it.join(s,"README.md"),V$(e.apiBase??"",c.length,t),"utf8"),{pages:c.map(g=>`pages/${g.name}.py`),components:d.map(g=>g.name)}}function B$(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function I$(e){if(!e)return"";let t=/<title>([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/\{[^}]*\}/g,"").trim():""}function W$(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}function Xp(e){let t=new Map,n=e.replace(/\/\*[\s\S]*?\*\//g,"");for(let s of n.matchAll(/([^{}]+)\{([^{}]*)\}/g)){let r=s[1].trim();if(r.startsWith("@"))continue;let i=/font-family\s*:\s*([^;]+)/i.exec(s[2])?.[1]?.trim();if(i)for(let o of r.split(",")){let a=/\.([\w-]+)/.exec(o.trim())?.[1];a&&t.set(a,i)}}return t}function Vp(e,t,n){if(!e.trim())return[];let s=Te(e);for(let o of s.warnings)t.push(`python: ${o}`);let r=Xp(e),i=new Map;for(let o of s.rules){let a=o.parts[o.parts.length-1];if(o.hover){for(let c of a.classes){let d=n?`__hover_${c}__${n}`:`__hover_${c}`;i.set(d,fe(i.get(d)??null,o.hover))}a.classes.length||t.push(`python: :hover on "${o.selector}" has no class to key on - the rule is dropped`)}if(!(o.media&&(o.media.min!==void 0&&Ta<o.media.min||o.media.max!==void 0&&Ta>o.media.max)))for(let c of a.classes){let d=n?`${c}__${n}`:c;i.set(d,fe(i.get(d)??null,o.model))}}for(let o of Cn(e))t.push(`python: font-family '${o}' needs a font installed on the host - the Tk default is used`);return[...i.entries()].map(([o,a])=>({className:o,model:a,rawFamily:r.get(o.split("__")[0])}))}function ai(e){if(!e)return null;let t=e.replace("#","").toLowerCase();return t.length===8&&t.slice(6)==="00"?null:`'#${t.slice(0,6)}'`}function D$(e,t){if(e.fontSize===void 0&&e.fontWeight===void 0&&!e.italic&&!e.fontFamily&&!e.underline&&!e.strike)return null;let n=nr(t??e.fontFamily??""),s=(e.fontFamily??"").replace(/^['"]|['"]$/g,"").trim(),r=n==="monospace"?"Courier New":n==="serif"?"Times New Roman":s&&!/^(?:system-ui|sans-serif|ui-sans-serif)$/i.test(s)?s:"Segoe UI",i=e.fontSize!==void 0?Math.max(8,Math.round(e.fontSize/1.5)):11,o=[`'${r.replace(/'/g,"\\'")}'`,String(i)];return(e.fontWeight??0)>=600&&o.push("'bold'"),e.italic&&o.push("'italic'"),e.underline&&o.push("'underline'"),e.strike&&o.push("'overstrike'"),`(${o.join(", ")})`}function Hn(e,t){let n=[],s=ai(e.background??e.gradient?.stops[0]?.color);e.width&&e.width.u==="px"&&n.push({key:"width",value:String(Math.round(e.width.n))}),e.height&&e.height.u==="px"&&n.push({key:"height",value:String(Math.round(e.height.n))}),s&&n.push({key:"bg",value:s});let r=ai(e.color);r&&n.push({key:"fg",value:r});let i=D$(e,t);if(i&&n.push({key:"font",value:i}),e.padding){let[o,a,c,d]=e.padding;n.push({key:"padx",value:String(Math.round((d+a)/2))}),n.push({key:"pady",value:String(Math.round((o+c)/2))})}return e.borderWidth&&e.borderWidth.some(o=>o>0)&&(n.push({key:"highlightbackground",value:ai(e.borderColor??"#cccccc")??"'#cccccc'"}),n.push({key:"highlightthickness",value:String(Math.max(...e.borderWidth))})),e.textAlign&&n.push({key:"justify",value:`'${e.textAlign==="center"?"center":e.textAlign==="right"?"right":"left"}'`}),n}function ts(e,t){let n={Frame:["bg","padx","pady","highlightbackground","highlightthickness","width","height"],Label:["bg","fg","font","padx","pady","highlightbackground","highlightthickness","justify","wraplength","width","height"],Button:["bg","fg","font","padx","pady","highlightbackground","highlightthickness","justify","state"],Entry:["bg","fg","font","padx","pady","highlightbackground","highlightthickness","justify"],Text:["bg","fg","font","padx","pady","highlightbackground","highlightthickness","wrap"]};return e.filter(s=>(n[t]??[]).includes(s.key))}function cs(e){return e.map(t=>`${t.key}=${t.value}`).join(", ")}function Yp(e){let t={};for(let n of["color","fontSize","fontWeight","fontFamily","italic","lineHeight","letterSpacing","textAlign","textTransform","underline","strike"]){let s=e[n];s!==void 0&&(t[n]=s)}return t}function ja(e,t){if(!t.textTransform)return e;let n=t.textTransform==="uppercase"?"upper":t.textTransform==="lowercase"?"lower":"title";if(e.startsWith('f"'))return`${e}.${n}()`;if(e.startsWith('"')&&e.endsWith('"')){let s=JSON.parse(e);return JSON.stringify(t.textTransform==="uppercase"?s.toUpperCase():t.textTransform==="lowercase"?s.toLowerCase():s.replace(/\b\w/g,r=>r.toUpperCase()))}return`${e}.${n}()`}function z$(e){let t=['"""The .rose <style> classes, compiled to Tk option dicts.',"","The tables are built by the same cascade the page renderer bakes at export","time. They exist at runtime for one caller: a class bound to state","(`class={expr}`), which no exporter can resolve ahead of time.",'"""',"","STYLES = {"];for(let n of e){let s=Hn(n.model,n.rawFamily);if(!s.length)continue;let r=s.map(i=>`'${i.key}': ${i.value}`);t.push(` '${n.className}': {${r.join(", ")}},`)}return t.push("}","",""),t.join(`
|
|
3598
3598
|
`)}function H$(e,t,n=[]){let s=t?`
|
|
3599
3599
|
# The project's markdown collections, baked at export time. A page reads them
|
|
3600
3600
|
# through rose_content_list / rose_content_get, the same shape the server-side
|
|
@@ -3918,7 +3918,7 @@ def data_patch(route):
|
|
|
3918
3918
|
"""The JSON half of a render: the state the page's $data produced."""
|
|
3919
3919
|
if not API_BASE:
|
|
3920
3920
|
return {}
|
|
3921
|
-
url = API_BASE + '/
|
|
3921
|
+
url = API_BASE + '/__rosefc/data?path=' + urllib.parse.quote(route)
|
|
3922
3922
|
try:
|
|
3923
3923
|
with urllib.request.urlopen(url, timeout=3) as response:
|
|
3924
3924
|
payload = json.loads(response.read().decode('utf-8'))
|
|
@@ -3950,14 +3950,14 @@ def action_patch(route, name):
|
|
|
3950
3950
|
return payload if isinstance(payload, dict) else {}
|
|
3951
3951
|
except Exception:
|
|
3952
3952
|
return {}
|
|
3953
|
-
${r}`}function V$(e,t,n){return`#
|
|
3953
|
+
${r}`}function V$(e,t,n){return`# Rosefc -> Python (Tkinter)
|
|
3954
3954
|
|
|
3955
|
-
Generated by \`
|
|
3955
|
+
Generated by \`rosefc export python\` from the project's \`.rose\` pages.
|
|
3956
3956
|
|
|
3957
3957
|
- ${t} page(s); stdlib only (no pip install)
|
|
3958
3958
|
- Run: \`python app.py\`
|
|
3959
|
-
- Server: \`
|
|
3960
|
-
\`
|
|
3959
|
+
- Server: \`rosefc export python --api <base>\` writes the base URL into
|
|
3960
|
+
\`rosefc.py\` (data channel + server actions). Current: \`${e||"(unset)"}\`
|
|
3961
3961
|
|
|
3962
3962
|
The state fields, handlers and the view tree are generated from the same IR the
|
|
3963
3963
|
web build and the mini-program target use. Every element is resolved through
|
|
@@ -3973,14 +3973,14 @@ media playback (a video or an audio becomes a placeholder label). A
|
|
|
3973
3973
|
class bound to state (class={expr}) resolves at runtime from styles.py.
|
|
3974
3974
|
${Nt(n)}`}function J$(e){let t=e.map(s=>`from pages import ${s.name} as page_${s.name}`).join(`
|
|
3975
3975
|
`),n=e.map(s=>` ('${s.route}', page_${s.name}),`).join(`
|
|
3976
|
-
`);return`"""
|
|
3976
|
+
`);return`"""Rosefc - the exported Python desktop app (stdlib Tkinter)."""
|
|
3977
3977
|
import json
|
|
3978
3978
|
import os
|
|
3979
3979
|
import re
|
|
3980
3980
|
import tkinter as tk
|
|
3981
3981
|
from tkinter import ttk
|
|
3982
3982
|
|
|
3983
|
-
import
|
|
3983
|
+
import rosefc
|
|
3984
3984
|
from styles import STYLES
|
|
3985
3985
|
|
|
3986
3986
|
${t}
|
|
@@ -3991,7 +3991,7 @@ ${n}
|
|
|
3991
3991
|
|
|
3992
3992
|
# $persist storage: one JSON file beside the app, so a persisted field survives
|
|
3993
3993
|
# a restart exactly as localStorage does on the web.
|
|
3994
|
-
STORE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.
|
|
3994
|
+
STORE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.rosefc-state.json')
|
|
3995
3995
|
try:
|
|
3996
3996
|
with open(STORE_PATH, 'r', encoding='utf-8') as __f:
|
|
3997
3997
|
_rose_store = json.load(__f)
|
|
@@ -4025,7 +4025,7 @@ class RoseState(dict):
|
|
|
4025
4025
|
class RoseApp(tk.Tk):
|
|
4026
4026
|
def __init__(self):
|
|
4027
4027
|
super().__init__()
|
|
4028
|
-
self.title('
|
|
4028
|
+
self.title('Rosefc')
|
|
4029
4029
|
self.geometry('900x720')
|
|
4030
4030
|
self.configure(bg='#ffffff')
|
|
4031
4031
|
# The shell's body { padding: 2rem }: a Frame's padx/pady is interior
|
|
@@ -4082,7 +4082,7 @@ class RoseApp(tk.Tk):
|
|
|
4082
4082
|
else:
|
|
4083
4083
|
st[__k] = __v
|
|
4084
4084
|
st.update(params)
|
|
4085
|
-
st.update(
|
|
4085
|
+
st.update(rosefc.data_patch(route))
|
|
4086
4086
|
# A $persist field starts from the on-disk store when it has been
|
|
4087
4087
|
# written before - that is what makes it survive a restart.
|
|
4088
4088
|
for __k in getattr(module, 'PERSIST', ()):
|
|
@@ -4116,7 +4116,7 @@ class RoseApp(tk.Tk):
|
|
|
4116
4116
|
self.show(self.current)
|
|
4117
4117
|
|
|
4118
4118
|
def run_action(self, route, name):
|
|
4119
|
-
patch =
|
|
4119
|
+
patch = rosefc.action_patch(route, name)
|
|
4120
4120
|
if patch:
|
|
4121
4121
|
self.states.setdefault(route, {}).update(patch)
|
|
4122
4122
|
self.render()
|
|
@@ -4146,8 +4146,8 @@ import tkinter as tk
|
|
|
4146
4146
|
from tkinter import ttk
|
|
4147
4147
|
|
|
4148
4148
|
from styles import STYLES
|
|
4149
|
-
import
|
|
4150
|
-
from
|
|
4149
|
+
import rosefc
|
|
4150
|
+
from rosefc import roseThrow, rose_text, rose_button, rose_entry, rose_html_label${b.dyn.used?", rose_resolve, rose_apply, rose_join, rose_tokens":""}${b.links.used?", rose_link":""}${s&&a.length?", rose_content_list, rose_content_get":""}${T?", rose_native":""}
|
|
4151
4151
|
|
|
4152
4152
|
${k}
|
|
4153
4153
|
${_}
|
|
@@ -4189,15 +4189,15 @@ ${S?S+`
|
|
|
4189
4189
|
${A}${$||" pass"}
|
|
4190
4190
|
`}function lt(e,t={}){let n=e.layout.dir,s=[],r="w";e.layout.align==="center"?r="center":(e.layout.align==="end"||e.layout.align==="stretch")&&(r=n==="row"?"s":"e"),s.push(`anchor='${r}'`),n==="row"?s.push(`side='${t.last&&e.layout.justify==="between"?"right":"left"}'`):t.last&&e.layout.justify==="between"&&s.push("side='bottom'"),t.fill&&s.push("fill='x'"),t.expand&&s.push("expand=True");let[i,o,a,c]=t.model?.margin??[0,0,0,0],d=e.seq.n>1?e.layout.gap:0;return n==="row"?((c||o||d)&&s.push(`padx=(${Math.round(c+d)}, ${Math.round(o)})`),(i||a)&&s.push(`pady=(${Math.round(i)}, ${Math.round(a)})`)):((i||a||d)&&s.push(`pady=(${Math.round(i+d)}, ${Math.round(a)})`),(c||o)&&s.push(`padx=(${Math.round(c)}, ${Math.round(o)})`)),s.join(", ")}function Ca(e){let t=e.surface?`, bg=${e.surface}`:"";e.layout.dir==="row"?H(`tk.Frame(${e.parent}, width=1, height=1${t}).pack(side='left', expand=True)`,e):H(`tk.Frame(${e.parent}, width=1, height=1${t}).pack(expand=True)`,e)}function q$(e,t){return{dir:ir(e,t,P$),justify:e.justify,align:e.align,gap:Math.round(e.gap??0)}}function H(e,t){t.lines.push(" ".repeat(t.depth)+e)}function As(e,t){return e.map(n=>{switch(n.kind){case"expr":return{...n,code:Se(n.code,t)};case"text":return n;case"html":return{...n,code:Se(n.code,t)};case"const":return{...n,code:Se(n.code,t)};case"element":return{...n,attrs:n.attrs.map(s=>({...s,value:s.value.kind==="expr"?{kind:"expr",code:Se(s.value.code,t)}:s.value.kind==="mixed"?{kind:"mixed",parts:s.value.parts.map(r=>r.kind==="expr"?{kind:"expr",value:Se(r.value,t)}:r)}:s.value})),children:As(n.children,t)};case"if":return{...n,branches:n.branches.map(s=>({cond:s.cond?Se(s.cond,t):null,children:As(s.children,t)}))};case"each":return{...n,items:Se(n.items,t),children:As(n.children,t),fallback:n.fallback?As(n.fallback,t):void 0};case"await":return{...n,expr:Se(n.expr,t),pending:As(n.pending,t),then:As(n.then,t),catch:As(n.catch,t)};case"block":return{...n,children:As(n.children,t),fallback:n.fallback?As(n.fallback,t):void 0};default:return n}})}function Cs(e,t){let n=[];for(let s of e){if(s.kind==="element"&&s.tag==="slot"){let r=s.attrs.find(a=>a.name==="name"),i=r&&r.value.kind==="text"?r.value.text:"default",o=t.get(i);n.push(...o&&o.length?o:s.children);continue}if(s.kind==="element"){n.push({...s,children:Cs(s.children,t)});continue}if(s.kind==="if"){n.push({...s,branches:s.branches.map(r=>({...r,children:Cs(r.children,t)}))});continue}if(s.kind==="each"){n.push({...s,children:Cs(s.children,t),fallback:s.fallback?Cs(s.fallback,t):void 0});continue}if(s.kind==="block"){n.push({...s,children:Cs(s.children,t),fallback:s.fallback?Cs(s.fallback,t):void 0});continue}if(s.kind==="await"){n.push({...s,pending:Cs(s.pending,t),then:Cs(s.then,t),catch:Cs(s.catch,t)});continue}n.push(s)}return n}function kc(e){let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")");){let c=0,d=!0;for(let u=0;u<t.length;u++){let l=t[u];if(l==='"'||l==="'"||l==="`"){let p=l;for(u++;u<t.length&&t[u]!==p;)t[u]==="\\"&&u++,u++;continue}if(l==="(")c++;else if(l===")"&&(c--,c===0&&u!==t.length-1)){d=!1;break}}if(!d)break;t=t.slice(1,-1).trim()}let n=(c,d,u=0)=>{let l=0;for(let p=u;p<c.length;p++){let f=c[p];if(f==='"'||f==="'"||f==="`"){let h=f;for(p++;p<c.length&&c[p]!==h;)c[p]==="\\"&&p++,p++;continue}if(f==="("||f==="["||f==="{")l++;else if(f===")"||f==="]"||f==="}")l--;else if(l===0&&f===d)return p}return-1},s=n(t,"?");if(s<0)return t;let r=n(t,":",s+1);if(r<0)return t;let i=t.slice(0,s).trim(),o=kc(t.slice(s+1,r).trim()),a=kc(t.slice(r+1).trim());return`(${o} if ${i} else ${a})`}function G$(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}function En(e,t){let n=[],s=[];for(let a of e){if(a.kind==="text"||a.kind==="expr"){s.push(a);continue}s.length&&(n.push({kind:"text",nodes:s}),s=[]),n.push({kind:"node",node:a})}s.length&&n.push({kind:"text",nodes:s});let r=n.filter(a=>a.kind==="node"||a.nodes.some(c=>c.kind==="expr"||c.kind==="text"&&c.value.trim()!=="")),i=t.layout.justify,o=0;(i==="center"||i==="end")&&t.layout.dir==="row"&&Ca(t);for(let a=0;a<n.length;a++){let c=n[a],d=c===r[r.length-1],u=t.lines.length;if(c.kind==="text"){let l=ja(ef(c.nodes,t).trim(),t.inherited);if(l&&!/^[\s'\"]*$/.test(l)){t.seq.n++;let p=ts(Hn(t.inherited,t.rawFamily),"Label");H(`tk.Label(${t.parent}, text=${l}, wraplength=680${p.length?", "+cs(p):""}).pack(${lt(t,{last:d})})`,t)}}else Q$(c.node,{...t,lastChild:d,seq:t.seq});t.lines.length!==u&&(o++,(i==="between"&&!d||(i==="center"||i==="end")&&d&&t.layout.dir==="column")&&Ca(t))}i==="center"&&t.layout.dir==="row"&&o&&Ca(t)}function Jp(e,t){return e.includes("{")?"f"+JSON.stringify(e):JSON.stringify(e||t)}function ef(e,t){let n=[];for(let r of e)r.kind==="text"?n.push(r.value.replace(/\s+/g," ")):r.kind==="expr"&&n.push(`{rose_text(lambda: ${Kt(r.code,t)})}`);let s=n.join("").replace(/`/g,"'");return s.includes("{")?"f"+JSON.stringify(s).replace(/f\\"/g,"f'").replace(/\\"/g,"'"):JSON.stringify(s)}function Q$(e,t){switch(e.kind){case"text":case"expr":En([e],t);return;case"html":H(`rose_html_label(${t.parent}, ${Kt(e.code,t)})`,t);return;case"const":{let n=pt(e.code,s=>`str(${s})`);H(`${e.name} = ${Kt(n,t)}`,t);return}case"render":t.warnings.push(`python: {@render ${e.code}} is not expanded yet - renders nothing`);return;case"snippet":t.warnings.push(`python: {#snippet ${e.name}} is emitted where declared (no call-site expansion yet)`),En(e.children,t);return;case"if":{e.branches.forEach((n,s)=>{let r=s===0?`if ${Kt(n.cond??"false",t)}:`:n.cond===null?"else:":`elif ${Kt(n.cond,t)}:`;H(r,t),t.depth++;let i=t.lines.length;En(n.children,t),t.lines.length===i&&H("pass",t),t.depth--});return}case"each":{H(`__items = ${Kt(e.items,t)}`,t),H(`for ${e.binding} in (__items or []):`,t),t.depth++;let n={...t,lastChild:!1,mapBinds:new Set([...t.mapBinds,e.binding.replace(/[^\w]/g,"")]),loopVars:new Set([...t.loopVars??[],e.binding.replace(/[^\w]/g,"")])},s=t.lines.length;En(e.children,n),t.lines.length===s&&H("pass",t),t.depth--;return}case"await":{let n=t.awaits.length,s=`__await${n}_started`,r=`__await${n}_done`,i=`__await${n}_value`,o=`__await${n}_err`,a=Kt(kc(Se(Bt(e.expr),t.scriptConsts)),t);un(e.expr)||t.warnings.push(`${t.file}: the {#await} head is a promise this target cannot await - the then branch renders only for Promise.resolve/reject literals`),t.awaits.push({started:s,done:r,value:i,err:o,expr:a});let c=new Map;e.thenName&&c.set(e.thenName,i);let d=new Map;e.catchName&&d.set(e.catchName,o),H(`if not globals().get('${s}'):`,t),t.depth++,H(`globals()['${s}'] = True`,t),H(`def __await${n}_run():`,t),t.depth++,H("try:",t),t.depth++,H(`globals()['${i}'] = ${a}`,t),t.depth--,H("except Exception as e:",t),t.depth++,H(`globals()['${o}'] = str(e)`,t),t.depth--,H(`globals()['${r}'] = True`,t),H("try:",t),t.depth++,H(`${t.app}.after(0, ${t.app}.render)`,t),t.depth--,H("except Exception:",t),t.depth++,H("pass",t),t.depth--,t.depth--,H(`import threading; threading.Thread(target=__await${n}_run, daemon=True).start()`,t),t.depth--,H(`if globals().get('${r}'):`,t),t.depth++,H(`if globals().get('${o}') is not None:`,t),t.depth++,En(Je(Ct(e.catch,e.catchName??""),d),t),t.depth--,H("else:",t),t.depth++,En(Je(e.then,c),t),t.depth--,t.depth--,H("else:",t),t.depth++,En(e.pending,t),t.depth--;return}case"block":if(e.name==="defer"){let n=Number(/hold\s*=\s*(\d+)/.exec(String(e.head??""))?.[1]??"0"),s=`__defer${t.deferred.length}`;t.deferred.push({name:s,hold:Number.isFinite(n)?n:0}),H(`if st.get('${s}'):`,t),t.depth++;let r=t.lines.length;En(e.children,t),t.lines.length===r&&H("pass",t),t.depth--;return}if(e.name==="boundary"){let n=t.lines.length,s=t.depth;t.depth=s+1,En(e.children,t);let r=t.lines.splice(n);t.depth=s,H("try:",t),t.lines.push(...r),H("except Exception:",t),e.fallback?(t.depth=s+1,En(e.fallback,t),t.depth=s):(t.depth=s+1,H(`tk.Label(${t.parent}, text="This section failed to render.").pack(anchor='w')`,t),t.depth=s);return}En(e.children,t);return;case"slot":t.warnings.push("python: a <slot> outside a component call has no content here - skipped");return;case"element":X$(e,t);return}}function K$(e,t){let n;for(let s of e){let r=t.fontStacks.get(s);r&&(n=r)}return n??t.rawFamily}function Z$(e,t,n){let s=(r,i)=>{let o=`${r} ${t}`;n.noted.has(o)||(n.noted.add(o),n.warnings.push(`python: ${i}`))};if(e.radius&&e.radius.some(r=>r>0)){let r=[...new Set(e.radius.filter(o=>o>0))].map(o=>`${o}px`).join("/"),i=new Set(e.radius.filter(o=>o>0)).size===1;s("radius",`border-radius on ${t} has no Tk equivalent - the ${r} corner${i?"":"s"} stay${i?"s":""} square`)}e.shadow&&s("shadow",`box-shadow on ${t} is dropped - Tk draws no shadow`),e.opacity!==void 0&&e.opacity<1&&s("opacity",`opacity on ${t} is dropped - Tk widgets have no alpha`),e.gradient&&s("gradient",`a CSS gradient on ${t} is flattened to its first stop`),e.letterSpacing&&s("spacing",`letter-spacing on ${t} is dropped - Tk fonts carry no tracking`),e.lineHeight!==void 0&&e.lineHeight!==1&&s("leading",`line-height on ${t} is dropped - Tk line spacing follows the face`),e.wrap&&s("wrap",`flex-wrap on ${t} is dropped - Tk pack lays a single line`),e.overflow==="hidden"&&s("overflow",`overflow:hidden on ${t} is dropped - Tk clips nothing`),e.overflow==="scroll"&&s("scroll",`overflow:auto on ${t} is dropped - Tk needs a scrolled frame here, so the list is not scrollable`),e.borderStyle&&e.borderStyle!=="solid"&&e.borderWidth?.some(r=>r>0)&&s("border-style",`a ${e.borderStyle} border on ${t} is drawn solid - Tk has no dashed stroke`),e.position&&s("position",`position: ${e.position} on ${t} is dropped - Tk pack/grid place every widget in the flow`)}function Vs(e,t,n){let s=ts(Hn(e,n),t);return s.length?`{${s.map(r=>`${JSON.stringify(r.key)}: ${r.value}`).join(", ")}}`:""}function oi(e,t,n){n.dyn.used=!0;let s=[];t.staticClasses.length&&s.push(JSON.stringify(t.staticClasses.join(" ")));for(let o of t.dynamicClassExprs)s.push(`rose_tokens(${Up(o,n)})`);let r=s.length?`rose_join([${s.join(", ")}])`:"[]",i=t.dynamicStyle.length?`{${t.dynamicStyle.map(o=>`${JSON.stringify(o.prop)}: ${Up(o.code,n)}`).join(", ")}}`:"None";return`rose_apply(${e}, rose_resolve(${r}, '${n.scope}', ${i}))`}function Up(e,t){let n=e.trim();return/^[A-Za-z_$][\w$]*$/.test(n)&&t.stateNames.has(n)?`${t.st}.get('${n}')`:Kt(n,t)}function X$(e,t){let n=e.tag.toLowerCase(),s=bt(e),r=t.components.find(_=>_.name.toLowerCase()===n);if(r){let _=[...(r.script??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)].map(A=>({name:A[1],init:A[2].trim()})),k=new Map;for(let A of _){let R=e.attrs.find(T=>T.name===A.name);k.set(A.name,R?R.value.kind==="expr"?R.value.code:G$(R.value.kind==="text"?R.value.text:""):A.init)}for(let[A,R]of It(e))t.propWriteTargets.set(A,R),k.set(A,R);let S=Pt(e.children),C=Ft(r.nodes),x=new Map;C.hasDefault&&x.set("default",S.defaultNodes.length?S.defaultNodes:st(r.nodes,"default"));for(let A of C.named){let R=S.named.get(A.name)??st(r.nodes,A.name),T=aa(r.nodes,A.name),M=new Map;for(let F of A.props){let I=T?.attrs.find(P=>P.name===F),O=I&&I.value.kind==="expr"?I.value.code:"''";M.set(F,Se(O,k))}x.set(A.name,Lt(R,A.props,F=>M.get(F)??F))}En(As(Cs(r.nodes,x),k),t);return}let i=e.attrs.find(_=>_.name==="id"),o={tag:n,id:i&&i.value.kind==="text"?i.value.text:void 0,classes:s.staticClasses},a=rt(t.sheet,o,t.ancestors,{viewport:Ta}),c=a.model,d=a.focus,u=a.active,l=fe(fe(t.inherited,c),s.inlineStyle);if(l.display==="none")return;let p=K$(s.staticClasses,t),f=s.staticClasses.length?`<${n} class="${s.staticClasses.join(" ")}">`:`<${n}>`;Z$(l,f,t),t.seq.n++;let h=t.lastChild,g=_=>{if(s.hasDynamic){let k=`__w${t.lines.length}`;H(`${k} = ${_}`,t),H(`${k}.pack(${lt(t,{model:l,last:h})})`,t),H(oi(k,s,t),t);return}H(`${_}.pack(${lt(t,{model:l,last:h})})`,t)},y=(_,k)=>{if(!d||!Object.keys(d).length)return;let S=d.borderColor&&!d.borderWidth?{...d,borderWidth:l.borderWidth}:d,C=ts(Hn(S,p),k),x=C.length?`{${C.map(R=>`${JSON.stringify(R.key==="highlightbackground"?"highlightcolor":R.key)}: ${R.value}`).join(", ")}}`:"";if(!x)return;t.dyn.used=!0,H(`${_}.bind('<FocusIn>', lambda e: rose_apply(${_}, ${x}))`,t);let A=Vs(l,k,p);H(`${_}.bind('<FocusOut>', lambda e: rose_apply(${_}, ${A||"{}"}))`,t)},m=(_,k)=>{if(!u||!Object.keys(u).length)return;let S=u.borderColor&&!u.borderWidth?{...u,borderWidth:l.borderWidth}:u,C=ts(Hn(S,p),k),x=C.length?`{${C.map(R=>`${JSON.stringify(R.key==="highlightbackground"?"highlightcolor":R.key)}: ${R.value}`).join(", ")}}`:"";if(!x)return;t.dyn.used=!0,H(`${_}.bind('<ButtonPress-1>', lambda e: rose_apply(${_}, ${x}))`,t);let A=Vs(l,k,p);H(`${_}.bind('<ButtonRelease-1>', lambda e: rose_apply(${_}, ${A||"{}"}))`,t)};if(n==="progress"){let _=e.attrs.find(A=>A.name==="value"),k=e.attrs.find(A=>A.name==="max"),S=_&&_.value.kind==="expr"?Kt(_.value.code,t):_&&_.value.kind==="text"?_.value.text:"0",C=k&&k.value.kind==="text"?k.value.text:"100",x=l.width&&l.width.u==="px"?`, length=${Math.round(l.width.n)}`:"";H(`__scale = ttk.Scale(${t.parent}, from_=0, to=${C}, value=${S}${x})`,t),H(`__scale.pack(${lt(t,{model:l,last:h})})`,t);return}if(n==="video"){let _=e.attrs.find(S=>S.name==="src"),k=_&&_.value.kind==="text"?_.value.text:"";t.warnings.push(`python: <video ${k}> has no Tk video widget - shown as a placeholder label`),H(`tk.Label(${t.parent}, text='[video: ${k.replace(/'/g,"\\\\'")}]').pack(${lt(t,{model:l,last:h})})`,t);return}if(n==="audio"){let _=e.attrs.find(S=>S.name==="src"),k=_&&_.value.kind==="text"?_.value.text:"";t.warnings.push(`python: <audio ${k}> has no Tk audio widget - shown as a placeholder label`),H(`tk.Label(${t.parent}, text='[audio: ${k.replace(/'/g,"\\\\'")}]').pack(${lt(t,{model:l,last:h})})`,t);return}if(n==="img"){let _=e.attrs.find(x=>x.name==="src"),k=_&&_.value.kind==="text"?_.value.text:"",S=Qp.get(k);if(S){H("try:",t),H(" __photo = tk.PhotoImage(file="+JSON.stringify(S)+")",t),H(" st.setdefault('__images', []).append(__photo)",t),H(` tk.Label(${t.parent}, image=__photo).pack(${lt(t,{model:l,last:h})})`,t),H("except Exception:",t),H(` tk.Label(${t.parent}, text='[image: ${k.replace(/'/g,"\\\\'")}]').pack(${lt(t,{model:l,last:h})})`,t);return}let C=Kp.get(k);if(C){let x=e.attrs.find(P=>P.name==="width"),A=e.attrs.find(P=>P.name==="height"),R=x&&x.value.kind==="text"&&Number(x.value.text)||72,T=A&&A.value.kind==="text"&&Number(A.value.text)||72,M=`__cv${t.lines.length}`;H(`${M} = tk.Canvas(${t.parent}, width=${R}, height=${T}, highlightthickness=0)`,t),H(`${M}.pack(${lt(t,{model:l,last:h})})`,t);let F=R/(C.viewBox[2]-C.viewBox[0]),I=T/(C.viewBox[3]-C.viewBox[1]),O=P=>String(Number(P.toFixed(2)));for(let P of C.subPaths){let j=[],B=0,U=0;for(let N of P.ops)if(N.op==="move")B=N.x,U=N.y,j.push([N.x,N.y]);else if(N.op==="line")B=N.x,U=N.y,j.push([N.x,N.y]);else if(N.op==="curve"){for(let W=1;W<=16;W++){let re=W/16,xe=1-re,X=xe*xe*xe*B+3*xe*xe*re*N.c1x+3*xe*re*re*N.c2x+re*re*re*N.x,ne=xe*xe*xe*U+3*xe*xe*re*N.c1y+3*xe*re*re*N.c2y+re*re*re*N.y;j.push([X,ne])}B=N.x,U=N.y}if(!j.length)continue;let ce=j.map(([N,W])=>`${O(N*F)}, ${O(W*I)}`).join(", ");H(`${M}.create_polygon(${ce}, fill='${P.fill}', outline='')`,t)}return}t.warnings.push("python: <img "+k+"> has no bundled raster asset - shown as a placeholder label"),g(`tk.Label(${t.parent}, text='[image: ${k.replace(/'/g,"\\\\'")}]')`);return}if(n==="a"){let _=e.attrs.find(R=>R.name==="href"),k=_?Kt(_.value.kind==="expr"?_.value.code:JSON.stringify(_.value.kind==="text"?_.value.text:""),t):"''",S=e.children.map(R=>R.kind==="text"?R.value.replace(/\s+/g," "):R.kind==="expr"?`{rose_text(lambda: ${Kt(R.code,t)})}`:"").join("").trim(),C=ja(Jp(S,""),l),x=Vs(l,"Label",p);t.links.used=!0;let A=`rose_link(${t.parent}, ${C}, lambda t=${k}: ${t.app}.navigate(t)${x?`, ${x}`:""})`;if(s.hasDynamic){let R=`__w${t.lines.length}`;H(`${R} = ${A}`,t),H(`${R}.pack(${lt(t,{model:l,last:h})})`,t),H(oi(R,s,t),t)}else H(`${A}.pack(${lt(t,{model:l,last:h})})`,t);return}if(n==="input"||n==="textarea"){let _=e.attrs.find(j=>j.name==="placeholder"),k=_?Kt(_.value.kind==="expr"?_.value.code:JSON.stringify(_.value.kind==="text"?_.value.text:""),t):"''",S=e.attrs.find(j=>j.name==="type"),C=S&&S.value.kind==="text"?S.value.text:"text",x=e.attrs.find(j=>j.name==="bind:checked"),A=e.attrs.find(j=>j.name==="bind:group"),R=e.attrs.find(j=>j.name==="bind:value"),T=j=>j&&j.value.kind==="expr"&&t.stateNames.has(j.value.code.trim())?j.value.code.trim():"",M=e.attrs.find(j=>j.name==="value"),F=M&&M.value.kind==="text"?JSON.stringify(M.value.text):M&&M.value.kind==="expr"?Kt(M.value.code,t):"''",I=Vs(l,"Button",p);if(C==="checkbox"){let j=T(A),B=T(x);if(j){let U=String(F).replace(/[^A-Za-z0-9]/g,"");H("__var_"+U+" = tk.BooleanVar(value="+F+" in "+t.st+".get('"+j+"', []))",t),H("__toggle_"+U+" = lambda: ("+t.st+".__setitem__('"+j+"', (list("+t.st+".get('"+j+"', [])) + ["+F+"]) if __var_"+U+".get() else [value for value in "+t.st+".get('"+j+"', []) if value != "+F+"]), "+t.app+".render())",t),g("tk.Checkbutton("+t.parent+", variable=__var_"+U+", command=__toggle_"+U+(I?", **"+I:"")+")")}else B?(H(`__var_${B} = tk.BooleanVar(value=bool(${t.st}.get('${B}', False)))`,t),g(`tk.Checkbutton(${t.parent}, variable=__var_${B}, command=lambda: (${t.st}.__setitem__('${B}', __var_${B}.get()), ${t.app}.render())${I?", **"+I:""})`)):g(`tk.Checkbutton(${t.parent}${I?", "+cs(ts(Hn(l,p),"Button")):""})`);return}if(C==="radio"){let j=T(A);j&&(H(`if '__var_${j}' not in ${t.st}:`,t),H(` ${t.st}['__var_${j}'] = tk.StringVar(value=${t.st}.get('${j}', ''))`,t),g(`tk.Radiobutton(${t.parent}, text=${F}, variable=${t.st}['__var_${j}'], value=${F}, command=lambda: (${t.st}.__setitem__('${j}', ${t.st}['__var_${j}'].get()), ${t.app}.render())${I?", **"+I:""})`));return}if(n==="textarea"){let j=ts(Hn(l,p),"Text");if(d&&Object.keys(d).length&&Vs(d,"Text",p)){let U=`__w${t.seq.n++}`;H(`${U} = tk.Text(${t.parent}, height=4${j.length?", "+cs(j):""})`,t),y(U,"Text"),H(`${U}.pack(${lt(t,{model:l,last:h})})`,t)}else g(`tk.Text(${t.parent}, height=4${j.length?", "+cs(j):""})`);return}if(C==="range"){let j=e.attrs.find(re=>re.name==="min"),B=e.attrs.find(re=>re.name==="max"),U=(re,xe)=>re&&re.value.kind==="text"?re.value.text:xe,ce=T(R)||(M&&M.value.kind==="expr"?M.value.code.trim():""),N=[`from_=${U(j,"0")}`,`to=${U(B,"100")}`,"orient=tk.HORIZONTAL"],W=ts(Hn(l,p),"Scale");W.length&&N.push(cs(W)),g(`tk.Scale(${t.parent}, ${N.join(", ")}${ce?`, command=lambda v: (${t.st}.__setitem__('${ce}', v), ${t.app}.render())`:""})`);return}if(!R&&M&&M.value.kind==="expr"&&[...t.propWriteTargets.values()].includes(M.value.code.trim())&&(R=M),R&&R.value.kind==="expr"&&t.stateNames.has(R.value.code.trim())){let j=R.value.code.trim(),B=t.propWriteTargets.get(j)??j,U=ts(Hn(l,p),"Entry");if(H(`__var_${j} = tk.StringVar(value=${t.st}.get('${B}', ''))`,t),H(`__var_${j}.trace_add('write', lambda *_: ${t.st}.__setitem__('${B}', __var_${j}.get()))`,t),H(`__var_${j}.trace_add('write', lambda *_: ${t.app}.render())`,t),d&&Object.keys(d).length&&Vs(d,"Entry",p)){let N=`__e${t.seq.n++}`;H(`${N} = tk.Entry(${t.parent}, textvariable=__var_${j}${U.length?", "+cs(U):""})`,t),y(N,"Entry"),H(`${N}.pack(${lt(t,{model:l,last:h})})`,t)}else g(`tk.Entry(${t.parent}, textvariable=__var_${j}${U.length?", "+cs(U):""})`);return}g(`tk.Label(${t.parent}, text=${k})`);let O=Vs(l,"Entry",p);if(d&&Object.keys(d).length&&Vs(d,"Entry",p)){let j=`__e${t.seq.n++}`;H(`${j} = rose_entry(${t.parent}${O?`, '', ${O}`:""})`,t),y(j,"Entry"),H(`${j}.pack(${lt(t,{model:l,last:h})})`,t)}else g(`rose_entry(${t.parent}${O?`, '', ${O}`:""})`);return}if(n==="button"){let _=e.attrs.find(T=>T.name==="on:click"||T.name==="on:submit"),k=_&&_.value.kind==="expr"?ew(_.value.code.trim(),t):"lambda: None",S=e.children.map(T=>T.kind==="text"?T.value.replace(/\s+/g," "):T.kind==="expr"?`{rose_text(lambda: ${Kt(T.code,t)})}`:"").join("").trim(),C=ja(Jp(S,"Button"),l),x=Vs(l,"Button",p),A=u&&Object.keys(u).length,R=s.staticClasses.map(T=>`__hover_${T}__${t.scope}`).find(T=>t.hoverKeys?.has(T));if(A||R||s.hasDynamic){let T=`__b${t.seq.n++}`;if(H(`${T} = rose_button(${t.parent}, ${C}, ${k}${x?`, '', ${x}`:""})`,t),H(`${T}.pack(${lt(t,{model:l,last:h})})`,t),s.hasDynamic&&H(oi(T,s,t),t),R){let M=`${s.staticClasses[0]}__${t.scope}`;H(`${T}.bind('<Enter>', lambda e: rose_apply(${T}, STYLES['${R}']))`,t),H(`${T}.bind('<Leave>', lambda e: rose_apply(${T}, STYLES['${M}']))`,t),t.dyn.used=!0}A&&m(T,"Button");return}Y$(t,`rose_button(${t.parent}, ${C}, ${k}${x?`, '', ${x}`:""})`,s,l,h);return}if(n==="select"){let _=e.attrs.find(O=>O.name==="bind:value"),k=_&&_.value.kind==="expr"&&t.stateNames.has(_.value.code.trim())?_.value.code.trim():"",S=e.children.filter(O=>O.kind==="element"&&O.tag.toLowerCase()==="option");if(e.attrs.some(O=>O.name==="multiple")&&k){let O=S.map(U=>{let ce=U.children.filter(W=>W.kind==="text").map(W=>W.value.trim()).join(""),N=U.attrs.find(W=>W.name==="value");return{label:ce,value:N&&N.value.kind==="text"?N.value.text:ce}}),P=`__lb_${k.replace(/[^\w]/g,"_")}`,j=O.map(U=>JSON.stringify(U.value)),B=ts(Hn(l,p),"Text");H(`${P} = tk.Listbox(${t.parent}, selectmode='multiple', exportselection=False, height=${Math.max(3,O.length)}${B.length?", "+cs(B):""})`,t),H(`for __opt in [${O.map(U=>JSON.stringify(U.label)).join(", ")}]: ${P}.insert(tk.END, __opt)`,t),H(`[${P}.selection_set(__i) for __i, __v in enumerate([${j.join(", ")}]) if __v in ${t.st}.get('${k}', [])]`,t),H(`${P}.pack(${lt(t,{model:l,last:h})})`,t),H(`${P}.bind('<<ListboxSelect>>', lambda *_: ${t.st}.__setitem__('${k}', [[${j.join(", ")}][__i] for __i in ${P}.curselection()]))`,t);return}let C=S.map(O=>{let P=O.children.filter(B=>B.kind==="text").map(B=>B.value.trim()).join(""),j=O.attrs.find(B=>B.name==="value");return{label:P,value:j&&j.value.kind==="text"?j.value.text:P}}),x=C.map(O=>O.label),A={};for(let O of C)O.value!==O.label&&(A[O.label]=O.value);let R=k?`${t.st}.get('${k}', ${JSON.stringify(C[0]?.value??"")})`:JSON.stringify(C[0]?.value??""),T=k?`${t.st}.get('${k}', ${JSON.stringify(C[0]?.value??"")})`:JSON.stringify(C[0]?.value??""),M=Object.keys(A).length?`next((__l for __l, __v in ${JSON.stringify(A)}.items() if __v == ${R}), ${T})`:T;if(H(`__choice = tk.StringVar(value=${M})`,t),k){let O=Object.keys(A).length?`${JSON.stringify(A)}.get(__choice.get(), __choice.get())`:"__choice.get()";H(`__choice.trace_add('write', lambda *_: ${t.st}.__setitem__('${k}', ${O}))`,t),H(`__choice.trace_add('write', lambda *_: ${t.app}.render())`,t)}let F=ts(Hn(l,p),"Button"),I=`tk.OptionMenu(${t.parent}, __choice, ${x.map(O=>JSON.stringify(O)).join(", ")||"''"})`;F.length?(H(`__om = ${I}`,t),H(`__om.configure(${cs(F)})`,t),g("__om")):g(I);return}if(n==="hr"){let _=ai(l.background)??"'#e0e0e0'",k=l.height&&l.height.u==="px"?Math.round(l.height.n):1;g(`tk.Frame(${t.parent}, height=${k}, bg=${_})`);return}if(n==="br"){H(`tk.Frame(${t.parent}, width=1, height=8).pack(${lt(t,{model:l,last:h})})`,t);return}if(F$.has(n)&&!e.children.some(_=>_.kind==="element")){let _=ja(ef(e.children,t),l),k=ts(Hn(l,p),"Label"),S=l.maxWidth&&l.maxWidth.u==="px"?Math.round(l.maxWidth.n):680,C=!k.some(A=>A.key==="bg")&&l.background===void 0&&t.surface?`, bg=${t.surface}`:"",x=`tk.Label(${t.parent}, text=${_}, wraplength=${S}${k.length?", "+cs(k):""}${C})`;if(s.hasDynamic){let A=`__w${t.lines.length}`;H(`${A} = ${x}`,t),H(`${A}.pack(${lt(t,{model:l,last:h})})`,t),H(oi(A,s,t),t)}else H(`${x}.pack(${lt(t,{model:l,last:h})})`,t);return}let b=`__f${t.depth}_${t.lines.length}`,$=ts(Hn(l,p),"Frame");!l.background&&t.surface&&!$.some(_=>_.key==="bg")&&$.push({key:"bg",value:t.surface}),H(`${b} = tk.Frame(${t.parent}${$.length?", "+cs($):""})`,t);let w=(l.grow??0)>0;H(`${b}.pack(${lt(t,{model:l,fill:t.layout.dir==="column"||w,expand:w,last:h})})`,t),s.hasDynamic&&H(oi(b,s,t),t);let v={...t,parent:b,surface:ai(l.background)??t.surface,layout:q$(l,n),seq:{n:0},ancestors:[...t.ancestors,o],inherited:Yp(l),lastChild:!1,rawFamily:p};En(e.children,v)}function Y$(e,t,n,s,r){let i=n.staticClasses.map(o=>`__hover_${o}__${e.scope}`).find(o=>e.hoverKeys?.has(o));if(i&&(e.dyn.used=!0),n.hasDynamic){let o=`__w${e.lines.length}`;if(H(`${o} = ${t}`,e),H(`${o}.pack(${lt(e,{model:s,last:r})})`,e),H(oi(o,n,e),e),i){let a=`${n.staticClasses[0]}__${e.scope}`;H(`${o}.bind('<Enter>', lambda e: rose_apply(${o}, STYLES['${i}']))`,e),H(`${o}.bind('<Leave>', lambda e: rose_apply(${o}, STYLES['${a}']))`,e)}return}if(i){let o=`__w${e.lines.length}`,a=`${n.staticClasses[0]}__${e.scope}`;H(`${o} = ${t}`,e),H(`${o}.pack(${lt(e,{model:s,last:r})})`,e),H(`${o}.bind('<Enter>', lambda e: rose_apply(${o}, STYLES['${i}']))`,e),H(`${o}.bind('<Leave>', lambda e: rose_apply(${o}, STYLES['${a}']))`,e);return}H(`${t}.pack(${lt(e,{model:s,last:r})})`,e)}function ew(e,t){if(!e)return"lambda: None";if(/^[A-Za-z_$][\w$]*$/.test(e))return e;let n=t.inline.get(e);if(n)return n;let s=jt(e,tw(t),t.stateNames);if(s.reason||!s.stmts.length)return t.warnings.push(`python: an inline handler (${e.slice(0,40)}...) is not translated (${s.reason??"empty"}); use a named function in <script>`),"lambda: None";let r=sr(new Set(t.inline.values()));return t.inline.set(e,r),t.inlineBodies.push(` def ${r}():
|
|
4191
4191
|
${s.stmts.map(i=>` ${i}`).join(`
|
|
4192
|
-
`)}`),r}function tw(e){return{expr:t=>Kt(t,e),set:(t,n)=>`st['${t}'] = ${n}`,action:t=>`__action('${t}')`,refresh:()=>"app.render()",refuses:t=>{let n=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/=>/,"an arrow function"]];for(let[s,r]of n)if(s.test(t))return r;return null}}}function nw(e){let t=new Set(["length","map","filter","reduce","find","some","every","slice","concat","join","split","indexOf","startsWith","endsWith","toUpperCase","toLowerCase","forEach","push","includes","keys","values","entries"]),n="rose_content_",s="",r=0;for(;;){let i=e.indexOf(n,r);if(i<0)return s+=e.slice(r),s;let o=e.indexOf("(",i);if(o<0)return s+=e.slice(r),s;let a=0,c=-1;for(let l=o;l<e.length;l++){let p=e[l];if(p==='"'||p==="'"){let f=p;for(l++;l<e.length&&e[l]!==f;)e[l]==="\\"&&l++,l++;continue}if(p==="(")a++;else if(p===")"&&(a--,a===0)){c=l;break}}if(c<0)return s+=e.slice(r),s;s+=e.slice(r,c+1);let d=/^\s*\.\s*([A-Za-z_$][\w$]*)/.exec(e.slice(c+1)),u=e.slice(c+1+(d?d[0].length:0));d&&!t.has(d[1])&&!/^\s*\(/.test(u)?(s+=`[${JSON.stringify(d[1])}]`,r=c+1+d[0].length):r=c+1}}function Kt(e,t){let n=Oe(e.trim(),"rose_content_list","rose_content_get","''");if(n=nw(n),/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\[[^\]]+\]/.test(n)||/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,{...Cr,read:r=>t.stateNames.has(r)&&!t.loopVars?.has(r)?`st.get('${r}')`:r},new Set);if(s!==null)return s}if(n=Gt(n,s=>t.loopVars?.has(s)?!1:t.stateNames.has(s)||!!t.funcBinds?.has(s),s=>`${s}()`),t.derivedExprs?.size)for(let[s,r]of t.derivedExprs){let i=Kt(r,{...t,derivedExprs:new Map});n=n.replace(new RegExp(`\\b${Js(s)}\\s*\\(\\s*\\)`,"g"),`(${i})`)}if(n=n.replace(/\$actionPending\s*\(\s*\)/g,"False"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"None"),n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,"'$2'"),n=n.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(s,r)=>`app.query.get('${r}', '')`),n=n.replace(/\$query\s*\(\s*\)/g,"app.query"),n=n.replace(/\$(?:store|kv|cookies)\s*\(\s*\)/g,"{}"),n=n.replace(/\b(?:getContext)\s*\(\s*\)/g,"{}"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"
|
|
4192
|
+
`)}`),r}function tw(e){return{expr:t=>Kt(t,e),set:(t,n)=>`st['${t}'] = ${n}`,action:t=>`__action('${t}')`,refresh:()=>"app.render()",refuses:t=>{let n=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/=>/,"an arrow function"]];for(let[s,r]of n)if(s.test(t))return r;return null}}}function nw(e){let t=new Set(["length","map","filter","reduce","find","some","every","slice","concat","join","split","indexOf","startsWith","endsWith","toUpperCase","toLowerCase","forEach","push","includes","keys","values","entries"]),n="rose_content_",s="",r=0;for(;;){let i=e.indexOf(n,r);if(i<0)return s+=e.slice(r),s;let o=e.indexOf("(",i);if(o<0)return s+=e.slice(r),s;let a=0,c=-1;for(let l=o;l<e.length;l++){let p=e[l];if(p==='"'||p==="'"){let f=p;for(l++;l<e.length&&e[l]!==f;)e[l]==="\\"&&l++,l++;continue}if(p==="(")a++;else if(p===")"&&(a--,a===0)){c=l;break}}if(c<0)return s+=e.slice(r),s;s+=e.slice(r,c+1);let d=/^\s*\.\s*([A-Za-z_$][\w$]*)/.exec(e.slice(c+1)),u=e.slice(c+1+(d?d[0].length:0));d&&!t.has(d[1])&&!/^\s*\(/.test(u)?(s+=`[${JSON.stringify(d[1])}]`,r=c+1+d[0].length):r=c+1}}function Kt(e,t){let n=Oe(e.trim(),"rose_content_list","rose_content_get","''");if(n=nw(n),/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\[[^\]]+\]/.test(n)||/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,{...Cr,read:r=>t.stateNames.has(r)&&!t.loopVars?.has(r)?`st.get('${r}')`:r},new Set);if(s!==null)return s}if(n=Gt(n,s=>t.loopVars?.has(s)?!1:t.stateNames.has(s)||!!t.funcBinds?.has(s),s=>`${s}()`),t.derivedExprs?.size)for(let[s,r]of t.derivedExprs){let i=Kt(r,{...t,derivedExprs:new Map});n=n.replace(new RegExp(`\\b${Js(s)}\\s*\\(\\s*\\)`,"g"),`(${i})`)}if(n=n.replace(/\$actionPending\s*\(\s*\)/g,"False"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"None"),n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,"'$2'"),n=n.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(s,r)=>`app.query.get('${r}', '')`),n=n.replace(/\$query\s*\(\s*\)/g,"app.query"),n=n.replace(/\$(?:store|kv|cookies)\s*\(\s*\)/g,"{}"),n=n.replace(/\b(?:getContext)\s*\(\s*\)/g,"{}"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"rosefc_$1"),/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,{...Cr,read:r=>t.stateNames.has(r)&&!t.loopVars?.has(r)?`st.get('${r}')`:r},new Set);s!==null&&(n=s)}return n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)(?!\s*[({\w])/g,(s,r,i)=>t.stateNames.has(r)&&!t.loopVars?.has(r)?`st.get('${r}', {}).get('${i}')`:s),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(s,r)=>t.stateNames.has(r)&&!t.loopVars?.has(r)?`st.get('${r}')`:s),n=Kr(n,s=>`len(${s})`),n=qn(n,(s,r)=>`${r}.join(${s})`),n=no(n),n=nn(n,tf),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,(s,r,i)=>t.mapBinds.has(r)?`${r}.get('${i}')`:s),n=n.replace(/\btrue\b/g,"True").replace(/\bfalse\b/g,"False"),n=n.replace(/\bnull\b/g,"None").replace(/\bundefined\b/g,"None"),n=n.replace(/===/g,"==").replace(/!==/g,"!="),n=n.replace(/&&/g," and ").replace(/\|\|/g," or "),n=n.replace(/\?\?/g," or ").replace(/\?\./g,"."),n=ec(n,/!(?!=)\s*/g,()=>"not "),n=Kr(n,s=>`len(${s})`),n}function no(e){let t=-1,n=0,s="";for(let u=0;u<e.length;u++){let l=e[u];if(s){if(l==="\\"){u++;continue}l===s&&(s="");continue}if(l==='"'||l==="'"){s=l;continue}if(l==="("||l==="["||l==="{")n++;else if(l===")"||l==="]"||l==="}")n--;else if(l==="?"&&n===0){t=u;break}}if(t<0)return e;let r=e.slice(0,t).trim(),i=e.slice(t+1),o=-1;n=0,s="";let a=0;for(let u=0;u<i.length;u++){let l=i[u];if(s){if(l==="\\"){u++;continue}l===s&&(s="");continue}if(l==='"'||l==="'"){s=l;continue}if(l==="("||l==="["||l==="{")n++;else if(l===")"||l==="]"||l==="}")n--;else if(n===0&&l==="?")a++;else if(n===0&&l===":"){if(a===0){o=u;break}a--}}if(o<0)return e;let c=i.slice(0,o).trim(),d=i.slice(o+1).trim();return`(${no(c)} if ${r} else ${no(d)})`}function sw(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^\w]/g,"_").toLowerCase().replace(/^(\d)/,"_$1")}function rw(e){let t={state:[],derived:[],data:[]};for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|persist|kv)\b(?:<[^>]*>)?\s*\(/g))t.state.push(n[1]);for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$derived\b(?:<[^>]*>)?\s*\(/g)){let s=(n.index??0)+n[0].length-1;t.derived.push({name:n[1],expr:rf(e,s)})}for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$data\b(?:<[^>]*>)?\s*\(/g))t.data.push(n[1]);return t}function iw(e,t,n=new Set){let r=new RegExp(`\\b(?:let|const|var)\\s+${Js(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$(state|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(e);if(!r||r[1]==="kv")return"None";let i=r.index+r[0].length-1,o=rf(e,i);return nf(o,n)}function nf(e,t=new Set){if(!e.trim())return"None";let n=e.trim();return n=ms(n,{empty:s=>`str(${s}) != ''`,nullish:(s,r)=>`(${s} if ${s} is not None else ${r})`,isState:()=>!0,dialect:{translate:(s,r)=>G(s,Cr,r)},query:s=>`app.query.get(${JSON.stringify(s)}, '')`}),n=n.replace(/\$(?:query|store|kv|cookies|actionError|actionPending|sessionCookie)\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"None"),n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,"'$2'"),n=n.replace(/\?\?/g," or "),n=n.replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g,(s,r,i)=>`${r}'${i}':`),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,(s,r,i)=>r==="app"||r==="st"||r==="self"||r==="parent"?s:`${r}['${i}']`),n=n.replace(/\btrue\b/g,"True").replace(/\bfalse\b/g,"False"),n=n.replace(/\bnull\b/g,"None").replace(/\bundefined\b/g,"None"),n=n.replace(/`([^`]*)`/g,"'$1'"),Zr(n,t,["len","str","int","float","list","dict","print","app","st","parent","rosefc"])!==null?"None":n}function sf(e){let t=[];for(let n of e.matchAll(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^\n;]+)/gm)){let s=n[2].trim();if(/^\$(?:state|derived|data|kv|persist)\b/.test(s))continue;let r=/^\(\s*([^)]*)\)\s*=>\s*(.*)$/.exec(s);if(r){let i=r[1].split(",").map(a=>a.trim()).filter(Boolean).map(a=>a.split(":")[0].trim()).join(", "),o=r[2].trim().replace(/^\{([\s\S]*)\}$/,"$1").trim();t.push({name:n[1],init:`__ARROW__${i}__ARROW__
|
|
4193
4193
|
return ${o}`});continue}/^([\[{'"`]|-?\d|true|false|null)/.test(s)&&ow(s)&&t.push({name:n[1],init:nf(s)})}return t}function ow(e){let t=0;for(let n of e)if(n==="("||n==="["||n==="{"?t++:(n===")"||n==="]"||n==="}")&&t--,t<0)return!1;return t===0}function rf(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return e.slice(t+1,s).trim()}return""}function Js(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function aw(e,t,n,s,r=[],i=[]){let o=n.name;if(!e.trim())return"";let a=e.replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,"");try{a=M$(a,{loader:"ts",format:"esm",target:"es2020"}).code}catch{s.push("python: the script did not parse as TypeScript - handlers are stubs")}for(let p of sf(e))a=a.replace(new RegExp(`\\b${Js(p.name)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g"),`${p.name}['$1']`);for(let p of[...t.state,...t.derived.map(f=>f.name),...t.data]){let h=new RegExp(`\\b(?:let|const|var)\\s+${Js(p)}\\s*(?::[^=;\\n]*)?=\\s*\\$(?:state|derived|data|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(a);if(!h)continue;let g=h.index+h[0].length-1,y=jr(a,g);y<0||(a=a.slice(0,h.index)+a.slice(y+1).replace(/^;/,""))}let c=[...e.matchAll(/export\s+async\s+function\s+([A-Za-z_$][\w$]*)\s*\(/g)].map(p=>p[1]),d=[],u=[],l=[...t.state,...t.derived.map(p=>p.name),...t.data];for(let p of a.matchAll(/^(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/gm)){let f=p[1];if(f.startsWith("__"))continue;let h=p.index+p[0].length-1,g=jr(a,h);if(g<0)continue;let y=a.slice(h+1,g);u.push(` def ${f}(${p[2].split(",").map(m=>m.trim()).filter(Boolean).map(m=>m.split(":")[0].trim()).join(", ")}):
|
|
4194
4194
|
${Gp(y,o,s,8,l,r)}`)}for(let p of oa(a)){if(p.call){s.push(`${o}: an effect on the function ${p.call}() is skipped on this platform - that function re-renders, and calling it from the render would recurse`);continue}if(!p.body){s.push(`${o}: an effect body the exporter could not read is skipped (${p.arg.slice(0,40)})`);continue}let[f,h]=lw(p.body);h&&s.push(`${o}: an effect's returned cleanup has nowhere to run on this platform, so it is dropped (the effect body itself still runs)`);let g=`__effect${i.length}`;i.push(g),u.push(` def ${g}():
|
|
4195
4195
|
${Gp(f,o,s,8,l,r,!1)}`)}return[...d,...u].join(`
|
|
4196
4196
|
`)}function lw(e){let t=0,n="";for(let s=0;s<e.length;s++){let r=e[s];if(n){r==="\\"?s++:r===n&&(n="");continue}if(r==='"'||r==="'"||r==="`"){n=r;continue}if(r==="("||r==="["||r==="{")t++;else if(r===")"||r==="]"||r==="}")t--;else if(t===0&&e.startsWith("return",s)&&!/[\w$]/.test(e[s-1]??"")&&!/[\w$]/.test(e[s+6]??""))return[e.slice(0,s).replace(/;$/,""),e.slice(s+6).replace(/;$/,"").trim()]}return[e,""]}function cw(e,t){let n=["join","split","indexOf","every","startsWith","endsWith","toUpperCase","toLowerCase"],s="",r=0;for(;r<e.length;){let i=e[r];if(i==='"'||i==="'"||i==="`"){let a=Rc(e,r);s+=e.slice(r,a),r=a;continue}let o=i==="."?n.find(a=>e.startsWith(`.${a}(`,r)):void 0;if(o){let a=r+o.length+1,c=jr(e,a),d=c<0?-1:gw(s);if(c>=0&&d>=0){let u=G(s.slice(d)+e.slice(r,c+1),t,new Set);if(u!==null){s=s.slice(0,d)+u,r=c+1;continue}}}s+=i,r++}return s}function Rc(e,t){let n=e[t],s=t+1;for(;s<e.length&&e[s]!==n;)e[s]==="\\"&&s++,s++;return Math.min(s+1,e.length)}function qp(e,t){let n=e[t];for(let s=t-1;s>=0;s--){if(e[s]!==n)continue;let r=0,i=s-1;for(;i>=0&&e[i]==="\\";)r++,i--;if(r%2===0)return s}return 0}function _c(e,t){let n=t;for(;;){for(;n>0&&/[\w$]/.test(e[n-1]);)n--;if(n>=2&&e[n-1]==="."&&/[\w$]/.test(e[n-2])){n-=1;continue}return n}}function uw(e,t){return e.split(`
|
|
4197
4197
|
`).map(n=>{let s=dw(n);if(s<0)return pt(n,t);let r=n.slice(0,s+1),i=n.slice(s+1);return r+pt(i,t)}).join(`
|
|
4198
|
-
`)}function dw(e){let t=0,n="",s=-1;for(let r=0;r<e.length;r++){let i=e[r];if(n){i==="\\"?r++:i===n&&(n="");continue}if(i==='"'||i==="'"||i==="`"){n=i;continue}if(i==="("||i==="["||i==="{"){t++;continue}if(i===")"||i==="]"||i==="}"){t--;continue}if(i!=="="||t!==0)continue;let o=e[r-1]??"",a=e[r+1]??"";if(a==="="||a===">"){r++;continue}if(!"=!<>+-*/%&|^".includes(o)){if(s>=0)return-1;s=r}}return s}function pw(e,t){let n="",s=0;for(;s<e.length;){let r=e[s];if(r==='"'||r==="'"||r==="`"){let o=Rc(e,s);n+=e.slice(s,o),s=o;continue}let i=null;if(/[A-Za-z_$]/.test(r)&&!/[.\w$]/.test(e[s-1]??""))for(let o of t){let a=o[0].toUpperCase()+o.slice(1);if(e.startsWith("set"+a,s)&&/^\s*\(/.test(e.slice(s+3+a.length))){i=o;break}}if(i){let o=e.indexOf("(",s),a=jr(e,o);if(a>0){n+=`st['${i}'] = `+e.slice(o+1,a),s=a+1,e[s]===";"&&s++;continue}}n+=r,s++}return n}function fw(e){let t="",n=0;for(;n<e.length;){let s=e[n];if(s==='"'||s==="'"||s==="`"){let i=Rc(e,n);t+=e.slice(n,i),n=i;continue}if(/^for\s*\(/.test(e.slice(n))&&!/[.\w$]/.test(e[n-1]??"")){let i=e.indexOf("(",n),o=jr(e,i);if(o>0){t+=e.slice(n,o+1),n=o+1;continue}}let r=/^([A-Za-z_$][\w$]*)\s*(\+\+|--)/.exec(e.slice(n));if(r&&!/[.\w$]/.test(e[n-1]??"")){t+=`${r[1]} ${r[2]==="++"?"+=":"-="} 1`,n+=r[0].length;continue}t+=s,n++}return t}function of(e){let t=[],n=0,s="",r=0;for(let i=0;i<e.length;i++){let o=e[i];if(s){o==="\\"?i++:o===s&&(s="");continue}if(o==='"'||o==="'"||o==="`"){s=o;continue}o==="("||o==="["||o==="{"?n++:o===")"||o==="]"||o==="}"?n--:o===";"&&n===0&&(t.push(e.slice(r,i).trim()),r=i+1)}return t.push(e.slice(r).trim()),t}function xc(e){let t=e.trim();return/^[-\w$.]+(?:\([^()]*\))?(?:\[[^\]]*\])?$/.test(t)?t:`(${t})`}function af(e){let t=of(e);if(t.length!==3)return null;let n=/^(?:(?:let|var|const)\s+)?([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(t[0]);if(!n)return null;let[,s,r]=n,i=new RegExp(`^${Js(s)}\\s*(<=?|>=?)\\s*([\\s\\S]+)$`).exec(t[1]);if(!i)return null;let[,o,a]=i,c=new RegExp(`^${Js(s)}\\s*(\\+\\+|\\+=\\s*([\\s\\S]+))$`).exec(t[2]),d=new RegExp(`^${Js(s)}\\s*(--|-=\\s*([\\s\\S]+))$`).exec(t[2]),u=!!c;if(!u&&!d)return null;let l=(u?c[2]:d[2])?.trim(),p=l?xc(l):"1";if(u!==(o==="<"||o==="<="))return null;let h=xc(r),g=xc(a);if(o==="<")return p==="1"?`for ${s} in range(${h}, ${g}):`:`for ${s} in range(${h}, ${g}, ${p}):`;if(o==="<="){let b=`(${a.trim()}) + 1`;return p==="1"?`for ${s} in range(${h}, ${b}):`:`for ${s} in range(${h}, ${b}, ${p}):`}if(o===">"){let b=p==="1"?"-1":`-${p}`;return`for ${s} in range(${h}, ${g}, ${b}):`}let y=`(${a.trim()}) - 1`,m=p==="1"?"-1":`-${p}`;return`for ${s} in range(${h}, ${y}, ${m}):`}function hw(e){let t=0,n="";for(let s=0;s<e.length;s++){let r=e[s];if(n){r==="\\"?s++:r===n&&(n="");continue}if(r==='"'||r==="'"||r==="`"){n=r;continue}if(r==="("||r==="["||r==="{"){t++;continue}if(r===")"||r==="]"||r==="}"){t--;continue}if(r!=="f"||!e.startsWith("for",s)||/[.\w$]/.test(e[s-1]??"")||/[\w$]/.test(e[s+3]??""))continue;let i=e.indexOf("(",s);if(i<0)continue;let o=jr(e,i);if(o<0)continue;let a=e.slice(i+1,o);if(of(a).length===3&&af(a)===null)return e.slice(s,o+1);s=o}return null}function gw(e){let t=e.length;for(;t>0&&e[t-1]===" ";)t--;if(t===0)return-1;let n=e[t-1];if(n==='"'||n==="'")return _c(e,qp(e,t-1));if(n===")"||n==="]"){let s=n===")"?"(":"[",r=0;for(let i=t-1;i>=0;i--){let o=e[i];if(o==='"'||o==="'"){i=qp(e,i);continue}if(o===n)r++;else if(o===s&&--r===0)return _c(e,i)}return-1}return/[\w$\]]/.test(n)?_c(e,t):-1}function Gp(e,t,n,s,r=[],i=[],o=!0){let a=" ".repeat(s),c=new Set(r),d=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/=>/,"an arrow function"]];e=Ot(sn(e)),e=tn(e),e=zt(e,{target:"python",options:m=>Dt(m,"quoted"),empty:"None",file:t,warn:m=>n.push(`python: ${m}`)}).code;{let m=0;e=Qn(e,b=>r.includes(b)?"set"+b.charAt(0).toUpperCase()+b.slice(1):null,()=>String(++m))}e=rn(e,(m,b,$)=>{let w=G($,Cr,new Set([b]));if(w===null)return null;let v=`${m}()`;return`st['${m}'] = ${w}`.replace(new RegExp(`\\b${b}\\b`,"g"),v)}),e=Kn(e,m=>{let b=m.slice(3,4).toLowerCase()+m.slice(4);return m.length>3&&c.has(b)?b:null},(m,b)=>{let $=G(b,{...Cr,read:w=>c.has(w)?`st.get('${w}')`:w},new Set);return $===null?null:`st['${m}'] = ${$}`}),e=on(e,(m,b)=>{let $=G(b,{...Cr,read:w=>c.has(w)?`st.get('${w}')`:w},new Set);return $===null?null:`st['${m}'] = ${$}`}),e=cw(e,{...Cr,read:m=>c.has(m)?`st.get('${m}')`:m});for(let[m,b]of d)if(m.test(e))return n.push(`python: ${t}: a handler uses ${b}, which has no Python equivalent - emitted as a stub`),`${a}#
|
|
4199
|
-
${a}pass`;let u=hw(e);if(u!==null)return n.push(`python: ${t}: a handler uses a loop shape with no Python spelling (${u.replace(/\s+/g," ").trim()}) - emitted as a stub`),`${a}#
|
|
4200
|
-
${a}pass`;let l=$w(e.trim());l=fw(l),l=l.replace(/^(\s*st\[[^\]]+\][^;]*);\s*$/gm,"$1"),l=l.replace(/\bawait\s+/g,""),l=l.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(m,b,$)=>`__action('${$}')`),l=l.replace(/\$t\s*\(/g,"
|
|
4198
|
+
`)}function dw(e){let t=0,n="",s=-1;for(let r=0;r<e.length;r++){let i=e[r];if(n){i==="\\"?r++:i===n&&(n="");continue}if(i==='"'||i==="'"||i==="`"){n=i;continue}if(i==="("||i==="["||i==="{"){t++;continue}if(i===")"||i==="]"||i==="}"){t--;continue}if(i!=="="||t!==0)continue;let o=e[r-1]??"",a=e[r+1]??"";if(a==="="||a===">"){r++;continue}if(!"=!<>+-*/%&|^".includes(o)){if(s>=0)return-1;s=r}}return s}function pw(e,t){let n="",s=0;for(;s<e.length;){let r=e[s];if(r==='"'||r==="'"||r==="`"){let o=Rc(e,s);n+=e.slice(s,o),s=o;continue}let i=null;if(/[A-Za-z_$]/.test(r)&&!/[.\w$]/.test(e[s-1]??""))for(let o of t){let a=o[0].toUpperCase()+o.slice(1);if(e.startsWith("set"+a,s)&&/^\s*\(/.test(e.slice(s+3+a.length))){i=o;break}}if(i){let o=e.indexOf("(",s),a=jr(e,o);if(a>0){n+=`st['${i}'] = `+e.slice(o+1,a),s=a+1,e[s]===";"&&s++;continue}}n+=r,s++}return n}function fw(e){let t="",n=0;for(;n<e.length;){let s=e[n];if(s==='"'||s==="'"||s==="`"){let i=Rc(e,n);t+=e.slice(n,i),n=i;continue}if(/^for\s*\(/.test(e.slice(n))&&!/[.\w$]/.test(e[n-1]??"")){let i=e.indexOf("(",n),o=jr(e,i);if(o>0){t+=e.slice(n,o+1),n=o+1;continue}}let r=/^([A-Za-z_$][\w$]*)\s*(\+\+|--)/.exec(e.slice(n));if(r&&!/[.\w$]/.test(e[n-1]??"")){t+=`${r[1]} ${r[2]==="++"?"+=":"-="} 1`,n+=r[0].length;continue}t+=s,n++}return t}function of(e){let t=[],n=0,s="",r=0;for(let i=0;i<e.length;i++){let o=e[i];if(s){o==="\\"?i++:o===s&&(s="");continue}if(o==='"'||o==="'"||o==="`"){s=o;continue}o==="("||o==="["||o==="{"?n++:o===")"||o==="]"||o==="}"?n--:o===";"&&n===0&&(t.push(e.slice(r,i).trim()),r=i+1)}return t.push(e.slice(r).trim()),t}function xc(e){let t=e.trim();return/^[-\w$.]+(?:\([^()]*\))?(?:\[[^\]]*\])?$/.test(t)?t:`(${t})`}function af(e){let t=of(e);if(t.length!==3)return null;let n=/^(?:(?:let|var|const)\s+)?([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(t[0]);if(!n)return null;let[,s,r]=n,i=new RegExp(`^${Js(s)}\\s*(<=?|>=?)\\s*([\\s\\S]+)$`).exec(t[1]);if(!i)return null;let[,o,a]=i,c=new RegExp(`^${Js(s)}\\s*(\\+\\+|\\+=\\s*([\\s\\S]+))$`).exec(t[2]),d=new RegExp(`^${Js(s)}\\s*(--|-=\\s*([\\s\\S]+))$`).exec(t[2]),u=!!c;if(!u&&!d)return null;let l=(u?c[2]:d[2])?.trim(),p=l?xc(l):"1";if(u!==(o==="<"||o==="<="))return null;let h=xc(r),g=xc(a);if(o==="<")return p==="1"?`for ${s} in range(${h}, ${g}):`:`for ${s} in range(${h}, ${g}, ${p}):`;if(o==="<="){let b=`(${a.trim()}) + 1`;return p==="1"?`for ${s} in range(${h}, ${b}):`:`for ${s} in range(${h}, ${b}, ${p}):`}if(o===">"){let b=p==="1"?"-1":`-${p}`;return`for ${s} in range(${h}, ${g}, ${b}):`}let y=`(${a.trim()}) - 1`,m=p==="1"?"-1":`-${p}`;return`for ${s} in range(${h}, ${y}, ${m}):`}function hw(e){let t=0,n="";for(let s=0;s<e.length;s++){let r=e[s];if(n){r==="\\"?s++:r===n&&(n="");continue}if(r==='"'||r==="'"||r==="`"){n=r;continue}if(r==="("||r==="["||r==="{"){t++;continue}if(r===")"||r==="]"||r==="}"){t--;continue}if(r!=="f"||!e.startsWith("for",s)||/[.\w$]/.test(e[s-1]??"")||/[\w$]/.test(e[s+3]??""))continue;let i=e.indexOf("(",s);if(i<0)continue;let o=jr(e,i);if(o<0)continue;let a=e.slice(i+1,o);if(of(a).length===3&&af(a)===null)return e.slice(s,o+1);s=o}return null}function gw(e){let t=e.length;for(;t>0&&e[t-1]===" ";)t--;if(t===0)return-1;let n=e[t-1];if(n==='"'||n==="'")return _c(e,qp(e,t-1));if(n===")"||n==="]"){let s=n===")"?"(":"[",r=0;for(let i=t-1;i>=0;i--){let o=e[i];if(o==='"'||o==="'"){i=qp(e,i);continue}if(o===n)r++;else if(o===s&&--r===0)return _c(e,i)}return-1}return/[\w$\]]/.test(n)?_c(e,t):-1}function Gp(e,t,n,s,r=[],i=[],o=!0){let a=" ".repeat(s),c=new Set(r),d=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/=>/,"an arrow function"]];e=Ot(sn(e)),e=tn(e),e=zt(e,{target:"python",options:m=>Dt(m,"quoted"),empty:"None",file:t,warn:m=>n.push(`python: ${m}`)}).code;{let m=0;e=Qn(e,b=>r.includes(b)?"set"+b.charAt(0).toUpperCase()+b.slice(1):null,()=>String(++m))}e=rn(e,(m,b,$)=>{let w=G($,Cr,new Set([b]));if(w===null)return null;let v=`${m}()`;return`st['${m}'] = ${w}`.replace(new RegExp(`\\b${b}\\b`,"g"),v)}),e=Kn(e,m=>{let b=m.slice(3,4).toLowerCase()+m.slice(4);return m.length>3&&c.has(b)?b:null},(m,b)=>{let $=G(b,{...Cr,read:w=>c.has(w)?`st.get('${w}')`:w},new Set);return $===null?null:`st['${m}'] = ${$}`}),e=on(e,(m,b)=>{let $=G(b,{...Cr,read:w=>c.has(w)?`st.get('${w}')`:w},new Set);return $===null?null:`st['${m}'] = ${$}`}),e=cw(e,{...Cr,read:m=>c.has(m)?`st.get('${m}')`:m});for(let[m,b]of d)if(m.test(e))return n.push(`python: ${t}: a handler uses ${b}, which has no Python equivalent - emitted as a stub`),`${a}# rosefc: handler body not translated (uses ${b}).
|
|
4199
|
+
${a}pass`;let u=hw(e);if(u!==null)return n.push(`python: ${t}: a handler uses a loop shape with no Python spelling (${u.replace(/\s+/g," ").trim()}) - emitted as a stub`),`${a}# rosefc: handler body not translated (uses an unsupported loop shape).
|
|
4200
|
+
${a}pass`;let l=$w(e.trim());l=fw(l),l=l.replace(/^(\s*st\[[^\]]+\][^;]*);\s*$/gm,"$1"),l=l.replace(/\bawait\s+/g,""),l=l.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(m,b,$)=>`__action('${$}')`),l=l.replace(/\$t\s*\(/g,"rosefc.t("),l=l.replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g,(m,b,$)=>`${b}'${$}':`),l=l.replace(/\brefresh\s*\(\s*\)/g,"app.render()"),l=l.replace(/\bconsole\.(?:log|warn|error)\(/g,"print("),l=l.replace(/\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(m,b,$)=>`st.get('${$}')`),l=l.replace(/\bString\(/g,"("),l=nn(l,tf),l=l.replace(/\bnull\b/g,"None").replace(/\bundefined\b/g,"None"),l=l.replace(/\btrue\b/g,"True").replace(/\bfalse\b/g,"False"),l=l.replace(/===/g,"==").replace(/!==/g,"!="),l=l.replace(/\|\|/g," or ").replace(/&&/g," and "),l=l.replace(/\?\?/g," or "),l=l.replace(/\?\./g,"."),l=l.replace(/`([^`]*)`/g,"'$1'"),l=l.replace(/\{\.\.\./g,"{**"),l=l.replace(/\bapp\.render\(\)/g,"app.render()");for(let m of r)l=l.replace(new RegExp(`\\b${Js(m)}\\s*\\(\\s*\\)\\s*\\.\\s*([A-Za-z_$][\\w$]*)(?![\\w$])`,"g"),(b,$,w)=>/^(?:length|map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase|forEach|push|includes)$/.test($)?b:`(st.get('${m}') or {}).get('${$}')`),l=l.replace(new RegExp(`\\b${Js(m)}\\s*\\(\\s*\\)`,"g"),`st.get('${m}')`);l=pw(l,r),l=Kr(l,m=>`len(${m})`),l=l.replace(/\b(?:const|let|var)\s+/g,""),l=l.replace(/\{\s*\.\.\./g,"{**"),l=l.replace(/\[\s*\.\.\./g,"[*"),l=l.replace(/, \s*\.\.\./g,", *"),l=ec(l,/!(?!=)\s*/g,()=>"not "),l=l.split(`
|
|
4201
4201
|
`).map(m=>m.trim().startsWith("return ")?no(m):m).join(`
|
|
4202
4202
|
`),l=uw(l,m=>`str(${m})`);let p=i.filter(m=>!r.includes(m));p.length&&(l=l.replace(/\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,(m,b,$)=>p.includes(b)?`${b}['${$}']`:m));let f=l.split(`
|
|
4203
4203
|
`).map(m=>m.trim()).filter(Boolean);if(o)!f.some(m=>m.includes("app.render()"))&&f.some(m=>m.startsWith("st["))&&f.push("app.render()");else{let m=f.filter(b=>!b.includes("app.render()"));f.length=0,f.push(...m)}f.length===0&&f.push("pass");let h=[],g=0,y=()=>a+" ".repeat(g);for(let m of f){let b=m,$=0;for(;;){let _=/\}\s*;?\s*$/.exec(b);if(!_||mw(b)>=0||($++,b=b.slice(0,_.index).trim(),!b))break}if(!b){g=Math.max(0,g-$);continue}if(b=yw(b),/^(if|for|while|else\s+if|else)\b[\s\S]*\{\s*;?$/.exec(b)){let _=b.slice(0,b.lastIndexOf("{")).replace(/;\s*$/,"").trim();h.push(y()+bw(_)),g++,g=Math.max(0,g-$);continue}let v=/^if\s*\(/.exec(b);if(v){let _=1,k=v[0].length;for(;k<b.length&&_>0&&(b[k]==="("?_++:b[k]===")"&&_--,_!==0);)k++;if(_===0){let S=b.slice(v[0].length,k),C=b.slice(k+1).trim().replace(/;$/,"");if(S&&C&&!C.endsWith("{")){h.push(y()+"if "+S+":",y()+" "+C),g=Math.max(0,g-$);continue}}}h.push(y()+b),g=Math.max(0,g-$)}return h.join(`
|
|
@@ -4207,14 +4207,14 @@ ${a}pass`;let l=$w(e.trim());l=fw(l),l=l.replace(/^(\s*st\[[^\]]+\][^;]*);\s*$/g
|
|
|
4207
4207
|
`),g=await Cw(n,r,h,t),y=new Set(Zn(h).map(A=>A.family));for(let A of Cn(h))!y.has(A)&&!g.has(A)&&t.push(`arkts: font-family '${A}' has no @font-face - the system default is used`);let m=Mt(n),b=xt([...u.map(A=>A.script),...l.map(A=>A.script)]),$=Tw(e.apiBase??"",m,b),w=Ew($);await _e.promises.writeFile(he.join(i,"kit","RoseKit.ets"),$,"utf8");let v=new Set,_=[],k=[],S=[],C=[];for(let A of u){let{rows:R,tagRows:T}=uf([A.style??"",ke].filter(M=>M&&M.trim()).join(`
|
|
4208
4208
|
`),A.struct,v);R&&_.push(R),T&&S.push(T)}for(let A of l){let{rows:R,tagRows:T}=uf([A.style??"",ke].filter(M=>M&&M.trim()).join(`
|
|
4209
4209
|
`),A.struct,v);R&&k.push(R),T&&C.push(T)}await _e.promises.writeFile(he.join(i,"kit","RoseStyles.ets"),Ow(_,k,S,C),"utf8"),await _e.promises.writeFile(he.join(i,"kit","RoseModifier.ets"),Nw(),"utf8");for(let A of l){let R=Mw(A,g,t,w);await _e.promises.writeFile(he.join(i,"components",A.struct+".ets"),R,"utf8")}for(let A of u){let R=Bw(A,l,p,f,g,t,m,w);await _e.promises.writeFile(he.join(i,"pages",A.struct+".ets"),R.replace(gf,hf(R,w,new Set(["roseData","roseAction","roseKv"]))),"utf8")}await _e.promises.writeFile(he.join(i,"entryability","EntryAbility.ets"),Lw(),"utf8"),await _e.promises.writeFile(he.join(r,"resources","base","profile","main_pages.json"),JSON.stringify({src:u.map(A=>`pages/${A.struct}`)},null,2)+`
|
|
4210
|
-
`,"utf8"),await _e.promises.writeFile(he.join(r,"resources","base","element","string.json"),JSON.stringify({string:[{name:"module_desc",value:"
|
|
4210
|
+
`,"utf8"),await _e.promises.writeFile(he.join(r,"resources","base","element","string.json"),JSON.stringify({string:[{name:"module_desc",value:"Rosefc app"},{name:"EntryAbility_desc",value:"Rosefc"},{name:"EntryAbility_label",value:"Rosefc"},{name:"app_name",value:"Rosefc"}]},null,2)+`
|
|
4211
4211
|
`,"utf8");let x=ha("arkts",b);return await _e.promises.writeFile(he.join(r,"module.json5"),JSON.stringify({module:{name:"entry",type:"entry",description:"$string:module_desc",mainElement:"EntryAbility",deviceTypes:["phone","tablet"],deliveryWithInstall:!0,installationFree:!1,pages:"$profile:main_pages",...x.length?{requestPermissions:x.map(A=>({name:A,reason:"$string:module_desc",usedScene:{abilities:["EntryAbility"],when:"inuse"}}))}:{},abilities:[{name:"EntryAbility",srcEntry:"./ets/entryability/EntryAbility.ets",description:"$string:EntryAbility_desc",icon:"$media:app_icon",label:"$string:EntryAbility_label",startWindowIcon:"$media:app_icon",startWindowBackground:"$media:startIcon",exported:!0,skills:[{entities:["entity.system.home"],actions:["action.system.home"]}]}]}},null,2)+`
|
|
4212
|
-
`,"utf8"),await _e.promises.writeFile(he.join(s,"AppScope","app.json5"),JSON.stringify({app:{bundleName:"dev.
|
|
4213
|
-
`,"utf8"),await _e.promises.writeFile(he.join(s,"AppScope","resources","base","element","string.json"),JSON.stringify({string:[{name:"app_name",value:"
|
|
4212
|
+
`,"utf8"),await _e.promises.writeFile(he.join(s,"AppScope","app.json5"),JSON.stringify({app:{bundleName:"dev.rosefc.app",vendor:"rosefc",versionCode:1e6,versionName:"1.0.0",icon:"$media:app_icon",label:"$string:app_name"}},null,2)+`
|
|
4213
|
+
`,"utf8"),await _e.promises.writeFile(he.join(s,"AppScope","resources","base","element","string.json"),JSON.stringify({string:[{name:"app_name",value:"Rosefc"}]},null,2)+`
|
|
4214
4214
|
`,"utf8"),await _e.promises.writeFile(he.join(s,"build-profile.json5"),Pw(),"utf8"),await _e.promises.writeFile(he.join(s,"hvigorfile.ts"),`export { appTasks } from '@ohos/hvigor-ohos-plugin';
|
|
4215
|
-
`,"utf8"),await _e.promises.writeFile(he.join(s,"oh-package.json5"),JSON.stringify({name:"
|
|
4215
|
+
`,"utf8"),await _e.promises.writeFile(he.join(s,"oh-package.json5"),JSON.stringify({name:"rosefc_app",version:"1.0.0",description:"A Rosefc app, exported with rosefc export arkts",main:"",author:"",license:"MIT",dependencies:{}},null,2)+`
|
|
4216
4216
|
`,"utf8"),await _e.promises.writeFile(he.join(s,"entry","hvigorfile.ts"),`export { hapTasks } from '@ohos/hvigor-ohos-plugin';
|
|
4217
|
-
`,"utf8"),await _e.promises.writeFile(he.join(s,"entry","oh-package.json5"),JSON.stringify({name:"entry",version:"1.0.0",description:"
|
|
4217
|
+
`,"utf8"),await _e.promises.writeFile(he.join(s,"entry","oh-package.json5"),JSON.stringify({name:"entry",version:"1.0.0",description:"Rosefc entry module",main:"",author:"",license:"MIT",dependencies:{}},null,2)+`
|
|
4218
4218
|
`,"utf8"),await _e.promises.writeFile(he.join(s,"README.md"),Fw(e.apiBase??"",u.length,l.length,t),"utf8"),{pages:u.map(A=>`entry/src/main/ets/pages/${A.struct}.ets`),components:l.map(A=>`entry/src/main/ets/components/${A.struct}.ets`)}}function xw(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function kw(e){if(!e)return"";let t=/<title>([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/\{[^}]*\}/g,"").trim():""}function cf(e){return(e.split("/").map(s=>s.replace(/^\[(.+)\]$/,"param_$1")).map(s=>s.replace(/[^\w]+/g,"_").split("_").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")).join("").replace(/^\d/,"_$&")||"Page")+"Page"}function Cc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^\w]/g,"_").toLowerCase()}function Rw(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}async function Aw(e,t,n,s){let r=new Map,i=new Map,o=d=>{for(let u of d)if(u.kind==="element"){if(u.tag.toLowerCase()==="img"){let l=u.attrs.find(h=>h.name==="src"),p=l&&l.value.kind==="text"?l.value.text:"",f=/^\/(?:public\/)?([^/]+\.(?:png|jpe?g|svg|gif|webp))$/i.exec(p);f?r.set(f[1],p):p&&s.push(`arkts: <img ${p}> is not a flat public/ image - needs a media resource`)}o(u.children)}else u.kind==="if"?u.branches.forEach(l=>o(l.children)):u.kind==="each"||u.kind==="block"?o(u.children):u.kind==="await"&&(o(u.pending),o(u.then),o(u.catch))};n.forEach(o);let a=he.join(t,"resources","base","media");await _e.promises.copyFile(he.join(e,"public","icon.png"),he.join(a,"app_icon.png")).catch(async()=>{let d=Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==","base64");await _e.promises.writeFile(he.join(a,"app_icon.png"),d)}),await _e.promises.copyFile(he.join(a,"app_icon.png"),he.join(a,"startIcon.png")).catch(()=>{});for(let[d,u]of r){let l=he.join(e,"public",d);if(!_e.existsSync(l)){s.push(`arkts: asset ${u} is not in public/ - Image() falls back to a placeholder`);continue}if(/\.svg$/i.test(d)){let f=Wt(await _e.promises.readFile(l,"utf8"));f.shape?i.set(u,f.shape):s.push(`arkts: ${d} uses ${f.reason??"an unsupported feature"} - rendered as a placeholder`);continue}let p=he.join(a,Cc(d.replace(/\.[^.]+$/,""))+he.extname(d).toLowerCase());await _e.promises.copyFile(l,p)}return{media:new Map([...r].filter(([d])=>!/\.svg$/i.test(d)).map(([d,u])=>[u,Cc(d.replace(/\.[^.]+$/,""))])),vectors:i}}async function Cw(e,t,n,s){let r=new Map;for(let i of Zn(n)){let o=he.join(e,"public",i.file.replace(/^\//,""));if(!_e.existsSync(o)){s.push(`arkts: font-family '${i.family}' points at ${i.file}, which is not in public/ - the system default is used`);continue}let a=he.extname(o).toLowerCase();if(!/^\.(ttf|otf|ttc|woff2?)$/.test(a)){s.push(`arkts: font-family '${i.family}' uses ${a}, which HarmonyOS cannot load - convert it to .ttf/.otf`);continue}let c=i.family.replace(/[^\w]/g,"")+a;await _e.promises.mkdir(he.join(t,"resources","rawfile"),{recursive:!0}),await _e.promises.copyFile(o,he.join(t,"resources","rawfile",c)),r.set(i.family,c)}return r}function so(e){let t=/^#([0-9a-f]{6})([0-9a-f]{2})$/i.exec(e);return t?`#${t[2]}${t[1]}`.toLowerCase():e}function li(e){return e.u==="%"?`'${e.n}%'`:`${e.n}`}function Oa(e){return e==="center"?"Center":e==="end"?"End":e==="stretch"?"Stretch":"Start"}function Ac(e){return e==="center"?"Center":e==="between"?"SpaceBetween":e==="around"?"SpaceAround":e==="evenly"?"SpaceEvenly":e==="end"?"End":"Start"}function yn(e){let t=[];if(e.background&&t.push(`.backgroundColor('${so(e.background)}')`),e.gradient){let n=e.gradient.stops.map(s=>`['${so(s.color)}', ${Math.round(s.at)/100}]`).join(", ");t.push(`.linearGradient({ angle: ${e.gradient.angle}, colors: [${n}] })`)}if(e.padding&&t.push(`.padding({ top: ${e.padding[0]}, right: ${e.padding[1]}, bottom: ${e.padding[2]}, left: ${e.padding[3]} })`),e.margin&&t.push(`.margin({ top: ${e.margin[0]}, right: ${e.margin[1]}, bottom: ${e.margin[2]}, left: ${e.margin[3]} })`),e.borderWidth&&e.borderWidth.some(n=>n>0)){let n=e.borderWidth,s=e.borderStyle==="dashed"?"BorderStyle.Dashed":e.borderStyle==="dotted"?"BorderStyle.Dotted":"BorderStyle.Solid";t.push(`.border({ width: { top: ${n[0]}, right: ${n[1]}, bottom: ${n[2]}, left: ${n[3]} }, color: '${so(e.borderColor??"#e0e0e0")}', style: ${s} })`)}if(e.radius){let[n,s,r,i]=e.radius;t.push(n===s&&s===r&&r===i?`.borderRadius(${n})`:`.borderRadius({ topLeft: ${n}, topRight: ${s}, bottomRight: ${r}, bottomLeft: ${i} })`)}if(e.shadow&&t.push(`.shadow({ radius: ${e.shadow.blur}, color: '${so(e.shadow.color)}', offsetX: ${e.shadow.x}, offsetY: ${e.shadow.y} })`),e.width&&t.push(`.width(${li(e.width)})`),e.height&&t.push(`.height(${li(e.height)})`),e.minWidth||e.maxWidth||e.minHeight||e.maxHeight){let n=[e.minWidth?`minWidth: ${li(e.minWidth)}`:"",e.maxWidth?`maxWidth: ${li(e.maxWidth)}`:"",e.minHeight?`minHeight: ${li(e.minHeight)}`:"",e.maxHeight?`maxHeight: ${li(e.maxHeight)}`:""].filter(Boolean);t.push(`.constraintSize({ ${n.join(", ")} })`)}return e.opacity!==void 0&&t.push(`.opacity(${e.opacity})`),e.overflow==="hidden"&&t.push(".clip(true)"),e.display==="none"&&t.push(".visibility(Visibility.None)"),e.grow!==void 0&&e.grow>0&&t.push(`.layoutWeight(${e.grow})`),e.alignSelf&&t.push(`.alignSelf(ItemAlign.${Oa(e.alignSelf)})`),e.position&&(e.insetTop!==void 0||e.insetLeft!==void 0)&&t.push(`.position({ x: ${e.insetLeft??0}, y: ${e.insetTop??0} })`),e.zIndex!==void 0&&(e.position||e.shadow)&&t.push(`.zIndex(${e.zIndex})`),t}function ar(e,t){let n=[];return e.color&&n.push(`.fontColor('${so(e.color)}')`),e.fontSize!==void 0&&n.push(`.fontSize(${e.fontSize})`),e.fontWeight!==void 0&&n.push(`.fontWeight(FontWeight.${e.fontWeight>=700?"Bold":e.fontWeight>=500?"Medium":"Regular"})`),e.italic&&n.push(".fontStyle(FontStyle.Italic)"),e.fontFamily&&t.has(e.fontFamily)&&n.push(`.fontFamily(${JSON.stringify(e.fontFamily)})`),e.letterSpacing!==void 0&&n.push(`.letterSpacing(${e.letterSpacing})`),e.lineHeight!==void 0&&e.fontSize&&n.push(`.lineHeight(${Math.round(e.fontSize*e.lineHeight)})`),e.textAlign&&n.push(`.textAlign(TextAlign.${e.textAlign==="center"?"Center":e.textAlign==="right"?"End":e.textAlign==="justify"?"Justify":"Start"})`),e.textTransform&&n.push(`.textCase(TextCase.${e.textTransform==="uppercase"?"UpperCase":e.textTransform==="lowercase"?"LowerCase":"Normal"})`),e.underline&&n.push(".decoration({ type: TextDecorationType.Underline })"),e.strike&&n.push(".decoration({ type: TextDecorationType.LineThrough })"),n}function Na(e,t){return[...yn(e),...ar(e,t)]}function uf(e,t,n){let s=Te(e),r=new Map,i=new Map;for(let d of s.rules){let u=d.parts[d.parts.length-1];if(!u.classes.length&&u.tag){i.set(u.tag,fe(i.get(u.tag)??null,d.model));continue}for(let l of u.classes){let p=`${l}__${t}`;r.set(p,fe(r.get(p)??null,d.model))}}let o=d=>Na(d,n).join("");for(let d of s.rules){if(!d.hover)continue;let l=`__h_${d.parts[d.parts.length-1].classes.join("_")||"x"}`.replace(/[^\w$]/g,"_");r.set(`__hover_${l}`,d.hover)}for(let d of s.rules){if(!d.focus)continue;let u=d.parts[d.parts.length-1],l=`__f_${u.classes.join("_")||"x"}`.replace(/[^\w$]/g,"_"),p=`${u.classes[0]??""}__${t}`,f=u.classes.length?r.get(p):void 0,h=d.focus.borderColor&&!d.focus.borderWidth?{...d.focus,borderWidth:(f??d.model).borderWidth}:d.focus;r.set(`__focus_${l}`,h)}for(let d of s.rules){if(!d.active)continue;let u=d.parts[d.parts.length-1],l=`__a_${u.classes.join("_")||"x"}`.replace(/[^\w$]/g,"_"),p=`${u.classes[0]??""}__${t}`,f=u.classes.length?r.get(p):void 0,h=d.active.borderColor&&!d.active.borderWidth?{...d.active,borderWidth:(f??d.model).borderWidth}:d.active;r.set(`__active_${l}`,h)}let a=[...r.entries()].map(([d,u])=>` '${d}': (it: RoseModifier) => {${o(u)}}`).join(`,
|
|
4219
4219
|
`),c=[...i.entries()].map(([d,u])=>` '${d}': (it: RoseModifier) => {${o(u)}}`).join(`,
|
|
4220
4220
|
`);return{rows:a,tagRows:c}}function ff(e){let t={};for(let n of["color","fontSize","fontWeight","fontFamily","italic","lineHeight","letterSpacing","textAlign","textTransform","underline","strike"]){let s=e[n];s!==void 0&&(t[n]=s)}return t}function jw(e,t){let n=ir(e,t,_w),s=e.gap!==void 0&&e.gap>0?`, space: ${e.gap}`:"";if(e.display==="flex"&&e.wrap){let i=[`direction: FlexDirection.${n==="row"?"Row":"Column"}`];return e.justify&&i.push(`justifyContent: FlexAlign.${Ac(e.justify)}`),e.align&&e.align!=="stretch"&&i.push(`alignItems: ItemAlign.${Oa(e.align)}`),i.push("wrap: FlexWrap.Wrap"),e.gap&&i.push(`space: { main: ${e.gap}, cross: ${e.gap} }`),{open:`Flex({ ${i.join(", ")} })`,layout:[]}}if(n==="row"){let i=[];return e.justify&&i.push(`.justifyContent(FlexAlign.${Ac(e.justify)})`),e.align&&e.align!=="stretch"&&i.push(`.alignItems(VerticalAlign.${Oa(e.align)})`),{open:`Row(${s?`{ ${s.slice(2)} }`:""})`,layout:i}}let r=[];return e.justify&&r.push(`.justifyContent(FlexAlign.${Ac(e.justify)})`),e.align&&e.align!=="stretch"&&r.push(`.alignItems(HorizontalAlign.${Oa(e.align)})`),{open:`Column(${s?`{ ${s.slice(2)} }`:""})`,layout:r}}function Tw(e,t,n=[]){let s=t?`
|
|
@@ -4290,7 +4290,7 @@ ${i}
|
|
|
4290
4290
|
}
|
|
4291
4291
|
`:"";return`import http from '@ohos.net.http';
|
|
4292
4292
|
|
|
4293
|
-
/// Base URL of the deployed
|
|
4293
|
+
/// Base URL of the deployed Rosefc server (rosefc export --api).
|
|
4294
4294
|
export const ROSE_API_BASE: string = ${JSON.stringify(e)};
|
|
4295
4295
|
${s}
|
|
4296
4296
|
|
|
@@ -4300,7 +4300,7 @@ export async function roseData(route: string): Promise<Record<string, Object>> {
|
|
|
4300
4300
|
const client = http.createHttp();
|
|
4301
4301
|
try {
|
|
4302
4302
|
const response = await client.request(
|
|
4303
|
-
ROSE_API_BASE + '/
|
|
4303
|
+
ROSE_API_BASE + '/__rosefc/data?path=' + encodeURIComponent(route),
|
|
4304
4304
|
{ method: http.RequestMethod.GET, expectDataType: http.HttpDataType.OBJECT, connectTimeout: 5000, readTimeout: 5000 },
|
|
4305
4305
|
);
|
|
4306
4306
|
const body = response.result as Record<string, Object>;
|
|
@@ -4462,14 +4462,14 @@ export function roseArr(...items: Object[]): Object[] {
|
|
|
4462
4462
|
/// the process - the client-side stand-in for the server-side memo the web build
|
|
4463
4463
|
/// uses (where the server computes and ships the value in the state). A restart
|
|
4464
4464
|
/// recomputes, which is the same trade an in-memory memo makes on the web.
|
|
4465
|
-
const
|
|
4465
|
+
const __rosefcKvCache = new Map<string, [number, Object]>();
|
|
4466
4466
|
|
|
4467
4467
|
export function roseKv<T>(name: string, compute: () => T, ttlSeconds: number): T {
|
|
4468
4468
|
const now = Date.now();
|
|
4469
|
-
const cached =
|
|
4469
|
+
const cached = __rosefcKvCache.get(name);
|
|
4470
4470
|
if (cached && now - cached[0] < ttlSeconds * 1000) return cached[1] as T;
|
|
4471
4471
|
const value = compute();
|
|
4472
|
-
|
|
4472
|
+
__rosefcKvCache.set(name, [now, value as Object]);
|
|
4473
4473
|
return value;
|
|
4474
4474
|
}
|
|
4475
4475
|
|
|
@@ -4517,7 +4517,7 @@ export function rosePatch<T>(current: T, patch: Record<string, Object>): T {
|
|
|
4517
4517
|
}
|
|
4518
4518
|
|
|
4519
4519
|
/** One styled run of trusted markup. */
|
|
4520
|
-
export interface
|
|
4520
|
+
export interface RosefcSpan {
|
|
4521
4521
|
text: string;
|
|
4522
4522
|
bold: boolean;
|
|
4523
4523
|
italic: boolean;
|
|
@@ -4526,7 +4526,7 @@ export interface RosefdSpan {
|
|
|
4526
4526
|
|
|
4527
4527
|
/** Trusted markup renders as markup: the inline HTML subset a content
|
|
4528
4528
|
* page uses becomes styled spans a ForEach can render, never escaped text. */
|
|
4529
|
-
export function roseHtmlSpans(html: string):
|
|
4529
|
+
export function roseHtmlSpans(html: string): RosefcSpan[] {
|
|
4530
4530
|
const entities: Record<string, string> = {
|
|
4531
4531
|
"amp": "&", "lt": "<", "gt": ">", "quot": "\\"", "nbsp": " ",
|
|
4532
4532
|
};
|
|
@@ -4546,7 +4546,7 @@ export function roseHtmlSpans(html: string): RosefdSpan[] {
|
|
|
4546
4546
|
}
|
|
4547
4547
|
return out;
|
|
4548
4548
|
};
|
|
4549
|
-
const spans:
|
|
4549
|
+
const spans: RosefcSpan[] = [];
|
|
4550
4550
|
let buffer = "";
|
|
4551
4551
|
let bold = false;
|
|
4552
4552
|
let italic = false;
|
|
@@ -4690,13 +4690,13 @@ ${c}
|
|
|
4690
4690
|
${mf(u,o)}
|
|
4691
4691
|
}${l}
|
|
4692
4692
|
}
|
|
4693
|
-
`}function Fw(e,t,n,s){return`#
|
|
4693
|
+
`}function Fw(e,t,n,s){return`# Rosefc -> HarmonyOS ArkTS
|
|
4694
4694
|
|
|
4695
|
-
Generated by \`
|
|
4695
|
+
Generated by \`rosefc export arkts\` from the project's \`.rose\` pages.
|
|
4696
4696
|
|
|
4697
4697
|
- ${t} page(s), ${n} component(s)
|
|
4698
4698
|
- Open in DevEco Studio (project root) and run on a phone/tablet emulator
|
|
4699
|
-
- Server: \`
|
|
4699
|
+
- Server: \`rosefc export arkts --api <base>\` writes the base URL into
|
|
4700
4700
|
\`entry/src/main/ets/kit/RoseKit.ets\`. Current: \`${e||"(unset)"}\`
|
|
4701
4701
|
|
|
4702
4702
|
ArkTS is TypeScript, so the page expressions are translated almost verbatim;
|
|
@@ -4710,19 +4710,19 @@ import type AbilityConstant from '@ohos.app.ability.AbilityConstant';
|
|
|
4710
4710
|
|
|
4711
4711
|
export default class EntryAbility extends UIAbility {
|
|
4712
4712
|
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
|
|
4713
|
-
hilog.info(0x0000, '
|
|
4713
|
+
hilog.info(0x0000, 'rosefc', 'EntryAbility onCreate');
|
|
4714
4714
|
}
|
|
4715
4715
|
|
|
4716
4716
|
onWindowStageCreate(windowStage: window.WindowStage): void {
|
|
4717
4717
|
windowStage.loadContent('pages/IndexPage', (err) => {
|
|
4718
4718
|
if (err.code) {
|
|
4719
|
-
hilog.error(0x0000, '
|
|
4719
|
+
hilog.error(0x0000, 'rosefc', 'loadContent failed: %{public}s', JSON.stringify(err));
|
|
4720
4720
|
}
|
|
4721
4721
|
});
|
|
4722
4722
|
}
|
|
4723
4723
|
|
|
4724
4724
|
onDestroy(): void {
|
|
4725
|
-
hilog.info(0x0000, '
|
|
4725
|
+
hilog.info(0x0000, 'rosefc', 'EntryAbility onDestroy');
|
|
4726
4726
|
}
|
|
4727
4727
|
}
|
|
4728
4728
|
`}function ie(e,t){t.lines.push(" ".repeat(t.depth)+e)}function Bw(e,t,n,s,r,i,o,a){let c=Gw(e.script),d=ln(e.script??"");for(let N of d)i.push(o?`arkts: ${N} reads the content collections, baked into the kit at export time`:`arkts: ${N} is a server-side bridge - a native build has no content collections, so it resolves empty`);let u=d.length?o?Oe(e.script??"","roseContentList","roseContentGet","''"):jn(e.script??"","[]"):e.script,l=new Set([...c.state.map(N=>N.name),...c.derived.map(N=>N.name),...c.data]),p=o&&d.length?cn(e.script??""):[],f=[...Qw(u),...p.map(N=>{let W=new RegExp(`(?:const|let|var)\\s+${N}\\s*(?::[^=;\\n]*)?=`).exec(e.script??""),re=W?e.script.slice(W.index+W[0].length).split(`
|
|
@@ -4732,11 +4732,11 @@ export default class EntryAbility extends UIAbility {
|
|
|
4732
4732
|
`),k=an(e.script??""),S=r.size?[...r].map(([N,W])=>` font.registerFont({ familyName: ${JSON.stringify(N)}, familySrc: $rawfile(${JSON.stringify(W)}) });`).join(`
|
|
4733
4733
|
`)+`
|
|
4734
4734
|
`:"",C=[...c.state.map(N=>{let W=v(N.name);return` @State${k.includes(N.name)?` @Watch('__persist_${N.name}')`:""} ${N.name}: ${ci(W)} = ${jc(W)};`}),...c.derived.map(N=>` get ${N.name}(): ${Kw(N.expr)} { return ${Vt(N.expr,m)}; }`),...c.data.map(N=>` @State ${N}: Object = null;`),...m.deferred.map(N=>` @State ${N.name}: boolean = false;`),...m.hoverStates.map(N=>` @State ${N.name}: boolean = false;`)].join(`
|
|
4735
|
-
`),x=k.map(N=>` if (
|
|
4735
|
+
`),x=k.map(N=>` if (__rosefcP.hasSync(${JSON.stringify("rosefc:"+N)})) this.${N} = String(__rosefcP.getSync(${JSON.stringify("rosefc:"+N)}, this.${N}));`).join(`
|
|
4736
4736
|
`),A=k.map(N=>`
|
|
4737
4737
|
__persist_${N}(): void {
|
|
4738
|
-
const __p = preferences.getPreferencesSync(getContext(this), '
|
|
4739
|
-
__p.putSync(${JSON.stringify("
|
|
4738
|
+
const __p = preferences.getPreferencesSync(getContext(this), 'rosefc');
|
|
4739
|
+
__p.putSync(${JSON.stringify("rosefc:"+N)}, this.${N});
|
|
4740
4740
|
__p.flush();
|
|
4741
4741
|
}`).join(`
|
|
4742
4742
|
`),R=St(e.nodes).flatMap(N=>N.fields),M=$s(e.script??"").filter(N=>new Set([...c.state.map(W=>W.name),...c.data]).has(N.name)).map(N=>` this.${N.name} = roseKv(${JSON.stringify(N.name)}, () => (${bs(N.fn)}), ${N.ttl});`).join(`
|
|
@@ -4780,7 +4780,7 @@ ${c.data.map(N=>` if (patch['${N}'] !== undefined) this.${N} = patch['${N}']
|
|
|
4780
4780
|
${A}${F}
|
|
4781
4781
|
|
|
4782
4782
|
aboutToAppear(): void {
|
|
4783
|
-
${k.length?" const
|
|
4783
|
+
${k.length?" const __rosefcP = preferences.getPreferencesSync(getContext(this), 'rosefc');":""}
|
|
4784
4784
|
${S}${ce||" // no route parameters"}
|
|
4785
4785
|
${x}
|
|
4786
4786
|
this.loadData();
|
|
@@ -4820,7 +4820,7 @@ ${" "+e.trim().split(`
|
|
|
4820
4820
|
`)}
|
|
4821
4821
|
}
|
|
4822
4822
|
.width('100%')${s}`}function bn(e,t){let n=[],s=()=>{if(!n.length)return;let r=Ma(n,t);r&&!/^`\s*`$/.test(r)&&ie(`Text(${r})${ar(t.inherited,t.fonts).join("")}`,t),n.length=0};for(let r of e){if(r.kind==="text"||r.kind==="expr"){n.push(r);continue}s(),Iw(r,t)}s()}function Ma(e,t){let n="";for(let s of e)if(s.kind==="text")n+=s.value.replace(/\s+/g," ");else if(s.kind==="expr"){let r=Vt(s.code,t);r.startsWith("`")&&r.endsWith("`")&&r.length>=2?n+=r.slice(1,-1):n+="${"+r+"}"}return n=n.trim(),n?n.includes("${")?"`"+n.replace(/`/g,"\\`")+"`":JSON.stringify(n):""}function Iw(e,t){switch(e.kind){case"text":case"expr":bn([e],t);return;case"html":ie(`Column() {
|
|
4823
|
-
ForEach(roseHtmlSpans(${Vt(e.code,t)}), (span:
|
|
4823
|
+
ForEach(roseHtmlSpans(${Vt(e.code,t)}), (span: RosefcSpan) => {
|
|
4824
4824
|
Text(span.text)
|
|
4825
4825
|
.fontWeight(span.bold ? FontWeight.Bold : FontWeight.Normal)
|
|
4826
4826
|
.fontStyle(span.italic ? FontStyle.Italic : FontStyle.Normal)
|
|
@@ -4828,7 +4828,7 @@ ${" "+e.trim().split(`
|
|
|
4828
4828
|
.fontColor(span.link ? Color.Blue : Color.Black)
|
|
4829
4829
|
})
|
|
4830
4830
|
}`,t);return;case"const":ie(`const ${e.name} = ${Vt(e.code,t)};`,t);return;case"render":t.warnings.push(`arkts: {@render ${e.code}} is not expanded yet - renders nothing`);return;case"snippet":t.warnings.push(`arkts: {#snippet ${e.name}} is emitted where declared (no call-site expansion yet)`),bn(e.children,t);return;case"if":{e.branches.forEach((n,s)=>{ie(s===0?`if (${Vt(n.cond??"false",t)}) {`:n.cond===null?"} else {":`} else if (${Vt(n.cond,t)}) {`,t),t.depth++,bn(n.children,t),t.depth--}),ie("}",t);return}case"each":{let n=Hw(e.children,e.binding)?"Record<string, Object>":zw(e.items,t.script);ie(`ForEach(${Vt(e.items,t)}, (${e.binding}: ${n}, index: number) => {`,t),t.depth++;let s={...t,mapBinds:new Set([...t.mapBinds,e.binding]),loopVars:new Set([...t.loopVars,e.binding])};bn(e.children,s),t.depth--,e.key?ie(`}, (${e.binding}: ${n}) => \`\${${Vt(e.key,t)}}\`)`,t):ie("})",t);return}case"await":{let n=t.awaits.length,s=`__await${n}Done`,r=`__await${n}Value`,i=`__await${n}Err`,o=Vt(Se(Bt(e.expr),t.scriptConsts),t);un(e.expr)||t.warnings.push(`${t.file}: the {#await} head is a promise this target cannot await - the then branch renders only for Promise.resolve/reject literals`),t.awaits.push({done:s,value:r,err:i,expr:o});let a=new Map;e.thenName&&a.set(e.thenName,`this.${r}`);let c=new Map;e.catchName&&c.set(e.catchName,`this.${i}`),ie(`if (this.${s}) {`,t),t.depth++,ie(`if (this.${i} !== null) {`,t),t.depth++,bn(Je(Ct(e.catch,e.catchName??""),c),t),t.depth--,ie("} else {",t),t.depth++,bn(Je(e.then,a),t),t.depth--,ie("}",t),t.depth--,ie("} else {",t),t.depth++,bn(e.pending,t),t.depth--,ie("}",t);return}case"block":if(e.name==="defer"){let n=Number(/hold\s*=\s*(\d+)/.exec(String(e.head??""))?.[1]??"0"),s=`__defer${t.deferred.length}`;t.deferred.push({name:s,hold:Number.isFinite(n)?n:0}),t.stateNames.add(s),ie(`if (this.${s}) {`,t),t.depth++,bn(e.children,t),t.depth--,ie("}",t);return}if(e.name==="boundary"){let n=t.lines.length,s=t.depth;t.depth=s+1,bn(e.children,t);let r=t.lines.splice(n);t.depth=s,ie("try {",t),t.lines.push(...r),ie("} catch (e) {",t),e.fallback?(t.depth=s+1,bn(e.fallback,t),t.depth=s):ie("Text('This section failed to render.')",t),ie("}",t);return}bn(e.children,t);return;case"slot":return;case"element":Ww(e,t);return}}function Ww(e,t){let n=e.tag.toLowerCase(),s=bt(e),r={tag:n,classes:s.staticClasses},i=rt(t.sheet,r,t.ancestors,{viewport:Fa}),o=fe(i.model,s.inlineStyle),a="",c="";if(i.hover){let l=Na(i.hover,t.fonts);l.length&&(a=`__h_${s.staticClasses.join("_")||"x"}`.replace(/[^\w$]/g,"_"),t.hoverStates.some(p=>p.name===a)||t.hoverStates.push({name:a,mods:l}),c=`.attributeModifier(roseModifier('${n}', [this.${a} ? '__hover_${a}' : ''], '${t.scope}')).onHover((isHover: boolean) => { this.${a} = isHover; })`)}if(i.focus){let l=Na(i.focus,t.fonts);if(l.length){let p=`__f_${s.staticClasses.join("_")||"x"}`.replace(/[^\w$]/g,"_");t.hoverStates.some(f=>f.name===p)||t.hoverStates.push({name:p,mods:l}),c+=`.attributeModifier(roseModifier('${n}', [this.${p} ? '__focus_${p}' : ''], '${t.scope}')).onFocus(() => { this.${p} = true; }).onBlur(() => { this.${p} = false; })`}}if(i.active){let l=Na(i.active,t.fonts);if(l.length){let p=`__a_${s.staticClasses.join("_")||"x"}`.replace(/[^\w$]/g,"_");t.hoverStates.some(f=>f.name===p)||t.hoverStates.push({name:p,mods:l}),c+=`.attributeModifier(roseModifier('${n}', [this.${p} ? '__active_${p}' : ''], '${t.scope}')).onTouch((event: TouchEvent) => { if (event.type === TouchType.Down) { this.${p} = true; } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) { this.${p} = false; } })`}}let d="";if(s.hasDynamic){let l=[...s.staticClasses.map(h=>`'${h}'`),...s.dynamicClassExprs.map(h=>`(${Vt(h,t)})`)],p=s.inlineDecls.length?`inline: [${s.inlineDecls.map(h=>JSON.stringify(h)).join(", ")}]`:"",f=s.dynamicStyle.length?`{ ${s.dynamicStyle.map(h=>`${JSON.stringify(h.prop)}: ${Vt(h.code,t)}`).join(", ")} }`:"undefined";d=`.attributeModifier(roseModifier('${n}', [${l.join(", ")}], '${t.scope}', ${f}${p?", "+p:""}))`}t.ancestors.push(r);let u=t.inherited;t.inherited=fe(u,ff(o));try{Dw(e,t,o,d,c)}finally{t.ancestors.pop(),t.inherited=u}}function Dw(e,t,n,s,r){let i=e.tag.toLowerCase(),o=l=>l+s+r;if(i==="slot"){let l=e.attrs.find(m=>m.name==="name"),p=l&&l.value.kind==="text"?l.value.text:"",f=!p||p==="default"?"slotDefault":`slot${p.charAt(0).toUpperCase()}${p.slice(1)}`,h=e.attrs.filter(m=>m.name!=="name"&&m.value.kind==="expr").map(m=>`'${m.name}': ${Vt(m.value.code,t)}`),g=[...t.loopVars].map(m=>`'${m}': this.__roseScope['${m}']`),y=[...h,...g];ie(y.length?`this.${f}({ ${y.join(", ")} })`:`this.${f}({})`,t);return}let a=t.components.find(l=>l.name.toLowerCase()===i);if(a){let p=[...It(e).entries()].map(([w,v])=>`${df(w)}: ${Vt(v,t)}, ${ze(w)}: (v: Object) => { this.${v} = v; }`),f=e.attrs.filter(w=>w.name!=="class"&&!/^bind:(value|checked|group|open)$/.test(w.name)).map(w=>`${df(w.name)}: ${Ea(w,t)}`).join(", "),h=Pt(e.children),g=[],y=[...t.loopVars],m=(w,v,_)=>{let k=`__sb${t.slotBuilders.length}${w.replace(/[^A-Za-z0-9]/g,"")}`,S={...t,lines:[],depth:0,loopVars:new Set};bn(Lt(v,[..._,...y],C=>`props['${C}']`),S),t.slotBuilders.push({name:k,lines:S.lines}),g.push(`${w}: this.${k}`)};if(a.slots.hasDefault){let w=h.defaultNodes.length?h.defaultNodes:st(a.nodes,"default");m("slotDefault",w,[])}for(let w of a.slots.named){let v=h.named.get(w.name)??st(a.nodes,w.name);m(`slot${w.name.charAt(0).toUpperCase()}${w.name.slice(1)}`,v,w.props)}let b=y.length&&(a.slots.hasDefault||a.slots.named.length)?`, __roseScope: { ${y.map(w=>`'${w}': ${Vt(w,t)}`).join(", ")} }`:"",$=[f,...p,...g].filter(Boolean).join(", ");ie(`${a.struct}({ ${$}${b} })`,t);return}if(Sw.has(i)&&!e.children.some(l=>l.kind==="element")){let l=Ma(e.children,t);ie(o(`Text(${l||"''"})${yn(n).join("")}${ar(t.inherited,t.fonts).join("")}`),t);return}if(i==="progress"){let l=e.attrs.find(g=>g.name==="value"),p=e.attrs.find(g=>g.name==="max"),f=l&&l.value.kind==="expr"?Vt(l.value.code,t):l&&l.value.kind==="text"?l.value.text:"0",h=p&&p.value.kind==="text"?p.value.text:"100";ie(o(`Progress({ value: ${f}, total: ${h}, type: ProgressType.Linear })${yn(n).join("")}`),t);return}if(i==="video"){let l=e.attrs.find(f=>f.name==="src"),p=l&&l.value.kind==="text"?l.value.text:"";ie(o(`Video({ src: ${JSON.stringify(p)} })${yn(n).join("")}`),t);return}if(i==="audio"){let l=e.attrs.find(f=>f.name==="src"),p=l&&l.value.kind==="text"?l.value.text:"";ie(o(`Video({ src: ${JSON.stringify(p)} })${yn(n).join("")}`),t);return}if(i==="img"){let l=e.attrs.find(h=>h.name==="src"),p=l&&l.value.kind==="text"?l.value.text:"",f=t.media.get(p);f?ie(o(`Image($r('app.media.${f}')).objectFit(ImageFit.Contain)${n.width?"":".width(72)"}${yn(n).join("")}`),t):t.vectors.has(p)?ie(qw(p,t),t):(t.warnings.push(`arkts: ${p||"<img>"} has no media resource - rendered as a placeholder`),ie(`Text('[image: ${p.replace(/'/g,"\\'")}]')`,t));return}if(i==="a"){let l=e.attrs.find(g=>g.name==="href"),p=l?Ea(l,t):"''",f=Ma(e.children,t),h=n.color?"":".fontColor('#e91e63')";ie(o(`Text(${f||"''"})${yn(n).join("")}${ar(t.inherited,t.fonts).join("")}${h}.onClick(() => { router.pushUrl({ url: ${p} }); })`),t);return}if(i==="input"||i==="textarea"){let l=e.attrs.find(R=>R.name==="placeholder"),p=l?Ea(l,t):"''",f=e.attrs.find(R=>R.name==="type"),h=f&&f.value.kind==="text"?f.value.text:"text",g=e.attrs.find(R=>R.name==="bind:checked"),y=e.attrs.find(R=>R.name==="bind:group"),m=e.attrs.find(R=>R.name==="bind:value"),b=R=>R&&R.value.kind==="expr"&&t.stateNames.has(R.value.code.trim())?R.value.code.trim():"",$=e.attrs.find(R=>R.name==="value"),w=$?$.value.kind==="text"?JSON.stringify($.value.text):Ea($,t):"''";if(h==="checkbox"){let R=b(y),T=b(g);R?(ie(`Toggle({ type: ToggleType.Checkbox, isOn: this.${R}.indexOf(${w}) >= 0 }).onChange((isOn: boolean) => {`,t),t.depth++,ie("if (isOn) { this."+R+" = [...this."+R+", "+w+"]; } else { this."+R+" = this."+R+".filter((value: string) => value !== "+w+"); }",t),t.depth--,ie("})",t)):ie(T?`Toggle({ type: ToggleType.Checkbox, isOn: this.${T} }).onChange((isOn: boolean) => { this.${T} = isOn; })`:"Toggle({ type: ToggleType.Checkbox, isOn: false })",t);return}if(h==="radio"){let R=b(y);ie(R?`Radio({ value: ${w}, group: '${R}' }).checked(this.${R} === ${w}).onChange((isChecked: boolean) => { if (isChecked) { this.${R} = ${w}; } })`:'Radio({ value: "", group: "" })',t);return}if(h==="range"){let R=b(m)||($&&$.value.kind==="expr"?$.value.code.trim():""),T=e.attrs.find(j=>j.name==="min"),M=e.attrs.find(j=>j.name==="max"),F=e.attrs.find(j=>j.name==="step"),I=(j,B)=>j&&j.value.kind==="text"?j.value.text:j&&j.value.kind==="expr"?Vt(j.value.code,t):B,O=[`value: ${R?`this.${R}`:I($,"0")}`,`min: ${I(T,"0")}`,`max: ${I(M,"100")}`];F&&O.push(`step: ${I(F,"1")}`);let P=R?`.onChange((value: number) => { this.${R} = value; })`:"";ie(o(`Slider({ ${O.join(", ")} })${n.width?"":".width('100%')"}${yn(n).join("")}${P}`),t);return}let v=m&&m.value.kind==="expr"&&/^[A-Za-z_$][\w$]*$/.test(m.value.code.trim())?m.value.code.trim():"",_=t.componentProps.has(v)?v:$&&$.value.kind==="expr"&&t.componentProps.has($.value.code.trim())?$.value.code.trim():"",k=e.attrs.find(R=>R.name==="name"),S=k&&k.value.kind==="text"?k.value.text.trim():"",C=S?An(t.forms,S):null,x=v||C||"",A=_?`.onChange((value: string) => { this.${ze(_)}(value); })`:x?`.onChange((value: string) => { this.${x} = value; })`:".onChange((value: string) => {})";ie(o(i==="textarea"?`TextArea({ placeholder: ${p} })${A}${n.width?"":".width('100%')"}${n.height?"":".height(96)"}${yn(n).join("")}${ar(t.inherited,t.fonts).join("")}`:`TextInput({ placeholder: ${p} })${A}${n.width?"":".width('100%')"}${yn(n).join("")}${ar(t.inherited,t.fonts).join("")}`),t);return}if(i==="button"){let l=e.attrs.find(h=>h.name==="on:click"||h.name==="on:submit"),p=l&&l.value.kind==="expr"?Vw(l.value.code.trim(),t):"() => {}";!l&&tr(e)&&t.pageAction&&(p=`() => { this.${t.pageAction}(); }`);let f=Ma(e.children,t);ie(o(`Button(${f||"'Button'"})${yn(n).join("")}${ar(t.inherited,t.fonts).join("")}.onClick(${p})`),t);return}if(i==="select"){let l=e.attrs.find(h=>h.name==="bind:value"),p=l&&l.value.kind==="expr"&&t.stateNames.has(l.value.code.trim())?l.value.code.trim():"",f=e.children.filter(h=>h.kind==="element"&&h.tag.toLowerCase()==="option").map(h=>{let g=h.children.filter($=>$.kind==="text").map($=>$.value.trim()).join(""),y=h.attrs.find($=>$.name==="value"),m=bt(h),b=fe(m.staticClasses.length||m.inlineStyle?rt(t.sheet,{tag:"option",classes:m.staticClasses},t.ancestors,{viewport:Fa}).model:null,m.inlineStyle);return{label:g,value:y&&y.value.kind==="text"?y.value.text:g,optMods:[...yn(b),...ar(fe(t.inherited,b),t.fonts)]}});if(e.attrs.some(h=>h.name==="multiple")&&p){ie("Column() {",t),t.depth++;for(let h of f)ie("Row() {",t),t.depth++,ie(`Toggle({ type: ToggleType.Checkbox, isOn: this.${p}.indexOf(${JSON.stringify(h.value)}) >= 0 }).onChange((isOn: boolean) => {`,t),t.depth++,ie(`if (isOn) { this.${p} = [...this.${p}, ${JSON.stringify(h.value)}]; } else { this.${p} = this.${p}.filter((value: string) => value !== ${JSON.stringify(h.value)}); }`,t),t.depth--,ie("})",t),ie(`Text(${JSON.stringify(h.label)})${h.optMods.join("")}`,t),t.depth--,ie("}",t);t.depth--,ie("}",t);return}ie(`Select([${f.map(h=>`{ value: ${JSON.stringify(h.value)}, label: Text(${JSON.stringify(h.label)})${h.optMods.join("")} }`).join(", ")}])`,t),p&&ie(` .selected(Math.max(0, [${f.map(h=>JSON.stringify(h.value)).join(", ")}].indexOf(this.${p})))`,t),ie(o(` ${n.width?"":".width(200)"}${yn(n).join("")}`),t),p&&ie(` .onSelect((index: number, value?: string) => { this.${p} = value ?? ''; })`,t);return}if(i==="hr"){ie("Divider()",t);return}if(i==="br"){ie("Blank(8)",t);return}let c=jw(n,i),d=n.overflow==="scroll";d&&(ie("Scroll() {",t),t.depth++),ie(`${c.open} {`,t),t.depth++,bn(e.children,t),t.depth--;let u=n.width?"":".width('100%')";ie(o(`}${d?"":u}${c.layout.join("")}${yn(n).join("")}`),t),d&&(t.depth--,ie(`}${u}${n.height||n.maxHeight?"":".constraintSize({ maxHeight: '100%' })"}`,t))}function zw(e,t){let n=/^(?:this\.)?([A-Za-z_$][\w$]*)\s*(?:\(\s*\))?$/.exec(e.trim());if(!n)return"Object";let s=ci(yf(t,n[1]));return/^Array<(.+)>$/.exec(s)?.[1]??"Object"}function Hw(e,t){let n=!1,s=i=>{new RegExp(`\\b${t}\\s*\\.`).test(i)&&(n=!0)},r=i=>{for(let o of i){if(n)return;if(o.kind==="expr")s(o.code);else if(o.kind==="element"){for(let a of o.attrs)a.value.kind==="expr"&&s(a.value.code);r(o.children)}else o.kind==="if"?o.branches.forEach(a=>r(a.children)):o.kind==="each"||o.kind==="block"?r(o.children):o.kind==="await"&&(r(o.pending),r(o.then),r(o.catch))}};return r(e),n}function Ea(e,t){return e.value.kind==="expr"?Vt(e.value.code,t):e.value.kind==="text"?JSON.stringify(e.value.text):"''"}function Vw(e,t){return e?/^[A-Za-z_$][\w$]*$/.test(e)?`() => this.${e}()`:`() => this.${Jw(e,t)}()`:"() => {}"}function Jw(e,t){let n=t.inline.get(e);if(n)return n;let s=sr(new Set(t.inline.values()));t.inline.set(e,s);let r=jt(e,Uw(t),t.stateNames);return r.reason||!r.stmts.length?(t.warnings.push(`arkts: an inline handler (${e.slice(0,40)}...) is not translated (${r.reason??"empty"}); use a named function in <script>`),t.inlineBodies.push(` private ${s}(): void {
|
|
4831
|
-
//
|
|
4831
|
+
// rosefc: handler not translated (${r.reason??"empty"}).
|
|
4832
4832
|
}`),s):(t.inlineBodies.push(` private ${s}(): void {
|
|
4833
4833
|
${r.stmts.map(i=>` ${i};`).join(`
|
|
4834
4834
|
`)}
|
|
@@ -4841,7 +4841,7 @@ ${r.stmts.map(i=>` ${i};`).join(`
|
|
|
4841
4841
|
const c = this.${i};
|
|
4842
4842
|
${a}
|
|
4843
4843
|
})
|
|
4844
|
-
}`}function Vt(e,t){let n=Oe(e.trim(),"roseContentList","roseContentGet","''");if(/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\.(?:map|filter|reduce|find|some|concat|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(n)&&!/^props\['[^']*'\]$/.test(n.trim())){let r=G(n,{...io,read:i=>t.stateNames.has(i)?`this.${i}`:i},new Set);if(r!==null)return r}return n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,"'$2'"),n=n.replace(/\$actionPending\s*\(\s*\)/g,"false"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),n=n.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(r,i)=>`this.params['${i}']`),n=n.replace(/\$query\s*\(\s*\)/g,"this.params"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"
|
|
4844
|
+
}`}function Vt(e,t){let n=Oe(e.trim(),"roseContentList","roseContentGet","''");if(/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\.(?:map|filter|reduce|find|some|concat|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(n)&&!/^props\['[^']*'\]$/.test(n.trim())){let r=G(n,{...io,read:i=>t.stateNames.has(i)?`this.${i}`:i},new Set);if(r!==null)return r}return n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,"'$2'"),n=n.replace(/\$actionPending\s*\(\s*\)/g,"false"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),n=n.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(r,i)=>`this.params['${i}']`),n=n.replace(/\$query\s*\(\s*\)/g,"this.params"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"rosefc_$1"),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(r,i)=>t.stateNames.has(i)?`this.${i}`:r),n=Gt(n,r=>t.stateNames.has(r)&&!t.componentProps.has(r),r=>`this.${r}`),n=os(n,(r,i)=>`(${r} !== null ? ${r} : ${i})`),n=At(n,r=>`(${r} !== '' && ${r} !== null)`,()=>!0),n=ys(n,r=>`(${r} != null)`,r=>t.stateNames.has(r)),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,(r,i,o)=>t.mapBinds.has(i)?`${i}['${o}']`:r),n=n.replace(/\bundefined\b/g,"null"),n=pt(n,r=>`(${r}).toString()`),n}function df(e){return e.replace(/[-_]([a-z0-9])/gi,(t,n)=>n.toUpperCase())}function Gw(e){let t={state:[],derived:[],data:[]};for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|persist|kv)\b(?:<[^>]*>)?\s*\(/g))t.state.push({name:n[1],init:Tc(e,(n.index??0)+n[0].length-1)});for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$derived\b(?:<[^>]*>)?\s*\(/g))t.derived.push({name:n[1],expr:Tc(e,(n.index??0)+n[0].length-1)});for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$data\b(?:<[^>]*>)?\s*\(/g))t.data.push(n[1]);return t}function yf(e,t){let s=new RegExp(`\\b(?:let|const|var)\\s+${Ec(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$(?:state|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(e);return!s||/\$(state|persist|kv)/.exec(s[0])?.[1]==="kv"?"null":Tc(e,s.index+s[0].length-1)}function Qw(e){let t=[];for(let n of e.matchAll(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^\n;]+)/gm)){let s=n[2].trim();/^\$(?:state|derived|data|kv|persist)\b/.test(s)||/^([\[{'"`]|-?\d|true|false|null)/.test(s)&&Zw(s)&&t.push({name:n[1],init:s})}return t}function ci(e){let t=e.trim();if(/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t))return"number";if(/^(true|false)$/.test(t))return"boolean";if(/^(['"`])/.test(t))return"string";if(/^\[/.test(t)){let n=/^\[\s*([^\],]+)/.exec(t)?.[1]?.trim()??"";return/^(['"`])/.test(n)?"Array<string>":/^-?\d/.test(n)?"Array<number>":/^\{/.test(n)?"Array<Record<string, Object>>":"Array<Object>"}return/^\{/.test(t)?"Record<string, Object>":"Object"}function Kw(e){return ci(e)}function jc(e){if(!e.trim())return"null";let t=e.trim();return t=ms(t,{empty:n=>`(${n} !== '' && ${n} !== null)`,nullish:(n,s)=>`(${n} !== null ? ${n} : ${s})`,isState:()=>!0,dialect:{translate:(n,s)=>G(n,io,s)},query:n=>`this.params[${JSON.stringify(n)}]`}),t=t.replace(/\$(?:query|store|kv|cookies|actionError|actionPending|sessionCookie)\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),t=t.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,"'$2'"),t=t.replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g,(n,s,r)=>`${s}'${r}':`),t=nt(t,(n,s)=>n==="this"?`this.${s}`:`${n}['${s}']`),t}function Zw(e){let t=0;for(let n of e)if(n==="("||n==="["||n==="{"?t++:(n===")"||n==="]"||n==="}")&&t--,t<0)return!1;return t===0}function Tc(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return e.slice(t+1,s).trim()}return""}function Ec(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xw(e,t){let n=e;for(let s=0;s<200;s++){let r=null;for(let o of n.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let a=o[1];if(a.length<=3)continue;let c=a.slice(3,4).toLowerCase()+a.slice(4);if(!t.has(c))continue;let d=(o.index??0)+o[0].lastIndexOf("("),u=ro(n,d);if(!(u<0)){r={at:o.index??0,open:d,close:u,key:c};break}}if(!r)return n;let i=n.slice(r.open+1,r.close).trim();n=n.slice(0,r.at)+`this.${r.key} = ${i||"null"}`+n.slice(r.close+1)}return n}function Yw(e){let t=e;for(;;){let n=t.indexOf("$setState(");if(n<0)return t;let s=n+9,r=ro(t,s);if(r<0)return t;let i=ev(t.slice(s+1,r)),o=/^['"](\w+)['"]$/.exec(i[0]?.trim()??"")?.[1];if(!o)return t;let a=(i.slice(1).join(", ")||"null").trim();t=t.slice(0,n)+`this.${o} = ${a}`+t.slice(r+1)}}function ev(e){let t=[],n=0,s="",r=0;for(let i=0;i<e.length;i++){let o=e[i];if(s){if(o==="\\"){i++;continue}o===s&&(s="");continue}if(o==='"'||o==="'"){s=o;continue}o==="("||o==="["||o==="{"?n++:o===")"||o==="]"||o==="}"?n--:o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function tv(e,t,n,s){let r=Zr(e,t,["emptyMap","emptyList"]);return r!==null?(n.push(`arkts: ${s}: an initializer reads module-level state (${r}) - it has no struct scope, so it starts null`),"null"):e}function ro(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return s}return-1}function nv(e,t,n,s,r=[],i=[]){if(!e.trim())return"";let o=e.replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,"");try{o=vw(o,{loader:"ts",format:"esm",target:"es2020"}).code}catch{s.push(`arkts: ${n.file}: the script did not parse as TypeScript - handlers are stubs`)}for(let d of[...t.state.map(u=>u.name),...t.derived.map(u=>u.name),...t.data]){let l=new RegExp(`\\b(?:let|const|var)\\s+${Ec(d)}\\s*(?::[^=;\\n]*)?=\\s*\\$(?:state|derived|data|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(o);if(!l)continue;let p=l.index+l[0].length-1,f=ro(o,p);f<0||(o=o.slice(0,l.index)+o.slice(f+1).replace(/^;/,""))}let a=[];try{a=Qe(e).actions.map(d=>d.name)}catch{}let c=[];for(let d of a){o=o.replace(new RegExp(`\\b(?:async\\s+)?function\\s+${Ec(d)}\\s*\\(`,"g"),`function __server_${d}(`);let u=[...t.state.map(l=>` if (patch['${l.name}'] !== undefined) this.${l.name} = patch['${l.name}'] as ${ci(l.init)};`),...t.data.map(l=>` if (patch['${l}'] !== undefined) this.${l} = patch['${l}'];`)].join(`
|
|
4845
4845
|
`);c.push(` async ${d}(): Promise<void> {
|
|
4846
4846
|
const patch = await roseAction(${JSON.stringify(n.route)}, ${JSON.stringify(d)}${r.length?", __formFields()":""});
|
|
4847
4847
|
if (!patch) return;
|
|
@@ -4850,9 +4850,9 @@ ${u}
|
|
|
4850
4850
|
${f}
|
|
4851
4851
|
}`)}return c.join(`
|
|
4852
4852
|
|
|
4853
|
-
`)}function sv(e,t){let n=e;for(let s of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let r=s[1],i=r.slice(3,4).toLowerCase()+r.slice(4);if(!t.has(i))continue;let o=s.index??0,a=o+s[0].length-1,c=ro(e,a);if(c<0)continue;let d=e.slice(a+1,c).trim();if(!/\.(?:map|filter|reduce|concat|join|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(d))continue;let u=G(d,{...io,read:p=>t.has(p)?`this.${p}`:p},new Set);if(u===null)continue;let l=c+1;e[l]===";"&&l++,n=n.replace(e.slice(o,l),()=>`this.${i} = ${u};`)}return n}function rv(e,t,n,s,r=[]){let i=new Set(n);if(e=zt(e,{target:"arkts",options:u=>Dt(u,"quoted"),empty:"null",file:t,warn:u=>s.push(`arkts: ${u}`)}).code,e=sn(e),/FormData\(|\bdocument\.|\bwindow\./.test(e))return s.push(`arkts: ${t}: a handler touches the DOM/FormData, which has no ArkTS equivalent - emitted as a stub`)," //
|
|
4853
|
+
`)}function sv(e,t){let n=e;for(let s of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let r=s[1],i=r.slice(3,4).toLowerCase()+r.slice(4);if(!t.has(i))continue;let o=s.index??0,a=o+s[0].length-1,c=ro(e,a);if(c<0)continue;let d=e.slice(a+1,c).trim();if(!/\.(?:map|filter|reduce|concat|join|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(d))continue;let u=G(d,{...io,read:p=>t.has(p)?`this.${p}`:p},new Set);if(u===null)continue;let l=c+1;e[l]===";"&&l++,n=n.replace(e.slice(o,l),()=>`this.${i} = ${u};`)}return n}function rv(e,t,n,s,r=[]){let i=new Set(n);if(e=zt(e,{target:"arkts",options:u=>Dt(u,"quoted"),empty:"null",file:t,warn:u=>s.push(`arkts: ${u}`)}).code,e=sn(e),/FormData\(|\bdocument\.|\bwindow\./.test(e))return s.push(`arkts: ${t}: a handler touches the DOM/FormData, which has no ArkTS equivalent - emitted as a stub`)," // rosefc: handler body not translated (web-only API).";let o=Ot(e);o=tn(o);{let u=0;o=Qn(o,l=>n.includes(l)?"set"+l.charAt(0).toUpperCase()+l.slice(1):null,()=>String(++u))}o=rn(o,(u,l,p)=>{let f=G(p,io,new Set([l]));if(f===null)return null;let h=`${u}()`;return`this.${u} = ${f}`.replace(new RegExp(`\\b${l}\\b`,"g"),h)}),o=on(o,(u,l)=>{let p=G(l,{...io,read:f=>i.has(f)?`this.${f}`:f},new Set);return p===null?null:`this.${u} = ${p};`}),o=sv(o,i),o=Gn(o,(u,l,p,f)=>u==="append"?`this.${l} = (${p}).concat([ ${f} ])`:`this.${l} = [ ${f} ].concat(${p})`,u=>{let l=u.slice(3,4).toLowerCase()+u.slice(4);return u.length>3&&n.includes(l)?l:null});let a=Yw(o.trim());a=a.replace(/\bawait\s+/g,""),a=a.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(u,l,p)=>`this.${p}()`),a=a.replace(/\brefresh\s*\(\s*\)/g,"this.loadData()"),a=a.replace(/\bconsole\.(?:log|warn|error)\(/g,"console.info("),a=a.replace(/\bnull\b/g,"null").replace(/\bundefined\b/g,"null");let c=new Set(n);a=a.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(u,l)=>c.has(l)?`this.${l}`:u),a=Xw(a,c),a=a.replace(/\$formRead\(\s*(['"])([^'"]*)\1\s*\)/g,(u,l,p)=>`this.${p}`),a=a.replace(/\bString\(/g,"("),a=Rn(a,u=>`${u} !== ''`),a=At(a,u=>`(${u} !== '' && ${u} !== null)`,()=>!0);let d=new Set(r);return d.size&&(a=nt(a,(u,l)=>d.has(u)?`${u}['${l}']`:`${u}.${l}`)),a.split(`
|
|
4854
4854
|
`).map(u=>" "+u.trim()).filter(u=>u.trim()).join(`
|
|
4855
|
-
`)}var Sw,_w,Fa,gf,io,bf=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();hn();gs();ls();Sw=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),_w=new Set(["header","footer","nav"]);Fa=390;gf="
|
|
4855
|
+
`)}var Sw,_w,Fa,gf,io,bf=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();hn();gs();ls();Sw=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),_w=new Set(["header","footer","nav"]);Fa=390;gf="__ROSEFC_KIT_IMPORT__";io={get:(e,t)=>`${e}['${t}']`,count:e=>`roseCount(${e})`,bool:e=>`roseBool(${e})`,merge:(e,t)=>`roseMerge(${e}, ${t})`,obj:e=>`{ ${e.map(([t,n])=>`'${t}': ${n}`).join(", ")} }`,map:(e,t,n)=>t.length>1?`roseMapIdx(${e}, (${t[0]}: Object, ${t[1]}: number) => ${n})`:`roseMap(${e}, (${t[0]}: Object) => ${n})`,filter:(e,t,n)=>`roseFilter(${e}, (${t[0]}: Object) => ${n})`,slice:(e,t,n)=>n===null?`roseSlice(${e}, ${t})`:`roseSlice(${e}, ${t}, ${n})`,find:(e,t,n)=>`roseFind(${e}, (${t[0]}: Object) => ${n})`,some:(e,t,n)=>`roseAny(${e}, (${t[0]}: Object) => ${n})`,reduce:(e,t,n,s)=>s===null?`roseReduce(${e}, (${t[0]}: Object, ${t[1]}: Object) => ${n})`:`roseReduce(${e}, ${s}, (${t[0]}: Object, ${t[1]}: Object) => ${n})`,append:(e,t)=>`roseAppend(${e}, ${t})`,concat:(e,t)=>`roseConcat(${e}, ${t})`,arr:e=>`roseArr(${e.join(", ")})`,not:e=>`!roseBool(${e})`,lit:e=>e,template:e=>"`"+e.map(t=>"expr"in t?"${"+t.expr+"}":t.text.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")).join("")+"`",index:(e,t)=>`roseIndex(${e}, ${t})`,nullish:(e,t)=>`(${e} !== null ? ${e} : ${t})`,optChain:(e,t)=>`(${e})?.['${t}']`,join:(e,t)=>`${e}.join(${t})`,split:(e,t)=>`roseSplit(${e}, ${t})`,indexOf:(e,t)=>`roseIndexOf(${e}, ${t})`,every:(e,t,n)=>`roseEvery(${e}, (${t[0]}: Object) => ${n})`,startsWith:(e,t)=>`roseStartsWith(${e}, ${t})`,endsWith:(e,t)=>`roseEndsWith(${e}, ${t})`,upper:e=>`roseUpper(${e})`,lower:e=>`roseLower(${e})`}});import*as Ne from"node:fs";import*as ve from"node:path";import{transformSync as iv}from"esbuild";async function xf(e){let t=e.warnings,n=e.projectRoot,s=ve.join(e.outDir,"android");Wa=new Map;let r=ve.join(s,"app","src","main","java",Ba),i=ve.join(n,"src","pages"),[o,a]=await Promise.all([Ye(n),Ke(n)]),c=new Map;for(let b of o){if(ve.basename(b)!=="_layout.rose")continue;let $=ve.dirname(ve.relative(i,b)).replace(/\\/g,"/"),w=Ce(await Ne.promises.readFile(b,"utf8"),b,"android");t.push(...w.warnings),c.set($==="."?"":$,{nodes:w.nodes,script:w.script,style:w.style})}let d=[];for(let b of o){let $=ve.relative(i,b).replace(/\\/g,"/"),w=$.replace(/\.rose$/,""),v=ve.basename(w);if(v==="_layout"||v==="404"||v==="_notfound"||v==="500"||v==="_middleware"||w==="api"||w.startsWith("api/"))continue;let _=Ce(await Ne.promises.readFile(b,"utf8"),b,"android");t.push(..._.warnings);let k=[],S=$.split("/").slice(0,-1);for(let x=S.length;x>=0;x--){let A=c.get(S.slice(0,x).join("/"));A&&k.push(A)}let C=_.nodes;for(let x of k)C=cv(x.nodes,C);d.push({route:lv(w),cls:$f(w),nodes:C,script:[...k.map(x=>x.script).filter(x=>!!x),_.script??""].filter(x=>x.trim()).join(`
|
|
4856
4856
|
`),style:[_.style,...k.map(x=>x.style)].filter(x=>!!x).join(`
|
|
4857
4857
|
`),params:[...w.matchAll(/\[([^\]]+)\]/g)].map(x=>x[1])})}let u=[];for(let b of a){let $=Ce(await Ne.promises.readFile(b,"utf8"),b,"android");t.push(...$.warnings);let w=ve.basename(b,".rose");u.push({name:w,cls:$f(w),nodes:$.nodes,script:$.script,style:$.style??"",slots:Ft($.nodes)})}await Ne.promises.rm(s,{recursive:!0,force:!0}),await Ne.promises.mkdir(ve.join(r,"pages"),{recursive:!0}),await Ne.promises.mkdir(ve.join(r,"components"),{recursive:!0}),await Ne.promises.mkdir(ve.join(r,"kit"),{recursive:!0}),await Ne.promises.mkdir(ve.join(s,"app","src","main","res","values"),{recursive:!0});let l=ve.join(s,"app","src","main","res","drawable");await Ne.promises.mkdir(l,{recursive:!0});let p=await uv(n,l,d.map(b=>b.nodes),t),f=new Map,h=[...d.map(b=>b.style??""),ke].join(`
|
|
4858
4858
|
`),g=await dv(n,ve.join(s,"app","src","main","res","font"),h,t);for(let b of d)for(let[$,w]of wf(b.style??"",t,g,b.cls))f.set($,w);for(let[b,$]of wf(ke,t,g))f.set(b,$);let y=Mt(n),m=xt([...d.map(b=>b.script),...u.map(b=>b.script)]);await Ne.promises.writeFile(ve.join(r,"kit","RoseKit.kt"),yv(e.apiBase??"",y,m),"utf8"),await Ne.promises.writeFile(ve.join(r,"kit","RoseTheme.kt"),gv(f,g),"utf8");for(let b of u)await Ne.promises.writeFile(ve.join(r,"components",b.cls+".kt"),Iv(b,f,p,g,t),"utf8");for(let b of d)await Ne.promises.writeFile(ve.join(r,"pages",b.cls+"Page.kt"),vv(b,u,f,p,g,t,y),"utf8");return await Ne.promises.writeFile(ve.join(r,"RoseApp.kt"),wv(d),"utf8"),await Ne.promises.writeFile(ve.join(r,"MainActivity.kt"),$v(),"utf8"),await Ne.promises.writeFile(ve.join(s,"settings.gradle.kts"),`pluginManagement {
|
|
@@ -4871,7 +4871,7 @@ dependencyResolutionManagement {
|
|
|
4871
4871
|
}
|
|
4872
4872
|
}
|
|
4873
4873
|
|
|
4874
|
-
rootProject.name = "
|
|
4874
|
+
rootProject.name = "rosefc-app"
|
|
4875
4875
|
include(":app")
|
|
4876
4876
|
`,"utf8"),await Ne.promises.writeFile(ve.join(s,"build.gradle.kts"),`plugins {
|
|
4877
4877
|
id("com.android.application") version "8.5.2" apply false
|
|
@@ -4931,7 +4931,7 @@ dependencies {
|
|
|
4931
4931
|
android:allowBackup="true"
|
|
4932
4932
|
android:label="@string/app_name"
|
|
4933
4933
|
android:supportsRtl="true"
|
|
4934
|
-
android:theme="@style/Theme.
|
|
4934
|
+
android:theme="@style/Theme.Rosefc">
|
|
4935
4935
|
<activity
|
|
4936
4936
|
android:name=".MainActivity"
|
|
4937
4937
|
android:exported="true">
|
|
@@ -4945,13 +4945,13 @@ dependencies {
|
|
|
4945
4945
|
</manifest>
|
|
4946
4946
|
`,"utf8"),await Ne.promises.writeFile(ve.join(s,"app","src","main","res","values","strings.xml"),`<?xml version="1.0" encoding="utf-8"?>
|
|
4947
4947
|
<resources>
|
|
4948
|
-
<string name="app_name">
|
|
4948
|
+
<string name="app_name">Rosefc</string>
|
|
4949
4949
|
</resources>
|
|
4950
4950
|
`,"utf8"),await Ne.promises.writeFile(ve.join(s,"app","src","main","res","values","themes.xml"),`<?xml version="1.0" encoding="utf-8"?>
|
|
4951
4951
|
<resources>
|
|
4952
|
-
<style name="Theme.
|
|
4952
|
+
<style name="Theme.Rosefc" parent="android:Theme.Material.Light.NoActionBar" />
|
|
4953
4953
|
</resources>
|
|
4954
|
-
`,"utf8"),await Ne.promises.writeFile(ve.join(s,"README.md"),bv(e.apiBase??"",d.length,u.length,t),"utf8"),await ti("android",s,t),{pages:d.map(b=>`app/src/main/java/${Ba}/pages/${b.cls}Page.kt`),components:u.map(b=>`app/src/main/java/${Ba}/components/${b.cls}.kt`)}}function lv(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function $f(e){return e.split("/").map(n=>n.replace(/^\[(.+)\]$/,"param_$1")).map(n=>n.replace(/[^\w]+/g,"_").split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")).join("").replace(/^\d/,"_$&")||"Page"}function cv(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}async function uv(e,t,n,s){let r=new Map,i=o=>{for(let a of o)if(a.kind==="element"){if(a.tag.toLowerCase()==="img"){let c=a.attrs.find(l=>l.name==="src"),d=c&&c.value.kind==="text"?c.value.text:"",u=/^\/(?:public\/)?([^/]+\.(png|jpe?g|webp|svg))$/i.exec(d);u?r.set(d,u[1].replace(/\.[^.]+$/,"").replace(/[^\w]/g,"_").toLowerCase()):d&&s.push(`android: <img ${d}> needs a drawable - rendered as a placeholder`)}i(a.children)}else a.kind==="if"?a.branches.forEach(c=>i(c.children)):a.kind==="each"||a.kind==="block"?i(a.children):a.kind==="await"&&(i(a.pending),i(a.then),i(a.catch))};n.forEach(i);for(let[o,a]of r){let c=ve.join(e,"public",o.replace(/^\//,""));if(!Ne.existsSync(c)){s.push(`android: asset ${o} is not in public/ - the placeholder is used`);continue}if(/\.svg$/i.test(c)){let d=Wt(await Ne.promises.readFile(c,"utf8"));if(!d.shape){s.push(`android: ${ve.basename(c)} uses ${d.reason??"an unsupported feature"} - rendered as a placeholder`),r.delete(o);continue}await Ne.promises.writeFile(ve.join(t,a+".xml"),Sp(d.shape),"utf8");continue}await Ne.promises.copyFile(c,ve.join(t,a+ve.extname(c).toLowerCase()))}return r}async function dv(e,t,n,s){let r=new Map;await Ne.promises.mkdir(t,{recursive:!0});for(let i of Zn(n)){let o=ve.join(e,"public",i.file.replace(/^\//,""));if(!Ne.existsSync(o)){s.push(`android: font-family '${i.family}' points at ${i.file}, which is not in public/ - the system default is used`);continue}let a=ve.extname(o).toLowerCase();if(!/^\.(ttf|otf|ttc)$/.test(a)){s.push(`android: font-family '${i.family}' uses ${a}, which Android cannot register - convert it to .ttf/.otf`);continue}let c=i.family.replace(/[^\w]/g,"_").toLowerCase();await Ne.promises.copyFile(o,ve.join(t,c+a)),r.set(i.family,c)}return r}function lo(e){return"__hovered"+e.replace(/[^\w$]/g,"_")}function oo(e){return"__focused"+e.replace(/[^\w$]/g,"_")}function ao(e){return"__pressed"+e.replace(/[^\w$]/g,"_")}function wf(e,t,n=new Map,s){let r=new Map;if(!e.trim())return r;let i=Te(e);for(let u of i.warnings)t.push(`android: ${u}`);let o=new Map,a=[],c=[];for(let u of i.rules){let l=u.parts[u.parts.length-1];if(u.hover&&l.classes.length)for(let p of l.classes){let f=s?`__hover_${p}__${s}`:`__hover_${p}`;o.set(f,fe(o.get(f)??null,u.hover))}if(u.focus&&l.classes.length&&a.push({last:l,focus:u.focus}),u.active&&l.classes.length&&c.push({last:l,active:u.active}),l.unsupported.includes(":hover")&&!u.hover&&t.push(`android: :hover has no Compose equivalent on "${u.selector}" - dropped`),!(u.media&&(u.media.min!==void 0||u.media.max!==void 0)&&(u.media.min!==void 0&&Nc<u.media.min||u.media.max!==void 0&&Nc>u.media.max))){if(!l.classes.length&&l.tag){Wa.set(l.tag,fe(Wa.get(l.tag)??null,u.model));continue}for(let p of l.classes){let f=s?`${p}__${s}`:p;o.set(f,fe(o.get(f)??null,u.model))}}}for(let u of a)for(let l of u.last.classes){let p=s?`__focus_${l}__${s}`:`__focus_${l}`,f=s?`${l}__${s}`:l,h=u.focus.borderColor&&!u.focus.borderWidth?{...u.focus,borderWidth:o.get(f)?.borderWidth??u.focus.borderWidth}:u.focus;o.set(p,fe(o.get(p)??null,h))}for(let u of c)for(let l of u.last.classes){let p=s?`__active_${l}__${s}`:`__active_${l}`,f=s?`${l}__${s}`:l,h=u.active.borderColor&&!u.active.borderWidth?{...u.active,borderWidth:o.get(f)?.borderWidth??u.active.borderWidth}:u.active;o.set(p,fe(o.get(p)??null,h))}for(let[u,l]of o)r.set(u,l);let d=new Set(Zn(e).map(u=>u.family));for(let u of Cn(e))!d.has(u)&&!n.has(u)&&t.push(`android: font-family '${u}' has no @font-face - the system default is used`);return r}function Be(e){return String(Math.round(e*10)/10)}function kf(e){return e>=900?"FontWeight.Black":e>=800?"FontWeight.ExtraBold":e>=700?"FontWeight.Bold":e>=500?"FontWeight.Medium":e>=300?"FontWeight.Light":e>=200?"FontWeight.Thin":"FontWeight.Normal"}function vf(e){let[t,n,s,r]=e;return t===n&&n===s&&s===r?`${Be(t)}.dp`:t===s&&n===r?`horizontal = ${Be(n)}.dp, vertical = ${Be(t)}.dp`:`start = ${Be(r)}.dp, top = ${Be(t)}.dp, end = ${Be(n)}.dp, bottom = ${Be(s)}.dp`}function pv(e){if(!e.radius)return null;let t=e.radius;return t[0]===t[1]&&t[1]===t[2]&&t[2]===t[3]?`RoundedCornerShape(${Be(t[0])}.dp)`:`RoundedCornerShape(topStart = ${Be(t[0])}.dp, topEnd = ${Be(t[1])}.dp, bottomEnd = ${Be(t[2])}.dp, bottomStart = ${Be(t[3])}.dp)`}function Pa(e,t){let n=[];if(e.color&&n.push(`color = ${cr(e.color)}`),e.fontSize!==void 0&&n.push(`fontSize = ${Be(e.fontSize)}.sp`),e.fontWeight!==void 0&&n.push(`fontWeight = ${kf(e.fontWeight)}`),e.italic&&n.push("fontStyle = FontStyle.Italic"),e.letterSpacing!==void 0&&n.push(`letterSpacing = ${Be(e.letterSpacing)}.sp`),e.underline||e.strike){let s=e.underline&&e.strike;n.push(`textDecoration = ${s?"TextDecoration.combine(listOf(TextDecoration.Underline, TextDecoration.LineThrough))":e.underline?"TextDecoration.Underline":"TextDecoration.LineThrough"}`)}if(e.textAlign){let s=e.textAlign==="center"?"Center":e.textAlign==="right"?"End":e.textAlign==="justify"?"Justify":"Start";n.push(`textAlign = TextAlign.${s}`)}if(e.lineHeight!==void 0&&e.fontSize!==void 0&&n.push(`lineHeight = ${Be(Math.round(e.fontSize*e.lineHeight*10)/10)}.sp`),e.fontFamily){let s=t.get(e.fontFamily);s?n.push(`fontFamily = FontFamily(Font(R.font.${s}))`):/^serif$/i.test(e.fontFamily)?n.push("fontFamily = FontFamily.Serif"):/^monospace$/i.test(e.fontFamily)?n.push("fontFamily = FontFamily.Monospace"):/^(sans-serif|system-ui)$/i.test(e.fontFamily)&&n.push("fontFamily = FontFamily.SansSerif")}return n}function lr(e){let t=[],n=pv(e);if(e.margin&&t.push(`.padding(${vf(e.margin)})`),n&&t.push(`.clip(${n})`),e.gradient&&e.gradient.stops.length>=2){let s=e.gradient.stops.map(r=>cr(r.color)).join(", ");t.push(`.background(Brush.verticalGradient(colors = listOf(${s})))`)}else e.background&&t.push(`.background(${cr(e.background)})`);if(e.borderWidth&&e.borderColor){let s=e.borderWidth,i=s[0]===s[1]&&s[1]===s[2]&&s[2]===s[3]?s[0]:Math.max(...s);i>0&&t.push(`.border(${Be(i)}.dp, ${cr(e.borderColor)}${n?`, ${n}`:""})`)}if(e.opacity!==void 0&&t.push(`.graphicsLayer { alpha = ${Be(e.opacity)}f }`),e.padding&&t.push(`.padding(${vf(e.padding)})`),e.width&&(e.width.u==="%"?t.push(".fillMaxWidth()"):e.width.u!=="auto"&&t.push(`.width(${Be(e.width.n)}.dp)`)),e.height&&(e.height.u==="%"?t.push(".fillMaxHeight()"):e.height.u!=="auto"&&t.push(`.height(${Be(e.height.n)}.dp)`)),e.minWidth!==void 0||e.maxWidth!==void 0){let s=e.minWidth&&e.minWidth.u==="px"?`min = ${Be(e.minWidth.n)}.dp`:"",r=e.maxWidth&&e.maxWidth.u==="px"?`max = ${Be(e.maxWidth.n)}.dp`:"";t.push(`.widthIn(${[s,r].filter(Boolean).join(", ")})`)}if(e.minHeight!==void 0||e.maxHeight!==void 0){let s=e.minHeight&&e.minHeight.u==="px"?`min = ${Be(e.minHeight.n)}.dp`:"",r=e.maxHeight&&e.maxHeight.u==="px"?`max = ${Be(e.maxHeight.n)}.dp`:"";t.push(`.heightIn(${[s,r].filter(Boolean).join(", ")})`)}if(e.overflow==="hidden"&&n&&t.push(`.clip(${n})`),e.overflow==="scroll"&&t.push(".verticalScroll(rememberScrollState())"),e.position){let s=e.insetLeft??e.insetRight??0,r=e.insetTop??e.insetBottom??0;t.push(`.offset(x = ${Be(s)}.dp, y = ${Be(r)}.dp)`)}return e.zIndex!==void 0&&(e.position||e.shadow)&&t.push(`.zIndex(${e.zIndex}f)`),t}function Sf(e){switch(e){case"center":return"Arrangement.Center";case"end":return"Arrangement.End";case"between":return"Arrangement.SpaceBetween";case"around":return"Arrangement.SpaceAround";case"evenly":return"Arrangement.SpaceEvenly";default:return null}}function fv(e,t){if(t)switch(e){case"start":return"Alignment.Top";case"center":return"Alignment.CenterVertically";case"end":return"Alignment.Bottom";default:return null}switch(e){case"start":return"Alignment.Start";case"center":return"Alignment.CenterHorizontally";case"end":return"Alignment.End";default:return null}}function hv(e,t){if(!e)return null;let n=e.gap,s=e.justify;return s==="between"||s==="around"||s==="evenly"?Sf(s):n!==void 0?s==="center"?`Arrangement.spacedBy(${Be(n)}.dp, ${t?"Alignment.CenterHorizontally":"Alignment.CenterVertically"})`:s==="end"?`Arrangement.spacedBy(${Be(n)}.dp, ${t?"Alignment.EndHorizontally":"Alignment.Bottom"})`:`Arrangement.spacedBy(${Be(n)}.dp)`:Sf(s)}function gv(e,t){let n=[...e.entries()].map(([r,i])=>{let o=_f(i,t);return` "${r}" to RoseStyle(${o.join(", ")}),`}),s=[...Wa.entries()].map(([r,i])=>{let o=_f(i,t);return` "${r}" to RoseStyle(${o.join(", ")}),`});return`package dev.
|
|
4954
|
+
`,"utf8"),await Ne.promises.writeFile(ve.join(s,"README.md"),bv(e.apiBase??"",d.length,u.length,t),"utf8"),await ti("android",s,t),{pages:d.map(b=>`app/src/main/java/${Ba}/pages/${b.cls}Page.kt`),components:u.map(b=>`app/src/main/java/${Ba}/components/${b.cls}.kt`)}}function lv(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function $f(e){return e.split("/").map(n=>n.replace(/^\[(.+)\]$/,"param_$1")).map(n=>n.replace(/[^\w]+/g,"_").split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")).join("").replace(/^\d/,"_$&")||"Page"}function cv(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}async function uv(e,t,n,s){let r=new Map,i=o=>{for(let a of o)if(a.kind==="element"){if(a.tag.toLowerCase()==="img"){let c=a.attrs.find(l=>l.name==="src"),d=c&&c.value.kind==="text"?c.value.text:"",u=/^\/(?:public\/)?([^/]+\.(png|jpe?g|webp|svg))$/i.exec(d);u?r.set(d,u[1].replace(/\.[^.]+$/,"").replace(/[^\w]/g,"_").toLowerCase()):d&&s.push(`android: <img ${d}> needs a drawable - rendered as a placeholder`)}i(a.children)}else a.kind==="if"?a.branches.forEach(c=>i(c.children)):a.kind==="each"||a.kind==="block"?i(a.children):a.kind==="await"&&(i(a.pending),i(a.then),i(a.catch))};n.forEach(i);for(let[o,a]of r){let c=ve.join(e,"public",o.replace(/^\//,""));if(!Ne.existsSync(c)){s.push(`android: asset ${o} is not in public/ - the placeholder is used`);continue}if(/\.svg$/i.test(c)){let d=Wt(await Ne.promises.readFile(c,"utf8"));if(!d.shape){s.push(`android: ${ve.basename(c)} uses ${d.reason??"an unsupported feature"} - rendered as a placeholder`),r.delete(o);continue}await Ne.promises.writeFile(ve.join(t,a+".xml"),Sp(d.shape),"utf8");continue}await Ne.promises.copyFile(c,ve.join(t,a+ve.extname(c).toLowerCase()))}return r}async function dv(e,t,n,s){let r=new Map;await Ne.promises.mkdir(t,{recursive:!0});for(let i of Zn(n)){let o=ve.join(e,"public",i.file.replace(/^\//,""));if(!Ne.existsSync(o)){s.push(`android: font-family '${i.family}' points at ${i.file}, which is not in public/ - the system default is used`);continue}let a=ve.extname(o).toLowerCase();if(!/^\.(ttf|otf|ttc)$/.test(a)){s.push(`android: font-family '${i.family}' uses ${a}, which Android cannot register - convert it to .ttf/.otf`);continue}let c=i.family.replace(/[^\w]/g,"_").toLowerCase();await Ne.promises.copyFile(o,ve.join(t,c+a)),r.set(i.family,c)}return r}function lo(e){return"__hovered"+e.replace(/[^\w$]/g,"_")}function oo(e){return"__focused"+e.replace(/[^\w$]/g,"_")}function ao(e){return"__pressed"+e.replace(/[^\w$]/g,"_")}function wf(e,t,n=new Map,s){let r=new Map;if(!e.trim())return r;let i=Te(e);for(let u of i.warnings)t.push(`android: ${u}`);let o=new Map,a=[],c=[];for(let u of i.rules){let l=u.parts[u.parts.length-1];if(u.hover&&l.classes.length)for(let p of l.classes){let f=s?`__hover_${p}__${s}`:`__hover_${p}`;o.set(f,fe(o.get(f)??null,u.hover))}if(u.focus&&l.classes.length&&a.push({last:l,focus:u.focus}),u.active&&l.classes.length&&c.push({last:l,active:u.active}),l.unsupported.includes(":hover")&&!u.hover&&t.push(`android: :hover has no Compose equivalent on "${u.selector}" - dropped`),!(u.media&&(u.media.min!==void 0||u.media.max!==void 0)&&(u.media.min!==void 0&&Nc<u.media.min||u.media.max!==void 0&&Nc>u.media.max))){if(!l.classes.length&&l.tag){Wa.set(l.tag,fe(Wa.get(l.tag)??null,u.model));continue}for(let p of l.classes){let f=s?`${p}__${s}`:p;o.set(f,fe(o.get(f)??null,u.model))}}}for(let u of a)for(let l of u.last.classes){let p=s?`__focus_${l}__${s}`:`__focus_${l}`,f=s?`${l}__${s}`:l,h=u.focus.borderColor&&!u.focus.borderWidth?{...u.focus,borderWidth:o.get(f)?.borderWidth??u.focus.borderWidth}:u.focus;o.set(p,fe(o.get(p)??null,h))}for(let u of c)for(let l of u.last.classes){let p=s?`__active_${l}__${s}`:`__active_${l}`,f=s?`${l}__${s}`:l,h=u.active.borderColor&&!u.active.borderWidth?{...u.active,borderWidth:o.get(f)?.borderWidth??u.active.borderWidth}:u.active;o.set(p,fe(o.get(p)??null,h))}for(let[u,l]of o)r.set(u,l);let d=new Set(Zn(e).map(u=>u.family));for(let u of Cn(e))!d.has(u)&&!n.has(u)&&t.push(`android: font-family '${u}' has no @font-face - the system default is used`);return r}function Be(e){return String(Math.round(e*10)/10)}function kf(e){return e>=900?"FontWeight.Black":e>=800?"FontWeight.ExtraBold":e>=700?"FontWeight.Bold":e>=500?"FontWeight.Medium":e>=300?"FontWeight.Light":e>=200?"FontWeight.Thin":"FontWeight.Normal"}function vf(e){let[t,n,s,r]=e;return t===n&&n===s&&s===r?`${Be(t)}.dp`:t===s&&n===r?`horizontal = ${Be(n)}.dp, vertical = ${Be(t)}.dp`:`start = ${Be(r)}.dp, top = ${Be(t)}.dp, end = ${Be(n)}.dp, bottom = ${Be(s)}.dp`}function pv(e){if(!e.radius)return null;let t=e.radius;return t[0]===t[1]&&t[1]===t[2]&&t[2]===t[3]?`RoundedCornerShape(${Be(t[0])}.dp)`:`RoundedCornerShape(topStart = ${Be(t[0])}.dp, topEnd = ${Be(t[1])}.dp, bottomEnd = ${Be(t[2])}.dp, bottomStart = ${Be(t[3])}.dp)`}function Pa(e,t){let n=[];if(e.color&&n.push(`color = ${cr(e.color)}`),e.fontSize!==void 0&&n.push(`fontSize = ${Be(e.fontSize)}.sp`),e.fontWeight!==void 0&&n.push(`fontWeight = ${kf(e.fontWeight)}`),e.italic&&n.push("fontStyle = FontStyle.Italic"),e.letterSpacing!==void 0&&n.push(`letterSpacing = ${Be(e.letterSpacing)}.sp`),e.underline||e.strike){let s=e.underline&&e.strike;n.push(`textDecoration = ${s?"TextDecoration.combine(listOf(TextDecoration.Underline, TextDecoration.LineThrough))":e.underline?"TextDecoration.Underline":"TextDecoration.LineThrough"}`)}if(e.textAlign){let s=e.textAlign==="center"?"Center":e.textAlign==="right"?"End":e.textAlign==="justify"?"Justify":"Start";n.push(`textAlign = TextAlign.${s}`)}if(e.lineHeight!==void 0&&e.fontSize!==void 0&&n.push(`lineHeight = ${Be(Math.round(e.fontSize*e.lineHeight*10)/10)}.sp`),e.fontFamily){let s=t.get(e.fontFamily);s?n.push(`fontFamily = FontFamily(Font(R.font.${s}))`):/^serif$/i.test(e.fontFamily)?n.push("fontFamily = FontFamily.Serif"):/^monospace$/i.test(e.fontFamily)?n.push("fontFamily = FontFamily.Monospace"):/^(sans-serif|system-ui)$/i.test(e.fontFamily)&&n.push("fontFamily = FontFamily.SansSerif")}return n}function lr(e){let t=[],n=pv(e);if(e.margin&&t.push(`.padding(${vf(e.margin)})`),n&&t.push(`.clip(${n})`),e.gradient&&e.gradient.stops.length>=2){let s=e.gradient.stops.map(r=>cr(r.color)).join(", ");t.push(`.background(Brush.verticalGradient(colors = listOf(${s})))`)}else e.background&&t.push(`.background(${cr(e.background)})`);if(e.borderWidth&&e.borderColor){let s=e.borderWidth,i=s[0]===s[1]&&s[1]===s[2]&&s[2]===s[3]?s[0]:Math.max(...s);i>0&&t.push(`.border(${Be(i)}.dp, ${cr(e.borderColor)}${n?`, ${n}`:""})`)}if(e.opacity!==void 0&&t.push(`.graphicsLayer { alpha = ${Be(e.opacity)}f }`),e.padding&&t.push(`.padding(${vf(e.padding)})`),e.width&&(e.width.u==="%"?t.push(".fillMaxWidth()"):e.width.u!=="auto"&&t.push(`.width(${Be(e.width.n)}.dp)`)),e.height&&(e.height.u==="%"?t.push(".fillMaxHeight()"):e.height.u!=="auto"&&t.push(`.height(${Be(e.height.n)}.dp)`)),e.minWidth!==void 0||e.maxWidth!==void 0){let s=e.minWidth&&e.minWidth.u==="px"?`min = ${Be(e.minWidth.n)}.dp`:"",r=e.maxWidth&&e.maxWidth.u==="px"?`max = ${Be(e.maxWidth.n)}.dp`:"";t.push(`.widthIn(${[s,r].filter(Boolean).join(", ")})`)}if(e.minHeight!==void 0||e.maxHeight!==void 0){let s=e.minHeight&&e.minHeight.u==="px"?`min = ${Be(e.minHeight.n)}.dp`:"",r=e.maxHeight&&e.maxHeight.u==="px"?`max = ${Be(e.maxHeight.n)}.dp`:"";t.push(`.heightIn(${[s,r].filter(Boolean).join(", ")})`)}if(e.overflow==="hidden"&&n&&t.push(`.clip(${n})`),e.overflow==="scroll"&&t.push(".verticalScroll(rememberScrollState())"),e.position){let s=e.insetLeft??e.insetRight??0,r=e.insetTop??e.insetBottom??0;t.push(`.offset(x = ${Be(s)}.dp, y = ${Be(r)}.dp)`)}return e.zIndex!==void 0&&(e.position||e.shadow)&&t.push(`.zIndex(${e.zIndex}f)`),t}function Sf(e){switch(e){case"center":return"Arrangement.Center";case"end":return"Arrangement.End";case"between":return"Arrangement.SpaceBetween";case"around":return"Arrangement.SpaceAround";case"evenly":return"Arrangement.SpaceEvenly";default:return null}}function fv(e,t){if(t)switch(e){case"start":return"Alignment.Top";case"center":return"Alignment.CenterVertically";case"end":return"Alignment.Bottom";default:return null}switch(e){case"start":return"Alignment.Start";case"center":return"Alignment.CenterHorizontally";case"end":return"Alignment.End";default:return null}}function hv(e,t){if(!e)return null;let n=e.gap,s=e.justify;return s==="between"||s==="around"||s==="evenly"?Sf(s):n!==void 0?s==="center"?`Arrangement.spacedBy(${Be(n)}.dp, ${t?"Alignment.CenterHorizontally":"Alignment.CenterVertically"})`:s==="end"?`Arrangement.spacedBy(${Be(n)}.dp, ${t?"Alignment.EndHorizontally":"Alignment.Bottom"})`:`Arrangement.spacedBy(${Be(n)}.dp)`:Sf(s)}function gv(e,t){let n=[...e.entries()].map(([r,i])=>{let o=_f(i,t);return` "${r}" to RoseStyle(${o.join(", ")}),`}),s=[...Wa.entries()].map(([r,i])=>{let o=_f(i,t);return` "${r}" to RoseStyle(${o.join(", ")}),`});return`package dev.rosefc.app.kit
|
|
4955
4955
|
|
|
4956
4956
|
import androidx.compose.foundation.background
|
|
4957
4957
|
import androidx.compose.foundation.border
|
|
@@ -5267,7 +5267,7 @@ ${s.join(`
|
|
|
5267
5267
|
}`:"",e.includes("clipboard-write")?` if (capability == "clipboard-write") {
|
|
5268
5268
|
val ctx = ROSE_NATIVE_CONTEXT ?: return false
|
|
5269
5269
|
val manager = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return false
|
|
5270
|
-
manager.setPrimaryClip(ClipData.newPlainText("
|
|
5270
|
+
manager.setPrimaryClip(ClipData.newPlainText("rosefc", opts["text"]?.toString() ?: ""))
|
|
5271
5271
|
return true
|
|
5272
5272
|
}`:"",e.includes("share")?` if (capability == "share") {
|
|
5273
5273
|
// Intent.ACTION_SEND is the platform API, but showing the sheet means
|
|
@@ -5349,13 +5349,13 @@ import androidx.compose.ui.text.style.TextDecoration
|
|
|
5349
5349
|
${s}
|
|
5350
5350
|
import androidx.compose.ui.graphics.Color
|
|
5351
5351
|
${mv(n)}
|
|
5352
|
-
/// Base URL of the deployed
|
|
5352
|
+
/// Base URL of the deployed Rosefc server (rosefc export --api).
|
|
5353
5353
|
const val ROSE_API_BASE: String = ${JSON.stringify(e)}
|
|
5354
5354
|
|
|
5355
5355
|
/// The JSON half of a render: the state the page's $data produced.
|
|
5356
5356
|
fun roseData(route: String): Map<String, Any?> {
|
|
5357
5357
|
if (ROSE_API_BASE.isEmpty()) return emptyMap()
|
|
5358
|
-
return roseRequest(ROSE_API_BASE + "/
|
|
5358
|
+
return roseRequest(ROSE_API_BASE + "/__rosefc/data?path=" + java.net.URLEncoder.encode(route, "UTF-8"), "GET", null)
|
|
5359
5359
|
}
|
|
5360
5360
|
|
|
5361
5361
|
/// Call a server action - the framework's own protocol: POST __action=<name>.
|
|
@@ -5610,13 +5610,13 @@ fun roseHtml(html: String): AnnotatedString = buildAnnotatedString {
|
|
|
5610
5610
|
}
|
|
5611
5611
|
flush()
|
|
5612
5612
|
}
|
|
5613
|
-
`}function bv(e,t,n,s){return`#
|
|
5613
|
+
`}function bv(e,t,n,s){return`# Rosefc -> Android (Kotlin + Jetpack Compose)
|
|
5614
5614
|
|
|
5615
|
-
Generated by \`
|
|
5615
|
+
Generated by \`rosefc export android\` from the project's \`.rose\` pages.
|
|
5616
5616
|
|
|
5617
5617
|
- ${t} page(s), ${n} component(s)
|
|
5618
5618
|
- Open this folder in Android Studio (Gradle sync) and run on a device/emulator
|
|
5619
|
-
- Server: \`
|
|
5619
|
+
- Server: \`rosefc export android --api <base>\` writes the base URL into
|
|
5620
5620
|
\`app/src/main/java/${Ba}/kit/RoseKit.kt\`. Current: \`${e||"(unset)"}\`
|
|
5621
5621
|
|
|
5622
5622
|
State fields become \`by remember { mutableStateOf(...) }\`, a handler is a lambda
|
|
@@ -5681,12 +5681,12 @@ ${s}
|
|
|
5681
5681
|
|
|
5682
5682
|
`),v=/\broseNative\s*\(/.test(w+m.inlineBodies.join(`
|
|
5683
5683
|
`))?`import ${pn}.kit.roseNative`:"",_=p.map(j=>{let B=j.init.startsWith("roseContentList(")?"List<Any?>":j.init.startsWith("roseContentGet(")?"Map<String, Any?>?":di(j.init),U=B==="List<Any?>"?j.init:B==="Map<String, Any?>"?Fc(j.init):Oc(j.init);return` val ${j.name}: ${B} = ${U}`}).join(`
|
|
5684
|
-
`),k=an(u??""),S=k.length?[" val
|
|
5685
|
-
`):"",C=k.length?k.map(j=>` LaunchedEffect(${j}) {
|
|
5684
|
+
`),k=an(u??""),S=k.length?[" val __rosefcCtx = LocalContext.current",' val __rosefcPrefs = remember { __rosefcCtx.getSharedPreferences("rosefc", android.content.Context.MODE_PRIVATE) }'].join(`
|
|
5685
|
+
`):"",C=k.length?k.map(j=>` LaunchedEffect(${j}) { __rosefcPrefs.edit().putString(${JSON.stringify("rosefc:"+j)}, ${j}.toString()).apply() }`).join(`
|
|
5686
5686
|
`):"",A=$s(u??"").filter(j=>new Set([...a.state.map(B=>B.name),...a.data]).has(j.name)).map(j=>` ${j.name} = roseKv(${JSON.stringify(j.name)}, { ${bs(j.fn)} }, ${j.ttl})`).join(`
|
|
5687
|
-
`),R=[...a.state.map(j=>{let B=g(j.name),U=di(B),ce=e.params.includes(j.name)?`params[${JSON.stringify(j.name)}] ?: ${Oc(B)}`:Oc(B),N=k.includes(j.name)?`
|
|
5687
|
+
`),R=[...a.state.map(j=>{let B=g(j.name),U=di(B),ce=e.params.includes(j.name)?`params[${JSON.stringify(j.name)}] ?: ${Oc(B)}`:Oc(B),N=k.includes(j.name)?`__rosefcPrefs.getString(${JSON.stringify("rosefc:"+j.name)}, null) ?: ${ce}`:ce;return` var ${j.name} by remember { mutableStateOf<${U}>(${N}) }`}),...a.data.map(j=>` var ${j}: Any? by remember { mutableStateOf(null) }`)].join(`
|
|
5688
5688
|
`),T=f.length?`
|
|
5689
|
-
fun
|
|
5689
|
+
fun __rosefcFormFields(keys: List<String>): Map<String, Any?> {
|
|
5690
5690
|
val all = mapOf<String, Any?>(`+f.map(j=>JSON.stringify(j)+" to "+j).join(", ")+`)
|
|
5691
5691
|
return keys.associateWith { all[it] }
|
|
5692
5692
|
}`:"",M=[...a.state.map(j=>` ${Af(j.name,di(g(j.name)))}`),...a.data.map(j=>` patch["${j}"]?.let { ${j} = it }`)].join(`
|
|
@@ -5794,13 +5794,13 @@ ${R.lines.join(`
|
|
|
5794
5794
|
`).map(x=>S+x).join(`
|
|
5795
5795
|
`);$e(`${i.cls}(
|
|
5796
5796
|
${C}
|
|
5797
|
-
${" ".repeat(t.depth)})`,t);return}if(ov.has(s)&&!e.children.some(m=>m.kind==="element")){let m=Ia(e.children,t),b=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],$=b.length?`, modifier = Modifier${b.join("")}`:"";$e(`Text(${m||'""'}${r}${$})`,t);return}if(s==="progress"){let m=e.attrs.find(k=>k.name==="value"),b=e.attrs.find(k=>k.name==="max"),$=m&&m.value.kind==="expr"?On(m.value.code,t):m&&m.value.kind==="text"?m.value.text:"0",w=b&&b.value.kind==="text"?b.value.text:"100",v=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],_=v.length?`, modifier = Modifier${v.join("")}`:"";$e(`LinearProgressIndicator(progress = { (${$}).toFloat() / (${w}).toFloat() }${_})`,t);return}if(s==="video"){let m=e.attrs.find(v=>v.name==="src"),b=m&&m.value.kind==="text"?m.value.text:"",$=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],w=$.length?`, modifier = Modifier${$.join("")}`:"";$e(`AndroidView(factory = { ctx -> android.widget.VideoView(ctx).apply { setVideoPath("${b.replace(/"/g,'\\"')}") } }${w})`,t);return}if(s==="audio"){let m=e.attrs.find(v=>v.name==="src"),b=m&&m.value.kind==="text"?m.value.text:"",$=n.model?lr(n.model):[],w=$.length?`, modifier = Modifier${$.join("")}`:"";$e(`Text("[audio: ${(b||"").replace(/"/g,'\\"')}]"${w})`,t);return}if(s==="img"){let m=e.attrs.find(_=>_.name==="src"),b=m&&m.value.kind==="text"?m.value.text:"",$=t.media.get(b),w=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],v=w.length?`, modifier = Modifier${w.join("")}`:"";$e($?`Image(painter = painterResource(id = R.drawable.${$}), contentDescription = null${v})`:`Text("[image: ${(b||"").replace(/"/g,'\\"')}]"${v})`,t);return}if(s==="a"){let m=e.attrs.find(_=>_.name==="href"),b=m?La(m,t):'""',$=Ia(e.children,t)||'""',w=n.expr?`, style = roseTextStyle(${n.expr})`:"",v=n.expr?`, modifier = Modifier.roseBox(${n.expr})`:"";$e(`TextButton(onClick = { onNavigate(${b}.toString()) }${v}) { Text(${$}${w}) }`,t);return}if(s==="input"||s==="textarea"){let m=e.attrs.find(X=>X.name==="placeholder"),b=m?La(m,t):'""',$=e.attrs.find(X=>X.name==="type"),w=$&&$.value.kind==="text"?$.value.text:"text",v=e.attrs.find(X=>X.name==="bind:checked"),_=e.attrs.find(X=>X.name==="bind:group"),k=e.attrs.find(X=>X.name==="bind:value"),S=X=>X&&X.value.kind==="expr"&&t.stateNames.has(X.value.code.trim())?X.value.code.trim():"",C=e.attrs.find(X=>X.name==="value"),x=C?C.value.kind==="text"?JSON.stringify(C.value.text):La(C,t):'"true"';if(w==="checkbox"){let X=S(_),ne=S(v);$e(X?`Checkbox(checked = (${X} as? List<*>)?.contains(${x}) == true, onCheckedChange = { on -> ${X} = (((${X} as? List<*>) ?: emptyList<Any?>()).toMutableList().also { if (on) it.add(${x}) else it.remove(${x}) }) })`:ne?`Checkbox(checked = ${ne}, onCheckedChange = { ${ne} = it })`:"Checkbox(checked = false, onCheckedChange = null)",t);return}if(w==="radio"){let X=S(_);$e(X?`RadioButton(selected = ${X} == ${x}, onClick = { ${X} = ${x} })`:"RadioButton(selected = false, onClick = null)",t);return}let A=k&&k.value.kind==="expr"&&/^[A-Za-z_$][\w$]*$/.test(k.value.code.trim())?k.value.code.trim():"",R=e.attrs.find(X=>X.name==="value"),T=t.componentProps.has(A)?A:R&&R.value.kind==="expr"&&t.componentProps.has(R.value.code.trim())?R.value.code.trim():"",M=e.attrs.find(X=>X.name==="name"),F=M&&M.value.kind==="text"?M.value.text.trim():"",I=F?An(t.forms,F):null,O=T?"":A||I||"",P=A||T||I?`value = ${A||T||I}.toString()`:'value = ""',j=T?`, onValueChange = { v -> ${ze(T)}(v) }`:O?`, onValueChange = { ${O} = it }`:"",B=n.model?lr(n.model):[],U=n.model?Pa(n.model,t.fontMap):[],ce=n.focusKey?`.onFocusChanged { ${oo(n.focusKey)} = it.isFocused }`:"",N=n.activeKey?`.clickable(interactionSource = ${ao(n.activeKey)}Source, indication = null) {}`:"",W="Modifier.fillMaxWidth()"+ce+N+(n.expr?`.roseBox(${n.expr})`:B.join("")),re=n.expr?`, style = roseTextStyle(${n.expr})`:U.length?`, style = TextStyle(${U.join(", ")})`:"",xe=`${b}${re}`;$e(`TextField(${P}${j}, label = { Text(${xe}) }, modifier = ${W})`,t);return}if(s==="button"){let m=e.attrs.find(w=>w.name==="on:click"||w.name==="on:submit"),b=m&&m.value.kind==="expr"?`() -> ${Av(m.value.code.trim(),t)}`:"{}";!m&&tr(e)&&t.pageAction&&(b=`() -> ${t.pageAction}()`);let $=Ia(e.children,t)||'""';if(n.expr){let w=n.hoverKey?`.hoverable(${lo(n.hoverKey)}Source)`:"",v=n.focusKey?`.onFocusChanged { ${oo(n.focusKey)} = it.isFocused }`:"",_=n.activeKey?`.clickable(interactionSource = ${ao(n.activeKey)}Source, indication = null) {}`:"";$e(`Button(onClick = ${b}, colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent), modifier = Modifier${w}${v}${_}.roseBox(${n.expr})) { Text(${$}, style = roseTextStyle(${n.expr})) }`,t);return}if(n.model){let w=lr(n.model),v=Pa(n.model,t.fontMap),_="colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)",k=w.length?`modifier = Modifier${w.join("")}`:null,S=[_,k].filter(Boolean).join(", "),C=v.length?`, ${v.join(", ")}`:"";$e(`Button(onClick = ${b}, ${S}) { Text(${$}${C}) }`,t);return}$e(`Button(onClick = ${b}) { Text(${$}) }`,t);return}if(s==="select"){let m=e.attrs.find(_=>_.name==="bind:value"),b=m&&m.value.kind==="expr"&&t.stateNames.has(m.value.code.trim())?m.value.code.trim():"",$=e.attrs.some(_=>_.name==="multiple"),w=e.children.filter(_=>_.kind==="element"&&_.tag.toLowerCase()==="option").map(_=>{let k=_.children.filter(T=>T.kind==="text").map(T=>T.value.trim()).join(""),S=_.attrs.find(T=>T.name==="value"),C=S&&S.value.kind==="text"?S.value.text:k,x=Rf(_,bt(_),t),A=x.model?Pa(x.model,t.fontMap):[],R=A.length?`style = TextStyle(${A.join(", ")})`:"";return{label:k,value:C,optStyle:R}}),v=n.expr?`, modifier = Modifier.roseBox(${n.expr})`:"";$e(`Row(horizontalArrangement = Arrangement.spacedBy(8.dp)${n.expr?", modifier = Modifier.roseBox("+n.expr+")":""}) {`,t),t.depth++;for(let _ of w){if($&&b){$e(`Checkbox(checked = (${b} as? List<*>)?.contains(${JSON.stringify(_.value)}) == true, onCheckedChange = { on -> ${b} = (((${b} as? List<*>) ?: emptyList<Any?>()).toMutableList().also { if (on) it.add(${JSON.stringify(_.value)}) else it.remove(${JSON.stringify(_.value)}) }) }, modifier = Modifier.padding(end = 4.dp))`,t),$e(`Text(${JSON.stringify(_.label)}${_.optStyle})`,t);continue}$e(`FilterChip(selected = ${b||"false"} == ${JSON.stringify(_.value)}, onClick = { ${b?b+" = "+JSON.stringify(_.value):"/* no binding */"} }, label = { Text(${JSON.stringify(_.label)}${_.optStyle}) }${v})`,t)}t.depth--,$e("}",t);return}if(s==="hr"){$e("Divider()",t);return}if(s==="br"){$e("Spacer(modifier = Modifier.height(8.dp))",t);return}let o=n.model,a=ir(o,s,av)==="row";if(o?.display==="none")return;let c=[t.inWrapRow?"Modifier":"Modifier.fillMaxWidth()"];if(n.expr)c.push(`.roseBox(${n.expr})`);else if(o)for(let m of lr(o))c.push(m);if(n.hoverKey){let m=lo(n.hoverKey);c.push(`.hoverable(${m}Source)`)}if(n.focusKey){let m=oo(n.focusKey);c.push(`.onFocusChanged { ${m} = it.isFocused }`)}if(n.activeKey){let m=ao(n.activeKey);c.push(`.clickable(interactionSource = ${m}Source, indication = null) {}`)}let d=!!n.expr||!!o&&(o.display==="flex"||o.direction!==void 0||o.justify!==void 0||o.align!==void 0||o.gap!==void 0||o.wrap===!0);d&&o?.wrap&&!a&&t.warnings.push(`${t.file}: android: flex-wrap on <${s}> has no Compose layout here - rendered as one ${a?"row":"column"}`);let u=d?hv(o,a):null,l=d?fv(o?.align,a):null,p=[u?`${a?"horizontalArrangement":"verticalArrangement"} = ${u}`:null,l?`${a?"verticalAlignment":"horizontalAlignment"} = ${l}`:null].filter(Boolean),f=p.length?`, ${p.join(", ")}`:"",h=a&&o?.wrap?"FlowRow":a?"Row":"Column",g=h==="FlowRow"&&o?.gap!==void 0?`verticalArrangement = Arrangement.spacedBy(${Be(o.gap)}.dp)`:"",y=[p.join(", "),g].filter(Boolean).join(", ");if($e(`${h}(modifier = ${c.join("")}${y?", "+y:""}) {`,t),t.depth++,h==="FlowRow"){let m=t.inWrapRow;t.inWrapRow=!0,Zt(e.children,t),t.inWrapRow=m}else Zt(e.children,t);t.depth--,$e("}",t)}function La(e,t){return e.value.kind==="expr"?On(e.value.code,t):e.value.kind==="text"?JSON.stringify(e.value.text):'""'}function Av(e,t){return/^[A-Za-z_$][\w$]*$/.test(e)?`${e}()`:`${Cv(e,t)}()`}function Cv(e,t){let n=t.inline.get(e);if(n)return n;let s=sr(new Set(t.inline.values()));t.inline.set(e,s);let r=jt(e,jv(t),t.stateNames);return r.reason||!r.stmts.length?(t.warnings.push(`android: an inline handler (${e.slice(0,40)}...) is not translated (${r.reason??"empty"}); use a named function in <script>`),t.inlineBodies.push(` val ${s}: () -> Unit = { /*
|
|
5797
|
+
${" ".repeat(t.depth)})`,t);return}if(ov.has(s)&&!e.children.some(m=>m.kind==="element")){let m=Ia(e.children,t),b=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],$=b.length?`, modifier = Modifier${b.join("")}`:"";$e(`Text(${m||'""'}${r}${$})`,t);return}if(s==="progress"){let m=e.attrs.find(k=>k.name==="value"),b=e.attrs.find(k=>k.name==="max"),$=m&&m.value.kind==="expr"?On(m.value.code,t):m&&m.value.kind==="text"?m.value.text:"0",w=b&&b.value.kind==="text"?b.value.text:"100",v=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],_=v.length?`, modifier = Modifier${v.join("")}`:"";$e(`LinearProgressIndicator(progress = { (${$}).toFloat() / (${w}).toFloat() }${_})`,t);return}if(s==="video"){let m=e.attrs.find(v=>v.name==="src"),b=m&&m.value.kind==="text"?m.value.text:"",$=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],w=$.length?`, modifier = Modifier${$.join("")}`:"";$e(`AndroidView(factory = { ctx -> android.widget.VideoView(ctx).apply { setVideoPath("${b.replace(/"/g,'\\"')}") } }${w})`,t);return}if(s==="audio"){let m=e.attrs.find(v=>v.name==="src"),b=m&&m.value.kind==="text"?m.value.text:"",$=n.model?lr(n.model):[],w=$.length?`, modifier = Modifier${$.join("")}`:"";$e(`Text("[audio: ${(b||"").replace(/"/g,'\\"')}]"${w})`,t);return}if(s==="img"){let m=e.attrs.find(_=>_.name==="src"),b=m&&m.value.kind==="text"?m.value.text:"",$=t.media.get(b),w=n.expr?[`.roseBox(${n.expr})`]:n.model?lr(n.model):[],v=w.length?`, modifier = Modifier${w.join("")}`:"";$e($?`Image(painter = painterResource(id = R.drawable.${$}), contentDescription = null${v})`:`Text("[image: ${(b||"").replace(/"/g,'\\"')}]"${v})`,t);return}if(s==="a"){let m=e.attrs.find(_=>_.name==="href"),b=m?La(m,t):'""',$=Ia(e.children,t)||'""',w=n.expr?`, style = roseTextStyle(${n.expr})`:"",v=n.expr?`, modifier = Modifier.roseBox(${n.expr})`:"";$e(`TextButton(onClick = { onNavigate(${b}.toString()) }${v}) { Text(${$}${w}) }`,t);return}if(s==="input"||s==="textarea"){let m=e.attrs.find(X=>X.name==="placeholder"),b=m?La(m,t):'""',$=e.attrs.find(X=>X.name==="type"),w=$&&$.value.kind==="text"?$.value.text:"text",v=e.attrs.find(X=>X.name==="bind:checked"),_=e.attrs.find(X=>X.name==="bind:group"),k=e.attrs.find(X=>X.name==="bind:value"),S=X=>X&&X.value.kind==="expr"&&t.stateNames.has(X.value.code.trim())?X.value.code.trim():"",C=e.attrs.find(X=>X.name==="value"),x=C?C.value.kind==="text"?JSON.stringify(C.value.text):La(C,t):'"true"';if(w==="checkbox"){let X=S(_),ne=S(v);$e(X?`Checkbox(checked = (${X} as? List<*>)?.contains(${x}) == true, onCheckedChange = { on -> ${X} = (((${X} as? List<*>) ?: emptyList<Any?>()).toMutableList().also { if (on) it.add(${x}) else it.remove(${x}) }) })`:ne?`Checkbox(checked = ${ne}, onCheckedChange = { ${ne} = it })`:"Checkbox(checked = false, onCheckedChange = null)",t);return}if(w==="radio"){let X=S(_);$e(X?`RadioButton(selected = ${X} == ${x}, onClick = { ${X} = ${x} })`:"RadioButton(selected = false, onClick = null)",t);return}let A=k&&k.value.kind==="expr"&&/^[A-Za-z_$][\w$]*$/.test(k.value.code.trim())?k.value.code.trim():"",R=e.attrs.find(X=>X.name==="value"),T=t.componentProps.has(A)?A:R&&R.value.kind==="expr"&&t.componentProps.has(R.value.code.trim())?R.value.code.trim():"",M=e.attrs.find(X=>X.name==="name"),F=M&&M.value.kind==="text"?M.value.text.trim():"",I=F?An(t.forms,F):null,O=T?"":A||I||"",P=A||T||I?`value = ${A||T||I}.toString()`:'value = ""',j=T?`, onValueChange = { v -> ${ze(T)}(v) }`:O?`, onValueChange = { ${O} = it }`:"",B=n.model?lr(n.model):[],U=n.model?Pa(n.model,t.fontMap):[],ce=n.focusKey?`.onFocusChanged { ${oo(n.focusKey)} = it.isFocused }`:"",N=n.activeKey?`.clickable(interactionSource = ${ao(n.activeKey)}Source, indication = null) {}`:"",W="Modifier.fillMaxWidth()"+ce+N+(n.expr?`.roseBox(${n.expr})`:B.join("")),re=n.expr?`, style = roseTextStyle(${n.expr})`:U.length?`, style = TextStyle(${U.join(", ")})`:"",xe=`${b}${re}`;$e(`TextField(${P}${j}, label = { Text(${xe}) }, modifier = ${W})`,t);return}if(s==="button"){let m=e.attrs.find(w=>w.name==="on:click"||w.name==="on:submit"),b=m&&m.value.kind==="expr"?`() -> ${Av(m.value.code.trim(),t)}`:"{}";!m&&tr(e)&&t.pageAction&&(b=`() -> ${t.pageAction}()`);let $=Ia(e.children,t)||'""';if(n.expr){let w=n.hoverKey?`.hoverable(${lo(n.hoverKey)}Source)`:"",v=n.focusKey?`.onFocusChanged { ${oo(n.focusKey)} = it.isFocused }`:"",_=n.activeKey?`.clickable(interactionSource = ${ao(n.activeKey)}Source, indication = null) {}`:"";$e(`Button(onClick = ${b}, colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent), modifier = Modifier${w}${v}${_}.roseBox(${n.expr})) { Text(${$}, style = roseTextStyle(${n.expr})) }`,t);return}if(n.model){let w=lr(n.model),v=Pa(n.model,t.fontMap),_="colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)",k=w.length?`modifier = Modifier${w.join("")}`:null,S=[_,k].filter(Boolean).join(", "),C=v.length?`, ${v.join(", ")}`:"";$e(`Button(onClick = ${b}, ${S}) { Text(${$}${C}) }`,t);return}$e(`Button(onClick = ${b}) { Text(${$}) }`,t);return}if(s==="select"){let m=e.attrs.find(_=>_.name==="bind:value"),b=m&&m.value.kind==="expr"&&t.stateNames.has(m.value.code.trim())?m.value.code.trim():"",$=e.attrs.some(_=>_.name==="multiple"),w=e.children.filter(_=>_.kind==="element"&&_.tag.toLowerCase()==="option").map(_=>{let k=_.children.filter(T=>T.kind==="text").map(T=>T.value.trim()).join(""),S=_.attrs.find(T=>T.name==="value"),C=S&&S.value.kind==="text"?S.value.text:k,x=Rf(_,bt(_),t),A=x.model?Pa(x.model,t.fontMap):[],R=A.length?`style = TextStyle(${A.join(", ")})`:"";return{label:k,value:C,optStyle:R}}),v=n.expr?`, modifier = Modifier.roseBox(${n.expr})`:"";$e(`Row(horizontalArrangement = Arrangement.spacedBy(8.dp)${n.expr?", modifier = Modifier.roseBox("+n.expr+")":""}) {`,t),t.depth++;for(let _ of w){if($&&b){$e(`Checkbox(checked = (${b} as? List<*>)?.contains(${JSON.stringify(_.value)}) == true, onCheckedChange = { on -> ${b} = (((${b} as? List<*>) ?: emptyList<Any?>()).toMutableList().also { if (on) it.add(${JSON.stringify(_.value)}) else it.remove(${JSON.stringify(_.value)}) }) }, modifier = Modifier.padding(end = 4.dp))`,t),$e(`Text(${JSON.stringify(_.label)}${_.optStyle})`,t);continue}$e(`FilterChip(selected = ${b||"false"} == ${JSON.stringify(_.value)}, onClick = { ${b?b+" = "+JSON.stringify(_.value):"/* no binding */"} }, label = { Text(${JSON.stringify(_.label)}${_.optStyle}) }${v})`,t)}t.depth--,$e("}",t);return}if(s==="hr"){$e("Divider()",t);return}if(s==="br"){$e("Spacer(modifier = Modifier.height(8.dp))",t);return}let o=n.model,a=ir(o,s,av)==="row";if(o?.display==="none")return;let c=[t.inWrapRow?"Modifier":"Modifier.fillMaxWidth()"];if(n.expr)c.push(`.roseBox(${n.expr})`);else if(o)for(let m of lr(o))c.push(m);if(n.hoverKey){let m=lo(n.hoverKey);c.push(`.hoverable(${m}Source)`)}if(n.focusKey){let m=oo(n.focusKey);c.push(`.onFocusChanged { ${m} = it.isFocused }`)}if(n.activeKey){let m=ao(n.activeKey);c.push(`.clickable(interactionSource = ${m}Source, indication = null) {}`)}let d=!!n.expr||!!o&&(o.display==="flex"||o.direction!==void 0||o.justify!==void 0||o.align!==void 0||o.gap!==void 0||o.wrap===!0);d&&o?.wrap&&!a&&t.warnings.push(`${t.file}: android: flex-wrap on <${s}> has no Compose layout here - rendered as one ${a?"row":"column"}`);let u=d?hv(o,a):null,l=d?fv(o?.align,a):null,p=[u?`${a?"horizontalArrangement":"verticalArrangement"} = ${u}`:null,l?`${a?"verticalAlignment":"horizontalAlignment"} = ${l}`:null].filter(Boolean),f=p.length?`, ${p.join(", ")}`:"",h=a&&o?.wrap?"FlowRow":a?"Row":"Column",g=h==="FlowRow"&&o?.gap!==void 0?`verticalArrangement = Arrangement.spacedBy(${Be(o.gap)}.dp)`:"",y=[p.join(", "),g].filter(Boolean).join(", ");if($e(`${h}(modifier = ${c.join("")}${y?", "+y:""}) {`,t),t.depth++,h==="FlowRow"){let m=t.inWrapRow;t.inWrapRow=!0,Zt(e.children,t),t.inWrapRow=m}else Zt(e.children,t);t.depth--,$e("}",t)}function La(e,t){return e.value.kind==="expr"?On(e.value.code,t):e.value.kind==="text"?JSON.stringify(e.value.text):'""'}function Av(e,t){return/^[A-Za-z_$][\w$]*$/.test(e)?`${e}()`:`${Cv(e,t)}()`}function Cv(e,t){let n=t.inline.get(e);if(n)return n;let s=sr(new Set(t.inline.values()));t.inline.set(e,s);let r=jt(e,jv(t),t.stateNames);return r.reason||!r.stmts.length?(t.warnings.push(`android: an inline handler (${e.slice(0,40)}...) is not translated (${r.reason??"empty"}); use a named function in <script>`),t.inlineBodies.push(` val ${s}: () -> Unit = { /* rosefc: handler not translated (${r.reason??"empty"}) */ }`),s):(t.inlineBodies.push(` val ${s}: () -> Unit = {
|
|
5798
5798
|
${r.stmts.map(i=>` ${i}`).join(`
|
|
5799
5799
|
`)}
|
|
5800
|
-
}`),s)}function jv(e){return{expr:t=>On(t,e),set:(t,n)=>`${t} = ${n}`,action:t=>`${t}()`,refresh:()=>"/* refresh: the data channel reloads on navigation */",refuses:(t,n)=>{let s=Dn(t,n);if(s)return s;let r=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/\.\.\.(?!\s*[\])])/,"spread"]];for(let[i,o]of r)if(i.test(t))return o;return null}}}function On(e,t){let n=Oe(e.trim(),"roseContentList","roseContentGet",'""');if(/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(n)||/\.(?:map|filter|reduce|find|some|every|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,Tr,new Set);if(s!==null)return s}if(t.derivedExprs?.size)for(let[s,r]of t.derivedExprs){let i=On(r,{...t,derivedExprs:new Map});n=n.replace(new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\(\\s*\\)`,"g"),`(${i})`),n=n.replace(new RegExp(`(?<![.\\w$])${s.replace(/\$/g,"\\$")}\\b(?!\\s*\\()`,"g"),`(${i})`)}return n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,'"$2"'),n=n.replace(/\$actionPending\s*\(\s*\)/g,"false"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),n=n.replace(/\$query\s*\(\s*\)/g,"params"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"
|
|
5800
|
+
}`),s)}function jv(e){return{expr:t=>On(t,e),set:(t,n)=>`${t} = ${n}`,action:t=>`${t}()`,refresh:()=>"/* refresh: the data channel reloads on navigation */",refuses:(t,n)=>{let s=Dn(t,n);if(s)return s;let r=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/\.\.\.(?!\s*[\])])/,"spread"]];for(let[i,o]of r)if(i.test(t))return o;return null}}}function On(e,t){let n=Oe(e.trim(),"roseContentList","roseContentGet",'""');if(/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(n)||/\.(?:map|filter|reduce|find|some|every|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,Tr,new Set);if(s!==null)return s}if(t.derivedExprs?.size)for(let[s,r]of t.derivedExprs){let i=On(r,{...t,derivedExprs:new Map});n=n.replace(new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\(\\s*\\)`,"g"),`(${i})`),n=n.replace(new RegExp(`(?<![.\\w$])${s.replace(/\$/g,"\\$")}\\b(?!\\s*\\()`,"g"),`(${i})`)}return n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,'"$2"'),n=n.replace(/\$actionPending\s*\(\s*\)/g,"false"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),n=n.replace(/\$query\s*\(\s*\)/g,"params"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"rosefc_$1"),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(s,r)=>t.stateNames.has(r)?r:s),n=At(n,s=>`${s}.toString().isNotEmpty()`,s=>t.stateNames.has(s)),n=os(n,(s,r)=>`${s} ?: ${r}`),n=ys(n,s=>`${s} != null`,s=>t.stateNames.has(s)),n=t.mapBinds.size?nt(n,(s,r)=>`${s}["${r}"]`):n,n=n.replace(/\bundefined\b/g,"null"),n=n.replace(/\.length\b/g,".size").replace(/\[(["'])length\1\]/g,".size"),n=n.replace(/'((?:[^'\\\\]|\\\\.)*)'/g,'"$1"'),n=qn(n,(s,r)=>`roseJoin(${s}, ${r})`),n=nn(n,(s,r,i,o)=>{let a=r==="trim"?`roseTrim(${s})`:r==="trimStart"?`roseTrimStart(${s})`:r==="trimEnd"?`roseTrimEnd(${s})`:r==="toLowerCase"?`roseLower(${s})`:r==="toUpperCase"?`roseUpper(${s})`:r==="startsWith"?`roseHasPrefix(${s}, ${i[0]??'""'})`:r==="endsWith"?`roseHasSuffix(${s}, ${i[0]??'""'})`:`roseContains(${s}, ${i[0]??'""'})`;return o?r==="startsWith"||r==="endsWith"||r==="includes"?a:`!${a}.isEmpty()`:a}),n=Da(n),n=n.replace(/===/g,"==").replace(/!==/g,"!="),n=pt(n,s=>`(${s}).toString()`),n}function Da(e){let t=-1,n=0,s="";for(let c=0;c<e.length;c++){let d=e[c];if(s){if(d==="\\"){c++;continue}d===s&&(s="");continue}if(d==='"'||d==="'"||d==="`"){s=d;continue}if(d==="("||d==="["||d==="{")n++;else if(d===")"||d==="]"||d==="}")n--;else if(d==="?"&&n===0){t=c;break}}if(t<0)return e;let r=e.slice(0,t).trim(),i=e.slice(t+1),o=-1;n=0,s="";let a=0;for(let c=0;c<i.length;c++){let d=i[c];if(s){if(d==="\\"){c++;continue}d===s&&(s="");continue}if(d==='"'||d==="'"||d==="`"){s=d;continue}if(d==="("||d==="["||d==="{")n++;else if(d===")"||d==="]"||d==="}")n--;else if(n===0&&d==="?")a++;else if(n===0&&d===":"){if(a===0){o=c;break}a--}}return o<0?e:`(if (${r}) ${Da(i.slice(0,o).trim())} else ${Da(i.slice(o+1).trim())})`}function Tv(e){let t={state:[],derived:[],data:[]};for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|persist|kv)\b(?:<[^>]*>)?\s*\(/g))t.state.push({name:n[1],init:Pc(e,(n.index??0)+n[0].length-1)});for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$derived\b(?:<[^>]*>)?\s*\(/g))t.derived.push({name:n[1],expr:Pc(e,(n.index??0)+n[0].length-1)});for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$data\b(?:<[^>]*>)?\s*\(/g))t.data.push(n[1]);return t}function Cf(e,t){let s=new RegExp(`\\b(?:let|const|var)\\s+${Lc(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$(state|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(e);return!s||s[1]==="kv"?"null":Pc(e,s.index+s[0].length-1)}function Ev(e){let t=[];for(let n of e.matchAll(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^\n;]+)/gm)){let s=n[2].trim();/^\$(?:state|derived|data|kv|persist)\b/.test(s)||["params","csr","headers","prefetch","revalidate","buffer","bundle","hotVary","prerender","csp"].includes(n[1])||/^([\[{'"`]|-?\d|true|false|null)/.test(s)&&Nv(s)&&t.push({name:n[1],init:s})}return t}function Ov(e,t,n,s){let r=Zr(e,t,["emptyMap","emptyList"]);return r!==null?(n.push(`android: ${s}: an initializer reads module-level state (${r}) - it has no composable scope, so it starts null`),"null"):e}function Nv(e){let t=0;for(let n of e)if(n==="("||n==="["||n==="{"?t++:(n===")"||n==="]"||n==="}")&&t--,t<0)return!1;return t===0}function Pc(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return e.slice(t+1,s).trim()}return""}function Lc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mv(e){let t=e;for(;;){let n=t.indexOf("$setState(");if(n<0)return t;let s=n+9,r=za(t,s);if(r<0)return t;let i=Ha(t.slice(s+1,r)),o=/^['"]?(\w+)['"]?$/.exec(i[0]?.trim()??"")?.[1];if(!o)return t;let a=(i.slice(1).join(", ")||"null").trim();t=t.slice(0,n)+o+" = "+a+t.slice(r+1)}}function za(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return s}return-1}function Fv(e,t,n,s,r,i=[]){if(!e.trim())return"";let o=e.replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,"");try{o=iv(o,{loader:"ts",format:"esm",target:"es2020"}).code}catch{r.push(`android: ${n.cls}: the script did not parse as TypeScript - handlers are stubs`)}let a=[...t.state.map(u=>u.name),...t.derived.map(u=>u.name),...t.data];for(let u of a){let p=new RegExp(`\\b(?:let|const|var)\\s+${Lc(u)}\\s*(?::[^=;\\n]*)?=\\s*\\$(?:state|derived|data|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(o);if(!p)continue;let f=p.index+p[0].length-1,h=za(o,f);h<0||(o=o.slice(0,p.index)+o.slice(h+1).replace(/^;/,""))}let c=[];try{c=Qe(e).actions.map(u=>u.name)}catch{}let d=[];for(let u of c){o=o.replace(new RegExp(`\\b(?:async\\s+)?function\\s+${Lc(u)}\\s*\\(`,"g"),`function __server_${u}(`);let l=[...t.state.map(p=>` ${Af(p.name,di(Cf(e,p.name)))}`),...t.data.map(p=>` patch["${p}"]?.let { ${p} = it }`)].join(`
|
|
5801
5801
|
`);d.push(` val ${u}: () -> Unit = {
|
|
5802
5802
|
scope.launch {
|
|
5803
|
-
val patch = roseAction(if (route.isEmpty()) ${JSON.stringify(n.route)} else route, ${JSON.stringify(u)}${i.length?`,
|
|
5803
|
+
val patch = roseAction(if (route.isEmpty()) ${JSON.stringify(n.route)} else route, ${JSON.stringify(u)}${i.length?`, __rosefcFormFields(${JSON.stringify(i)})`:""})
|
|
5804
5804
|
if (patch.isNotEmpty()) {
|
|
5805
5805
|
${l}
|
|
5806
5806
|
}
|
|
@@ -5809,10 +5809,10 @@ ${l}
|
|
|
5809
5809
|
}`)}return d.join(`
|
|
5810
5810
|
|
|
5811
5811
|
`)}function Lv(e,t){let n=/\.(?:map|filter|reduce|find|some|every|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase|trim|trimStart|trimEnd)\s*\(/,s=e,r=[{re:/\b(set[A-Z][\w$]*)\s*\(/g,key:i=>i[1].length>3?i[1].slice(3,4).toLowerCase()+i[1].slice(4):null,callOpen:i=>(i.index??0)+i[0].lastIndexOf("("),argStart:i=>(i.index??0)+i[0].lastIndexOf("(")+1},{re:/(?:\$setState|__set)\s*\(\s*(['"])([^'"]*)\1\s*,/g,key:i=>i[2],callOpen:i=>(i.index??0)+i[0].indexOf("("),argStart:i=>(i.index??0)+i[0].length}];for(let i of r)for(let o of e.matchAll(i.re)){let a=i.key(o);if(!a||!t.includes(a))continue;let c=za(e,i.callOpen(o));if(c<0)continue;let d=i.argStart(o),u=e.slice(d,c).trim();if(!n.test(u))continue;let l=G(u,Tr,new Set);if(l===null)continue;let p=c+1;e[p]===";"&&p++,s=s.replace(e.slice(o.index??0,p),()=>`${a} = ${l};`)}return s}function Bv(e,t,n,s,r=[]){e=Ot(e),e=tn(e),e=zt(e,{target:"android",options:u=>{let l=Dt(u,"bare");return l===null?null:Fc(l)},empty:"null",file:t,warn:u=>s.push(`android: ${u}`)}).code,e=sn(e);{let u=0;e=Qn(e,l=>n.includes(l)?"set"+l.charAt(0).toUpperCase()+l.slice(1):null,()=>String(++u))}e=rn(e,(u,l,p)=>{let f=G(p,Tr,new Set([l]));if(f===null)return null;let h=`${u}()`;return`${u} = ${f}`.replace(new RegExp(`\\b${l}\\b`,"g"),h)}),e=Lv(e,n),e=Kn(e,u=>u.length>3&&n.includes(u.slice(3,4).toLowerCase()+u.slice(4))?u.slice(3,4).toLowerCase()+u.slice(4):null,(u,l)=>{let p=G(l,Tr,new Set);return p===null?null:`${u} = ${p};`}),e=on(e,(u,l)=>{let p=G(l,Tr,new Set);return p===null?null:`${u} = ${p};`}),e=Gn(e,(u,l,p,f)=>u==="append"?`${l} = (${p} as List<Any?>) + listOf(${f})`:`${l} = listOf(${f}) + (${p} as List<Any?>)`,u=>{let l=u.slice(3,4).toLowerCase()+u.slice(4);return u.length>3&&n.includes(l)?l:null});let i=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/\.map\(/,".map("],[/\.\.\.(?!\s*[\])])/,"spread"],[/(?<![\w$])\$setState/,"raw $setState"]];for(let[u,l]of i)if(u.test(e)){if(l==="raw $setState")continue;return s.push(`android: ${t}: a handler uses ${l}, which has no direct Kotlin equivalent here - emitted as a stub`),`
|
|
5812
|
-
//
|
|
5812
|
+
// rosefc: handler body not translated (uses `+l+")."}let o=Mv(e.trim());o=o.replace(/\bawait\s+/g,""),o=o.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(u,l,p)=>`${p}()`),o=o.replace(/\brefresh\s*\(\s*\)/g,"/* refresh: the data channel reloads on navigation */"),o=o.replace(/\bconsole\.(?:log|warn|error)\(/g,"println("),o=o.replace(/\.length\b/g,".size"),o=o.replace(/\.trim\(\)/g,".trim()"),o=o.replace(/\bString\(/g,"("),o=o.replace(/\bnull\b/g,"null").replace(/\bundefined\b/g,"null"),o=o.replace(/'((?:[^'\\]|\\.)*)'/g,'"$1"');let a=new Set(n);o=o.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(u,l)=>a.has(l)?l:u),o=At(o,u=>`${u}.toString().isNotEmpty()`,u=>a.has(u));for(let u of a){let l=u.charAt(0).toUpperCase()+u.slice(1);o=o.replace(new RegExp(`\\bset${l}\\s*\\(`,"g"),`${u} = `)}o=o.replace(/\$formRead\(\s*(['"])([^'"]*)\1\s*\)/g,(u,l,p)=>p),o=o.replace(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,"var $1 ="),o=Rn(o,u=>`${u}.isNotEmpty()`),o=Da(o);let c=new Set(r);c.size&&(o=nt(o,(u,l)=>c.has(u)?`${u}["${l}"]`:`${u}.${l}`));let d=o.split(`
|
|
5813
5813
|
`).map(u=>u.trim()).filter(Boolean);return d.length?d.map(u=>`
|
|
5814
5814
|
`+u).join(""):`
|
|
5815
|
-
//
|
|
5815
|
+
// rosefc: an empty handler.`}function jf(e){return[...(e??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)].map(t=>({name:t[1],init:t[2].trim()}))}function Iv(e,t,n,s,r){let i=jf(e.script),o=i.map(b=>b.name),a={warnings:r,file:e.cls,stateNames:new Set(o),mapBinds:new Set,components:[],lines:[],depth:1,styles:t,media:n,scope:e.cls,script:e.script??"",awaits:[],deferred:[],scriptConsts:new Map,componentProps:new Set(o),forms:[],pageAction:null,inline:new Map,inlineBodies:[],hoverKeys:new Set([...t.keys()].filter(b=>b.startsWith("__hover_")&&b.endsWith("__"+e.cls))),focusKeys:new Set([...t.keys()].filter(b=>b.startsWith("__focus_")&&b.endsWith("__"+e.cls))),activeKeys:new Set([...t.keys()].filter(b=>b.startsWith("__active_")&&b.endsWith("__"+e.cls))),sheet:Te([e.style,ke].filter(b=>b&&b.trim()).join(`
|
|
5816
5816
|
`)),ancestors:[],fontMap:s};Zt(e.nodes,a);let c=new Map(i.map(b=>[b.name,ur(b.init)])),d=o.map(b=>`${b}: Any? = ${c.get(b)??"null"}`);e.slots.hasDefault&&d.push("slotDefault: @Composable () -> Unit = {}");for(let b of e.slots.named)d.push(`slot${b.name.charAt(0).toUpperCase()}${b.name.slice(1)}: @Composable (Map<String, Any?>) -> Unit = {}`);let u=gn(e.nodes,o);for(let b of u)d.push(`${ze(b)}: (Any?) -> Unit = {}`);let l=d.join(", "),p=a.inlineBodies.length?`
|
|
5817
5817
|
|
|
5818
5818
|
`+a.inlineBodies.join(`
|
|
@@ -5852,11 +5852,11 @@ ${f}
|
|
|
5852
5852
|
}
|
|
5853
5853
|
}
|
|
5854
5854
|
${p}
|
|
5855
|
-
`}var pn,Ba,ov,av,Wa,Nc,Pv,Tr,Tf=De(()=>{"use strict";Un();kn();vs();hn();gs();_a();ls();_s();xs();ks();pn="dev.
|
|
5855
|
+
`}var pn,Ba,ov,av,Wa,Nc,Pv,Tr,Tf=De(()=>{"use strict";Un();kn();vs();hn();gs();_a();ls();_s();xs();ks();pn="dev.rosefc.app",Ba=pn.replace(/\./g,"/"),ov=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),av=new Set(["header","footer","nav"]),Wa=new Map;Nc=390;Pv=/\.(?:join|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/,Tr={get:(e,t)=>`${e}["${t}"]`,count:e=>`(${e} as List<*>).size`,bool:e=>`${e} as? Boolean ?: false`,merge:(e,t)=>`${e} + ${t}`,obj:e=>`mapOf(${e.map(([t,n])=>`"${t}" to ${n}`).join(", ")})`,map:(e,t,n)=>t.length>1?`roseMapIdx(${e}) { ${t[0]}, ${t[1]} -> ${n} }`:`${e}.map { ${t[0]} -> ${n} }`,filter:(e,t,n)=>`roseFilter(${e}) { ${t[0]} -> ${n} }`,slice:(e,t,n)=>n===null?`roseSlice(${e}, ${t})`:`roseSlice(${e}, ${t}, ${n})`,find:(e,t,n)=>`roseFind(${e}, { ${t[0]} -> ${n} })`,some:(e,t,n)=>`roseAny(${e}, { ${t[0]} -> ${n} })`,join:(e,t)=>`roseJoin(${e}, ${t})`,split:(e,t)=>`roseSplit(${e}, ${t})`,indexOf:(e,t)=>`roseIndexOf(${e}, ${t})`,every:(e,t,n)=>`roseEvery(${e}, { ${t[0]} -> ${n} })`,startsWith:(e,t)=>`roseHasPrefix(${e}, ${t})`,endsWith:(e,t)=>`roseHasSuffix(${e}, ${t})`,upper:e=>`roseUpper(${e})`,lower:e=>`roseLower(${e})`,reduce:(e,t,n,s)=>s===null?`roseReduce(${e}) { ${t[0]}, ${t[1]} -> ${n} }`:`roseReduce(${e}, ${s}) { ${t[0]}, ${t[1]} -> ${n} }`,append:(e,t)=>`(${e} as List<Any?>) + ${t}`,concat:(e,t)=>`(${e} as List<Any?>) + (${t} as List<Any?>)`,arr:e=>`listOf(${e.join(", ")})`,not:e=>`!(${e} as? Boolean ?: false)`,lit:e=>e,template:e=>'"'+e.map(t=>"expr"in t?/^([A-Za-z_$][\w$]*)$/.test(t.expr)?`$${t.expr}`:`\${${t.expr}}`:t.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$")).join("")+'"',index:(e,t)=>`roseIndex(${e}, ${t})`,nullish:(e,t)=>`(${e}) ?: (${t})`,optChain:(e,t)=>`(${e})?.get("${t}")`}});import*as je from"node:fs";import*as be from"node:path";import{transformSync as Wv}from"esbuild";async function Bf(e){let t=e.warnings,n=e.projectRoot,s=be.join(e.outDir,"xcode");Ga=new Map;let r=be.join(s,co),i=be.join(n,"src","pages"),[o,a]=await Promise.all([Ye(n),Ke(n)]),c=new Map;for(let $ of o){if(be.basename($)!=="_layout.rose")continue;let w=be.dirname(be.relative(i,$)).replace(/\\/g,"/"),v=Ce(await je.promises.readFile($,"utf8"),$,"xcode");t.push(...v.warnings),c.set(w==="."?"":w,{nodes:v.nodes,script:v.script,style:v.style})}let d=[];for(let $ of o){let w=be.relative(i,$).replace(/\\/g,"/"),v=w.replace(/\.rose$/,""),_=be.basename(v);if(_==="_layout"||_==="404"||_==="_notfound"||_==="500"||_==="_middleware"||v==="api"||v.startsWith("api/"))continue;let k=Ce(await je.promises.readFile($,"utf8"),$,"xcode");t.push(...k.warnings);let S=[],C=w.split("/").slice(0,-1);for(let A=C.length;A>=0;A--){let R=c.get(C.slice(0,A).join("/"));R&&S.push(R)}let x=k.nodes;for(let A of S)x=Vv(A.nodes,x);d.push({route:Hv(v),view:Ef(v),file:v.replace(/[^\w-]/g,"_"),nodes:x,script:[...S.map(A=>A.script).filter(A=>!!A),k.script??""].filter(A=>A.trim()).join(`
|
|
5856
5856
|
`),style:[k.style,...S.map(A=>A.style)].filter(A=>!!A).join(`
|
|
5857
5857
|
`),params:[...v.matchAll(/\[([^\]]+)\]/g)].map(A=>A[1])})}let u=[];for(let $ of a){let w=Ce(await je.promises.readFile($,"utf8"),$,"xcode");t.push(...w.warnings);let v=be.basename($,".rose");u.push({name:v,view:Ef(v),nodes:w.nodes,script:w.script,slots:Ft(w.nodes),style:w.style??""})}await je.promises.rm(s,{recursive:!0,force:!0}),await je.promises.mkdir(be.join(r,"Pages"),{recursive:!0}),await je.promises.mkdir(be.join(r,"Components"),{recursive:!0}),await je.promises.mkdir(be.join(r,"Kit"),{recursive:!0}),await je.promises.mkdir(be.join(r,"Resources"),{recursive:!0}),await je.promises.mkdir(be.join(s,`${co}.xcodeproj`),{recursive:!0});let{assets:l,vectors:p}=await Jv(n,be.join(r,"Resources"),d.map($=>$.nodes),t),f=[...d.map($=>$.style)].join(`
|
|
5858
5858
|
`)+`
|
|
5859
|
-
`+ke,h=await Uv(n,be.join(r,"Resources"),f,t),g=new Map;for(let $ of d)for(let[w,v]of Bc($.style??"",t,h,$.view))g.set(w,v);for(let $ of u)for(let[w,v]of Bc($.style,t,h,$.view))g.set(w,v);for(let[$,w]of Bc(ke,t,h))g.set($,w);let y=Mt(n),m=xt([...d.map($=>$.script),...u.map($=>$.script)]);await je.promises.writeFile(be.join(r,"Kit","RoseKit.swift"),Zv(e.apiBase??"",y,m),"utf8"),await je.promises.writeFile(be.join(r,"Kit","RoseTheme.swift"),Qv(g,h),"utf8");for(let $ of u)await je.promises.writeFile(be.join(r,"Components",$.view+".swift"),wS($,l,t,h),"utf8");for(let $ of d)await je.promises.writeFile(be.join(r,"Pages",$.view+".swift"),nS($,u,l,p,t,y,h),"utf8");await je.promises.writeFile(be.join(r,"RoseRootView.swift"),eS(d),"utf8"),await je.promises.writeFile(be.join(r,"
|
|
5859
|
+
`+ke,h=await Uv(n,be.join(r,"Resources"),f,t),g=new Map;for(let $ of d)for(let[w,v]of Bc($.style??"",t,h,$.view))g.set(w,v);for(let $ of u)for(let[w,v]of Bc($.style,t,h,$.view))g.set(w,v);for(let[$,w]of Bc(ke,t,h))g.set($,w);let y=Mt(n),m=xt([...d.map($=>$.script),...u.map($=>$.script)]);await je.promises.writeFile(be.join(r,"Kit","RoseKit.swift"),Zv(e.apiBase??"",y,m),"utf8"),await je.promises.writeFile(be.join(r,"Kit","RoseTheme.swift"),Qv(g,h),"utf8");for(let $ of u)await je.promises.writeFile(be.join(r,"Components",$.view+".swift"),wS($,l,t,h),"utf8");for(let $ of d)await je.promises.writeFile(be.join(r,"Pages",$.view+".swift"),nS($,u,l,p,t,y,h),"utf8");await je.promises.writeFile(be.join(r,"RoseRootView.swift"),eS(d),"utf8"),await je.promises.writeFile(be.join(r,"RosefcApp.swift"),Yv(),"utf8"),await je.promises.writeFile(be.join(r,"Info.plist"),tS([...h].map(([$,w])=>({family:$,file:w}))),"utf8");let b=Hf(r).filter($=>$.endsWith(".swift"));return await je.promises.writeFile(be.join(s,`${co}.xcodeproj`,"project.pbxproj"),vS(b,r),"utf8"),await je.promises.writeFile(be.join(s,"README.md"),Xv(e.apiBase??"",d.length,u.length,t),"utf8"),await ti("xcode",s,t),{pages:d.map($=>`${co}/Pages/${$.view}.swift`),components:u.map($=>`${co}/Components/${$.view}.swift`)}}function Hv(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function Ef(e){return(e.split("/").map(n=>n.replace(/^\[(.+)\]$/,"param_$1")).map(n=>n.replace(/[^\w]+/g,"_").split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")).join("").replace(/^\d/,"_$&")||"Page")+"View"}function Vv(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}async function Jv(e,t,n,s){let r=new Map,i=new Map,o=c=>{for(let d of c)if(d.kind==="element"){if(d.tag.toLowerCase()==="img"){let u=d.attrs.find(f=>f.name==="src"),l=u&&u.value.kind==="text"?u.value.text:"",p=/^\/(?:public\/)?([^/]+\.(png|jpe?g|svg))$/i.exec(l);p?/\.svg$/i.test(p[1])?i.set(l,null):r.set(l,p[1].replace(/\.[^.]+$/,"").toLowerCase()):l&&s.push(`xcode: <img ${l}> needs a raster asset - rendered as a symbol`)}o(d.children)}else d.kind==="if"?d.branches.forEach(u=>o(u.children)):d.kind==="each"||d.kind==="block"?o(d.children):d.kind==="await"&&(o(d.pending),o(d.then),o(d.catch))};n.forEach(o);let a=new Map;for(let c of i.keys())a.set(c.replace(/^\//,""),c);for(let[c,d]of a){let u=be.join(e,"public",c);if(!je.existsSync(u)){i.delete(d),s.push(`xcode: asset ${d} is not in public/ - the symbol is used`);continue}let l=Wt(await je.promises.readFile(u,"utf8"));l.shape?i.set(d,l.shape):(i.delete(d),s.push(`xcode: ${c} uses ${l.reason??"an unsupported feature"} - rendered as a symbol`))}for(let[c,d]of r){let u=be.join(e,"public",c.replace(/^\//,""));if(!je.existsSync(u)){s.push(`xcode: asset ${c} is not in public/ - the symbol is used`);continue}let l=be.join(t,"Assets.xcassets",d+".imageset");await je.promises.mkdir(l,{recursive:!0}),await je.promises.writeFile(be.join(l,d+be.extname(u).toLowerCase()),await je.promises.readFile(u)),await je.promises.writeFile(be.join(l,"Contents.json"),JSON.stringify({images:[{filename:d+be.extname(u).toLowerCase(),idiom:"universal",scale:"1x"}],info:{author:"xcode",version:1},properties:{"preserves-vector-representation":!1}},null,2)+`
|
|
5860
5860
|
`,"utf8")}return r.size&&(await je.promises.mkdir(be.join(t,"Assets.xcassets"),{recursive:!0}),await je.promises.writeFile(be.join(t,"Assets.xcassets","Contents.json"),JSON.stringify({info:{author:"xcode",version:1}},null,2)+`
|
|
5861
5861
|
`,"utf8")),{assets:r,vectors:i}}async function Uv(e,t,n,s){let r=new Map;for(let i of Zn(n)){let o=be.join(e,"public",i.file.replace(/^\//,""));if(!je.existsSync(o)){s.push(`xcode: font-family '${i.family}' points at ${i.file}, which is not in public/ - the system default is used`);continue}let a=be.extname(o).toLowerCase();if(!/^\.(ttf|otf|ttc|woff2?)$/.test(a)){s.push(`xcode: font-family '${i.family}' uses ${a}, which iOS cannot load - convert it to .ttf/.otf`);continue}let c=i.family.replace(/[^\w]/g,"")+a;await je.promises.mkdir(t,{recursive:!0}),await je.promises.copyFile(o,be.join(t,c)),r.set(i.family,c)}return r}function Bc(e,t,n=new Map,s){let r=new Map;if(!e.trim())return r;let i=Te(e);for(let u of i.warnings)t.push(`xcode: ${u}`);let o=new Map,a=[],c=[];for(let u of i.rules){let l=u.parts[u.parts.length-1];if(u.hover&&l.classes.length)for(let p of l.classes){let f=s?`__hover_${p}__${s}`:`__hover_${p}`;o.set(f,fe(o.get(f)??null,u.hover))}if(u.focus&&l.classes.length&&a.push({last:l,focus:u.focus}),u.active&&l.classes.length&&c.push({last:l,active:u.active}),l.unsupported.includes(":hover")&&!u.hover&&t.push(`xcode: :hover has no SwiftUI equivalent on "${u.selector}" - dropped`),!(u.media&&(u.media.min!==void 0||u.media.max!==void 0)&&(u.media.min!==void 0&&Dc<u.media.min||u.media.max!==void 0&&Dc>u.media.max))){if(!l.classes.length&&l.tag){Ga.set(l.tag,fe(Ga.get(l.tag)??null,u.model));continue}for(let p of l.classes){let f=s?`${p}__${s}`:p;o.set(f,fe(o.get(f)??null,u.model))}}}for(let u of a)for(let l of u.last.classes){let p=s?`__focus_${l}__${s}`:`__focus_${l}`,f=s?`${l}__${s}`:l,h=u.focus.borderColor&&!u.focus.borderWidth?{...u.focus,borderWidth:o.get(f)?.borderWidth??u.focus.borderWidth}:u.focus;o.set(p,fe(o.get(p)??null,h))}for(let u of c)for(let l of u.last.classes){let p=s?`__active_${l}__${s}`:`__active_${l}`,f=s?`${l}__${s}`:l,h=u.active.borderColor&&!u.active.borderWidth?{...u.active,borderWidth:o.get(f)?.borderWidth??u.active.borderWidth}:u.active;o.set(p,fe(o.get(p)??null,h))}for(let[u,l]of o)r.set(u,l);/(^|[\s,])body\b|(^|[\s,])html\b/.test(e)&&t.push("xcode: body/html rules become the root view (SwiftUI has no document)");let d=new Set(Zn(e).map(u=>u.family));for(let u of Cn(e))!d.has(u)&&!n.has(u)&&t.push(`xcode: font-family '${u}' has no @font-face - the system default is used`);return r}function uo(e){let t=e.toLowerCase().trim(),n={white:"ffffff",black:"000000",red:"e53935",green:"43a047",blue:"1e88e5",grey:"9e9e9e",gray:"9e9e9e",pink:"e91e63",transparent:"00000000"};if(n[t])return n[t];let s=/#([0-9a-fA-F]{3,8})/.exec(t)?.[1];return s?s.length===3?s.split("").map(r=>r+r).join(""):s.slice(0,8):"000000"}function Me(e){return String(Math.round(e*100)/100)}function qv(e){return e>=800?".heavy":e>=700?".bold":e>=600?".semibold":e>=500?".medium":e>=300?".light":e>=200||e>=100?".thin":".regular"}function Of(e){return`EdgeInsets(top: ${Me(e[0])}, leading: ${Me(e[3])}, bottom: ${Me(e[2])}, trailing: ${Me(e[1])})`}function Nf(e,t){let n=[];if(e.color&&n.push(`.foregroundColor(Color.rose(${JSON.stringify(uo(e.color))}))`),e.fontSize!==void 0||e.fontFamily){let s=Me(e.fontSize??16),r=e.fontFamily?t.get(e.fontFamily):void 0;n.push(r?`.font(.custom(${JSON.stringify(e.fontFamily)}, size: ${s}))`:`.font(.system(size: ${s}))`)}return e.fontWeight!==void 0&&n.push(`.fontWeight(${qv(e.fontWeight)})`),e.italic&&n.push(".italic()"),e.letterSpacing!==void 0&&n.push(`.kerning(${Me(e.letterSpacing)})`),e.underline&&n.push(".underline()"),e.strike&&n.push(".strikethrough()"),e.textAlign&&n.push(`.multilineTextAlignment(${Gv[e.textAlign]??".leading"})`),e.lineHeight!==void 0&&e.fontSize!==void 0&&e.lineHeight>1&&n.push(`.lineSpacing(${Me(Math.round((e.fontSize*e.lineHeight-e.fontSize)*10)/10)})`),n}function Mf(e,t){let n=[];if(e.padding&&n.push(`.padding(${Of(e.padding)})`),t.full&&n.push(`.frame(maxWidth: .infinity, alignment: ${t.align})`),e.gradient&&e.gradient.stops.length>=2){let s=e.gradient.stops.map(r=>`Color.rose(${JSON.stringify(uo(r.color))})`).join(", ");n.push(`.background(LinearGradient(colors: [${s}], startPoint: .top, endPoint: .bottom))`)}else e.background&&n.push(`.background(Color.rose(${JSON.stringify(uo(e.background))}))`);if(e.borderWidth&&e.borderColor){let s=e.borderWidth,i=s[0]===s[1]&&s[1]===s[2]&&s[2]===s[3]?s[0]:Math.max(...s);i>0&&n.push(`.overlay(Rectangle().strokeBorder(Color.rose(${JSON.stringify(uo(e.borderColor))}), lineWidth: ${Me(i)}))`)}if(e.radius){let s=e.radius,r=s[0]===s[1]&&s[1]===s[2]&&s[2]===s[3];n.push(r?`.clipShape(RoundedRectangle(cornerRadius: ${Me(s[0])}))`:`.clipShape(RoseCorners(radii: [${s.map(i=>Me(i)).join(", ")}]))`)}if(e.shadow&&n.push(`.shadow(color: Color.rose(${JSON.stringify(uo(e.shadow.color))}), radius: ${Me(e.shadow.blur)}, x: ${Me(e.shadow.x)}, y: ${Me(e.shadow.y)})`),e.opacity!==void 0&&n.push(`.opacity(${Me(e.opacity)})`),e.width&&e.width.u!=="auto"&&n.push(e.width.u==="%"?".frame(maxWidth: .infinity)":`.frame(width: ${Me(e.width.n)})`),e.height&&e.height.u!=="auto"&&n.push(e.height.u==="%"?".frame(maxHeight: .infinity)":`.frame(height: ${Me(e.height.n)})`),e.margin&&n.push(`.padding(${Of(e.margin)})`),e.position){let s=e.insetLeft??e.insetRight??0,r=e.insetTop??e.insetBottom??0;n.push(`.offset(x: ${Me(s)}, y: ${Me(r)})`)}return e.zIndex!==void 0&&(e.position||e.shadow)&&n.push(`.zIndex(${Me(e.zIndex)})`),e.overflow==="scroll"&&n.push(".roseScroll()"),n}function Ff(e,t){return t!=="row"||!e?".leading":e==="center"||e==="around"||e==="evenly"?".center":e==="end"?".trailing":".leading"}function Pf(e,t){let n=[],s=i=>JSON.stringify(i),r=i=>`[${i.map(o=>Me(o)).join(", ")}]`;if(e.color&&n.push(`color: ${s(e.color)}`),e.background&&n.push(`background: ${s(e.background)}`),e.gradient&&e.gradient.stops.length>=2&&n.push(`gradient: [${e.gradient.stops.map(i=>s(i.color)).join(", ")}]`),e.fontSize!==void 0&&n.push(`fontSize: ${Me(e.fontSize)}`),e.fontWeight!==void 0&&n.push(`weight: ${e.fontWeight}`),e.italic&&n.push("italic: true"),e.letterSpacing!==void 0&&n.push(`letterSpacing: ${Me(e.letterSpacing)}`),e.lineHeight!==void 0&&e.fontSize!==void 0&&n.push(`lineHeight: ${Me(Math.round(e.fontSize*e.lineHeight*10)/10)}`),e.textAlign&&n.push(`align: ${s(e.textAlign)}`),e.underline&&n.push("underline: true"),e.strike&&n.push("strike: true"),e.fontFamily&&(t.get(e.fontFamily)?n.push(`fontFamily: ${s(e.fontFamily)}`):/^(serif|monospace|sans-serif)$/i.test(e.fontFamily)&&n.push(`fontFamily: ${s(e.fontFamily.toLowerCase())}`)),e.padding&&n.push(`padding: ${r(e.padding)}`),e.margin&&n.push(`margin: ${r(e.margin)}`),e.radius&&n.push(`radius: ${r(e.radius)}`),e.borderWidth&&e.borderColor){let i=e.borderWidth,o=i[0]===i[1]&&i[1]===i[2]&&i[2]===i[3];n.push(`borderWidth: ${Me(o?i[0]:Math.max(...i))}`),n.push(`borderColor: ${s(e.borderColor)}`)}return e.shadow&&(n.push(`shadowX: ${Me(e.shadow.x)}`),n.push(`shadowY: ${Me(e.shadow.y)}`),n.push(`shadowBlur: ${Me(e.shadow.blur)}`),n.push(`shadowColor: ${s(e.shadow.color)}`)),e.opacity!==void 0&&n.push(`opacity: ${Me(e.opacity)}`),e.width&&e.width.u==="px"&&n.push(`width: ${Me(e.width.n)}`),e.height&&e.height.u==="px"&&n.push(`height: ${Me(e.height.n)}`),e.display==="none"&&n.push("hidden: true"),e.gap!==void 0&&n.push(`gap: ${Me(e.gap)}`),e.direction&&n.push(`direction: ${s(e.direction)}`),e.justify&&n.push(`justify: ${s(e.justify)}`),e.align&&n.push(`items: ${s(e.align)}`),n.join(", ")}function Qv(e,t){let n=[...e].map(([r,i])=>` ${JSON.stringify(r)}: RoseStyle(${Pf(i,t)}),`).join(`
|
|
5862
5862
|
`)||" // no style rules",s=[...Ga].map(([r,i])=>` ${JSON.stringify(r)}: RoseStyle(${Pf(i,t)}),`).join(`
|
|
@@ -6269,21 +6269,21 @@ func roseContentGet(_ coll: String, _ slug: String) -> [String: Any]? {
|
|
|
6269
6269
|
}
|
|
6270
6270
|
`:"";return`import Foundation
|
|
6271
6271
|
|
|
6272
|
-
/// Base URL of the deployed
|
|
6272
|
+
/// Base URL of the deployed Rosefc server (rosefc export --api).
|
|
6273
6273
|
let roseApiBase = ${JSON.stringify(e)}
|
|
6274
6274
|
${s}
|
|
6275
6275
|
${Kv(n)}
|
|
6276
6276
|
/// The await reject branch: it always throws, so the catch arm renders.
|
|
6277
6277
|
/// (Swift has no throwing expression, so the value type is a white lie.)
|
|
6278
6278
|
func roseThrow(_ message: Any) -> Any {
|
|
6279
|
-
throw NSError(domain: "
|
|
6279
|
+
throw NSError(domain: "Rosefc", code: 1, userInfo: [NSLocalizedDescriptionKey: "(message)"])
|
|
6280
6280
|
}
|
|
6281
6281
|
|
|
6282
6282
|
/// The JSON half of a render: the state the page's $data produced.
|
|
6283
6283
|
func roseData(_ route: String) async -> [String: Any] {
|
|
6284
6284
|
guard !roseApiBase.isEmpty,
|
|
6285
6285
|
let encoded = route.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
|
|
6286
|
-
let url = URL(string: roseApiBase + "/
|
|
6286
|
+
let url = URL(string: roseApiBase + "/__rosefc/data?path=" + encoded) else { return [:] }
|
|
6287
6287
|
do {
|
|
6288
6288
|
let (data, response) = try await URLSession.shared.data(from: url)
|
|
6289
6289
|
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { return [:] }
|
|
@@ -6328,15 +6328,15 @@ func roseAction(_ route: String, _ name: String, _ fields: [String: Any]? = nil)
|
|
|
6328
6328
|
/// the process - the client-side stand-in for the server-side memo the web build
|
|
6329
6329
|
/// uses (where the server computes and ships the value in the state). A restart
|
|
6330
6330
|
/// recomputes, which is the same trade an in-memory memo makes on the web.
|
|
6331
|
-
private var
|
|
6331
|
+
private var __rosefcKvCache = [String: (Double, Any)]()
|
|
6332
6332
|
|
|
6333
6333
|
func roseKv<T>(_ name: String, _ compute: () -> T, _ ttlSeconds: Int) -> T {
|
|
6334
6334
|
let now = Date().timeIntervalSince1970 * 1000
|
|
6335
|
-
if let cached =
|
|
6335
|
+
if let cached = __rosefcKvCache[name], now - cached.0 < Double(ttlSeconds * 1000) {
|
|
6336
6336
|
return cached.1 as? T ?? compute()
|
|
6337
6337
|
}
|
|
6338
6338
|
let value = compute()
|
|
6339
|
-
|
|
6339
|
+
__rosefcKvCache[name] = (now, value)
|
|
6340
6340
|
return value
|
|
6341
6341
|
}
|
|
6342
6342
|
|
|
@@ -6554,14 +6554,14 @@ func roseConcat(_ a: Any?, _ b: Any?) -> [Any?] {
|
|
|
6554
6554
|
func roseArr(_ items: Any?...) -> [Any?] {
|
|
6555
6555
|
items
|
|
6556
6556
|
}
|
|
6557
|
-
`}function Xv(e,t,n,s){return`#
|
|
6557
|
+
`}function Xv(e,t,n,s){return`# Rosefc -> Xcode (SwiftUI)
|
|
6558
6558
|
|
|
6559
|
-
Generated by \`
|
|
6559
|
+
Generated by \`rosefc export xcode\` from the project's \`.rose\` pages.
|
|
6560
6560
|
|
|
6561
6561
|
- ${t} page(s), ${n} component(s)
|
|
6562
|
-
- Open \`
|
|
6563
|
-
- Server: \`
|
|
6564
|
-
\`
|
|
6562
|
+
- Open \`RosefcApp.xcodeproj\` in Xcode and run on an iOS simulator/device
|
|
6563
|
+
- Server: \`rosefc export xcode --api <base>\` writes the base URL into
|
|
6564
|
+
\`RosefcApp/Kit/RoseKit.swift\`. Current: \`${e||"(unset)"}\`
|
|
6565
6565
|
|
|
6566
6566
|
\`@State\` fields, one SwiftUI \`View\` per route, a deterministic \`project.pbxproj\`
|
|
6567
6567
|
(regenerated with every export), and a URLSession kit that speaks the same data
|
|
@@ -6570,7 +6570,7 @@ ${Nt(s)}`}function Yv(){return`import SwiftUI
|
|
|
6570
6570
|
import AVKit
|
|
6571
6571
|
|
|
6572
6572
|
@main
|
|
6573
|
-
struct
|
|
6573
|
+
struct RosefcApp: App {
|
|
6574
6574
|
var body: some Scene {
|
|
6575
6575
|
WindowGroup {
|
|
6576
6576
|
RoseRootView()
|
|
@@ -6618,7 +6618,7 @@ struct RoseRootView: View {
|
|
|
6618
6618
|
<key>CFBundleDevelopmentRegion</key>
|
|
6619
6619
|
<string>en</string>
|
|
6620
6620
|
<key>CFBundleDisplayName</key>
|
|
6621
|
-
<string>
|
|
6621
|
+
<string>Rosefc</string>
|
|
6622
6622
|
<key>CFBundleExecutable</key>
|
|
6623
6623
|
<string>$(EXECUTABLE_NAME)</string>
|
|
6624
6624
|
<key>CFBundleIdentifier</key>
|
|
@@ -6658,8 +6658,8 @@ ${e.map(n=>` <string>${n.file}</string>`).join(`
|
|
|
6658
6658
|
`),$=[...y.activeKeys??[]].map(O=>` @State private var ${Gc(O)}: Bool = false`).join(`
|
|
6659
6659
|
`),w=y.lines.join(`
|
|
6660
6660
|
`),v=l.map(O=>{if(zc.test(O.init)){let P=O.init.slice(O.init.indexOf(">")+1).trim();return P.startsWith("roseContentList(")?` static let ${O.name}: () -> [[String: Any]] = { ${Va(P)} }`:P.startsWith("roseContentGet(")?` static let ${O.name}: () -> [String: Any]? = { ${Va(P)} }`:` static let ${O.name}: () -> [String: Any] = { [:] }`}return O.init.startsWith("roseContentList(")?` static let ${O.name}: [[String: Any]] = ${Va(O.init)}`:O.init.startsWith("roseContentGet(")?` static let ${O.name}: [String: Any]? = ${Va(O.init)}`:` static let ${O.name}: [String: Any] = ${Vc(O.init)}`}).join(`
|
|
6661
|
-
`),_=an(e.script??""),k=[...a.state.map(O=>{let P=h(O.name),j=Ua(P),B=_.includes(O.name)?`UserDefaults.standard.string(forKey: ${JSON.stringify("
|
|
6662
|
-
`),S=_.length?_.map(O=>` .onChange(of: ${O}) { _, new in UserDefaults.standard.set(new, forKey: ${JSON.stringify("
|
|
6661
|
+
`),_=an(e.script??""),k=[...a.state.map(O=>{let P=h(O.name),j=Ua(P),B=_.includes(O.name)?`UserDefaults.standard.string(forKey: ${JSON.stringify("rosefc:"+O.name)}) ?? ${dr(P)}`:e.params.includes(O.name)?`params[${JSON.stringify(O.name)}] ?? ${dr(P)}`:dr(P);return` @State private var ${O.name}: ${j} = ${B}`}),...a.data.map(O=>` @State private var ${O}: Any? = nil`),...y.deferred.map(O=>` @State private var ${O.name}: Bool = false`)].join(`
|
|
6662
|
+
`),S=_.length?_.map(O=>` .onChange(of: ${O}) { _, new in UserDefaults.standard.set(new, forKey: ${JSON.stringify("rosefc:"+O)}) }`).join(`
|
|
6663
6663
|
`):"",C=St(e.nodes).flatMap(O=>O.fields),A=$s(e.script??"").filter(O=>new Set([...a.state.map(P=>P.name),...a.data]).has(O.name)).map(O=>` ${O.name} = roseKv(${JSON.stringify(O.name)}, { ${bs(O.fn)} }, ${O.ttl})`).join(`
|
|
6664
6664
|
`),R=C.length?`
|
|
6665
6665
|
private func __formFields() -> [String: Any] {
|
|
@@ -6737,7 +6737,7 @@ ${ce.lines.join(`
|
|
|
6737
6737
|
`);se(`${d.view}(
|
|
6738
6738
|
${j}
|
|
6739
6739
|
${O})`,t);return}if(Dv.has(s)&&!e.children.some(x=>x.kind==="element")){let x=qa(e.children,t);Wc(`Text(${x||'""'})${[...o,...a].join("")}`,Ic(e.children),t);return}if(s==="progress"){let x=e.attrs.find(M=>M.name==="value"),A=e.attrs.find(M=>M.name==="max"),R=x&&x.value.kind==="expr"?$n(x.value.code,t):x&&x.value.kind==="text"?x.value.text:"0",T=A&&A.value.kind==="text"?A.value.text:"100";se(`ProgressView(value: Double(${R}) / Double(${T}))${a.join("")}`,t);return}if(s==="video"){let x=e.attrs.find(R=>R.name==="src"),A=x&&x.value.kind==="text"?x.value.text:"";se(`VideoPlayer(player: AVPlayer(url: URL(string: ${JSON.stringify(A)})!))${a.join("")}`,t);return}if(s==="audio"){let x=e.attrs.find(R=>R.name==="src"),A=x&&x.value.kind==="text"?x.value.text:"";se(`VideoPlayer(player: AVPlayer(url: URL(string: ${JSON.stringify(A)})!))${a.join("")}`,t);return}if(s==="img"){let x=e.attrs.find(M=>M.name==="src"),A=x&&x.value.kind==="text"?x.value.text:"",R=t.assets.get(A);if(R){se(`Image(${JSON.stringify(R)}).resizable().scaledToFit().frame(width: 72)${a.join("")}`,t);return}let T=t.vectors.get(A);if(T){se(`${uS(T)}${a.join("")}`,t);return}se(`Image(systemName: "photo")${a.join("")}`,t);return}if(s==="a"){let x=e.attrs.find(T=>T.name==="href"),A=x?Ja(x,t):'""',R=qa(e.children,t)||'""';Wc(`Button(action: { ${t.navigate}(${A}) }) { Text(${R})${o.join("")} }${a.join("")}`,Ic(e.children),t);return}if(s==="input"||s==="textarea"){let x=e.attrs.find(N=>N.name==="placeholder"),A=x?Ja(x,t):'""',R=e.attrs.find(N=>N.name==="type"),T=R&&R.value.kind==="text"?R.value.text:"text",M=e.attrs.find(N=>N.name==="bind:checked"),F=e.attrs.find(N=>N.name==="bind:group"),I=e.attrs.find(N=>N.name==="bind:value"),O=N=>N&&N.value.kind==="expr"&&t.stateNames.has(N.value.code.trim())?N.value.code.trim():"",P=e.attrs.find(N=>N.name==="value"),j=P?P.value.kind==="text"?JSON.stringify(P.value.text):Ja(P,t):"true";if(T==="checkbox"){let N=O(F),W=O(M);se(N?`Toggle(isOn: Binding(get: { (${N} as? [Any])?.contains(where: { String(describing: $0) == String(describing: ${j}) }) ?? false }, set: { on in var list = (${N} as? [Any]) ?? []; if on { list.append(${j}) } else { list.removeAll { String(describing: $0) == String(describing: ${j}) } }; ${N} = list })) { Text("") }`:W?`Toggle(isOn: Binding(get: { ${W} }, set: { ${W} = $0 })) { Text("") }`:'Toggle(isOn: .constant(false)) { Text("") }',t);return}if(T==="radio"){let N=O(F);se(N?`Button(action: { ${N} = ${j} as? String ?? String(describing: ${j}) }) { Image(systemName: String(describing: ${N}) == String(describing: ${j}) ? "largecircle.fill.circle" : "circle") }`:"EmptyView()",t);return}let B=[...o,...a].join(""),U=I&&I.value.kind==="expr"&&/^[A-Za-z_$][\w$]*$/.test(I.value.code.trim())?I.value.code.trim():"",ce=t.componentProps.has(U)?U:"";if(ce)se(`TextField(${A}, text: Binding(get: { ${ce} as? String ?? "" }, set: { v in ${ze(ce)}(v) }))${B}`,t);else if(U)se(`TextField(${A}, text: Binding(get: { ${U} }, set: { ${U} = $0 }))${B}`,t);else{let N=e.attrs.find(X=>X.name==="name"),W=N&&N.value.kind==="text"?N.value.text.trim():"",re=W?An(t.forms,W):null;if(re){se(`TextField(${A}, text: Binding(get: { ${re} }, set: { ${re} = $0 }))${B}`,t);return}let xe=P&&P.value.kind==="expr"&&t.componentProps.has(P.value.code.trim())?P.value.code.trim():"";se(xe?`TextField(${A}, text: Binding(get: { ${xe} as? String ?? "" }, set: { v in ${ze(xe)}(v) }))${B}`:`TextField(${A}, text: .constant(""))${B}`,t)}return}if(s==="button"){let x=e.attrs.find(T=>T.name==="on:click"||T.name==="on:submit"),A=x&&x.value.kind==="expr"?aS(x.value.code.trim(),t):"";!x&&tr(e)&&t.pageAction&&(A=`${t.pageAction}()`);let R=qa(e.children,t)||'""';Wc(`Button(action: { ${A} }) { Text(${R})${o.join("")} }${a.join("")}`,Ic(e.children),t);return}if(s==="select"){let x=e.attrs.find(M=>M.name==="bind:value"),A=x&&x.value.kind==="expr"&&t.stateNames.has(x.value.code.trim())?x.value.code.trim():"",R=e.children.filter(M=>M.kind==="element"&&M.tag.toLowerCase()==="option").map(M=>{let F=M.children.filter(B=>B.kind==="text").map(B=>B.value.trim()).join(""),I=M.attrs.find(B=>B.name==="value"),O=I&&I.value.kind==="text"?I.value.text:F,P=Wf(M,bt(M),t),j=P.expr?`.roseText(${P.expr})`:Nf(P.model,t.fontMap).join("");return{label:F,value:O,optStyle:j}});if(!A){t.warnings.push("xcode: <select> without bind:value is inert"),se('Text("[select]")',t);return}if(e.attrs.some(M=>M.name==="multiple")){se("VStack(alignment: .leading, spacing: 4) {",t),t.depth++;for(let M of R){let F=`(${A} as? [Any])?.contains(where: { String(describing: $0) == String(describing: ${JSON.stringify(M.value)}) }) ?? false`;se(`Button(action: { var list = (${A} as? [Any]) ?? []; if ${F} { list.removeAll { String(describing: $0) == String(describing: ${JSON.stringify(M.value)}) } } else { list.append(${JSON.stringify(M.value)}) }; ${A} = list }) {`,t),t.depth++,se(`HStack { Image(systemName: ${F} ? "checkmark.square" : "square"); Text(${JSON.stringify(M.label)}) }`,t),t.depth--,se("}",t)}t.depth--,se("}",t);return}let T=`Binding(get: { ${A} }, set: { ${A} = $0 })`;se(`Picker("select", selection: ${T}) {`,t),t.depth++;for(let M of R)se(`Text(${JSON.stringify(M.label)})${M.optStyle}.tag(${JSON.stringify(M.value)})`,t);t.depth--,se(`}.pickerStyle(.menu)${[...a].join("")}`,t);return}if(s==="hr"){se("Divider()",t);return}if(s==="br"){se("Spacer().frame(height: 8)",t);return}let u=ir(i,s,zv),l=u==="row",p=r!==null||i.display==="flex"||i.direction!==void 0||i.justify!==void 0||i.align!==void 0||i.gap!==void 0,f=r?null:Mf(i,{full:!0,align:Ff(i.justify,u)});if(!p&&!r&&(!f||f.length===0)){l?(se("HStack(alignment: .center, spacing: 8) {",t),t.depth++,js(e.children,t),t.depth--,se("}",t)):(se("VStack(alignment: .leading, spacing: 6) {",t),t.depth++,js(e.children,t),t.depth--,se("}.frame(maxWidth: .infinity, alignment: .leading)",t));return}i.wrap&&t.warnings.push(`xcode: flex-wrap on <${s}> has no SwiftUI layout - rendered as one ${u}`);let y=u==="row"?{start:".top",center:".center",end:".bottom",stretch:".top"}[i.align??""]??".center":{start:".leading",center:".center",end:".trailing",stretch:".leading"}[i.align??""]??".leading",m=i.gap!==void 0?Me(i.gap):u==="row"?"8":"6",b=Ff(i.justify,u),$=(r?`.frame(maxWidth: .infinity, alignment: ${b}).roseBox(${r})`:(f??[]).join(""))+c.join("");se(`${u==="row"?"HStack":"VStack"}(alignment: ${y}, spacing: ${m}) {`,t),t.depth++;let w=i.justify,v=e.children,_=v.filter(x=>x.kind!=="text"||x.value.trim().length>0),k=w==="between"||w==="evenly"||w==="around",S=w==="evenly"||w==="around",C=0;for(let x of v){let A=x.kind!=="text"||x.value.trim().length>0;A&&S&&C===0&&se("Spacer()",t),js([x],t),A&&(k&&C<_.length-1&&se("Spacer()",t),S&&C===_.length-1&&se("Spacer()",t),C++)}t.depth--,se(`}${$}`,t)}function Ja(e,t){return e.value.kind==="expr"?$n(e.value.code,t):e.value.kind==="text"?JSON.stringify(e.value.text):'""'}function aS(e,t){return/^[A-Za-z_$][\w$]*$/.test(e)?`${e}()`:`${lS(e,t)}()`}function lS(e,t){let n=t.inline.get(e);if(n)return n;let s=sr(new Set(t.inline.values()));t.inline.set(e,s);let r=jt(e,cS(t),t.stateNames);return r.reason||!r.stmts.length?(t.warnings.push(`xcode: an inline handler (${e.slice(0,40)}...) is not translated (${r.reason??"empty"}); use a named function in <script>`),t.inlineBodies.push(` private func ${s}() {
|
|
6740
|
-
//
|
|
6740
|
+
// rosefc: handler not translated (${r.reason??"empty"}).
|
|
6741
6741
|
}`),s):(t.inlineBodies.push(` private func ${s}() {
|
|
6742
6742
|
${r.stmts.map(i=>` ${i}`).join(`
|
|
6743
6743
|
`)}
|
|
@@ -6750,7 +6750,7 @@ ${i.ops.map(a=>{switch(a.op){case"move":return` p.move(to: CGPoin
|
|
|
6750
6750
|
.frame(width: 72, height: 72)`).join(`
|
|
6751
6751
|
`)}
|
|
6752
6752
|
}
|
|
6753
|
-
.frame(width: 72, height: 72)`}function $n(e,t){let n=Oe(e.trim(),"roseContentList","roseContentGet",'""');if(t.constAlias?.size){let s=t.constAlias;n=Gt(n,r=>(s.get(r)??r)!==r,r=>s.get(r))}if(/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(n)||/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,Er,new Set);if(s!==null)return s}if(t.derivedExprs?.size)for(let[s,r]of t.derivedExprs){let i=$n(r,{...t,derivedExprs:new Map});n=n.replace(new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\(\\s*\\)`,"g"),`(${i})`),n=n.replace(new RegExp(`(?<![.\\w$])${s.replace(/\$/g,"\\$")}\\b(?!\\s*\\()`,"g"),`(${i})`)}if(n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,'"$2"'),n=n.replace(/\$actionPending\s*\(\s*\)/g,"false"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),n=n.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(s,r)=>`(params[${JSON.stringify(r)}] ?? "")`),n=n.replace(/\$query\s*\(\s*\)/g,"params"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"
|
|
6753
|
+
.frame(width: 72, height: 72)`}function $n(e,t){let n=Oe(e.trim(),"roseContentList","roseContentGet",'""');if(t.constAlias?.size){let s=t.constAlias;n=Gt(n,r=>(s.get(r)??r)!==r,r=>s.get(r))}if(/`/.test(n)||/\?\./.test(n)||/\?\?/.test(n)||/\[\s*(?:'[^']*'|[A-Za-z0-9_.]+)\s*\]/.test(n)||/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(n)){let s=G(n,Er,new Set);if(s!==null)return s}if(t.derivedExprs?.size)for(let[s,r]of t.derivedExprs){let i=$n(r,{...t,derivedExprs:new Map});n=n.replace(new RegExp(`\\b${s.replace(/\$/g,"\\$")}\\s*\\(\\s*\\)`,"g"),`(${i})`),n=n.replace(new RegExp(`(?<![.\\w$])${s.replace(/\$/g,"\\$")}\\b(?!\\s*\\()`,"g"),`(${i})`)}if(n=n.replace(/\$t\s*\(\s*(['"])([^'"]*)\1[^)]*\)/g,'"$2"'),n=n.replace(/\$actionPending\s*\(\s*\)/g,"false"),n=n.replace(/\$actionError\s*\([^)]*\)(?:\s*\.\s*[A-Za-z_$][\w$]*)?/g,"null"),n=n.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(s,r)=>`(params[${JSON.stringify(r)}] ?? "")`),n=n.replace(/\$query\s*\(\s*\)/g,"params"),n=n.replace(/\$([A-Za-z_$][\w$]*)/g,"rosefc_$1"),n=n.replace(/'((?:[^'\\\\]|\\\\.)*)'/g,'"$1"'),n=n.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(s,r)=>t.stateNames.has(r)?r:s),t.thunkBinds?.size)for(let s of t.thunkBinds)n=n.replace(new RegExp(`(?<![.\\w$])${Qa(s)}\\b(?!\\s*\\()`),`${s}()`);return n=At(n,s=>`!(${s}).isEmpty`,s=>t.stateNames.has(s)),n=ys(n,s=>{let r=t.stateTypes?.get(s.trim().replace(/\s*\(\s*\)$/,""));return r==="Bool"?s:r==="String"||r?.startsWith("[")&&r.endsWith("]")?`!(${s}).isEmpty`:r==="Int"||r==="Double"?`(${s}) != 0`:`${s} != nil`},s=>t.stateNames.has(s)),n=t.mapBinds.size?nt(n,(s,r)=>`${s}["${r}"] ?? ""`):n,n=qn(n,(s,r)=>`roseJoin(${s}, ${r})`),n=nn(n,(s,r,i,o)=>{let a=r==="trim"?`roseTrim(${s})`:r==="trimStart"?`roseTrimStart(${s})`:r==="trimEnd"?`roseTrimEnd(${s})`:r==="toLowerCase"?`roseLower(${s})`:r==="toUpperCase"?`roseUpper(${s})`:r==="startsWith"?`roseHasPrefix(${s}, ${i[0]??'""'})`:r==="endsWith"?`roseHasSuffix(${s}, ${i[0]??'""'})`:`roseContains(${s}, ${i[0]??'""'})`;return o?r==="startsWith"||r==="endsWith"||r==="includes"?a:`!${a}.isEmpty`:a}),n=n.replace(/===/g,"==").replace(/!==/g,"!="),n=n.replace(/\bundefined\b/g,"nil"),n=pt(n,s=>`String(${s})`),n}function dS(e){let t={state:[],derived:[],data:[]};for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$(state|persist|kv)\b(?:<[^>]*>)?\s*\(/g))t.state.push({name:n[1],init:Hc(e,(n.index??0)+n[0].length-1)});for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$derived\b(?:<[^>]*>)?\s*\(/g))t.derived.push({name:n[1],expr:Hc(e,(n.index??0)+n[0].length-1)});for(let n of e.matchAll(/\b(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*\$data\b(?:<[^>]*>)?\s*\(/g))t.data.push(n[1]);return t}function Df(e,t){let s=new RegExp(`\\b(?:let|const|var)\\s+${Qa(t)}\\s*(?::[^=;\\n]*)?=\\s*\\$(state|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(e);return!s||s[1]==="kv"?"nil":Hc(e,s.index+s[0].length-1)}function pS(e){let t=[];for(let n of e.matchAll(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^\n;]+)/gm)){let s=n[2].trim();if(!/^\$(?:state|derived|data|kv|persist)\b/.test(s)&&!["params","csr","headers","prefetch","revalidate","buffer","bundle","hotVary","prerender","csp"].includes(n[1])){if(zc.test(s)){if(!Lf(s))continue;t.push({name:n[1],init:s});continue}/^([\[{'"`]|-?\d|true|false|null)/.test(s)&&Lf(s)&&t.push({name:n[1],init:s})}}return t}function fS(e,t,n,s){let r=e.replace(/\$query\s*\(\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g,(l,p)=>`(params[${JSON.stringify(p)}] ?? "")`).replace(/\$query\s*\(\s*\)/g,"params"),o=[...r.replace(/'(?:[^'\\]|\\.)*'/g,"''").replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/([{,]\s*)[A-Za-z_$][\w$]*\s*:/g,"$1").matchAll(/\b([A-Za-z_$][\w$]*)\b/g)].map(l=>l[1]),a=new Set(["true","false","nil","null","undefined","Math","Date","JSON","$query","$store","$kv","$cookies","$actionPending","$sessionCookie","$t","params"]);if(o.some(l=>!t.has(l)&&!a.has(l)))return n.push(`xcode: ${s}: an initializer reads module-level state - it has no view scope, so it starts nil`),"nil";let c=nt(r,(l,p)=>t.has(l)?`Self.${l}["${p}"]`:`${l}["${p}"]`),d=c.replace(/'(?:[^'\\]|\\.)*'/g,"''").replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/Self\.[A-Za-z_$][\w$]*\[[^\]]*\]/g,"");return[...t].filter(l=>new RegExp(`\\b${l}\\s*\\.`).test(r)).some(l=>new RegExp(`\\b${l}\\b`).test(d))?(n.push(`xcode: ${s}: an initializer reads module-level state - it has no view scope, so it starts nil`),"nil"):c}function Lf(e){let t=0;for(let n of e)if(n==="("||n==="["||n==="{"?t++:(n===")"||n==="]"||n==="}")&&t--,t<0)return!1;return t===0}function Hc(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="`"){for(s++;s<e.length&&e[s]!=="`";s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return e.slice(t+1,s).trim()}return""}function Qa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function po(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r==='"'||r==="'"){for(s++;s<e.length&&e[s]!==r;s++)e[s]==="\\"&&s++;continue}if(r==="("||r==="["||r==="{")n++;else if((r===")"||r==="]"||r==="}")&&(n--,n===0))return s}return-1}function hS(e,t){let n=e;for(;;){let s=n.indexOf("$setState(");if(s<0)return n;let r=s+9,i=po(n,r);if(i<0)return n;let o=Jc(n.slice(r+1,i)),a=/^['"]?(\w+)['"]?$/.exec(o[0]?.trim()??"")?.[1];if(!a)return n;let c=(o.slice(1).join(", ")||"nil").trim();n=n.slice(0,s)+a+" = "+c+n.slice(i+1)}}function gS(e,t,n,s,r,i=[]){if(!e.trim())return"";let o=e.replace(/^\s*import\s+[^;]*?from\s*['"][^'"]*['"]\s*;?\s*$/gm,"");try{o=Wv(o,{loader:"ts",format:"esm",target:"es2020"}).code}catch{r.push(`xcode: ${n.view}: the script did not parse as TypeScript - handlers are stubs`)}let a=[...t.state.map(u=>u.name),...t.derived.map(u=>u.name),...t.data];for(let u of a){let p=new RegExp(`\\b(?:let|const|var)\\s+${Qa(u)}\\s*(?::[^=;\\n]*)?=\\s*\\$(?:state|derived|data|persist|kv)\\b(?:<[^>]*>)?\\s*\\(`).exec(o);if(!p)continue;let f=p.index+p[0].length-1,h=po(o,f);h<0||(o=o.slice(0,p.index)+o.slice(h+1).replace(/^;/,""))}let c=[];try{c=Qe(e).actions.map(u=>u.name)}catch{}let d=[];for(let u of c){o=o.replace(new RegExp(`\\b(?:async\\s+)?function\\s+${Qa(u)}\\s*\\(`,"g"),`function __server_${u}(`);let l=t.state.map(p=>{let f=Ua(Df(e,p.name));return f==="Int"?` ${p.name} = roseInt(patch, "${p.name}", ${p.name})`:f==="Double"?` ${p.name} = (patch["${p.name}"] as? NSNumber)?.doubleValue ?? ${p.name}`:f==="Bool"?` ${p.name} = roseBool(patch, "${p.name}", ${p.name})`:f==="String"?` ${p.name} = roseString(patch, "${p.name}", ${p.name})`:` if let value = patch["${p.name}"] { ${p.name} = value }`}).join(`
|
|
6754
6754
|
`);d.push(` private func ${u}() async {
|
|
6755
6755
|
let patch = await roseAction(route, "${u}"${i.length?", __formFields()":""})
|
|
6756
6756
|
guard !patch.isEmpty else { return }
|
|
@@ -6763,9 +6763,9 @@ ${h}
|
|
|
6763
6763
|
|
|
6764
6764
|
`)}function mS(e){return e.split(`
|
|
6765
6765
|
`).flatMap(t=>{let n=t.trim(),s=/^if\s*\(/.exec(n);if(!s)return[t];let r=1,i=s[0].length;for(;i<n.length&&r>0&&(n[i]==="("?r++:n[i]===")"&&r--,r!==0);)i++;if(r!==0)return[t];let o=n.slice(s[0].length,i),a=n.slice(i+1).trim().replace(/;$/,"");return!o||!a?[t]:[`if (${o}) {`,` ${a}`,"}"]}).join(`
|
|
6766
|
-
`)}function yS(e,t){let n=e;for(let s of e.matchAll(/(?:\$setState|__set)\s*\(\s*(['"])([^'"]*)\1\s*,/g)){let r=s.index??0,i=r+s[0].indexOf("("),o=po(e,i);if(o<0)continue;let a=e.slice(r+s[0].length,o).trim();if(/^(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(a)||a.includes("...")||!/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(a))continue;let c=t(s[2],a);if(c===null)continue;let d=o+1;e[d]===";"&&d++,n=n.replace(e.slice(r,d),()=>c)}return n}function bS(e,t,n){let s=e;for(let r of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let i=r[1],o=t(i);if(!o)continue;let a=r.index??0,c=a+r[0].length-1,d=po(e,c);if(d<0)continue;let u=e.slice(c+1,d).trim();if(/^(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(u)||u.includes("...")||!/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(u))continue;let l=n(o,u);if(l===null)continue;let p=d+1;e[p]===";"&&p++,s=s.replace(e.slice(a,p),()=>l)}return s}function $S(e,t,n,s,r){if(e=zt(e,{target:"xcode",options:d=>{let u=Dt(d,"bare");return u===null?null:Vc(u)},empty:"nil",file:t,warn:d=>r.push(`xcode: ${d}`)}).code,e=sn(e),/\bFormData\(|\bdocument\.|\bwindow\./.test(e))return r.push(`xcode: ${t}: a handler touches the DOM/FormData, which has no SwiftUI equivalent - emitted as a stub`)," //
|
|
6766
|
+
`)}function yS(e,t){let n=e;for(let s of e.matchAll(/(?:\$setState|__set)\s*\(\s*(['"])([^'"]*)\1\s*,/g)){let r=s.index??0,i=r+s[0].indexOf("("),o=po(e,i);if(o<0)continue;let a=e.slice(r+s[0].length,o).trim();if(/^(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(a)||a.includes("...")||!/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(a))continue;let c=t(s[2],a);if(c===null)continue;let d=o+1;e[d]===";"&&d++,n=n.replace(e.slice(r,d),()=>c)}return n}function bS(e,t,n){let s=e;for(let r of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let i=r[1],o=t(i);if(!o)continue;let a=r.index??0,c=a+r[0].length-1,d=po(e,c);if(d<0)continue;let u=e.slice(c+1,d).trim();if(/^(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(u)||u.includes("...")||!/\.(?:map|filter|reduce|find|some|every|slice|concat|join|split|indexOf|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(u))continue;let l=n(o,u);if(l===null)continue;let p=d+1;e[p]===";"&&p++,s=s.replace(e.slice(a,p),()=>l)}return s}function $S(e,t,n,s,r){if(e=zt(e,{target:"xcode",options:d=>{let u=Dt(d,"bare");return u===null?null:Vc(u)},empty:"nil",file:t,warn:d=>r.push(`xcode: ${d}`)}).code,e=sn(e),/\bFormData\(|\bdocument\.|\bwindow\./.test(e))return r.push(`xcode: ${t}: a handler touches the DOM/FormData, which has no SwiftUI equivalent - emitted as a stub`)," // rosefc: handler body not translated (web-only API).";let i=Ot(e);i=tn(i),i=rn(i,(d,u,l)=>{let p=G(l,Er,new Set([u]));if(p===null)return null;let f=`${d}()`;return`${d} = ${p}`.replace(new RegExp(`\\b${u}\\b`,"g"),f)}),i=on(i,(d,u)=>{let l=G(u,Er,new Set);return l===null?null:`${d} = ${l}`}),i=Kn(i,d=>{let u=d.slice(3,4).toLowerCase()+d.slice(4);return d.length>3&&n.includes(u)?u:null},(d,u)=>{let l=G(u,Er,new Set);return l===null?null:`${d} = ${l}`}),i=bS(i,d=>{let u=d.slice(3,4).toLowerCase()+d.slice(4);return d.length>3&&n.includes(u)?u:null},(d,u)=>{let l=G(u,Er,new Set);return l===null?null:`${d} = ${l}`}),i=yS(i,(d,u)=>{let l=G(u,Er,new Set);return l===null?null:`${d} = ${l}`}),i=Gn(i,(d,u,l,p)=>d==="append"?`${u} = (${l}) + [ ${p} ]`:`${u} = [ ${p} ] + (${l})`,d=>{let u=d.slice(3,4).toLowerCase()+d.slice(4);return d.length>3&&n.includes(u)?u:null});let o=hS(i.trim(),new Set(n));o=o.replace(/\bawait\s+/g,""),o=o.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(d,u,l)=>`${l}()`),o=o.replace(/\brefresh\s*\(\s*\)/g,"/* refresh: the data channel reloads on navigation */"),o=o.replace(/\bconsole\.(?:log|warn|error)\(/g,"print("),o=o.replace(/\.length\b/g,".count"),o=o.replace(/\bString\(/g,"String("),o=o.replace(/\bnull\b/g,"nil").replace(/\bundefined\b/g,"nil"),o=o.replace(/'((?:[^'\\\\]|\\\\.)*)'/g,'"$1"');let a=new Set(n);o=o.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(d,u)=>a.has(u)?u:d);for(let d of a){let u=d.charAt(0).toUpperCase()+d.slice(1);o=o.replace(new RegExp(`\\bset${u}\\s*\\(`,"g"),`${d} = `)}if(o=pt(o,d=>`String(describing: ${d})`),s.size&&(o=nt(o,(d,u)=>s.has(d)?`Self.${d}["${u}"]`:`${d}.${u}`)),o=o.replace(/\$formRead\(\s*(['"])([^'"]*)\1\s*\)/g,(d,u,l)=>l),o=o.replace(/\.trim\(\)/g,".trimmingCharacters(in: .whitespaces)"),o=o.replace(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,"let $1 ="),o=Rn(o,d=>`!${d}.isEmpty`),o=At(o,d=>`!(${d}).isEmpty`,()=>!0),o=mS(o),/=>/.test(o))return r.push(`xcode: ${t}: a handler uses an arrow function, which has no direct Swift equivalent here - emitted as a stub`)," // rosefc: handler body not translated (uses an arrow function).";let c=o.split(`
|
|
6767
6767
|
`).map(d=>d.trim()).filter(Boolean);return c.length?c.map(d=>" "+d).join(`
|
|
6768
|
-
`):" //
|
|
6768
|
+
`):" // rosefc: an empty handler."}function zf(e){return[...(e??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)].map(t=>({name:t[1],init:t[2].trim()}))}function wS(e,t,n,s){let r=[...(e.script??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)/g)].map(u=>u[1]),i={warnings:n,file:e.view,stateNames:new Set(r),mapBinds:new Set,components:[],lines:[],depth:3,sheet:Te([e.style,ke].filter(u=>u&&u.trim()).join(`
|
|
6769
6769
|
`)),ancestors:[],fontMap:s,assets:t,vectors:new Map,navigate:"onNavigate",awaits:[],scriptConsts:new Map,componentProps:new Set(r),inline:new Map,inlineBodies:[],deferred:[],forms:[],pageAction:null};js(e.nodes,i);let o=new Map(zf(e.script).map(u=>[u.name,dr(u.init)])),a=r.map(u=>` var ${u}: Any? = ${o.get(u)??"nil"}`).join(`
|
|
6770
6770
|
`),c=gn(e.nodes,r);for(let u of c)a+=`
|
|
6771
6771
|
var ${ze(u)}: (Any?) -> Void = { _ in }`;e.slots.hasDefault&&(a+=`
|
|
@@ -6826,11 +6826,11 @@ ${l}
|
|
|
6826
6826
|
|
|
6827
6827
|
/* Begin PBXFileReference section */
|
|
6828
6828
|
${u}
|
|
6829
|
-
${g} /*
|
|
6829
|
+
${g} /* RosefcApp.app */ = {
|
|
6830
6830
|
isa = PBXFileReference;
|
|
6831
6831
|
explicitFileType = wrapper.application;
|
|
6832
6832
|
includeInIndex = 0;
|
|
6833
|
-
path =
|
|
6833
|
+
path = RosefcApp.app;
|
|
6834
6834
|
sourceTree = BUILT_PRODUCTS_DIR;
|
|
6835
6835
|
};
|
|
6836
6836
|
${m} /* Assets.xcassets */ = {
|
|
@@ -6842,12 +6842,12 @@ ${u}
|
|
|
6842
6842
|
/* End PBXFileReference section */
|
|
6843
6843
|
|
|
6844
6844
|
/* Begin PBXGroup section */
|
|
6845
|
-
${y} /*
|
|
6845
|
+
${y} /* RosefcApp */ = {
|
|
6846
6846
|
isa = PBXGroup;
|
|
6847
6847
|
children = (
|
|
6848
6848
|
${d.map($=>` ${$},`).join(`
|
|
6849
6849
|
`)}
|
|
6850
|
-
${g} /*
|
|
6850
|
+
${g} /* RosefcApp.app */,
|
|
6851
6851
|
);
|
|
6852
6852
|
sourceTree = "<group>";
|
|
6853
6853
|
};
|
|
@@ -6856,9 +6856,9 @@ ${c.join(`
|
|
|
6856
6856
|
/* End PBXGroup section */
|
|
6857
6857
|
|
|
6858
6858
|
/* Begin PBXNativeTarget section */
|
|
6859
|
-
${h} /*
|
|
6859
|
+
${h} /* RosefcApp */ = {
|
|
6860
6860
|
isa = PBXNativeTarget;
|
|
6861
|
-
buildConfigurationList = ${et("configList:target")} /* Build configuration list for PBXNativeTarget "
|
|
6861
|
+
buildConfigurationList = ${et("configList:target")} /* Build configuration list for PBXNativeTarget "RosefcApp" */;
|
|
6862
6862
|
buildPhases = (
|
|
6863
6863
|
${et("phase:sources")} /* Sources */,
|
|
6864
6864
|
${et("phase:resources")} /* Resources */,
|
|
@@ -6867,9 +6867,9 @@ ${c.join(`
|
|
|
6867
6867
|
);
|
|
6868
6868
|
dependencies = (
|
|
6869
6869
|
);
|
|
6870
|
-
name =
|
|
6871
|
-
productName =
|
|
6872
|
-
productReference = ${g} /*
|
|
6870
|
+
name = RosefcApp;
|
|
6871
|
+
productName = RosefcApp;
|
|
6872
|
+
productReference = ${g} /* RosefcApp.app */;
|
|
6873
6873
|
productType = "com.apple.product-type.application";
|
|
6874
6874
|
};
|
|
6875
6875
|
/* End PBXNativeTarget section */
|
|
@@ -6881,7 +6881,7 @@ ${c.join(`
|
|
|
6881
6881
|
BuildIndependentTargetsInParallel = 1;
|
|
6882
6882
|
LastSwiftUpdateCheck = 1500;
|
|
6883
6883
|
};
|
|
6884
|
-
buildConfigurationList = ${et("configList:project")} /* Build configuration list for PBXProject "
|
|
6884
|
+
buildConfigurationList = ${et("configList:project")} /* Build configuration list for PBXProject "RosefcApp" */;
|
|
6885
6885
|
compatibilityVersion = "Xcode 14.0";
|
|
6886
6886
|
developmentRegion = en;
|
|
6887
6887
|
hasScannedForEncodings = 0;
|
|
@@ -6894,7 +6894,7 @@ ${c.join(`
|
|
|
6894
6894
|
projectDirPath = "";
|
|
6895
6895
|
projectRoot = "";
|
|
6896
6896
|
targets = (
|
|
6897
|
-
${h} /*
|
|
6897
|
+
${h} /* RosefcApp */,
|
|
6898
6898
|
);
|
|
6899
6899
|
};
|
|
6900
6900
|
/* End PBXProject section */
|
|
@@ -6945,8 +6945,8 @@ ${p}
|
|
|
6945
6945
|
buildSettings = {
|
|
6946
6946
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
|
6947
6947
|
GENERATE_INFOPLIST_FILE = NO;
|
|
6948
|
-
INFOPLIST_FILE =
|
|
6949
|
-
PRODUCT_BUNDLE_IDENTIFIER = dev.
|
|
6948
|
+
INFOPLIST_FILE = RosefcApp/Info.plist;
|
|
6949
|
+
PRODUCT_BUNDLE_IDENTIFIER = dev.rosefc.app;
|
|
6950
6950
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
6951
6951
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
6952
6952
|
TARGETED_DEVICE_FAMILY = "1,2";
|
|
@@ -6958,8 +6958,8 @@ ${p}
|
|
|
6958
6958
|
buildSettings = {
|
|
6959
6959
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
|
6960
6960
|
GENERATE_INFOPLIST_FILE = NO;
|
|
6961
|
-
INFOPLIST_FILE =
|
|
6962
|
-
PRODUCT_BUNDLE_IDENTIFIER = dev.
|
|
6961
|
+
INFOPLIST_FILE = RosefcApp/Info.plist;
|
|
6962
|
+
PRODUCT_BUNDLE_IDENTIFIER = dev.rosefc.app;
|
|
6963
6963
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
6964
6964
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
6965
6965
|
TARGETED_DEVICE_FAMILY = "1,2";
|
|
@@ -6969,7 +6969,7 @@ ${p}
|
|
|
6969
6969
|
/* End XCBuildConfiguration section */
|
|
6970
6970
|
|
|
6971
6971
|
/* Begin XCConfigurationList section */
|
|
6972
|
-
${et("configList:project")} /* Build configuration list for PBXProject "
|
|
6972
|
+
${et("configList:project")} /* Build configuration list for PBXProject "RosefcApp" */ = {
|
|
6973
6973
|
isa = XCConfigurationList;
|
|
6974
6974
|
buildConfigurations = (
|
|
6975
6975
|
${et("config:project:debug")} /* Debug */,
|
|
@@ -6978,7 +6978,7 @@ ${p}
|
|
|
6978
6978
|
defaultConfigurationIsVisible = 0;
|
|
6979
6979
|
defaultConfigurationName = Release;
|
|
6980
6980
|
};
|
|
6981
|
-
${et("configList:target")} /* Build configuration list for PBXNativeTarget "
|
|
6981
|
+
${et("configList:target")} /* Build configuration list for PBXNativeTarget "RosefcApp" */ = {
|
|
6982
6982
|
isa = XCConfigurationList;
|
|
6983
6983
|
buildConfigurations = (
|
|
6984
6984
|
${et("config:target:debug")} /* Debug */,
|
|
@@ -6991,16 +6991,16 @@ ${p}
|
|
|
6991
6991
|
};
|
|
6992
6992
|
rootObject = ${f} /* Project object */;
|
|
6993
6993
|
}
|
|
6994
|
-
`}function et(e){let t=2166136261,n=16777619;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0,n=Math.imul(n^e.charCodeAt(o),2246822507)>>>0;let s=t.toString(16).padStart(8,"0"),r=n.toString(16).padStart(8,"0"),i=((t^n)>>>0).toString(16).padStart(8,"0");return(s+r+i).toUpperCase()}function Hf(e){let t=[];for(let n of je.readdirSync(e,{withFileTypes:!0})){let s=be.join(e,n.name);n.isDirectory()?t.push(...Hf(s)):t.push(s)}return t}var co,Dv,zv,Ga,Dc,Gv,zc,Er,Vf=De(()=>{"use strict";Un();kn();vs();_s();xs();hn();gs();_a();ls();ks();co="
|
|
6994
|
+
`}function et(e){let t=2166136261,n=16777619;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0,n=Math.imul(n^e.charCodeAt(o),2246822507)>>>0;let s=t.toString(16).padStart(8,"0"),r=n.toString(16).padStart(8,"0"),i=((t^n)>>>0).toString(16).padStart(8,"0");return(s+r+i).toUpperCase()}function Hf(e){let t=[];for(let n of je.readdirSync(e,{withFileTypes:!0})){let s=be.join(e,n.name);n.isDirectory()?t.push(...Hf(s)):t.push(s)}return t}var co,Dv,zv,Ga,Dc,Gv,zc,Er,Vf=De(()=>{"use strict";Un();kn();vs();_s();xs();hn();gs();_a();ls();ks();co="RosefcApp",Dv=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),zv=new Set(["header","footer","nav"]),Ga=new Map;Dc=390;Gv={left:".leading",center:".center",right:".trailing",justify:".justified"};zc=/^(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\S/;Er={get:(e,t)=>`((${e}) as? [String: Any])?["${t}"]`,count:e=>`roseCount(${e})`,bool:e=>`roseBool(${e})`,merge:(e,t)=>`roseMerge(${e}, ${t})`,obj:e=>`[${e.map(([t,n])=>`"${t}": ${n}`).join(", ")}]`,map:(e,t,n)=>t.length>1?`roseMapIdx(${e}) { ${t[0]}, ${t[1]} in ${n} }`:`roseMap(${e}) { ${t[0]} in ${n} }`,filter:(e,t,n)=>`roseFilter(${e}) { ${t[0]} in ${n} }`,reduce:(e,t,n,s)=>s===null?`roseReduce(${e}) { ${t[0]}, ${t[1]} in ${n} }`:`roseReduce(${e}, ${s}) { ${t[0]}, ${t[1]} in ${n} }`,append:(e,t)=>`roseAppend(${e}, ${t})`,concat:(e,t)=>`roseConcat(${e}, ${t})`,arr:e=>`roseArr(${e.join(", ")})`,not:e=>`!roseBool(${e})`,lit:e=>e,template:e=>'"'+e.map(t=>"expr"in t?/^([A-Za-z_$][\w$]*)$/.test(t.expr)?`\\(${t.expr})`:`\\((${t.expr}))`:t.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"')).join("")+'"',index:(e,t)=>`roseIndex(${e}, ${t})`,nullish:(e,t)=>`(${e}) ?? (${t})`,optChain:(e,t)=>`((${e}) as? [String: Any])?["${t}"]`,join:(e,t)=>`roseJoin(${e}, ${t})`,split:(e,t)=>`roseSplit(${e}, ${t})`,indexOf:(e,t)=>`roseIndexOf(${e}, ${t})`,every:(e,t,n)=>`roseEvery(${e}) { ${t[0]} in ${n} }`,find:(e,t,n)=>`roseFind(${e}) { ${t[0]} in ${n} }`,some:(e,t,n)=>`roseAny(${e}) { ${t[0]} in ${n} }`,slice:(e,t,n)=>n===null?`roseSlice(${e}, ${t})`:`roseSlice(${e}, ${t}, ${n})`,startsWith:(e,t)=>`roseHasPrefix(${e}, ${t})`,endsWith:(e,t)=>`roseHasSuffix(${e}, ${t})`,upper:e=>`roseUpper(${e})`,lower:e=>`roseLower(${e})`}});import*as Xt from"node:fs";import*as Jf from"node:os";import*as Nn from"node:path";async function Uf(e){let t=Nn.join(e.outDir,"electron");await Xt.promises.rm(t,{recursive:!0,force:!0}),await Xt.promises.mkdir(t,{recursive:!0});let n=Nn.join(t,"dist");{let c=Xt.mkdtempSync(Nn.join(Jf.tmpdir(),"rosefc-electron-"));try{await Uo(e.projectRoot,c,{}),await qf(c,n),e.warnings.push("electron: built the project from source into the export (the shell serves the static half; --api proxies the dynamic half)")}catch(d){e.warnings.push(`electron: the project did not build (${String(d?.message??d).slice(0,120)}) - run \`rosefc build\` and re-export`),await Xt.promises.mkdir(n,{recursive:!0}),await Xt.promises.writeFile(Nn.join(n,"index.html"),`<!DOCTYPE html>
|
|
6995
6995
|
<html lang="en">
|
|
6996
|
-
<head><meta charset="utf-8"><title>
|
|
6996
|
+
<head><meta charset="utf-8"><title>Rosefc</title></head>
|
|
6997
6997
|
<body style="font-family: system-ui; padding: 2rem">
|
|
6998
|
-
<h1>
|
|
6999
|
-
<p>The build failed. Fix the errors shown by <code>
|
|
6998
|
+
<h1>Rosefc desktop shell</h1>
|
|
6999
|
+
<p>The build failed. Fix the errors shown by <code>rosefc build</code>, then <code>rosefc export electron</code> again.</p>
|
|
7000
7000
|
</body>
|
|
7001
7001
|
</html>
|
|
7002
|
-
`,"utf8")}finally{Xt.rmSync(c,{recursive:!0,force:!0})}}await Xt.promises.writeFile(Nn.join(t,"package.json"),JSON.stringify({name:"
|
|
7003
|
-
`,"utf8"),await Xt.promises.writeFile(Nn.join(t,"main.cjs"),xS(e.apiBase??""),"utf8");let s=await Ye(e.projectRoot),r=await Ke(e.projectRoot),i=xt(await Promise.all([...s,...r].map(c=>Xt.promises.readFile(c,"utf8"))));await Xt.promises.writeFile(Nn.join(t,"preload.cjs"),SS(i),"utf8"),await Xt.promises.writeFile(Nn.join(t,"README.md"),_S(e.apiBase??""),"utf8");let o=s.map(c=>Nn.basename(c,".rose")),a=r.map(c=>Nn.basename(c,".rose"));return{pages:o,components:a}}function SS(e){return e.length?`//
|
|
7002
|
+
`,"utf8")}finally{Xt.rmSync(c,{recursive:!0,force:!0})}}await Xt.promises.writeFile(Nn.join(t,"package.json"),JSON.stringify({name:"rosefc-desktop",version:"1.0.0",private:!0,description:"A Rosefc app, exported with rosefc export electron",main:"main.cjs",scripts:{start:"electron .",dev:"electron ."},devDependencies:{electron:"^31.0.0"}},null,2)+`
|
|
7003
|
+
`,"utf8"),await Xt.promises.writeFile(Nn.join(t,"main.cjs"),xS(e.apiBase??""),"utf8");let s=await Ye(e.projectRoot),r=await Ke(e.projectRoot),i=xt(await Promise.all([...s,...r].map(c=>Xt.promises.readFile(c,"utf8"))));await Xt.promises.writeFile(Nn.join(t,"preload.cjs"),SS(i),"utf8"),await Xt.promises.writeFile(Nn.join(t,"README.md"),_S(e.apiBase??""),"utf8");let o=s.map(c=>Nn.basename(c,".rose")),a=r.map(c=>Nn.basename(c,".rose"));return{pages:o,components:a}}function SS(e){return e.length?`// Rosefc - the capability bridge.
|
|
7004
7004
|
//
|
|
7005
7005
|
// This shell ships the framework's real web bundle untouched, where
|
|
7006
7006
|
// useNative(...) is a bare call the page's own world never defines. The
|
|
@@ -7079,21 +7079,21 @@ ${e.includes("camera")?` if (capability === 'camera') {
|
|
|
7079
7079
|
`:`// Deliberately empty: the renderer gets no Node surface.
|
|
7080
7080
|
// The document is the framework's own one-request page, so a preload bridge
|
|
7081
7081
|
// would only widen the attack surface. Add your own if the app needs one.
|
|
7082
|
-
`}async function qf(e,t){await Xt.promises.mkdir(t,{recursive:!0});for(let n of await Xt.promises.readdir(e,{withFileTypes:!0})){if(n.name.endsWith(".br"))continue;let s=Nn.join(e,n.name),r=Nn.join(t,n.name);n.isDirectory()?await qf(s,r):await Xt.promises.copyFile(s,r)}}function _S(e){return`#
|
|
7082
|
+
`}async function qf(e,t){await Xt.promises.mkdir(t,{recursive:!0});for(let n of await Xt.promises.readdir(e,{withFileTypes:!0})){if(n.name.endsWith(".br"))continue;let s=Nn.join(e,n.name),r=Nn.join(t,n.name);n.isDirectory()?await qf(s,r):await Xt.promises.copyFile(s,r)}}function _S(e){return`# Rosefc -> Electron
|
|
7083
7083
|
|
|
7084
|
-
Generated by \`
|
|
7084
|
+
Generated by \`rosefc export electron\` from the project's built site.
|
|
7085
7085
|
|
|
7086
7086
|
- \`npm install && npm start\` (installs the one devDependency, Electron)
|
|
7087
7087
|
- The shell serves \`dist/\` from a tiny in-process server and opens it in a
|
|
7088
7088
|
hardened window (contextIsolation, no Node in the renderer).
|
|
7089
7089
|
- Dynamic half (server actions, unbaked \`/api\`): export with
|
|
7090
|
-
\`
|
|
7090
|
+
\`rosefc export electron --api <base>\` to proxy those requests to the deployed
|
|
7091
7091
|
Rose server. Current: \`${e||"(unset - static half only)"}\`
|
|
7092
7092
|
|
|
7093
|
-
Re-run \`
|
|
7093
|
+
Re-run \`rosefc export electron\` after every \`rosefc build\` to refresh \`dist/\`.
|
|
7094
7094
|
`}function xS(e){return`'use strict';
|
|
7095
7095
|
|
|
7096
|
-
//
|
|
7096
|
+
// Rosefc - the exported desktop shell.
|
|
7097
7097
|
//
|
|
7098
7098
|
// 1. serve the built site from an in-process static server (the same dist/ the
|
|
7099
7099
|
// web build produces, so the desktop app IS the web app);
|
|
@@ -7171,7 +7171,7 @@ function renderViaSsr(req, res) {
|
|
|
7171
7171
|
.then((m) => { renderPage = m.renderPage; renderViaSsr(req, res); })
|
|
7172
7172
|
.catch((e) => {
|
|
7173
7173
|
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
7174
|
-
res.end('no index.html and no server.js in dist/ - run
|
|
7174
|
+
res.end('no index.html and no server.js in dist/ - run rosefc build and re-export\\n' + e);
|
|
7175
7175
|
});
|
|
7176
7176
|
return;
|
|
7177
7177
|
}
|
|
@@ -7196,7 +7196,7 @@ function proxy(req, res) {
|
|
|
7196
7196
|
});
|
|
7197
7197
|
upstream.on('error', () => {
|
|
7198
7198
|
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
7199
|
-
res.end('
|
|
7199
|
+
res.end('Rosefc: the dynamic half is unreachable (API_BASE=' + API_BASE + ')');
|
|
7200
7200
|
});
|
|
7201
7201
|
req.pipe(upstream);
|
|
7202
7202
|
}
|
|
@@ -7204,11 +7204,11 @@ function proxy(req, res) {
|
|
|
7204
7204
|
function startServer(done) {
|
|
7205
7205
|
const server = http.createServer((req, res) => {
|
|
7206
7206
|
if (!req.url || req.method === 'OPTIONS') { res.writeHead(204).end(); return; }
|
|
7207
|
-
const dynamic = req.method !== 'GET' || req.url.startsWith('/api/') || req.url.startsWith('/
|
|
7207
|
+
const dynamic = req.method !== 'GET' || req.url.startsWith('/api/') || req.url.startsWith('/__rosefc/');
|
|
7208
7208
|
if (dynamic && API_BASE) { proxy(req, res); return; }
|
|
7209
7209
|
if (dynamic) {
|
|
7210
7210
|
res.writeHead(405, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
7211
|
-
res.end('
|
|
7211
|
+
res.end('Rosefc: this shell is the static half - export with --api for server actions');
|
|
7212
7212
|
return;
|
|
7213
7213
|
}
|
|
7214
7214
|
const file = safePath(req.url);
|
|
@@ -7461,7 +7461,7 @@ ${t||" // no style rules"}
|
|
|
7461
7461
|
if (style != null) {
|
|
7462
7462
|
// R257: the child stamp the Flex manager reads its margins and grow
|
|
7463
7463
|
// weights from; the panel itself paints through applyBox.
|
|
7464
|
-
panel.putClientProperty("
|
|
7464
|
+
panel.putClientProperty("rosefc.style", style);
|
|
7465
7465
|
if (style.isFlex()) panel.setLayout(new Flex(style.direction, style.gap, style.justify, style.items));
|
|
7466
7466
|
else panel.setLayout(new BoxLayout(panel, horizontal ? BoxLayout.X_AXIS : BoxLayout.Y_AXIS));
|
|
7467
7467
|
} else panel.setLayout(new BoxLayout(panel, horizontal ? BoxLayout.X_AXIS : BoxLayout.Y_AXIS));
|
|
@@ -7519,7 +7519,7 @@ ${t||" // no style rules"}
|
|
|
7519
7519
|
style.maxWidth > 0 ? style.maxWidth : Math.max(style.minWidth, d.width),
|
|
7520
7520
|
style.maxHeight > 0 ? style.maxHeight : Math.max(style.minHeight, d.height)));
|
|
7521
7521
|
}
|
|
7522
|
-
widget.putClientProperty("
|
|
7522
|
+
widget.putClientProperty("rosefc.style", style);
|
|
7523
7523
|
if (style.zIndex != 0 && widget.getParent() instanceof javax.swing.JLayeredPane pane) {
|
|
7524
7524
|
pane.setLayer(widget, Math.max(0, Math.min(999, style.zIndex + 500)));
|
|
7525
7525
|
}
|
|
@@ -7737,7 +7737,7 @@ ${t||" // no style rules"}
|
|
|
7737
7737
|
}
|
|
7738
7738
|
|
|
7739
7739
|
/** One cascaded style, on whatever widget the element became. The three
|
|
7740
|
-
* Swing widget families a
|
|
7740
|
+
* Swing widget families a rosefc element maps to each have their own
|
|
7741
7741
|
* painter, so the style is handed to the one that fits. */
|
|
7742
7742
|
public static void apply(JComponent widget, Style style) {
|
|
7743
7743
|
if (widget == null || style == null) return;
|
|
@@ -7775,7 +7775,7 @@ ${t||" // no style rules"}
|
|
|
7775
7775
|
if (style.lineHeight != 1) {
|
|
7776
7776
|
widget.setFont(widget.getFont().deriveFont((float) (widget.getFont().getSize2D() * style.lineHeight)));
|
|
7777
7777
|
}
|
|
7778
|
-
widget.putClientProperty("
|
|
7778
|
+
widget.putClientProperty("rosefc.style", style);
|
|
7779
7779
|
}
|
|
7780
7780
|
|
|
7781
7781
|
/** R199: a button the stylesheet owns - type, colour, background, border
|
|
@@ -7846,7 +7846,7 @@ ${t||" // no style rules"}
|
|
|
7846
7846
|
* and carries one - otherwise no spacing is reserved for it. */
|
|
7847
7847
|
private static int[] margins(Component c) {
|
|
7848
7848
|
if (c instanceof JComponent j) {
|
|
7849
|
-
Object s = j.getClientProperty("
|
|
7849
|
+
Object s = j.getClientProperty("rosefc.style");
|
|
7850
7850
|
if (s instanceof Style style) return new int[]{style.marginTop, style.marginRight, style.marginBottom, style.marginLeft};
|
|
7851
7851
|
}
|
|
7852
7852
|
return new int[]{0, 0, 0, 0};
|
|
@@ -7856,7 +7856,7 @@ ${t||" // no style rules"}
|
|
|
7856
7856
|
* it packs - the flex the stylesheet asked for. */
|
|
7857
7857
|
private static double grow(Component c) {
|
|
7858
7858
|
if (c instanceof JComponent j) {
|
|
7859
|
-
Object s = j.getClientProperty("
|
|
7859
|
+
Object s = j.getClientProperty("rosefc.style");
|
|
7860
7860
|
if (s instanceof Style style && style.grow > 0) return style.grow;
|
|
7861
7861
|
}
|
|
7862
7862
|
return 0;
|
|
@@ -8033,7 +8033,7 @@ ${t||" // no style rules"}
|
|
|
8033
8033
|
style.maxWidth > 0 ? style.maxWidth : Math.max(style.minWidth, d.width),
|
|
8034
8034
|
style.maxHeight > 0 ? style.maxHeight : Math.max(style.minHeight, d.height)));
|
|
8035
8035
|
}
|
|
8036
|
-
label.putClientProperty("
|
|
8036
|
+
label.putClientProperty("rosefc.style", style);
|
|
8037
8037
|
}
|
|
8038
8038
|
|
|
8039
8039
|
public static JButton button(JPanel parent, String text, ActionListener onClick) {
|
|
@@ -8576,7 +8576,7 @@ ${s}${PS(n)}
|
|
|
8576
8576
|
public static Map<String, Object> data(String route) {
|
|
8577
8577
|
if (API_BASE.isEmpty()) return new LinkedHashMap<>();
|
|
8578
8578
|
try {
|
|
8579
|
-
String body = request(API_BASE + "/
|
|
8579
|
+
String body = request(API_BASE + "/__rosefc/data?path=" + URLEncoder.encode(route, "UTF-8"), "GET", null);
|
|
8580
8580
|
Object parsed = Json.parse(body);
|
|
8581
8581
|
if (parsed instanceof Map) {
|
|
8582
8582
|
Object state = ((Map<String, Object>) parsed).get("state");
|
|
@@ -8758,7 +8758,7 @@ import java.util.*;
|
|
|
8758
8758
|
/** The frame, the shared state and the route table. */
|
|
8759
8759
|
public final class RoseApp {
|
|
8760
8760
|
private static final String[] PERSIST_KEYS = {${t}};
|
|
8761
|
-
private final JFrame frame = new JFrame("
|
|
8761
|
+
private final JFrame frame = new JFrame("Rosefc");
|
|
8762
8762
|
private final Map<String, Object> state = new LinkedHashMap<>();
|
|
8763
8763
|
private final Map<String, String> params = new LinkedHashMap<>();
|
|
8764
8764
|
private final Set<String> loadedRoutes = new HashSet<>();
|
|
@@ -8775,7 +8775,7 @@ public final class RoseApp {
|
|
|
8775
8775
|
// A $persist field starts from Preferences when it has been written
|
|
8776
8776
|
// before - that is what makes it survive a restart.
|
|
8777
8777
|
for (String key : persisted) {
|
|
8778
|
-
String saved = prefs.get("
|
|
8778
|
+
String saved = prefs.get("rosefc:" + key, null);
|
|
8779
8779
|
if (saved != null) state.put(key, saved);
|
|
8780
8780
|
}
|
|
8781
8781
|
// Alt+Left / Escape replays the previous route - matches the web back gesture.
|
|
@@ -8799,7 +8799,7 @@ public final class RoseApp {
|
|
|
8799
8799
|
|
|
8800
8800
|
public void set(String key, Object value) {
|
|
8801
8801
|
state.put(key, value);
|
|
8802
|
-
if (persisted.contains(key)) prefs.put("
|
|
8802
|
+
if (persisted.contains(key)) prefs.put("rosefc:" + key, String.valueOf(value));
|
|
8803
8803
|
}
|
|
8804
8804
|
|
|
8805
8805
|
public String param(String key) {
|
|
@@ -8865,8 +8865,8 @@ ${n.join(`
|
|
|
8865
8865
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
8866
8866
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
8867
8867
|
<modelVersion>4.0.0</modelVersion>
|
|
8868
|
-
<groupId>dev.
|
|
8869
|
-
<artifactId>
|
|
8868
|
+
<groupId>dev.rosefc</groupId>
|
|
8869
|
+
<artifactId>rosefc-desktop</artifactId>
|
|
8870
8870
|
<version>1.0.0</version>
|
|
8871
8871
|
<packaging>jar</packaging>
|
|
8872
8872
|
|
|
@@ -8885,7 +8885,7 @@ ${n.join(`
|
|
|
8885
8885
|
<configuration>
|
|
8886
8886
|
<archive>
|
|
8887
8887
|
<manifest>
|
|
8888
|
-
<mainClass>dev.
|
|
8888
|
+
<mainClass>dev.rosefc.app.Main</mainClass>
|
|
8889
8889
|
</manifest>
|
|
8890
8890
|
</archive>
|
|
8891
8891
|
</configuration>
|
|
@@ -8893,14 +8893,14 @@ ${n.join(`
|
|
|
8893
8893
|
</plugins>
|
|
8894
8894
|
</build>
|
|
8895
8895
|
</project>
|
|
8896
|
-
`}function DS(e,t,n,s){return`#
|
|
8896
|
+
`}function DS(e,t,n,s){return`# Rosefc -> Java desktop (Swing, stdlib only)
|
|
8897
8897
|
|
|
8898
|
-
Generated by \`
|
|
8898
|
+
Generated by \`rosefc export java\` from the project's \`.rose\` pages.
|
|
8899
8899
|
|
|
8900
8900
|
- ${t} page(s), ${n} component(s)
|
|
8901
|
-
- Build: \`mvn package\`, run: \`java -jar target/
|
|
8901
|
+
- Build: \`mvn package\`, run: \`java -jar target/rosefc-desktop-1.0.0.jar\`
|
|
8902
8902
|
(or open the folder in IntelliJ IDEA / Eclipse / VS Code)
|
|
8903
|
-
- Server: \`
|
|
8903
|
+
- Server: \`rosefc export java --api <base>\` writes the base URL into
|
|
8904
8904
|
\`src/main/java/${Za}/RoseKit.java\`. Current: \`${e||"(unset)"}\`
|
|
8905
8905
|
|
|
8906
8906
|
State lives in the app's map, a handler mutates it and re-renders, and the data
|
|
@@ -8955,9 +8955,9 @@ ${h}
|
|
|
8955
8955
|
app.render();
|
|
8956
8956
|
}`)}return c.join(`
|
|
8957
8957
|
|
|
8958
|
-
`)}function YS(e,t){let n=e[t],s=t+1;for(;s<e.length&&e[s]!==n;)e[s]==="\\"&&s++,s++;return Math.min(s+1,e.length)}function nh(e,t){let n=e[t];for(let s=t-1;s>=0;s--){if(e[s]!==n)continue;let r=0,i=s-1;for(;i>=0&&e[i]==="\\";)r++,i--;if(r%2===0)return s}return 0}function Kc(e,t){let n=t;for(;;){for(;n>0&&/[\w$]/.test(e[n-1]);)n--;if(n>=2&&e[n-1]==="."&&/[\w$]/.test(e[n-2])){n-=1;continue}return n}}function e_(e){let t=e.length;for(;t>0&&e[t-1]===" ";)t--;if(t===0)return-1;let n=e[t-1];if(n==='"'||n==="'")return Kc(e,nh(e,t-1));if(n===")"){let s=0;for(let r=t-1;r>=0;r--){let i=e[r];if(i==='"'||i==="'"){r=nh(e,r);continue}if(i===")")s++;else if(i==="("&&--s===0)return Kc(e,r)}return-1}return/[\w$\]]/.test(n)?Kc(e,t):-1}function t_(e,t){let n=["join","split","indexOf","every","startsWith","endsWith","toUpperCase","toLowerCase"],s="",r=0;for(;r<e.length;){let i=e[r];if(i==='"'||i==="'"||i==="`"){let a=YS(e,r);s+=e.slice(r,a),r=a;continue}let o=i==="."?n.find(a=>e.startsWith(`.${a}(`,r)):void 0;if(o){let a=r+o.length+1,c=Xa(e,a),d=c<0?-1:e_(s);if(c>=0&&d>=0){let u=el(e.slice(a+1,c)),l=t(o,s.slice(d),u);if(l!==null){s=s.slice(0,d)+l,r=c+1;continue}}}s+=i,r++}return s}function n_(e,t,n,s,r,i){let o=Ot(sn(e));o=tn(o),o=zt(o,{target:"java",options:f=>{let h=Dt(f,"quoted");if(h===null)return null;let g=h.slice(1,-1).trim();if(!g)return"RoseKit.nativeOpts()";let y=[];for(let m of g.split(",")){let b=m.trim();if(!b)continue;let $=b.match(/^'([A-Za-z_$][\w$]*)'\s*:\s*([\s\S]+)$/);if(!$||/\{|=>/.test($[2]))return null;y.push(`"${$[1]}"`,$[2].trim())}return`RoseKit.nativeOpts(${y.join(", ")})`},empty:"null",file:t,warn:f=>i.push(`java: ${f}`)}).code.replace(/\broseNative\((['"][^'"]*['"]), \{\}\)/g,"roseNative($1, RoseKit.nativeOpts())");{let f=0;o=Qn(o,h=>n.includes(h)?"set"+h.charAt(0).toUpperCase()+h.slice(1):null,()=>String(++f))}o=rn(o,(f,h,g)=>{let y=G(g,go,new Set([h]));if(y===null)return null;let m=`RoseTheme.list(app.v("${f}"))`;return`app.set("${f}", ${y.replace(new RegExp(`\\b${h}\\b`,"g"),m)})`}),o=Kn(o,f=>{let h=f.slice(3,4).toLowerCase()+f.slice(4);return f.length>3&&n.includes(h)?h:null},(f,h)=>{let g=G(h,{...go,read:y=>`app.v("${y}")`},new Set);return g===null?null:`app.set("${f}", ${g})`}),o=on(o,(f,h)=>{let g=G(h,{...go,read:y=>`app.v("${y}")`},new Set);return g===null?null:`app.set("${f}", ${g})`}),o=t_(o,(f,h,g)=>{switch(f){case"join":return`RoseTheme.join(${h}, ${g[0]??'","'})`;case"split":return`RoseTheme.split(${h}, ${g[0]??'","'})`;case"indexOf":return`RoseTheme.indexOf(${h}, ${g[0]??'""'})`;case"every":{let y=xr(g[0]??"");return!y||!y.params.length?null:`RoseTheme.all(${h}, ${y.params[0]} -> ${y.body})`}case"startsWith":return`RoseTheme.startsWith(${h}, ${g[0]??'""'})`;case"endsWith":return`RoseTheme.endsWith(${h}, ${g[0]??'""'})`;case"toUpperCase":return`RoseTheme.upper(${h})`;default:return`RoseTheme.lower(${h})`}});let a=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/=>/,"an arrow function"],[/\.map\(/,".map("],[/\.(push|unshift|splice)\(/,"array mutation"]];for(let[f,h]of a)if(f.test(o))return i.push(`java: ${t}: a handler uses ${h}, which has no direct Java equivalent here - emitted as a stub`)," //
|
|
8958
|
+
`)}function YS(e,t){let n=e[t],s=t+1;for(;s<e.length&&e[s]!==n;)e[s]==="\\"&&s++,s++;return Math.min(s+1,e.length)}function nh(e,t){let n=e[t];for(let s=t-1;s>=0;s--){if(e[s]!==n)continue;let r=0,i=s-1;for(;i>=0&&e[i]==="\\";)r++,i--;if(r%2===0)return s}return 0}function Kc(e,t){let n=t;for(;;){for(;n>0&&/[\w$]/.test(e[n-1]);)n--;if(n>=2&&e[n-1]==="."&&/[\w$]/.test(e[n-2])){n-=1;continue}return n}}function e_(e){let t=e.length;for(;t>0&&e[t-1]===" ";)t--;if(t===0)return-1;let n=e[t-1];if(n==='"'||n==="'")return Kc(e,nh(e,t-1));if(n===")"){let s=0;for(let r=t-1;r>=0;r--){let i=e[r];if(i==='"'||i==="'"){r=nh(e,r);continue}if(i===")")s++;else if(i==="("&&--s===0)return Kc(e,r)}return-1}return/[\w$\]]/.test(n)?Kc(e,t):-1}function t_(e,t){let n=["join","split","indexOf","every","startsWith","endsWith","toUpperCase","toLowerCase"],s="",r=0;for(;r<e.length;){let i=e[r];if(i==='"'||i==="'"||i==="`"){let a=YS(e,r);s+=e.slice(r,a),r=a;continue}let o=i==="."?n.find(a=>e.startsWith(`.${a}(`,r)):void 0;if(o){let a=r+o.length+1,c=Xa(e,a),d=c<0?-1:e_(s);if(c>=0&&d>=0){let u=el(e.slice(a+1,c)),l=t(o,s.slice(d),u);if(l!==null){s=s.slice(0,d)+l,r=c+1;continue}}}s+=i,r++}return s}function n_(e,t,n,s,r,i){let o=Ot(sn(e));o=tn(o),o=zt(o,{target:"java",options:f=>{let h=Dt(f,"quoted");if(h===null)return null;let g=h.slice(1,-1).trim();if(!g)return"RoseKit.nativeOpts()";let y=[];for(let m of g.split(",")){let b=m.trim();if(!b)continue;let $=b.match(/^'([A-Za-z_$][\w$]*)'\s*:\s*([\s\S]+)$/);if(!$||/\{|=>/.test($[2]))return null;y.push(`"${$[1]}"`,$[2].trim())}return`RoseKit.nativeOpts(${y.join(", ")})`},empty:"null",file:t,warn:f=>i.push(`java: ${f}`)}).code.replace(/\broseNative\((['"][^'"]*['"]), \{\}\)/g,"roseNative($1, RoseKit.nativeOpts())");{let f=0;o=Qn(o,h=>n.includes(h)?"set"+h.charAt(0).toUpperCase()+h.slice(1):null,()=>String(++f))}o=rn(o,(f,h,g)=>{let y=G(g,go,new Set([h]));if(y===null)return null;let m=`RoseTheme.list(app.v("${f}"))`;return`app.set("${f}", ${y.replace(new RegExp(`\\b${h}\\b`,"g"),m)})`}),o=Kn(o,f=>{let h=f.slice(3,4).toLowerCase()+f.slice(4);return f.length>3&&n.includes(h)?h:null},(f,h)=>{let g=G(h,{...go,read:y=>`app.v("${y}")`},new Set);return g===null?null:`app.set("${f}", ${g})`}),o=on(o,(f,h)=>{let g=G(h,{...go,read:y=>`app.v("${y}")`},new Set);return g===null?null:`app.set("${f}", ${g})`}),o=t_(o,(f,h,g)=>{switch(f){case"join":return`RoseTheme.join(${h}, ${g[0]??'","'})`;case"split":return`RoseTheme.split(${h}, ${g[0]??'","'})`;case"indexOf":return`RoseTheme.indexOf(${h}, ${g[0]??'""'})`;case"every":{let y=xr(g[0]??"");return!y||!y.params.length?null:`RoseTheme.all(${h}, ${y.params[0]} -> ${y.body})`}case"startsWith":return`RoseTheme.startsWith(${h}, ${g[0]??'""'})`;case"endsWith":return`RoseTheme.endsWith(${h}, ${g[0]??'""'})`;case"toUpperCase":return`RoseTheme.upper(${h})`;default:return`RoseTheme.lower(${h})`}});let a=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/=>/,"an arrow function"],[/\.map\(/,".map("],[/\.(push|unshift|splice)\(/,"array mutation"]];for(let[f,h]of a)if(f.test(o))return i.push(`java: ${t}: a handler uses ${h}, which has no direct Java equivalent here - emitted as a stub`)," // rosefc: handler body not translated (uses "+h+").";o=Gn(o,(f,h,g,y)=>`app.set("${h}", RoseTheme.${f}(${g}, ${y}))`,f=>{let h=f.slice(3,4).toLowerCase()+f.slice(4);return f.length>3&&n.includes(h)?h:null});let c=ZS(o.trim());c=c.replace(/\bawait\s+/g,""),c=c.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(f,h,g)=>`${g}(app)`),c=c.replace(/\brefresh\s*\(\s*\)/g,"app.render()"),c=c.replace(/\bconsole\.(?:log|warn|error)\(/g,"System.out.println("),c=c.replace(/\bString\(\s*\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)\s*(?:\|\|\s*'[^']*')?\s*\)/g,(f,h,g)=>`RoseTheme.text(app.v("${g}"))`),c=c.replace(/\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(f,h,g)=>`RoseTheme.text(app.v("${g}"))`),c=c.replace(/\bString\(/g,"RoseTheme.text("),c=c.replace(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,"var $1 ="),c=c.replace(/\bnull\b/g,"null").replace(/\bundefined\b/g,"null"),c=c.replace(/'((?:[^'\\\\]|\\\\.)*)'/g,'"$1"'),c=c.replace(/===/g,"==").replace(/!==/g,"!=");let d=new Set(n),u=f=>{let h=r.get(f)??"Object";return h==="long"?`RoseTheme.integer(app.v("${f}"))`:h==="double"?`RoseTheme.decimal(app.v("${f}"))`:h==="boolean"?`RoseTheme.bool(app.v("${f}"))`:h==="List<Object>"?`RoseTheme.list(app.v("${f}"))`:`RoseTheme.text(app.v("${f}"))`};c=c.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(f,h)=>d.has(h)?u(h):f),c=Gt(c,f=>d.has(f),u,(f,h)=>`RoseTheme.get(${f}, "${h}")`);let l=[...s].filter(f=>!d.has(f));l.length&&(c=nt(c,(f,h)=>l.includes(f)?`RoseTheme.get(${f}, "${h}")`:`${f}.${h}`));for(let f of d){let h=f.charAt(0).toUpperCase()+f.slice(1);c=c.replace(new RegExp(`\\bset${h}\\s*\\(`,"g"),`app.set("${f}", `)}c=c.replace(/\.length\b/g,".size()"),c=Rn(c,f=>`!${f}.isEmpty()`),c=At(c,f=>`!RoseTheme.text(${f}).isEmpty()`,()=>!0);let p=c.split(`
|
|
8959
8959
|
`).map(f=>f.trim()).filter(Boolean);return p.length?p.map(f=>" "+f).join(`
|
|
8960
|
-
`):" //
|
|
8960
|
+
`):" // rosefc: an empty handler."}function s_(e){let t=72/e.w,n=72/e.h,s=e.shape.subPaths.map(i=>JSON.stringify(i.fill)).join(", "),r=e.shape.subPaths.map(i=>JSON.stringify(Rr(i.ops.map(o=>r_(o,t,n))))).join(", ");return`${e.w.toFixed(2)}, ${e.h.toFixed(2)}, new String[] { ${s} }, new String[] { ${r} }`}function r_(e,t,n){switch(e.op){case"move":return{op:"move",x:e.x*t,y:e.y*n};case"line":return{op:"line",x:e.x*t,y:e.y*n};case"curve":return{op:"curve",c1x:e.c1x*t,c1y:e.c1y*n,c2x:e.c2x*t,c2y:e.c2y*n,x:e.x*t,y:e.y*n};case"close":return e}}function i_(e){return{expr:t=>Vn(t,e),set:(t,n)=>`app.set("${t}", ${n})`,action:t=>`${t}(${e.app})`,refresh:()=>"app.render()",refuses:(t,n)=>{let s=Dn(t,n);if(s)return s;let r=[[/\bFormData\(/,"FormData"],[/\bdocument\.|\bwindow\./,"the DOM"],[/\bnew\s+[A-Z]/,"new"],[/=>/,"an arrow function"],[/\.map\(/,".map("],[/\.(push|unshift|splice)\(/,"array mutation"]];for(let[i,o]of r)if(i.test(t))return o;return null}}}function o_(e){return[...(e??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)].map(t=>({name:t[1],init:t[2].trim()}))}function a_(e,t,n,s){let r=[...(e.script??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)/g)].map(c=>c[1]),i={warnings:n,file:e.cls,stateNames:new Set(r),componentProps:new Set(r),stateTypes:new Map(r.map(c=>[c,"Object"])),mapBinds:new Set,components:[],lines:[],depth:1,styles:t,sheet:s,ancestors:[],app:"app",parent:"parent",counter:{n:0},deferred:[],awaits:[],scriptConsts:_t(e.script,new Set(r)),localNames:new Map,locals:new Set(["app","parent",...r]),forms:[],formSubmit:null,pageAction:null};Mn(e.nodes,i);let o=[],a=gn(e.nodes,r);for(let c of a)o.push(`java.util.function.Consumer<Object> ${ze(c)}`);e.slots.hasDefault&&o.push("java.util.function.Consumer<JPanel> slotDefault");for(let c of e.slots.named)o.push(`java.util.function.BiConsumer<Map<String, Object>, JPanel> slot${c.name.charAt(0).toUpperCase()}${c.name.slice(1)}`);return`package ${us}.components;
|
|
8961
8961
|
|
|
8962
8962
|
import ${us}.RoseApp;
|
|
8963
8963
|
import ${us}.RoseTheme;
|
|
@@ -8974,9 +8974,9 @@ ${i.lines.join(`
|
|
|
8974
8974
|
`)}
|
|
8975
8975
|
}
|
|
8976
8976
|
}
|
|
8977
|
-
`}var us,Za,RS,AS,Zc,sh,rh,ES,go,dh=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();hn();gs();hn();ls();us="dev.
|
|
8977
|
+
`}var us,Za,RS,AS,Zc,sh,rh,ES,go,dh=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();hn();gs();hn();ls();us="dev.rosefc.app",Za="dev/rosefc/app",RS=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),AS=new Set(["header","footer","nav"]),Zc=390,sh=new Map,rh=new Map;ES=(e,t)=>e.fontSize===t.fontSize&&e.color===t.color&&e.background===t.background&&e.padding===t.padding&&e.bold===t.bold&&e.align===t.align&&e.fontName===t.fontName&&e.borderColor===t.borderColor&&e.borderWidth===t.borderWidth&&JSON.stringify(e.pad??"")===JSON.stringify(t.pad??"")&&JSON.stringify(e.flex??"")===JSON.stringify(t.flex??"")&&e.fade===t.fade&&e.lineHeight===t.lineHeight&&e.grow===t.grow&&e.shrink===t.shrink&&e.basis===t.basis&&e.zIndex===t.zIndex&&JSON.stringify(e.margin??"")===JSON.stringify(t.margin??"")&&JSON.stringify(e.gradient??"")===JSON.stringify(t.gradient??"")&&JSON.stringify(e.shadow??"")===JSON.stringify(t.shadow??"")&&JSON.stringify(e.minSize??"")===JSON.stringify(t.minSize??"")&&JSON.stringify(e.maxSize??"")===JSON.stringify(t.maxSize??"")&&JSON.stringify(e.radius??"")===JSON.stringify(t.radius??"");go={get:(e,t)=>`RoseTheme.get(${e}, "${t}")`,count:e=>`((java.util.List<?>) (${e})).size()`,bool:e=>`RoseTheme.bool(${e})`,merge:(e,t)=>`RoseTheme.merge(${e}, ${t})`,obj:e=>`RoseTheme.mapOf(${e.map(([t,n])=>`Map.entry("${t}", ${n})`).join(", ")})`,map:(e,t,n)=>t.length>1?`RoseTheme.mapListIdx(${e}, (${t[0]}, ${t[1]}) -> ${n})`:`RoseTheme.mapList(${e}, ${t[0]} -> ${n})`,filter:(e,t,n)=>`RoseTheme.filterList(${e}, ${t[0]} -> ${n})`,slice:(e,t,n)=>n===null?`RoseTheme.slice(${e}, ${t})`:`RoseTheme.slice(${e}, ${t}, ${n})`,find:(e,t,n)=>`RoseTheme.find(${e}, ${t[0]} -> ${n})`,some:(e,t,n)=>`RoseTheme.any(${e}, ${t[0]} -> ${n})`,reduce:(e,t,n,s)=>s===null?`RoseTheme.reduceList(${e}, (${t[0]}, ${t[1]}) -> ${n})`:`RoseTheme.reduceList(${e}, ${s}, (${t[0]}, ${t[1]}) -> ${n})`,append:(e,t)=>`RoseTheme.append(${e}, ${t})`,concat:(e,t)=>`RoseTheme.concat(${e}, ${t})`,arr:e=>`RoseTheme.list(${e.join(", ")})`,not:e=>`!RoseTheme.bool(${e})`,lit:e=>e,template:e=>{let t=e.map(n=>"expr"in n?`RoseTheme.str(${n.expr})`:JSON.stringify(n.text));return t.length===0?'""':t.length===1?t[0]:`(${t.join(" + ")})`},index:(e,t)=>`RoseTheme.index(${e}, ${t})`,nullish:(e,t)=>`(${e} != null ? ${e} : ${t})`,optChain:(e,t)=>`RoseTheme.get(${e}, "${t}")`,join:(e,t)=>`RoseTheme.join(${e}, ${t})`,split:(e,t)=>`RoseTheme.split(${e}, ${t})`,indexOf:(e,t)=>`RoseTheme.indexOf(${e}, ${t})`,every:(e,t,n)=>`RoseTheme.all(${e}, ${t[0]} -> ${n})`,startsWith:(e,t)=>`RoseTheme.startsWith(${e}, ${t})`,endsWith:(e,t)=>`RoseTheme.endsWith(${e}, ${t})`,upper:e=>`RoseTheme.upper(${e})`,lower:e=>`RoseTheme.lower(${e})`}});import*as ot from"node:fs";import*as Ie from"node:path";import{transformSync as l_}from"esbuild";async function d_(e,t,n){let s=new Map,r=Ie.join(e,"public");if(!ot.existsSync(r))return s;await ot.promises.mkdir(t,{recursive:!0});for(let i of await ot.promises.readdir(r,{withFileTypes:!0}))if(!i.isDirectory()){if(/\.svg$/i.test(i.name)){let o=Wt(await ot.promises.readFile(Ie.join(r,i.name),"utf8"));o.shape?yh.set("/"+i.name,o.shape):n.push("dotnet: "+i.name+" uses "+(o.reason??"an unsupported feature")+" - skipped");continue}/\.(png|jpe?g|webp)$/i.test(i.name)&&(await ot.promises.copyFile(Ie.join(r,i.name),Ie.join(t,i.name)),s.set("/"+i.name,"Assets/"+i.name))}return s}async function bh(e){let t=e.warnings,n=e.projectRoot,s=Ie.join(e.outDir,"dotnet"),r=Ie.join(n,"src","pages"),[i,o]=await Promise.all([Ye(n),Ke(n)]),a=new Map;for(let g of i){if(Ie.basename(g)!=="_layout.rose")continue;let y=Ie.dirname(Ie.relative(r,g)).replace(/\\/g,"/"),m=Ce(await ot.promises.readFile(g,"utf8"),g,"dotnet");t.push(...m.warnings),a.set(y==="."?"":y,{nodes:m.nodes,script:m.script,style:m.style})}let c=[];for(let g of i){let y=Ie.relative(r,g).replace(/\\/g,"/"),m=y.replace(/\.rose$/,""),b=Ie.basename(m);if(b==="_layout"||b==="404"||b==="_notfound"||b==="500"||b==="_middleware"||m==="api"||m.startsWith("api/"))continue;let $=Ce(await ot.promises.readFile(g,"utf8"),g,"dotnet");t.push(...$.warnings);let w=[],v=y.split("/").slice(0,-1);for(let k=v.length;k>=0;k--){let S=a.get(v.slice(0,k).join("/"));S&&w.push(S)}let _=$.nodes;for(let k of w)_=f_(k.nodes,_);c.push({route:p_(m),cls:ph(m),nodes:_,script:[...w.map(k=>k.script).filter(k=>!!k),$.script??""].filter(k=>k.trim()).join(`
|
|
8978
8978
|
`),style:[$.style,...w.map(k=>k.style)].filter(k=>!!k).join(`
|
|
8979
|
-
`),params:[...m.matchAll(/\[([^\]]+)\]/g)].map(k=>k[1])})}let d=[];for(let g of o){let y=Ce(await ot.promises.readFile(g,"utf8"),g,"dotnet");t.push(...y.warnings);let m=Ie.basename(g,".rose");d.push({name:m,cls:ph(m),nodes:y.nodes,script:y.script,style:y.style??"",slots:Ft(y.nodes)})}await ot.promises.rm(s,{recursive:!0,force:!0}),await ot.promises.mkdir(Ie.join(s,"Pages"),{recursive:!0}),await ot.promises.mkdir(Ie.join(s,"Components"),{recursive:!0}),mh=await d_(n,Ie.join(s,"Assets"),t);let u=Yc(ke,null,"",t),l=new Map;for(let g of c)l.set(g.cls,Yc(g.style??"",u.sheet,g.cls,t));let p=new Map;for(let g of d)p.set(g.cls,Yc(g.style,u.sheet,g.cls,t));let f=Mt(n),h=xt([...c.map(g=>g.script),...d.map(g=>g.script)]);await ot.promises.writeFile(Ie.join(s,"RoseTheme.cs"),g_([...l].map(([g,y])=>({scope:g,styles:y})),u),"utf8"),await ot.promises.writeFile(Ie.join(s,"RoseKit.cs"),y_(e.apiBase??"",f,h),"utf8"),await ot.promises.writeFile(Ie.join(s,"RoseApp.cs"),__(c,[...new Set(c.flatMap(g=>an(g.script??"")))]),"utf8"),await ot.promises.writeFile(Ie.join(s,"
|
|
8979
|
+
`),params:[...m.matchAll(/\[([^\]]+)\]/g)].map(k=>k[1])})}let d=[];for(let g of o){let y=Ce(await ot.promises.readFile(g,"utf8"),g,"dotnet");t.push(...y.warnings);let m=Ie.basename(g,".rose");d.push({name:m,cls:ph(m),nodes:y.nodes,script:y.script,style:y.style??"",slots:Ft(y.nodes)})}await ot.promises.rm(s,{recursive:!0,force:!0}),await ot.promises.mkdir(Ie.join(s,"Pages"),{recursive:!0}),await ot.promises.mkdir(Ie.join(s,"Components"),{recursive:!0}),mh=await d_(n,Ie.join(s,"Assets"),t);let u=Yc(ke,null,"",t),l=new Map;for(let g of c)l.set(g.cls,Yc(g.style??"",u.sheet,g.cls,t));let p=new Map;for(let g of d)p.set(g.cls,Yc(g.style,u.sheet,g.cls,t));let f=Mt(n),h=xt([...c.map(g=>g.script),...d.map(g=>g.script)]);await ot.promises.writeFile(Ie.join(s,"RoseTheme.cs"),g_([...l].map(([g,y])=>({scope:g,styles:y})),u),"utf8"),await ot.promises.writeFile(Ie.join(s,"RoseKit.cs"),y_(e.apiBase??"",f,h),"utf8"),await ot.promises.writeFile(Ie.join(s,"RoseApp.cs"),__(c,[...new Set(c.flatMap(g=>an(g.script??"")))]),"utf8"),await ot.promises.writeFile(Ie.join(s,"RosefcApp.csproj"),b_(),"utf8"),await ot.promises.writeFile(Ie.join(s,"App.xaml"),$_(),"utf8"),await ot.promises.writeFile(Ie.join(s,"App.xaml.cs"),w_(),"utf8"),await ot.promises.writeFile(Ie.join(s,"MainWindow.xaml"),v_(),"utf8"),await ot.promises.writeFile(Ie.join(s,"MainWindow.xaml.cs"),S_(),"utf8");for(let g of d)await ot.promises.writeFile(Ie.join(s,"Components",g.cls+"View.cs"),U_(g,p.get(g.cls),t),"utf8");for(let g of c)await ot.promises.writeFile(Ie.join(s,"Pages",g.cls+"Page.cs"),k_(g,d,l.get(g.cls),t,f),"utf8");return await ot.promises.writeFile(Ie.join(s,"README.md"),x_(e.apiBase??"",c.length,d.length,t),"utf8"),{pages:c.map(g=>`Pages/${g.cls}Page.cs`),components:d.map(g=>`Components/${g.cls}View.cs`)}}function p_(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function ph(e){return e.split("/").map(n=>n.replace(/^\[(.+)\]$/,"param_$1")).map(n=>n.replace(/[^\w]+/g,"_").split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")).join("").replace(/^\d/,"_$&")||"Page"}function f_(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}function Yc(e,t,n,s){let r=Te(e);if(n)for(let c of r.warnings)s.push(`dotnet: ${n}: ${c}`);let i=t?{rules:[...r.rules,...t.rules],warnings:[]}:r,o=new Set;for(let c of r.rules)for(let d of c.parts)for(let u of d.classes)o.add(u);let a=new Map;for(let c of[...o].sort()){let d=rt(i,{tag:"div",classes:[c]},[],{viewport:tu});(Object.keys(d.model).length||d.hover)&&a.set(c,d)}return{sheet:i,classes:a}}function h_(e){let t=nr(e);return t==="monospace"?"Consolas":t==="serif"?"Times New Roman":"Segoe UI"}function wn(e){return String(Math.round(e*1e3)/1e3)}function tl(e){return`new double[] { ${e.map(wn).join(", ")} }`}function Nr(e){return`new RoseLen(${wn(e.n)}, "${e.u}")`}function Ts(e,t={}){let n=[],s=(i,o)=>{o!=null&&n.push(`${i} = ${o}`)};if(e.color&&s("Color",JSON.stringify(e.color)),e.fontSize!==void 0&&s("FontSize",wn(e.fontSize)),e.fontWeight!==void 0&&s("FontWeight",String(Math.round(e.fontWeight))),e.fontFamily&&s("FontFamily",JSON.stringify(h_(e.fontFamily))),e.italic!==void 0&&s("Italic",e.italic?"true":"false"),e.lineHeight!==void 0&&s("LineHeight",wn(e.lineHeight)),t.table&&e.letterSpacing!==void 0&&s("LetterSpacing",wn(e.letterSpacing)),e.textAlign&&s("TextAlign",JSON.stringify(e.textAlign)),t.table&&e.textTransform&&s("TextTransform",JSON.stringify(e.textTransform)),e.underline!==void 0&&s("Underline",e.underline?"true":"false"),e.strike!==void 0&&s("Strike",e.strike?"true":"false"),e.background&&s("Background",JSON.stringify(e.background)),e.gradient){let i=e.gradient.stops.map(o=>JSON.stringify(`${wn(o.at)}:${o.color}`)).join(", ");s("Gradient",`new RoseGradient(${wn(e.gradient.angle)}, new[] { ${i} })`)}e.padding&&s("Padding",tl(e.padding)),e.margin&&s("Margin",tl(e.margin)),e.gap!==void 0&&s("Gap",wn(e.gap)),e.borderWidth&&s("BorderWidth",tl(e.borderWidth)),e.borderColor&&s("BorderColor",JSON.stringify(e.borderColor)),e.borderStyle&&s("BorderStyle",JSON.stringify(e.borderStyle)),e.radius&&s("Radius",tl(e.radius)),e.shadow&&s("Shadow",`new RoseShadow(${wn(e.shadow.x)}, ${wn(e.shadow.y)}, ${wn(e.shadow.blur)}, ${wn(e.shadow.spread)}, ${JSON.stringify(e.shadow.color)})`),e.opacity!==void 0&&s("Opacity",wn(e.opacity)),e.display&&s("Display",JSON.stringify(e.display));let r=e.direction??t.direction;return r&&s("Direction",JSON.stringify(r)),e.wrap!==void 0&&s("Wrap",e.wrap?"true":"false"),e.justify&&s("Justify",JSON.stringify(e.justify)),e.align&&s("Align",JSON.stringify(e.align)),e.alignSelf&&s("AlignSelf",JSON.stringify(e.alignSelf)),e.grow!==void 0&&s("Grow",wn(e.grow)),e.shrink!==void 0&&s("Shrink",wn(e.shrink)),e.basis&&s("Basis",Nr(e.basis)),e.width&&s("Width",Nr(e.width)),e.height&&s("Height",Nr(e.height)),e.minWidth&&s("MinWidth",Nr(e.minWidth)),e.maxWidth&&s("MaxWidth",Nr(e.maxWidth)),e.minHeight&&s("MinHeight",Nr(e.minHeight)),e.maxHeight&&s("MaxHeight",Nr(e.maxHeight)),e.overflow&&s("Overflow",JSON.stringify(e.overflow)),e.zIndex!==void 0&&s("ZIndex",String(Math.round(e.zIndex))),n.length?`new RoseStyle { ${n.join(", ")} }`:"new RoseStyle()"}function nu(e){let t={};for(let n of["color","fontSize","fontWeight","fontFamily","italic","lineHeight","letterSpacing","textAlign","textTransform","underline","strike"]){let s=e[n];s!==void 0&&(t[n]=s)}return t}function yo(e,t){if(!t)return e;if(e.startsWith('"')&&e.endsWith('"'))try{let n=JSON.parse(e),s=t==="uppercase"?n.toUpperCase():t==="lowercase"?n.toLowerCase():n.replace(/\b\w/g,r=>r.toUpperCase());return JSON.stringify(s)}catch{}return`RoseTheme.Case(${e}, ${JSON.stringify(t)})`}function wh(e,t,n){let s=(r,i)=>{n.noted.has(r)||(n.noted.add(r),n.warnings.push(`dotnet: ${i}`))};e.letterSpacing&&s("spacing",`letter-spacing on ${t} is dropped - WPF text has no tracking`),e.height?.u==="%"&&s("height",`a percentage height on ${t} needs a host height - WPF measures its content`),e.position&&s("position",`position: ${e.position} on ${t} is dropped - the page is a stack of panels, so nothing leaves the flow`)}function g_(e,t){let n=[],s=[],r=(i,o)=>{Object.keys(o.model).length&&n.push(` ["${i}"] = ${Ts(o.model,{table:!0})},`),o.hover&&s.push(` ["${i}"] = ${Ts(o.hover,{table:!0})},`)};for(let i of e)for(let[o,a]of[...i.styles.classes.entries()].sort((c,d)=>c[0].localeCompare(d[0])))r(`${o}__${i.scope}`,a);for(let[i,o]of[...t.classes.entries()].sort((a,c)=>a[0].localeCompare(c[0])))r(i,o);return`namespace ${ns};
|
|
8980
8980
|
|
|
8981
8981
|
using System.Globalization;
|
|
8982
8982
|
using System.Windows;
|
|
@@ -10458,7 +10458,7 @@ ${s}${m_(n)}
|
|
|
10458
10458
|
if (ApiBase.Length == 0) return new Dictionary<string, object?>();
|
|
10459
10459
|
try
|
|
10460
10460
|
{
|
|
10461
|
-
var url = ApiBase + "/
|
|
10461
|
+
var url = ApiBase + "/__rosefc/data?path=" + Uri.EscapeDataString(route);
|
|
10462
10462
|
var text = Http.GetStringAsync(url).GetAwaiter().GetResult();
|
|
10463
10463
|
return State(text);
|
|
10464
10464
|
}
|
|
@@ -10551,7 +10551,7 @@ public partial class App : Application
|
|
|
10551
10551
|
`}function v_(){return`<Window x:Class="${ns}.MainWindow"
|
|
10552
10552
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
|
10553
10553
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
10554
|
-
Title="
|
|
10554
|
+
Title="Rosefc" Height="800" Width="1100">
|
|
10555
10555
|
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
|
10556
10556
|
<ContentControl x:Name="Host" Margin="16" />
|
|
10557
10557
|
</ScrollViewer>
|
|
@@ -10581,7 +10581,7 @@ public sealed class RoseApp
|
|
|
10581
10581
|
private static readonly string[] PersistKeys = {${t.map(r=>JSON.stringify(r)).join(", ")}};
|
|
10582
10582
|
private readonly ContentControl host;
|
|
10583
10583
|
private readonly HashSet<string> loadedRoutes = new();
|
|
10584
|
-
private static readonly string StorePath = System.IO.Path.Combine(AppContext.BaseDirectory, ".
|
|
10584
|
+
private static readonly string StorePath = System.IO.Path.Combine(AppContext.BaseDirectory, ".rosefc-state.json");
|
|
10585
10585
|
private static readonly System.Collections.Generic.HashSet<string> Persisted = new(PersistKeys);
|
|
10586
10586
|
private static readonly System.Collections.Generic.Dictionary<string, object?> Store = LoadStore();
|
|
10587
10587
|
|
|
@@ -10668,13 +10668,13 @@ ${n.join(`
|
|
|
10668
10668
|
host.Content = panel;
|
|
10669
10669
|
}
|
|
10670
10670
|
}
|
|
10671
|
-
`}function x_(e,t,n,s){return`#
|
|
10671
|
+
`}function x_(e,t,n,s){return`# Rosefc -> .NET desktop (WPF, net8.0-windows)
|
|
10672
10672
|
|
|
10673
|
-
Generated by \`
|
|
10673
|
+
Generated by \`rosefc export dotnet\` from the project's \`.rose\` pages.
|
|
10674
10674
|
|
|
10675
10675
|
- ${t} page(s), ${n} component(s)
|
|
10676
10676
|
- Build: \`dotnet build\`, run: \`dotnet run\` (Windows)
|
|
10677
|
-
- Server: \`
|
|
10677
|
+
- Server: \`rosefc export dotnet --api <base>\` writes the base URL into \`RoseKit.cs\`.
|
|
10678
10678
|
Current: \`${e||"(unset)"}\`
|
|
10679
10679
|
|
|
10680
10680
|
State lives in the app's dictionary, a handler mutates it and re-renders, and the
|
|
@@ -10732,9 +10732,9 @@ ${h}
|
|
|
10732
10732
|
app.Render();
|
|
10733
10733
|
}`)}return c.join(`
|
|
10734
10734
|
|
|
10735
|
-
`)}function H_(e,t){let n=e;for(let s of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let r=s[1],i=r.slice(3,4).toLowerCase()+r.slice(4);if(!t(i))continue;let o=s.index??0,a=o+s[0].length-1,c=fi(e,a);if(c<0)continue;let d=e.slice(a+1,c).trim();if(!/\.(?:join|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(d))continue;let u=G(d,{...pi,read:p=>`app.V("${p}")`},new Set);if(u===null)continue;let l=c+1;e[l]===";"&&l++,n=n.replace(e.slice(o,l),()=>`app.Set("${i}", ${u})`)}return n}function V_(e,t,n,s,r,i){let o=Ot(sn(e));o=tn(o),o=zt(o,{target:"dotnet",options:l=>{let p=Dt(l,"quoted");if(p===null)return null;let f=p.slice(1,-1).trim();if(!f)return"RoseTheme.Obj()";let h=[];for(let g of f.split(",")){let y=g.trim();if(!y)continue;let m=y.match(/^'([A-Za-z_$][\w$]*)'\s*:\s*([\s\S]+)$/);if(!m||/\{|=>/.test(m[2]))return null;h.push(`("${m[1]}", ${m[2].trim()})`)}return`RoseTheme.Obj(${h.join(", ")})`},empty:"null",file:t,warn:l=>i.push(`dotnet: ${l}`)}).code.replace(/\bRoseNative\((['"][^'"]*['"]), \{\}\)/g,"RoseNative($1, RoseTheme.Obj())");{let l=0;o=Qn(o,p=>n.includes(p)?"set"+p.charAt(0).toUpperCase()+p.slice(1):null,()=>String(++l))}if(o=rn(o,(l,p,f)=>{let h=G(f,pi,new Set([p]));if(h===null)return null;let g=`RoseTheme.List(app.V("${l}"))`;return`app.Set("${l}", ${h})`.replace(new RegExp(`\\b${p}\\b`,"g"),g)}),o=Kn(o,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null},(l,p)=>{let f=G(p,{...pi,read:h=>`app.V("${h}")`},new Set);return f===null?null:`app.Set("${l}", ${f})`}),o=H_(o,l=>n.includes(l)),o=on(o,(l,p)=>{let f=G(p,{...pi,read:h=>`app.V("${h}")`},new Set);return f===null?null:`app.Set("${l}", ${f})`}),/\bFormData\(|\bdocument\.|\bwindow\.|\bnew\s+[A-Z]/.test(o)||/=>/.test(o))return i.push(`dotnet: ${t}: a handler uses a web-only construct (DOM/FormData/new/arrow) - emitted as a stub`)," //
|
|
10735
|
+
`)}function H_(e,t){let n=e;for(let s of e.matchAll(/\b(set[A-Z][\w$]*)\s*\(/g)){let r=s[1],i=r.slice(3,4).toLowerCase()+r.slice(4);if(!t(i))continue;let o=s.index??0,a=o+s[0].length-1,c=fi(e,a);if(c<0)continue;let d=e.slice(a+1,c).trim();if(!/\.(?:join|split|indexOf|every|startsWith|endsWith|toUpperCase|toLowerCase)\s*\(/.test(d))continue;let u=G(d,{...pi,read:p=>`app.V("${p}")`},new Set);if(u===null)continue;let l=c+1;e[l]===";"&&l++,n=n.replace(e.slice(o,l),()=>`app.Set("${i}", ${u})`)}return n}function V_(e,t,n,s,r,i){let o=Ot(sn(e));o=tn(o),o=zt(o,{target:"dotnet",options:l=>{let p=Dt(l,"quoted");if(p===null)return null;let f=p.slice(1,-1).trim();if(!f)return"RoseTheme.Obj()";let h=[];for(let g of f.split(",")){let y=g.trim();if(!y)continue;let m=y.match(/^'([A-Za-z_$][\w$]*)'\s*:\s*([\s\S]+)$/);if(!m||/\{|=>/.test(m[2]))return null;h.push(`("${m[1]}", ${m[2].trim()})`)}return`RoseTheme.Obj(${h.join(", ")})`},empty:"null",file:t,warn:l=>i.push(`dotnet: ${l}`)}).code.replace(/\bRoseNative\((['"][^'"]*['"]), \{\}\)/g,"RoseNative($1, RoseTheme.Obj())");{let l=0;o=Qn(o,p=>n.includes(p)?"set"+p.charAt(0).toUpperCase()+p.slice(1):null,()=>String(++l))}if(o=rn(o,(l,p,f)=>{let h=G(f,pi,new Set([p]));if(h===null)return null;let g=`RoseTheme.List(app.V("${l}"))`;return`app.Set("${l}", ${h})`.replace(new RegExp(`\\b${p}\\b`,"g"),g)}),o=Kn(o,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null},(l,p)=>{let f=G(p,{...pi,read:h=>`app.V("${h}")`},new Set);return f===null?null:`app.Set("${l}", ${f})`}),o=H_(o,l=>n.includes(l)),o=on(o,(l,p)=>{let f=G(p,{...pi,read:h=>`app.V("${h}")`},new Set);return f===null?null:`app.Set("${l}", ${f})`}),/\bFormData\(|\bdocument\.|\bwindow\.|\bnew\s+[A-Z]/.test(o)||/=>/.test(o))return i.push(`dotnet: ${t}: a handler uses a web-only construct (DOM/FormData/new/arrow) - emitted as a stub`)," // rosefc: handler body not translated (web-only construct).";o=Gn(o,(l,p,f,h)=>`app.Set("${p}", RoseTheme.${l==="append"?"Append":"Prepend"}(${f}, ${h}))`,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null});let a=D_(o.trim());a=a.replace(/\bawait\s+/g,""),a=a.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(l,p,f)=>`${f}(app)`),a=a.replace(/\brefresh\s*\(\s*\)/g,"app.Render()"),a=a.replace(/\bconsole\.(?:log|warn|error)\(/g,"Console.WriteLine("),a=a.replace(/\bString\(\s*\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)\s*(?:\|\|\s*'[^']*')?\s*\)/g,(l,p,f)=>`RoseTheme.Str(app.V("${f}"))`),a=a.replace(/\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(l,p,f)=>`RoseTheme.Str(app.V("${f}"))`),a=a.replace(/\bString\(/g,"RoseTheme.Str("),a=a.replace(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,"var $1 ="),a=a.replace(/\bnull\b/g,"null").replace(/\bundefined\b/g,"null"),a=M_(a),a=F_(a),a=P_(a),a=Ah(a),a=a.replace(/'((?:[^'\\\\]|\\\\.)*)'/g,'"$1"'),a=a.replace(/===/g,"==").replace(/!==/g,"!="),a=a.replace(/\.length\b/g,".Count"),a=a.replace(/\.trim\(\)/g,".Trim()").replace(/\.toLowerCase\(\)/g,".ToLower()").replace(/\.toUpperCase\(\)/g,".ToUpper()");let c=new Set(n);a=a.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(l,p)=>c.has(p)?nl(p,r.get(p),"app"):l),a=Gt(a,l=>c.has(l),l=>nl(l,r.get(l),"app"),(l,p)=>`RoseTheme.Get(${l}, "${p}")`);for(let l of c){let p=l.charAt(0).toUpperCase()+l.slice(1);a=a.replace(new RegExp(`\\bset${p}\\s*\\(`,"g"),`app.Set("${l}", `)}let d=[...s].filter(l=>!c.has(l));d.length&&(a=nt(a,(l,p)=>d.includes(l)?`RoseTheme.Get(${l}, "${p}")`:`${l}.${p}`)),a=Rn(a,l=>`!string.IsNullOrEmpty(${l})`),a=At(a,l=>`!string.IsNullOrEmpty(RoseTheme.Str(${l}))`,()=>!0),a=xh(a),a=L_(a);let u=a.split(`
|
|
10736
10736
|
`).map(l=>l.trim()).filter(Boolean);return u.length?u.map(l=>" "+l).join(`
|
|
10737
|
-
`):" //
|
|
10737
|
+
`):" // rosefc: an empty handler."}function J_(e){return[...(e??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)].map(t=>({name:t[1],init:t[2].trim()}))}function U_(e,t,n){let s=[...(e.script??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)/g)].map(c=>c[1]),r=fe($h,{}),i={warnings:n,file:e.cls,stateNames:new Set(s),componentProps:new Set(s),awaits:[],deferred:[],scriptConsts:_t(e.script,new Set(s)),pageAction:null,stateTypes:new Map(s.map(c=>[c,"object"])),mapBinds:new Set,components:[],lines:[],depth:2,styles:t,scope:e.cls,ancestors:[],inherited:nu(r),noted:new Set,app:"app",parent:`panel${e.cls}`,counter:{n:0,c:0},forms:St(e.nodes),formSubmit:null};Fn(e.nodes,i);let o=[],a=gn(e.nodes,s);for(let c of a)o.push(`Action<object?> ${ze(c)}`);e.slots.hasDefault&&o.push("Action<Panel> slotDefault");for(let c of e.slots.named)o.push(`Action<IDictionary<string, object?>, Panel> slot${c.name.charAt(0).toUpperCase()}${c.name.slice(1)}`);return`namespace ${ns}.Components;
|
|
10738
10738
|
|
|
10739
10739
|
using System.Windows.Controls;
|
|
10740
10740
|
|
|
@@ -10748,7 +10748,7 @@ ${i.lines.join(`
|
|
|
10748
10748
|
return panel${e.cls};
|
|
10749
10749
|
}
|
|
10750
10750
|
}
|
|
10751
|
-
`}var ns,c_,u_,mh,yh,tu,$h,pi,Ch=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();hn();gs();hn();ls();ns="
|
|
10751
|
+
`}var ns,c_,u_,mh,yh,tu,$h,pi,Ch=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();hn();gs();hn();ls();ns="RosefcApp",c_=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),u_=new Set(["header","footer","nav"]),mh=new Map,yh=new Map;tu=390,$h={color:"#222222",fontSize:16,fontFamily:"system-ui, sans-serif"};pi={get:(e,t)=>`RoseTheme.Get(${e}, "${t}")`,count:e=>`RoseTheme.Count(${e})`,bool:e=>`RoseTheme.Bool(${e})`,merge:(e,t)=>`RoseTheme.Merge(${e}, ${t})`,obj:e=>`RoseTheme.Obj(${e.map(([t,n])=>`("${t}", ${n})`).join(", ")})`,map:(e,t,n)=>t.length>1?`RoseTheme.MapIdx(${e}, delegate(object ${t[0]}, int ${t[1]}) { return ${n}; })`:`RoseTheme.Map(${e}, delegate(object ${t[0]}) { return ${n}; })`,filter:(e,t,n)=>`RoseTheme.Filter(${e}, delegate(object ${t[0]}) { return ${n}; })`,slice:(e,t,n)=>n===null?`RoseTheme.SliceObj(${e}, ${t})`:`RoseTheme.SliceObj(${e}, ${t}, ${n})`,find:(e,t,n)=>`RoseTheme.FindObj(${e}, delegate(object ${t[0]}) { return ${n}; })`,some:(e,t,n)=>`RoseTheme.AnyObj(${e}, delegate(object ${t[0]}) { return ${n}; })`,reduce:(e,t,n,s)=>s===null?`RoseTheme.Reduce(${e}, delegate(object ${t[0]}, object ${t[1]}) { return ${n}; })`:`RoseTheme.Reduce(${e}, ${s}, delegate(object ${t[0]}, object ${t[1]}) { return ${n}; })`,append:(e,t)=>`RoseTheme.Append(${e}, ${t})`,concat:(e,t)=>`RoseTheme.Concat(${e}, ${t})`,arr:e=>`RoseTheme.List(${e.join(", ")})`,not:e=>`!RoseTheme.Bool(${e})`,lit:e=>e,template:e=>'$"'+e.map(t=>"expr"in t?`{${t.expr}}`:t.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\{/g,"{{").replace(/\}/g,"}}")).join("")+'"',index:(e,t)=>`RoseTheme.Index(${e}, ${t})`,nullish:(e,t)=>`(${e} ?? ${t})`,optChain:(e,t)=>`RoseTheme.Get(${e}, "${t}")`,join:(e,t)=>`RoseTheme.Join(${e}, ${t})`,split:(e,t)=>`RoseKit.SplitObj(${e}, ${t})`,indexOf:(e,t)=>`RoseKit.IndexOfObj(${e}, ${t})`,every:(e,t,n)=>`RoseKit.AllObj(${e}, delegate(object ${t[0]}) { return ${n}; })`,startsWith:(e,t)=>`RoseTheme.Str(${e}).StartsWith(RoseTheme.Str(${t}))`,endsWith:(e,t)=>`RoseTheme.Str(${e}).EndsWith(RoseTheme.Str(${t}))`,upper:e=>`RoseTheme.Str(${e}).ToUpper()`,lower:e=>`RoseTheme.Str(${e}).ToLower()`}});import*as wt from"node:fs";import*as Ue from"node:path";import{transformSync as q_}from"esbuild";async function K_(e,t,n){let s=new Map,r=Ue.join(e,"public");if(!wt.existsSync(r))return s;await wt.promises.mkdir(t,{recursive:!0});for(let i of await wt.promises.readdir(r,{withFileTypes:!0}))if(!i.isDirectory()){if(/\.svg$/i.test(i.name)){let o=Wt(await wt.promises.readFile(Ue.join(r,i.name),"utf8"));o.shape?Fh.set("/"+i.name,o.shape):n.push("cpp: "+i.name+" uses "+(o.reason??"an unsupported feature")+" - skipped");continue}/\.(png|jpe?g|webp)$/i.test(i.name)&&(await wt.promises.copyFile(Ue.join(r,i.name),Ue.join(t,i.name)),s.set("/"+i.name,"assets/"+i.name))}return s}async function Ph(e){let t=e.warnings,n=e.projectRoot,s=Ue.join(e.outDir,"cpp"),r=Ue.join(n,"src","pages"),[i,o]=await Promise.all([Ye(n),Ke(n)]),a=new Map;for(let f of i){if(Ue.basename(f)!=="_layout.rose")continue;let h=Ue.dirname(Ue.relative(r,f)).replace(/\\/g,"/"),g=Ce(await wt.promises.readFile(f,"utf8"),f,"cpp");t.push(...g.warnings),a.set(h==="."?"":h,{nodes:g.nodes,script:g.script,style:g.style})}let c=[];for(let f of i){let h=Ue.relative(r,f).replace(/\\/g,"/"),g=h.replace(/\.rose$/,""),y=Ue.basename(g);if(y==="_layout"||y==="404"||y==="_notfound"||y==="500"||y==="_middleware"||g==="api"||g.startsWith("api/"))continue;let m=Ce(await wt.promises.readFile(f,"utf8"),f,"cpp");t.push(...m.warnings);let b=[],$=h.split("/").slice(0,-1);for(let v=$.length;v>=0;v--){let _=a.get($.slice(0,v).join("/"));_&&b.push(_)}let w=m.nodes;for(let v of b)w=X_(v.nodes,w);c.push({route:Z_(g),cls:jh(g),nodes:w,script:[...b.map(v=>v.script).filter(v=>!!v),m.script??""].filter(v=>v.trim()).join(`
|
|
10752
10752
|
`),style:[m.style,...b.map(v=>v.style)].filter(v=>!!v).join(`
|
|
10753
10753
|
`),params:[...g.matchAll(/\[([^\]]+)\]/g)].map(v=>v[1])})}let d=[];for(let f of o){let h=Ce(await wt.promises.readFile(f,"utf8"),f,"cpp");t.push(...h.warnings);let g=Ue.basename(f,".rose");d.push({name:g,cls:jh(g),nodes:h.nodes,script:h.script,style:h.style??"",slots:Ft(h.nodes)})}await wt.promises.rm(s,{recursive:!0,force:!0}),await wt.promises.mkdir(Ue.join(s,"src","pages"),{recursive:!0}),await wt.promises.mkdir(Ue.join(s,"src","components"),{recursive:!0}),Mh=await K_(n,Ue.join(s,"assets"),t);let u=new Map;for(let f of c)Th(f.style??"",t);for(let f of c)for(let[h,g]of ru(f.style??"",t,f.cls))u.set(h,g);for(let f of d){Th(f.style??"",t);for(let[h,g]of ru(f.style??"",t,f.cls))u.set(h,g)}for(let[f,h]of ru(ke,t))u.set(f,h);let l=Mt(n),p=xt([...c.map(f=>f.script),...d.map(f=>f.script)]);await wt.promises.writeFile(Ue.join(s,"src","rose.h"),rx(u,e.apiBase??"",l,p),"utf8"),await wt.promises.writeFile(Ue.join(s,"src","rose.cpp"),ix(c,p),"utf8"),await wt.promises.writeFile(Ue.join(s,"src","pages.h"),ox(c,d),"utf8"),await wt.promises.writeFile(Ue.join(s,"src","main.cpp"),ax([...new Set(c.flatMap(f=>an(f.script??"")))]),"utf8"),await wt.promises.writeFile(Ue.join(s,"CMakeLists.txt"),lx(c,d),"utf8");for(let f of d)await wt.promises.writeFile(Ue.join(s,"src","components",f.cls+"View.cpp"),Cx(f,u,t,Eh(f.style??"")),"utf8");for(let f of c)await wt.promises.writeFile(Ue.join(s,"src","pages",f.cls+"Page.cpp"),ux(f,d,u,t,l,Eh(f.style??"")),"utf8");return await wt.promises.writeFile(Ue.join(s,"README.md"),cx(e.apiBase??"",c.length,d.length,t),"utf8"),{pages:c.map(f=>`src/pages/${f.cls}Page.cpp`),components:d.map(f=>`src/components/${f.cls}View.cpp`)}}function Z_(e){let t=e.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?":"+n.slice(1,-1):n);return t.length===1&&t[0]==="index"?"/":(t[t.length-1]==="index"&&t.pop(),"/"+t.join("/"))}function jh(e){return e.split("/").map(n=>n.replace(/^\[(.+)\]$/,"param_$1")).map(n=>n.replace(/[^\w]+/g,"_").split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")).join("").replace(/^\d/,"_$&")||"Page"}function X_(e,t){let n=s=>s.flatMap(r=>r.kind==="element"?r.tag==="slot"?t:[{...r,children:n(r.children)}]:r.kind==="if"?[{...r,branches:r.branches.map(i=>({...i,children:n(i.children)}))}]:r.kind==="each"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="block"?[{...r,children:n(r.children),fallback:r.fallback?n(r.fallback):void 0}]:r.kind==="await"?[{...r,pending:n(r.pending),then:n(r.then),catch:n(r.catch)}]:[r]);return n(e)}function Y_(e){return e.position!=="absolute"&&e.position!=="fixed"?{absolute:!1,insetX:0,insetY:0}:e.insetTop===void 0&&e.insetLeft===void 0&&e.insetRight===void 0&&e.insetBottom===void 0?{absolute:!0,insetX:0,insetY:0}:{absolute:!0,insetX:e.insetLeft??e.insetRight??0,insetY:e.insetTop??e.insetBottom??0}}function ru(e,t,n){let s=new Map,r=e.replace(/\/\*[\s\S]*?\*\//g,""),i=Te(e);for(let d of i.warnings)t.push(`cpp: ${d}`);let o=new Map,a=[],c=[];for(let d of i.rules){let u=d.parts[d.parts.length-1];if(d.hover)for(let l of u.classes){let p=n?`__hover_${l}__${n}`:`__hover_${l}`;o.set(p,fe(o.get(p)??null,d.hover))}if(d.focus&&a.push({scope:n,last:u,focus:d.focus,model:d.model}),d.active&&c.push({scope:n,last:u,active:d.active,model:d.model}),!(d.media&&(d.media.min!==void 0&&au<d.media.min||d.media.max!==void 0&&au>d.media.max)))for(let l of u.classes){let p=n?`${l}__${n}`:l;o.set(p,fe(o.get(p)??null,d.model))}}for(let d of a)for(let u of d.last.classes){let l=d.scope?`__focus_${u}__${d.scope}`:`__focus_${u}`,p=d.scope?`${u}__${d.scope}`:u,f=d.focus.borderColor&&!d.focus.borderWidth?{...d.focus,borderWidth:(o.get(p)??d.model).borderWidth}:d.focus;o.set(l,fe(o.get(l)??null,f))}for(let d of c)for(let u of d.last.classes){let l=d.scope?`__active_${u}__${d.scope}`:`__active_${u}`,p=d.scope?`${u}__${d.scope}`:u,f=d.active.borderColor&&!d.active.borderWidth?{...d.active,borderWidth:(o.get(p)??d.model).borderWidth}:d.active;o.set(l,fe(o.get(l)??null,f))}for(let[d,u]of o)s.set(d,Lh(u));/(^|[\s,])body\b|(^|[\s,])html\b/.test(r)&&t.push("cpp: body/html rules become the window default (Qt has no document)");for(let d of Cn(r))t.push(`cpp: font-family '${d}' needs a registered font family - the Qt default is used`);return s}function Th(e,t){let n=[];fa(e,"cpp",n);for(let r of n)/is not a single class|@media guard|:hover half/.test(r)||t.push(r);let s=e.replace(/\/\*[\s\S]*?\*\//g,"");/letter-spacing\s*:/.test(s)&&t.push("cpp: letter-spacing has no Qt glyph equivalent - dropped"),/box-shadow\s*:/.test(s)&&t.push("cpp: box-shadow has no Qt equivalent - the widget paints flat")}function Eh(e){return Te([e,ke].filter(t=>t&&t.trim()).join(`
|
|
10754
10754
|
`))}function Lh(e){let[t,n,s,r]=e.padding??[0,0,0,0],[i,o,a,c]=e.margin??[0,0,0,0],d=nr(e.fontFamily??"");return{fontSize:ex(e.fontSize??14),color:e.color??"#222222",background:e.background??null,gradient:e.gradient?tx(e.gradient):"",padding:Math.round(Math.max(t,n,s,r)),bold:(e.fontWeight??400)>=600,fontFamily:d==="monospace"?"Monospace":d==="serif"?"Serif":"SansSerif",borderColor:e.borderColor??"",borderWidth:e.borderWidth?Math.round(Math.max(...e.borderWidth)):0,padTop:Math.round(t),padRight:Math.round(n),padBottom:Math.round(s),padLeft:Math.round(r),direction:e.display==="flex"?e.direction??"row":"",gap:Math.round(e.gap??0),justify:e.justify??"",items:e.align??"",alpha:e.opacity??1,...Y_(e),scrolls:e.overflow==="scroll",width:e.width&&e.width.u==="px"?Math.round(e.width.n):0,height:e.height&&e.height.u==="px"?Math.round(e.height.n):0,marginTop:Math.round(i),marginRight:Math.round(o),marginBottom:Math.round(a),marginLeft:Math.round(c),textAlign:e.textAlign??"",lineHeight:e.lineHeight??0,textTransform:e.textTransform??"",italic:e.italic??!1,underline:e.underline??!1,strike:e.strike??!1,minWidth:e.minWidth&&e.minWidth.u==="px"?Math.round(e.minWidth.n):0,maxWidth:e.maxWidth&&e.maxWidth.u==="px"?Math.round(e.maxWidth.n):0,minHeight:e.minHeight&&e.minHeight.u==="px"?Math.round(e.minHeight.n):0,maxHeight:e.maxHeight&&e.maxHeight.u==="px"?Math.round(e.maxHeight.n):0,zIndex:e.zIndex??0}}function tx(e){let t=e.angle*Math.PI/180,n=(.5-Math.sin(t)/2).toFixed(3),s=(.5+Math.cos(t)/2).toFixed(3),r=(.5+Math.sin(t)/2).toFixed(3),i=(.5-Math.cos(t)/2).toFixed(3),o=e.stops.map(a=>`stop:${(Math.max(0,Math.min(100,a.at))/100).toFixed(3)} ${a.color}`).join(", ");return`qlineargradient(x1:${n}, y1:${s}, x2:${r}, y2:${i}, ${o})`}function Es(e){let t=Lh(e);return`RoseStyle{${t.fontSize}, "${t.color}", ${t.background?`"${t.background}"`:'""'}, ${t.padding}, ${t.bold?"true":"false"}, "${t.fontFamily}", "${t.borderColor}", ${t.borderWidth}, ${t.padTop}, ${t.padRight}, ${t.padBottom}, ${t.padLeft}, "${t.direction}", ${t.gap}, "${t.justify}", "${t.items}", ${t.alpha}, ${t.absolute?"true":"false"}, ${t.insetX}, ${t.insetY}, ${t.scrolls?"true":"false"}, ${t.width}, ${t.height}, "${t.gradient}", ${t.marginTop}, ${t.marginRight}, ${t.marginBottom}, ${t.marginLeft}, "${t.textAlign}", ${t.lineHeight}, "${t.textTransform}", ${t.italic?"true":"false"}, ${t.underline?"true":"false"}, ${t.strike?"true":"false"}, ${t.minWidth}, ${t.maxWidth}, ${t.minHeight}, ${t.maxHeight}, ${t.zIndex}}`}function nx(e){let t={};return e.color!==void 0&&(t.color=e.color),e.fontSize!==void 0&&(t.fontSize=e.fontSize),e.fontWeight!==void 0&&(t.fontWeight=e.fontWeight),e.italic!==void 0&&(t.italic=e.italic),e.underline!==void 0&&(t.underline=e.underline),e.strike!==void 0&&(t.strike=e.strike),e.fontFamily!==void 0&&(t.fontFamily=e.fontFamily),e.textTransform!==void 0&&(t.textTransform=e.textTransform),Tt(t)?null:t}function sx(e,t,n,s){let r=t.staticClasses.length?`<${n.tag} class="${t.staticClasses.join(" ")}">`:`<${n.tag}>`;if(e.letterSpacing!==void 0&&s.warnings.push(`cpp: letter-spacing on ${r} - Qt has no glyph-level tracking, dropped`),e.shadow&&s.warnings.push(`cpp: box-shadow on ${r} - Qt widgets paint flat, dropped`),e.radius!==void 0){let i=[...new Set(e.radius.map(o=>`${o}px`))];s.warnings.push(`cpp: border-radius on ${r} - Qt widgets are rectangular, the ${i.join("/")} corner stays square`)}}function rx(e,t,n,s=[]){let r=[...e.entries()].map(([a,c])=>` {"${a}", {${c.fontSize}, "${c.color}", ${c.background?`"${c.background}"`:'""'}, ${c.padding}, ${c.bold?"true":"false"}, ${JSON.stringify(c.fontFamily)}, ${JSON.stringify(c.borderColor)}, ${c.borderWidth}, ${c.padTop}, ${c.padRight}, ${c.padBottom}, ${c.padLeft}, ${JSON.stringify(c.direction)}, ${c.gap}, ${JSON.stringify(c.justify)}, ${JSON.stringify(c.items)}, ${c.alpha}, ${c.absolute?"true":"false"}, ${c.insetX}, ${c.insetY}, ${c.scrolls?"true":"false"}, ${c.width}, ${c.height}, "${c.gradient}", ${c.marginTop}, ${c.marginRight}, ${c.marginBottom}, ${c.marginLeft}, "${c.textAlign}", ${c.lineHeight}, "${c.textTransform}", ${c.italic?"true":"false"}, ${c.underline?"true":"false"}, ${c.strike?"true":"false"}, ${c.minWidth}, ${c.maxWidth}, ${c.minHeight}, ${c.maxHeight}, ${c.zIndex}}},`).join(`
|
|
@@ -10786,7 +10786,7 @@ inline RoseValue roseContentGet(const std::string& coll, const std::string& slug
|
|
|
10786
10786
|
if (rose_get(last, "slug").raw() == quote(slug)) return last;
|
|
10787
10787
|
return RoseValue();
|
|
10788
10788
|
}
|
|
10789
|
-
`:"";return`//
|
|
10789
|
+
`:"";return`// Rosefc - C++ desktop runtime (Qt 6 Widgets).
|
|
10790
10790
|
#pragma once
|
|
10791
10791
|
|
|
10792
10792
|
#include <QApplication>
|
|
@@ -11530,16 +11530,16 @@ std::vector<std::string> rose_keys(const RoseValue& container) {
|
|
|
11530
11530
|
// --- the app --------------------------------------------------------------------
|
|
11531
11531
|
// --- the app --------------------------------------------------------------------
|
|
11532
11532
|
RoseApp::RoseApp(QWidget* parent) : QMainWindow(parent) {
|
|
11533
|
-
setWindowTitle("
|
|
11533
|
+
setWindowTitle("Rosefc");
|
|
11534
11534
|
resize(1100, 800);
|
|
11535
11535
|
scroll_ = new QScrollArea(this);
|
|
11536
11536
|
scroll_->setWidgetResizable(true);
|
|
11537
11537
|
setCentralWidget(scroll_);
|
|
11538
11538
|
// A $persist field starts from QSettings when it has been written before -
|
|
11539
11539
|
// that is what makes it survive a restart.
|
|
11540
|
-
QSettings __s("
|
|
11540
|
+
QSettings __s("Rosefc", "Rosefc");
|
|
11541
11541
|
for (const std::string& key : persisted_) {
|
|
11542
|
-
const QString __k = QString::fromStdString("
|
|
11542
|
+
const QString __k = QString::fromStdString("rosefc:" + key);
|
|
11543
11543
|
if (__s.contains(__k)) state_[key] = RoseValue(__s.value(__k).toString().toStdString());
|
|
11544
11544
|
}
|
|
11545
11545
|
render();
|
|
@@ -11553,8 +11553,8 @@ RoseValue RoseApp::v(const std::string& key) const {
|
|
|
11553
11553
|
void RoseApp::set(const std::string& key, const RoseValue& value) {
|
|
11554
11554
|
state_[key] = value;
|
|
11555
11555
|
if (persisted_.count(key)) {
|
|
11556
|
-
QSettings __s("
|
|
11557
|
-
__s.setValue(QString::fromStdString("
|
|
11556
|
+
QSettings __s("Rosefc", "Rosefc");
|
|
11557
|
+
__s.setValue(QString::fromStdString("rosefc:" + key), QString::fromStdString(rose_str(value)));
|
|
11558
11558
|
}
|
|
11559
11559
|
}
|
|
11560
11560
|
|
|
@@ -11607,7 +11607,7 @@ void RoseApp::render() {
|
|
|
11607
11607
|
loadedRoutes_.push_back(route_);
|
|
11608
11608
|
if (ROSE_API_BASE.size() > 0) {
|
|
11609
11609
|
QNetworkAccessManager manager;
|
|
11610
|
-
QNetworkRequest request(QUrl(QString::fromStdString(ROSE_API_BASE + "/
|
|
11610
|
+
QNetworkRequest request(QUrl(QString::fromStdString(ROSE_API_BASE + "/__rosefc/data?path=" + route_)));
|
|
11611
11611
|
QNetworkReply* reply = manager.get(request);
|
|
11612
11612
|
QEventLoop loop;
|
|
11613
11613
|
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
|
|
@@ -12377,26 +12377,26 @@ int main(int argc, char* argv[]) {
|
|
|
12377
12377
|
return app.exec();
|
|
12378
12378
|
}
|
|
12379
12379
|
`}function lx(e,t){return`cmake_minimum_required(VERSION 3.16)
|
|
12380
|
-
project(
|
|
12380
|
+
project(RosefcApp LANGUAGES CXX)
|
|
12381
12381
|
|
|
12382
12382
|
set(CMAKE_CXX_STANDARD 17)
|
|
12383
12383
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
12384
12384
|
|
|
12385
12385
|
find_package(Qt6 COMPONENTS Widgets Network REQUIRED)
|
|
12386
12386
|
|
|
12387
|
-
add_executable(
|
|
12387
|
+
add_executable(rosefc-app
|
|
12388
12388
|
${[" src/main.cpp"," src/rose.cpp",...e.map(s=>` src/pages/${s.cls}Page.cpp`),...t.map(s=>` src/components/${s.cls}View.cpp`)].join(`
|
|
12389
12389
|
`)}
|
|
12390
12390
|
)
|
|
12391
12391
|
|
|
12392
|
-
target_link_libraries(
|
|
12393
|
-
`}function cx(e,t,n,s){return`#
|
|
12392
|
+
target_link_libraries(rosefc-app PRIVATE Qt6::Widgets Qt6::Network)
|
|
12393
|
+
`}function cx(e,t,n,s){return`# Rosefc -> C++ desktop (Qt 6 Widgets + CMake)
|
|
12394
12394
|
|
|
12395
|
-
Generated by \`
|
|
12395
|
+
Generated by \`rosefc export cpp\` from the project's \`.rose\` pages.
|
|
12396
12396
|
|
|
12397
12397
|
- ${t} page(s), ${n} component(s)
|
|
12398
|
-
- Build: \`cmake -S . -B build && cmake --build build\`, run: \`./build/
|
|
12399
|
-
- Server: \`
|
|
12398
|
+
- Build: \`cmake -S . -B build && cmake --build build\`, run: \`./build/rosefc-app\`
|
|
12399
|
+
- Server: \`rosefc export cpp --api <base>\` writes the base URL into RoseKit.h.
|
|
12400
12400
|
Current: \`${e||"(unset)"}\`
|
|
12401
12401
|
|
|
12402
12402
|
State is a map of \`RoseValue\` variants, a handler mutates it and re-renders, and
|
|
@@ -12445,9 +12445,9 @@ ${g}
|
|
|
12445
12445
|
app.render();
|
|
12446
12446
|
}`)}return{text:d.join(`
|
|
12447
12447
|
|
|
12448
|
-
`),names:o}}function _x(e){let t=["join","split","indexOf","every","startsWith","endsWith","toUpperCase","toLowerCase"],n="",s=0;for(;s<e.length;){let r=e[s];if(r==='"'||r==="'"||r==="`"){let o=xx(e,s);n+=e.slice(s,o),s=o;continue}let i=r==="."?t.find(o=>e.startsWith(`.${o}(`,s)):void 0;if(i){let o=s+i.length+1,a=il(e,o),c=a<0?-1:kx(n);if(a>=0&&c>=0){let d=`${n.slice(c)}.${i}(${e.slice(o+1,a)})`,u=G(d,{...hi,read:l=>`app.v("${l}")`},new Set);if(u!==null){n=n.slice(0,c)+u,s=a+1;continue}}}n+=r,s++}return n}function xx(e,t){let n=e[t],s=t+1;for(;s<e.length&&e[s]!==n;)e[s]==="\\"&&s++,s++;return Math.min(s+1,e.length)}function Nh(e,t){let n=e[t];for(let s=t-1;s>=0;s--){if(e[s]!==n)continue;let r=0,i=s-1;for(;i>=0&&e[i]==="\\";)r++,i--;if(r%2===0)return s}return 0}function ou(e,t){let n=t;for(;;){for(;n>0&&/[\w$]/.test(e[n-1]);)n--;if(n>=2&&e[n-1]==="."&&/[\w$]/.test(e[n-2])){n-=1;continue}return n}}function kx(e){let t=e.length;for(;t>0&&e[t-1]===" ";)t--;if(t===0)return-1;let n=e[t-1];if(n==='"'||n==="'")return ou(e,Nh(e,t-1));if(n===")"){let s=0;for(let r=t-1;r>=0;r--){let i=e[r];if(i==='"'||i==="'"){r=Nh(e,r);continue}if(i===")")s++;else if(i==="("&&--s===0)return ou(e,r)}return-1}return/[\w$\]]/.test(n)?ou(e,t):-1}function Rx(e){let t=Dt(e,"bare");if(t===null)return null;let n=t.slice(1,-1).trim();return n?`RoseValue::object({${n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>{let i=r.indexOf(":");return`{"${r.slice(0,i).trim()}", ${r.slice(i+1).trim()}}`}).join(", ")}})`:"{}"}function Ax(e,t,n,s,r,i){let o=Ot(sn(e));o=tn(o),o=zt(o,{target:"cpp",options:Rx,empty:"RoseValue()",file:t,warn:l=>i.push(`cpp: ${l}`)}).code;{let l=0;o=Qn(o,p=>n.includes(p)?"set"+p.charAt(0).toUpperCase()+p.slice(1):null,()=>String(++l))}if(o=rn(o,(l,p,f)=>{let h=G(f,hi,new Set([p]));if(h===null)return null;let g=`rose_list(app.v("${l}"))`;return`app.set("${l}", ${h})`.replace(new RegExp(`\\b${p}\\b`,"g"),g)}),o=Kn(o,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null},(l,p)=>{let f=G(p,{...hi,read:h=>`app.v("${h}")`},new Set);return f===null?null:`app.set("${l}", ${f});`}),o=on(o,(l,p)=>{let f=G(p,{...hi,read:h=>`app.v("${h}")`},new Set);return f===null?null:`app.set("${l}", ${f});`}),o=_x(o),o=Gn(o,(l,p,f,h)=>`app.set("${p}", rose_${l}(${f}, ${h}))`,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null}),o=Kr(o,l=>`rose_count(${l})`),/\bFormData\(|\bdocument\.|\bwindow\.|\bnew\s+[A-Z]/.test(o)||/=>/.test(o)||/\.\.\./.test(o)||/\.(push|unshift|splice)\(/.test(o))return i.push(`cpp: ${t}: a handler uses a web-only construct (DOM/FormData/new/arrow) - emitted as a stub`)," //
|
|
12448
|
+
`),names:o}}function _x(e){let t=["join","split","indexOf","every","startsWith","endsWith","toUpperCase","toLowerCase"],n="",s=0;for(;s<e.length;){let r=e[s];if(r==='"'||r==="'"||r==="`"){let o=xx(e,s);n+=e.slice(s,o),s=o;continue}let i=r==="."?t.find(o=>e.startsWith(`.${o}(`,s)):void 0;if(i){let o=s+i.length+1,a=il(e,o),c=a<0?-1:kx(n);if(a>=0&&c>=0){let d=`${n.slice(c)}.${i}(${e.slice(o+1,a)})`,u=G(d,{...hi,read:l=>`app.v("${l}")`},new Set);if(u!==null){n=n.slice(0,c)+u,s=a+1;continue}}}n+=r,s++}return n}function xx(e,t){let n=e[t],s=t+1;for(;s<e.length&&e[s]!==n;)e[s]==="\\"&&s++,s++;return Math.min(s+1,e.length)}function Nh(e,t){let n=e[t];for(let s=t-1;s>=0;s--){if(e[s]!==n)continue;let r=0,i=s-1;for(;i>=0&&e[i]==="\\";)r++,i--;if(r%2===0)return s}return 0}function ou(e,t){let n=t;for(;;){for(;n>0&&/[\w$]/.test(e[n-1]);)n--;if(n>=2&&e[n-1]==="."&&/[\w$]/.test(e[n-2])){n-=1;continue}return n}}function kx(e){let t=e.length;for(;t>0&&e[t-1]===" ";)t--;if(t===0)return-1;let n=e[t-1];if(n==='"'||n==="'")return ou(e,Nh(e,t-1));if(n===")"){let s=0;for(let r=t-1;r>=0;r--){let i=e[r];if(i==='"'||i==="'"){r=Nh(e,r);continue}if(i===")")s++;else if(i==="("&&--s===0)return ou(e,r)}return-1}return/[\w$\]]/.test(n)?ou(e,t):-1}function Rx(e){let t=Dt(e,"bare");if(t===null)return null;let n=t.slice(1,-1).trim();return n?`RoseValue::object({${n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>{let i=r.indexOf(":");return`{"${r.slice(0,i).trim()}", ${r.slice(i+1).trim()}}`}).join(", ")}})`:"{}"}function Ax(e,t,n,s,r,i){let o=Ot(sn(e));o=tn(o),o=zt(o,{target:"cpp",options:Rx,empty:"RoseValue()",file:t,warn:l=>i.push(`cpp: ${l}`)}).code;{let l=0;o=Qn(o,p=>n.includes(p)?"set"+p.charAt(0).toUpperCase()+p.slice(1):null,()=>String(++l))}if(o=rn(o,(l,p,f)=>{let h=G(f,hi,new Set([p]));if(h===null)return null;let g=`rose_list(app.v("${l}"))`;return`app.set("${l}", ${h})`.replace(new RegExp(`\\b${p}\\b`,"g"),g)}),o=Kn(o,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null},(l,p)=>{let f=G(p,{...hi,read:h=>`app.v("${h}")`},new Set);return f===null?null:`app.set("${l}", ${f});`}),o=on(o,(l,p)=>{let f=G(p,{...hi,read:h=>`app.v("${h}")`},new Set);return f===null?null:`app.set("${l}", ${f});`}),o=_x(o),o=Gn(o,(l,p,f,h)=>`app.set("${p}", rose_${l}(${f}, ${h}))`,l=>{let p=l.slice(3,4).toLowerCase()+l.slice(4);return l.length>3&&n.includes(p)?p:null}),o=Kr(o,l=>`rose_count(${l})`),/\bFormData\(|\bdocument\.|\bwindow\.|\bnew\s+[A-Z]/.test(o)||/=>/.test(o)||/\.\.\./.test(o)||/\.(push|unshift|splice)\(/.test(o))return i.push(`cpp: ${t}: a handler uses a web-only construct (DOM/FormData/new/arrow) - emitted as a stub`)," // rosefc: handler body not translated (web-only construct).";let a=vx(o.trim());a=a.replace(/\bawait\s+/g,""),a=a.replace(/\$action\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(l,p,f)=>`${f}(app)`),a=a.replace(/\brefresh\s*\(\s*\)/g,"app.render()"),a=a.replace(/\bconsole\.(?:log|warn|error)\(/g,"qDebug("),a=a.replace(/\bString\(\s*\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)\s*(?:\|\|\s*'[^']*')?\s*\)/g,(l,p,f)=>`rose_str(app.v("${f}"))`),a=a.replace(/\$formRead\s*\(\s*(['"])([^'"]*)\1\s*\)/g,(l,p,f)=>`rose_str(app.v("${f}"))`),a=a.replace(/\bString\(/g,"rose_str("),a=a.replace(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,"auto $1 ="),a=a.replace(/\bnull\b/g,"RoseValue()").replace(/\bundefined\b/g,"RoseValue()"),a=a.replace(/'((?:[^'\\\\]|\\\\.)*)'/g,'"$1"'),a=a.replace(/===/g,"==").replace(/!==/g,"!=");let c=new Set(n);a=a.replace(/\b([A-Za-z_$][\w$]*)\s*\(\s*\)/g,(l,p)=>{if(!c.has(p))return l;let f=r.get(p)??"RoseValue";return f==="double"?`rose_num(app.v("${p}"))`:f==="bool"?`rose_bool(app.v("${p}"))`:f==="std::string"?`rose_str(app.v("${p}"))`:`app.v("${p}")`});for(let l of c){let p=l.charAt(0).toUpperCase()+l.slice(1);a=a.replace(new RegExp(`\\bset${p}\\s*\\(`,"g"),`app.set("${l}", `)}let d=[...s].filter(l=>!c.has(l));d.length&&(a=nt(a,(l,p)=>d.includes(l)?`rose_get(${l}, "${p}")`:`${l}.${p}`)),a=Rn(a,l=>`!${l}.empty()`),a=At(a,l=>`!rose_str(${l}).empty()`,()=>!0),a=pt(a,l=>`std::to_string(${l})`);let u=a.split(`
|
|
12449
12449
|
`).map(l=>l.trim()).filter(Boolean);return u.length?u.map(l=>" "+l).join(`
|
|
12450
|
-
`):" //
|
|
12450
|
+
`):" // rosefc: an empty handler."}function cu(e){return[...(e??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]*)?=\s*([^;\n]+)/g)].map(t=>({name:t[1],init:t[2].trim()}))}function Cx(e,t,n,s){let r=[...(e.script??"").matchAll(/export\s+let\s+([A-Za-z_$][\w$]*)/g)].map(c=>c[1]),i={warnings:n,file:e.cls,stateNames:new Set(r),componentProps:new Set(r),scope:e.cls,stateTypes:new Map(r.map(c=>[c,"RoseValue"])),mapBinds:new Set,components:[],lines:[],depth:1,sheet:s,ancestors:[],inherited:null,styles:t,app:"app",parent:"parent",counter:{n:0},forms:St(e.nodes),formSubmit:null,pageAction:null,awaits:[],deferred:[],scriptConsts:new Map};Ln(e.nodes,i);let o=[],a=gn(e.nodes,r);for(let c of a)o.push(`, const std::function<void(const RoseValue&)>& ${ze(c)}`);e.slots.hasDefault&&o.push(", const std::function<void(QWidget*)>& slotDefault");for(let c of e.slots.named)o.push(`, const std::function<void(const std::map<std::string, RoseValue>&, QWidget*)>& slot${c.name.charAt(0).toUpperCase()}${c.name.slice(1)}`);return`// ${e.name} - generated from a .rose component.
|
|
12451
12451
|
#include "../rose.h"
|
|
12452
12452
|
#include "../pages.h"
|
|
12453
12453
|
|
|
@@ -12461,29 +12461,29 @@ ${i.lines.join(`
|
|
|
12461
12461
|
} // namespace pages
|
|
12462
12462
|
`}var G_,Q_,au,Mh,Fh,ex,hi,Dh=De(()=>{"use strict";Un();kn();vs();ks();_s();xs();ls();hn();gs();hn();G_=new Set(["h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","small","code","pre","label","legend","blockquote","time","mark","q","s","u","sub","sup","abbr","cite","caption","td","th"]),Q_=new Set(["header","footer","nav"]),au=390,Mh=new Map,Fh=new Map;ex=e=>Math.round(e);hi={get:(e,t)=>`rose_get(${e}, "${t}")`,count:e=>`rose_count(${e})`,bool:e=>`rose_bool(${e})`,merge:(e,t)=>`rose_merge(${e}, ${t})`,obj:e=>`RoseValue::object({${e.map(([t,n])=>`{"${t}", ${n}}`).join(", ")}})`,map:(e,t,n)=>t.length>1?`rose_map_idx(${e}, [](const RoseValue& ${t[0]}, int ${t[1]}) { return ${n}; })`:`rose_map(${e}, [](const RoseValue& ${t[0]}) { return ${n}; })`,filter:(e,t,n)=>`rose_filter(${e}, [](const RoseValue& ${t[0]}) { return ${n}; })`,slice:(e,t,n)=>n===null?`rose_slice(${e}, ${t})`:`rose_slice(${e}, ${t}, ${n})`,find:(e,t,n)=>`rose_find(${e}, [&](const RoseValue& ${t[0]}) { return ${n}; })`,some:(e,t,n)=>`rose_any(${e}, [&](const RoseValue& ${t[0]}) { return ${n}; })`,join:(e,t)=>`rose_join(${e}, ${t})`,split:(e,t)=>`rose_split(${e}, ${t})`,indexOf:(e,t)=>`rose_index_of(${e}, ${t})`,every:(e,t,n)=>`rose_all(${e}, [&](const RoseValue& ${t[0]}) { return ${n}; })`,startsWith:(e,t)=>`rose_starts_with(${e}, ${t})`,endsWith:(e,t)=>`rose_ends_with(${e}, ${t})`,upper:e=>`rose_upper(${e})`,lower:e=>`rose_lower(${e})`,reduce:(e,t,n,s)=>s===null?`rose_reduce(${e}, [](const RoseValue& ${t[0]}, const RoseValue& ${t[1]}) { return ${n}; })`:`rose_reduce(${e}, ${s}, [](const RoseValue& ${t[0]}, const RoseValue& ${t[1]}) { return ${n}; })`,append:(e,t)=>`rose_append(${e}, ${t})`,concat:(e,t)=>`rose_concat(${e}, ${t})`,arr:e=>`RoseValue::list({${e.join(", ")}})`,not:e=>`!rose_bool(${e})`,lit:e=>e,template:e=>{let t=e.map(n=>"expr"in n?`rose_str(${n.expr})`:`std::string(${JSON.stringify(n.text)})`);return t.length===0?"std::string()":t.length===1?t[0]:`(${t.join(" + ")})`},index:(e,t)=>`rose_index(${e}, ${t})`,nullish:(e,t)=>`(!rose_is_null(${e}) ? ${e} : ${t})`,optChain:(e,t)=>`rose_get(${e}, "${t}")`}});var zh={};hg(zh,{TARGETS:()=>ol,exportProject:()=>Ox,isTarget:()=>jx,targetList:()=>uu});import*as vt from"node:fs";import*as qe from"node:path";function jx(e){return Object.prototype.hasOwnProperty.call(ol,e)}function uu(){let e=new Map;for(let t of Object.values(ol)){let n=e.get(t.family)??[];n.push(t.status==="ready"?t.name:`${t.name} (planned)`),e.set(t.family,n)}return[...e.entries()].map(([t,n])=>` ${t}: ${n.join(", ")}`).join(`
|
|
12463
12463
|
`)}async function Ex(e,t,n){let s=Tx[e];if(!s)return;let r=e==="python"?await Ke(t):[...await Ye(t),...await Ke(t)];for(let i of r){let o="";try{o=await vt.promises.readFile(i,"utf8")}catch{continue}let a=0;for(let c of o.matchAll(/<script[^>]*>([\s\S]*?)<\/script>/g))a+=oa(c[1]??"").length;a&&n.push(`${qe.relative(t,i).replace(/\\/g,"/")}: ${gp(s,a)}`)}}async function Ox(e,t,n={}){let s=ol[e];if(!s)throw new Error(`unknown export target "${e}"
|
|
12464
|
-
${uu()}`);let r=n.outRoot??qe.join(t,".
|
|
12465
|
-
${uu()}`);if(await Ex(e,t,i),s.family==="mini-program"){let o=await jp({projectRoot:t,outDir:r,target:e,apiBase:n.apiBase,cloud:n.cloud,cloudEnv:n.cloudEnv,warnings:i}),a=qe.join(r,wa[e].dir);await vt.promises.mkdir(a,{recursive:!0}),await vt.promises.writeFile(qe.join(a,"
|
|
12466
|
-
`,"utf8");try{let c=qe.join(t,"
|
|
12464
|
+
${uu()}`);let r=n.outRoot??qe.join(t,".rosefc-export"),i=[];if(s.status!=="ready")throw new Error(`export target "${e}" is planned, not implemented yet - shipping targets today:
|
|
12465
|
+
${uu()}`);if(await Ex(e,t,i),s.family==="mini-program"){let o=await jp({projectRoot:t,outDir:r,target:e,apiBase:n.apiBase,cloud:n.cloud,cloudEnv:n.cloudEnv,warnings:i}),a=qe.join(r,wa[e].dir);await vt.promises.mkdir(a,{recursive:!0}),await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12466
|
+
`,"utf8");try{let c=qe.join(t,"rosefc.mp.json");if(vt.existsSync(c)){let d=(await vt.promises.readFile(c,"utf8")).replace(/^\uFEFF/,""),u=JSON.parse(d),l=qe.join(a,"app.json"),p=JSON.parse(await vt.promises.readFile(l,"utf8")),f=u.projectname??u.projectName,h=u.cloudEnv;delete u.projectname,delete u.projectName,delete u.cloudEnv,delete u.appid;for(let g of Object.keys(u)){let y=u[g];y&&typeof y=="object"&&!Array.isArray(y)&&p[g]&&typeof p[g]=="object"&&!Array.isArray(p[g])?p[g]={...p[g],...y}:p[g]=y}if(await vt.promises.writeFile(l,JSON.stringify(p,null,2)+`
|
|
12467
12467
|
`,"utf8"),f){let g=qe.join(a,"project.config.json");if(vt.existsSync(g)){let y=JSON.parse(await vt.promises.readFile(g,"utf8"));y.projectname=f,await vt.promises.writeFile(g,JSON.stringify(y,null,2)+`
|
|
12468
|
-
`,"utf8")}}}}catch(c){i.push(`
|
|
12469
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="cpp"){let o=await Ph({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"cpp");return await vt.promises.writeFile(qe.join(a,"
|
|
12470
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="dotnet"){let o=await bh({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"dotnet");return await vt.promises.writeFile(qe.join(a,"
|
|
12471
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="java"){let o=await ih({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"java");return await vt.promises.writeFile(qe.join(a,"
|
|
12472
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="electron"){let o=await Uf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"electron");return await vt.promises.writeFile(qe.join(a,"
|
|
12473
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="xcode"){let o=await Bf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"xcode");return await vt.promises.writeFile(qe.join(a,"
|
|
12474
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="android"){let o=await xf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"android");return await vt.promises.writeFile(qe.join(a,"
|
|
12475
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="arkts"){let o=await pf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"arkts");return await vt.promises.writeFile(qe.join(a,"
|
|
12476
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="python"){let o=await Zp({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"python");return await vt.promises.writeFile(qe.join(a,"
|
|
12477
|
-
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}throw new Error(`no emitter for target family "${s.family}"`)}var ol,Tx,Hh=De(()=>{"use strict";Lp();Hp();lf();bf();Tf();Vf();Gf();dh();Ch();Dh();hn();kn();ol={weapp:{name:"weapp",family:"mini-program",dir:"weapp",status:"ready",summary:"WeChat mini program (WXML/WXSS/JS)"},qq:{name:"qq",family:"mini-program",dir:"qq",status:"ready",summary:"QQ mini program (QML/QSS)"},alipay:{name:"alipay",family:"mini-program",dir:"alipay",status:"ready",summary:"Alipay mini program (AXML/ACSS)"},baidu:{name:"baidu",family:"mini-program",dir:"baidu",status:"ready",summary:"Baidu smart program (SWAN)"},toutiao:{name:"toutiao",family:"mini-program",dir:"toutiao",status:"ready",summary:"Douyin/Toutiao mini program (TTML)"},flutter:{name:"flutter",family:"native",dir:"flutter",status:"ready",summary:"Flutter/Dart project (one codebase: iOS, Android, desktop, web)"},android:{name:"android",family:"native",dir:"android",status:"ready",summary:"Android Studio project (Kotlin + Jetpack Compose)"},arkts:{name:"arkts",family:"native",dir:"arkts",status:"ready",summary:"HarmonyOS project (ArkTS + ArkUI, DevEco Studio)"},xcode:{name:"xcode",family:"native",dir:"xcode",status:"ready",summary:"Xcode project (SwiftUI, iOS/macOS)"},electron:{name:"electron",family:"desktop",dir:"electron",status:"ready",summary:"Electron desktop shell around the built web app"},python:{name:"python",family:"desktop",dir:"python",status:"ready",summary:"Python desktop app (stdlib Tkinter, no pip install)"},dotnet:{name:"dotnet",family:"desktop",dir:"dotnet",status:"ready",summary:".NET desktop app (WPF, net8.0-windows, C#)"},java:{name:"java",family:"desktop",dir:"java",status:"ready",summary:"JVM desktop app (Java Swing, stdlib only)"},cpp:{name:"cpp",family:"desktop",dir:"cpp",status:"ready",summary:"C++ desktop app (Qt 6 Widgets, CMake)"}};Tx={flutter:"flutter",android:"android",arkts:"arkts",xcode:"swift",java:"java",dotnet:"dotnet",cpp:"cpp",python:"python"}});kn();Rl();Un();import*as K from"fs";import*as Z from"path";import*as Xh from"os";import*as Ze from"zlib";import{createHash as Nx}from"crypto";import{createRequire as Mx}from"module";import{pathToFileURL as ul,fileURLToPath as $u}from"url";import{promisify as wu}from"util";import{AsyncLocalStorage as Fx}from"async_hooks";import{Worker as Px}from"worker_threads";import*as Ui from"node:fs";import*as Qr from"node:path";function ry(e){let t={name:e.name,short_name:e.shortName??e.name,description:e.description??"",start_url:e.startUrl??"/",display:e.display??"standalone",background_color:e.backgroundColor??"#ffffff",theme_color:e.themeColor??"#000000",icons:e.icon?[{src:e.icon,sizes:"any",type:"image/png",purpose:"any"}]:[]};return JSON.stringify(t,null,2)}function iy(e,t){let n="
|
|
12468
|
+
`,"utf8")}}}}catch(c){i.push(`rosefc.mp.json could not be merged (${c instanceof Error?c.message:String(c)}) - the generated app.json is kept`)}return{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="flutter"){let o=await zp({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"flutter");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12469
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="cpp"){let o=await Ph({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"cpp");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12470
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="dotnet"){let o=await bh({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"dotnet");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12471
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="java"){let o=await ih({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"java");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12472
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="electron"){let o=await Uf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"electron");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12473
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="xcode"){let o=await Bf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"xcode");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12474
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="android"){let o=await xf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"android");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12475
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="arkts"){let o=await pf({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"arkts");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12476
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}if(e==="python"){let o=await Zp({projectRoot:t,outDir:r,apiBase:n.apiBase,warnings:i}),a=qe.join(r,"python");return await vt.promises.writeFile(qe.join(a,"rosefc-export.json"),JSON.stringify({framework:"rosefc",target:e,generatedBy:"rosefc export",pages:o.pages,components:o.components,apiBase:n.apiBase??""},null,2)+`
|
|
12477
|
+
`,"utf8"),{target:e,outDir:a,pages:o.pages,components:o.components,warnings:i}}throw new Error(`no emitter for target family "${s.family}"`)}var ol,Tx,Hh=De(()=>{"use strict";Lp();Hp();lf();bf();Tf();Vf();Gf();dh();Ch();Dh();hn();kn();ol={weapp:{name:"weapp",family:"mini-program",dir:"weapp",status:"ready",summary:"WeChat mini program (WXML/WXSS/JS)"},qq:{name:"qq",family:"mini-program",dir:"qq",status:"ready",summary:"QQ mini program (QML/QSS)"},alipay:{name:"alipay",family:"mini-program",dir:"alipay",status:"ready",summary:"Alipay mini program (AXML/ACSS)"},baidu:{name:"baidu",family:"mini-program",dir:"baidu",status:"ready",summary:"Baidu smart program (SWAN)"},toutiao:{name:"toutiao",family:"mini-program",dir:"toutiao",status:"ready",summary:"Douyin/Toutiao mini program (TTML)"},flutter:{name:"flutter",family:"native",dir:"flutter",status:"ready",summary:"Flutter/Dart project (one codebase: iOS, Android, desktop, web)"},android:{name:"android",family:"native",dir:"android",status:"ready",summary:"Android Studio project (Kotlin + Jetpack Compose)"},arkts:{name:"arkts",family:"native",dir:"arkts",status:"ready",summary:"HarmonyOS project (ArkTS + ArkUI, DevEco Studio)"},xcode:{name:"xcode",family:"native",dir:"xcode",status:"ready",summary:"Xcode project (SwiftUI, iOS/macOS)"},electron:{name:"electron",family:"desktop",dir:"electron",status:"ready",summary:"Electron desktop shell around the built web app"},python:{name:"python",family:"desktop",dir:"python",status:"ready",summary:"Python desktop app (stdlib Tkinter, no pip install)"},dotnet:{name:"dotnet",family:"desktop",dir:"dotnet",status:"ready",summary:".NET desktop app (WPF, net8.0-windows, C#)"},java:{name:"java",family:"desktop",dir:"java",status:"ready",summary:"JVM desktop app (Java Swing, stdlib only)"},cpp:{name:"cpp",family:"desktop",dir:"cpp",status:"ready",summary:"C++ desktop app (Qt 6 Widgets, CMake)"}};Tx={flutter:"flutter",android:"android",arkts:"arkts",xcode:"swift",java:"java",dotnet:"dotnet",cpp:"cpp",python:"python"}});kn();Rl();Un();import*as K from"fs";import*as Z from"path";import*as Xh from"os";import*as Ze from"zlib";import{createHash as Nx}from"crypto";import{createRequire as Mx}from"module";import{pathToFileURL as ul,fileURLToPath as $u}from"url";import{promisify as wu}from"util";import{AsyncLocalStorage as Fx}from"async_hooks";import{Worker as Px}from"worker_threads";import*as Ui from"node:fs";import*as Qr from"node:path";function ry(e){let t={name:e.name,short_name:e.shortName??e.name,description:e.description??"",start_url:e.startUrl??"/",display:e.display??"standalone",background_color:e.backgroundColor??"#ffffff",theme_color:e.themeColor??"#000000",icons:e.icon?[{src:e.icon,sizes:"any",type:"image/png",purpose:"any"}]:[]};return JSON.stringify(t,null,2)}function iy(e,t){let n="rosefc-sw-v1",s=JSON.stringify([...new Set(["/",...t,e.offlineFallback].filter(Boolean))]);return`const CACHE='${n}';const PRECACHE=${s};
|
|
12478
12478
|
self.addEventListener('install',e=>{e.waitUntil(caches.open(CACHE).then(c=>c.addAll(PRECACHE)).then(()=>self.skipWaiting()));});
|
|
12479
12479
|
self.addEventListener('activate',e=>{e.waitUntil(caches.keys().then(ks=>Promise.all(ks.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()));});
|
|
12480
12480
|
self.addEventListener('fetch',e=>{const r=e.request;if(r.method!=='GET')return;const u=new URL(r.url);if(u.origin!==location.origin)return;
|
|
12481
12481
|
if(PRECACHE.includes(u.pathname)){e.respondWith(caches.match(r).then(c=>c||fetch(r).then(resp=>{const cp=resp.clone();caches.open(CACHE).then(c=>c.put(r,cp));return resp;})););return;}
|
|
12482
12482
|
e.respondWith(fetch(r).then(resp=>{const cp=resp.clone();caches.open(CACHE).then(c=>c.put(r,cp));return resp;}).catch(()=>caches.match(r).then(c=>c||caches.match('${e.offlineFallback??"/"}'))));});`}function oy(e,t){let n=new Set(t??[]),s=(r,i)=>{for(let o of Ui.readdirSync(r,{withFileTypes:!0})){if(o.name==="sw.js"||o.name.endsWith(".br"))continue;let a=Qr.join(r,o.name);o.isDirectory()?s(a,i+o.name+"/"):/\.(js|css|html)$/.test(o.name)&&n.add("/"+(i+o.name).split(Qr.sep).join("/"))}};try{s(e,"")}catch{}return[...n]}async function qd(e,t){let n=Qr.join(e,"manifest.webmanifest"),s=Qr.join(e,"sw.js");await Ui.promises.writeFile(n,ry(t));let r=oy(e,t.precache);return await Ui.promises.writeFile(s,iy(t,r)),[n,s]}function Gd(e,t){return e.includes("</head>")?e.replace("</head>",` <link rel="manifest" href="/manifest.webmanifest">
|
|
12483
12483
|
<script>if('serviceWorker' in navigator){addEventListener('load',()=>navigator.serviceWorker.register('/sw.js').catch(()=>{}));}</script>
|
|
12484
|
-
</head>`):e}var Qd=`#
|
|
12484
|
+
</head>`):e}var Qd=`# Rosefc authoring contract (printed by \`rosefc prompt\`)
|
|
12485
12485
|
|
|
12486
|
-
|
|
12486
|
+
Rosefc is a zero-hydration web framework: a .rose file compiles to a server
|
|
12487
12487
|
render plus a client resume bundle, one request per page, no hydration. Write
|
|
12488
12488
|
the smallest thing that works - the compiler decides what ships.
|
|
12489
12489
|
|
|
@@ -12576,7 +12576,7 @@ Rules the compiler enforces (breaking one fails the build):
|
|
|
12576
12576
|
slide-up/down/left/right, scale, spin, blur, stagger; params via
|
|
12577
12577
|
transition:fade={300} or transition:fade={duration: 300} (the trailing
|
|
12578
12578
|
number wins), or the bare name (300 ms default). Custom: register
|
|
12579
|
-
globalThis.
|
|
12579
|
+
globalThis.__rosefcTransitions.NAME = (el, duration, phase) => cleanup? \u2014
|
|
12580
12580
|
a transition:NAME that is not a built-in falls through to it (phase
|
|
12581
12581
|
'both'/'in'/'out'; built-ins always win).
|
|
12582
12582
|
- $actionPending() is true while a server action is in flight: use it to
|
|
@@ -12674,7 +12674,7 @@ $t('key', { name }) translates reactively; unknown locales answer 404.
|
|
|
12674
12674
|
## When a build fails
|
|
12675
12675
|
|
|
12676
12676
|
Every compiler failure is structured: { code, file, line, message, hint }.
|
|
12677
|
-
Run \`
|
|
12677
|
+
Run \`rosefc build --json\` to read it as JSON, fix the named file at the named
|
|
12678
12678
|
line, and build again. The plain (non-JSON) output prints the same message,
|
|
12679
12679
|
the hint, a numbered excerpt of the offending source line, and the file:line
|
|
12680
12680
|
locator. Codes: E-IMPORT (unresolvable .rose import), E-PLUGIN (transform
|
|
@@ -12690,8 +12690,8 @@ A route ships ONE request with ZERO hydration: the whole client bundle is
|
|
|
12690
12690
|
inlined in the document. Keep it that way - browser-only code (document.,
|
|
12691
12691
|
window., timers) belongs in onMount, and anything the predicate cannot see
|
|
12692
12692
|
(inline on* attributes, javascript: URLs, eval) is reported by the build.
|
|
12693
|
-
`;Un();import{pathToFileURL as ay}from"url";import{join as ra}from"path";function ta(e,t,n){let s=String(n("accept-language")??"").trim().toLowerCase(),r=t?.(e)??[];return r.length?[s,...r.map(i=>String(n(i)??"").trim())]:[s]}var na=[],qi=null;globalThis.__rosefdOnShutdown=Kd;globalThis.__rosefdRunShutdownHooks=sa;function Kd(e,t){let n={name:e,fn:t};return na.push(n),()=>{let s=na.indexOf(n);s!==-1&&na.splice(s,1)}}function sa(e){return qi||(qi=(async()=>{let t=[];for(let n of na.slice())try{await n.fn(),t.push({name:n.name,ok:!0})}catch(s){let r=s instanceof Error?s.message:String(s);t.push({name:n.name,ok:!1,error:r}),console.error(`[rosefd] shutdown hook ${n.name} failed (${e}):`,r)}return t})().finally(()=>{qi=null}),qi)}function ly(e){let t=e.method;if(t!=="POST"&&t!=="PUT"&&t!=="PATCH"&&t!=="DELETE")return null;let n=e.headers.get("origin");if(n){let r;try{r=new URL(n).host}catch{return new Response("Cross-site request blocked (unparsable Origin header)",{status:403})}return r===new URL(e.url).host?null:new Response("Cross-site request blocked (Origin does not match Host)",{status:403})}let s=e.headers.get("sec-fetch-site");return s&&s!=="same-origin"&&s!=="same-site"&&s!=="none"?new Response(`Cross-site request blocked (sec-fetch-site: ${s})`,{status:403}):null}var Zd=Promise.resolve(),cy=e=>{let t=Zd,n;return Zd=new Promise(s=>{n=s}),t.then(e).finally(n)};async function Xd(e,t){let n=t?.server??await import(ay(ra(e,"server.js")).href),s=null,r="";if(t&&"client"in t)s=t.client??null;else try{s=await(await import("fs/promises")).readFile(ra(e,"client.js"),"utf-8")}catch{s=null}s&&s.includes("chunks/")&&(s=null);let i=typeof n.sliceKeyFor=="function";i&&Xo("sliced");let o=d=>i?Ws(n.sliceKeyFor(d),e):s;if(t&&"styles"in t)r=t.styles??"";else try{r=await(await import("fs/promises")).readFile(ra(e,"styles.css"),"utf-8")}catch{r=""}let a=new Set;if(t&&"broken"in t)a=new Set(t.broken);else try{a=new Set(JSON.parse(await(await import("fs/promises")).readFile(ra(e,"broken.json"),"utf-8")))}catch{a=new Set}let c=(d,u="")=>{let l={};for(let[f,h]of Object.entries(Gr(o(d),u)))l[f.toLowerCase()]=h;l["cache-control"]||(l["cache-control"]="no-cache");let p=n.headersFor?.(d);if(p)for(let[f,h]of Object.entries(p))l[f.toLowerCase()]=h;return l};return async function(u){let l=ly(u);if(l)return l;let{pathname:p,searchParams:f}=new URL(u.url),h=p.replace(/\/+$/,"")||"/";return h!==p?new Response(null,{status:308,headers:{location:h+new URL(u.url).search}}):cy(async()=>{n.setQuery?.(Object.fromEntries(f));let g=n.hasRequestHooks||n.hasResponseHooks?{request:u,url:new URL(u.url),method:u.method,pathname:p,state:{}}:null;if(g){let C=await n.runRequestHooks(g);if(C)return n.runResponseHooks(g,C)}if(n.middleware){let C=await n.runMiddleware(u);if(C)return g?n.runResponseHooks(g,C):C}if(p==="/__rosefd/data"&&u.method==="GET"){let C=f.get("path")||"/";try{if(n.middleware){let R=await n.runMiddleware(new Request(new URL(C,u.url),{method:"GET",headers:u.headers}));if(R){let T=new Headers(R.headers);return T.set("access-control-allow-origin","*"),new Response(await R.arrayBuffer(),{status:R.status,headers:T})}}n.setQuery?.(Object.fromEntries(new URL("http://x"+C).searchParams));let x=await n.renderPage(C,void 0,{withState:!0}),A={};try{A=JSON.parse(x?.state||"{}")}catch{A={}}return new Response(JSON.stringify({path:C,status:x?.status??200,state:A}),{status:200,headers:{"content-type":"application/json; charset=utf-8","access-control-allow-origin":"*","cache-control":"no-store"}})}catch(x){return new Response(JSON.stringify({error:String(x?.message??x).slice(0,200)}),{status:500,headers:{"content-type":"application/json; charset=utf-8","access-control-allow-origin":"*"}})}}if(n.isApi(p)){if(u.method!=="GET"){let x=n.invalidateRenderCache;typeof x=="function"&&x()}let C=await n.handleApi(u.method,p,u);return g?n.runResponseHooks(g,C):C}let y=u.method==="POST"?await u.formData():void 0;if(y){let C=n.invalidateRenderCache;typeof C=="function"&&C()}if(!y&&!a.has(p)&&!n.isBuffered?.(p)&&n.canStream(p)&&!n.isNoJs(p)&&!u.headers.get("x-pjax")){let C=n.cspNonce?.(p)?Vi():"",x=new Response(null,{status:200,headers:{"content-type":"text/html; charset=utf-8",...c(p,C)}}),A=g?await n.runResponseHooks(g,x):x,R=new TextEncoder,T=new ReadableStream({async start(M){let F=n.docAttrs(p);await n.renderPageStream(p,I=>M.enqueue(R.encode(I)),Yo(r,F.lang,F.dir,!n.shellOff?.(p)),Ji(o(p),C)),M.close()}});return new Response(T,{status:A.status,headers:A.headers})}let m=u.headers.get("cookie")||"",b=f.toString(),$=ta(p,n.hotVaryFor,C=>u.headers.get(C)).join("\0"),v=(!y&&n.isCachedRoute?.(p)?n.peekRenderCache?.(p,m,b,$):null)??(n.renderPageCached&&!y?await n.renderPageCached(p,m,b,$):await n.renderPage(p,y)),_=n.cspNonce?.(p)?Vi():"";if(v.redirect){let C=v.redirect,x=new URL(C,u.url),A=`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${C}">${C}</a>.</p>`;return new Response(A,{status:v.status??302,headers:{"content-type":"text/html; charset=utf-8",location:x.pathname+x.search}})}let k=Xl(v.html,v.state,o(p),v.head,r,v.csr!==!1,v.lang,v.dir,_,v.shell!==!1);u.headers.get("x-pjax")&&(k=uy(k));let S=new Response(k,{status:v.status??200,headers:{"content-type":"text/html; charset=utf-8",...c(p,_)}});return g?n.runResponseHooks(g,S):S})}}function uy(e){let t=e.indexOf('<main id="sk-main"');if(t<0)return e;let n=e.indexOf("</main>",t);if(n<0)return e;let s=e.slice(t,n+7),r=e.match(/<title>([\s\S]*?)<\/title>/i);return(r?r[0]:"")+s}function Yd(e,t){let s=String(e.headers?.["x-forwarded-proto"]||"").split(",")[0].trim(),r=s==="https"||s==="http"?s:"http",o=String(e.headers?.["x-forwarded-host"]||"").split(",")[0].trim()||e.headers?.host||`localhost:${t}`;return`${r}://${o}`}import{createHash as dy}from"node:crypto";function py(e){return'W/"'+dy("sha1").update(e).digest("base64url").slice(0,24)+'"'}function Gi(e,t){return e.headers.get("etag")??py(t)}function Sr(e,t){if(!e)return!1;let n=t.startsWith("W/")?t.slice(2):t;for(let s of(Array.isArray(e)?e.join(","):e).split(",")){let r=s.trim();if(r&&(r==="*"||(r.startsWith("W/")?r.slice(2):r)===n))return!0}return!1}function dl(e){let t=e.headers["accept-encoding"]||"";return t.includes("br")?"br":t.includes("gzip")?"gzip":t.includes("deflate")?"deflate":null}function mi(e,t){let n=e.getHeader("vary"),r=(n==null?"":Array.isArray(n)?n.join(", "):String(n)).split(",").map(i=>i.trim()).filter(Boolean);r.some(i=>i.toLowerCase()===t.toLowerCase())||r.push(t),e.setHeader("Vary",r.join(", "))}var ml={[Ze.constants.BROTLI_PARAM_QUALITY]:5};function Lx(e,t){return e==="br"?Ze.brotliCompressSync(t,{params:ml}):e==="gzip"?Ze.gzipSync(t):Ze.deflateSync(t)}function Bx(e){return e==="br"?Ze.createBrotliCompress({params:ml}):e==="gzip"?Ze.createGzip():Ze.createDeflate()}var Ix=new Set([".png",".jpg",".jpeg",".webp",".avif",".gif",".ico",".woff",".woff2",".mp4",".webm",".mp3",".pdf",".zip",".gz",".br"]),Wx=new Set([".rose",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".json",".html",".svg"]);function Dx(e,t){return t==="br"?e.br??=Ze.brotliCompressSync(e.raw,{params:ml}):e.gzip??=Ze.gzipSync(e.raw)}function zx(e,t){try{let n=e+".br",s=K.statSync(n);return!s.isFile()||s.mtimeMs<t?null:K.readFileSync(n)}catch{return null}}var Hx=wu(Ze.gzip),Vx=wu(Ze.deflate);async function Yh(e,t){return e==="br"?eg(t,{params:ml}):e==="gzip"?Hx(t):Vx(t)}async function Jx(e,t,n,s,r){if(t.statusCode=n,t.setHeader("Content-Type","text/html; charset=utf-8"),Object.keys(r||{}).some(a=>a.toLowerCase()==="cache-control")||t.setHeader("Cache-Control","no-cache"),r)for(let[a,c]of Object.entries(r))t.setHeader(a,c);mi(t,"Accept-Encoding");let i='W/"'+Nx("sha1").update(s,"utf8").digest("base64url").slice(0,24)+'"';if(t.setHeader("ETag",i),Sr(e.headers["if-none-match"],i)){t.statusCode=304,t.end();return}let o=Jn?null:dl(e);o?(t.setHeader("Content-Encoding",o),t.end(await Yh(o,s))):t.end(s)}var Ux=new Set(["content-length","transfer-encoding","connection","keep-alive"]);function cl(e,t){let n=e.headers.getSetCookie?.()??[];e.headers.forEach((s,r)=>{n.length&&r.toLowerCase()==="set-cookie"||Ux.has(r.toLowerCase())||t.setHeader(r,s)}),n.length&&t.setHeader("set-cookie",n)}async function du(e,t,n){let s=Buffer.from(await t.arrayBuffer());if(cl(t,n),mi(n,"Accept-Encoding"),n.statusCode=t.status,s.length>0){let r=Gi(t,s);if(n.setHeader("ETag",r),e&&e.method==="GET"&&Sr(e.headers["if-none-match"],r)){n.statusCode=304,n.end();return}}n.end(s)}function qx(e){let t=e.indexOf('<main id="sk-main"');if(t<0)return e;let n=e.indexOf("</main>",t);if(n<0)return e;let s=e.slice(t,n+7),r=e.match(/<title>([\s\S]*?)<\/title>/i);return(r?r[0]:"")+s}function Gx(e){let t=e.headers;return t?!!(typeof t.get=="function"?t.get("x-pjax"):t["x-pjax"]):!1}async function Vh(e,t,n,s,r,i){let o=r.status??200;if(r.redirect){let u=`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${r.redirect}">${r.redirect}</a>.</p>`,l=fl(n,i,"");if(s){let p=await n.runResponseHooks(s,new Response(u,{status:o,headers:{"content-type":"text/html; charset=utf-8",location:r.redirect,...l}}));o=p.status,l=_o(p)}l.location=r.redirect,t.statusCode=o,t.setHeader("Content-Type","text/html; charset=utf-8"),t.setHeader("Location",r.redirect);for(let[p,f]of Object.entries(l))p!=="location"&&t.setHeader(p,f);mi(t,"Accept-Encoding"),t.end(u);return}let a=tg(n,i),c=ea(r.html,r.state,r.head,r.csr!==!1,r.lang,r.dir,a,r.shell!==!1,n.sliceKeyFor?.(i)??null);Gx(e)&&(c=qx(c));let d=fl(n,i,a);if(s){let u=await n.runResponseHooks(s,new Response(c,{status:o,headers:{"content-type":"text/html; charset=utf-8",...d}}));o=u.status,d=_o(u),c=u.bodyUsed?c:await u.text()}await Jx(e,t,o,c,d)}var gu=new Map,al=process.argv.find(e=>e==="--port"||e.startsWith("--port="));if(al){let e=al.includes("=")?al.slice(7):process.argv[process.argv.indexOf(al)+1];e&&Number(e)>0&&(process.env.PORT=e)}var ss=process.argv[3]&&!process.argv[3].startsWith("-")?Z.resolve(process.argv[3]):process.cwd(),tt=Z.join(process.cwd(),"dist"),pl=Number(process.env.PORT)||3e3,hr=null,Jh=-1,pu=0;function Qx(e){try{let t=K.readFileSync(Z.join(e,".env"),"utf-8");for(let n of t.split(/\r?\n/)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r<=0)continue;let i=s.slice(0,r).trim(),o=s.slice(r+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),i in process.env||(process.env[i]=o)}}catch{}}Qx(process.cwd());async function yi(){let e=Z.join(tt,"server.js"),t=K.statSync(e).mtimeMs;if(!hr||t!==Jh){Jh=t,pu++;let n=ul(e).href;if(Jn){let s=Z.join(ss,".rosefd-dev"),r=Z.join(s,`server-${process.pid}-${pu}.mjs`);await K.promises.mkdir(s,{recursive:!0}),await K.promises.copyFile(e,r),await K.promises.rm(Z.join(s,`server-${process.pid}-${pu-1}.mjs`),{force:!0}),n=ul(r).href}hr=await import(n)}return hr}async function fu(e,t){let n=null;try{n=await K.promises.readFile(e,"utf-8")}catch{}n!==t&&await K.promises.writeFile(e,t)}async function yl(){let e=!Jn&&!xo.includes("--no-minify"),{routes:t,bundle:n,config:s}=await Uo(ss,tt,{minify:e,incremental:Jn}),r=s.brotli?.quality??11;await fu(Z.join(tt,"package.json"),`{"type":"module"}
|
|
12694
|
-
`),Xo(n),Zl(s.csp?.connectSrc??"",s.csp?.imgSrc??"");let i=Jn?[]:await tk(t);await fu(Z.join(tt,"broken.json"),JSON.stringify(i));let o=await yi(),a=o.routeHeaders??[];if(n==="sliced"){let c=new Map;for(let d of a)c.set(d.pattern,{...d.headers});for(let d of t){let u=o.sliceKeyFor?.(d.routePath);if(!u)continue;let l=c.get(d.pattern)??{};Object.keys(l).some(f=>f.toLowerCase()==="content-security-policy")||c.set(d.pattern,{...l,"content-security-policy":Gr(Ws(u))["Content-Security-Policy"]})}a=[...c].map(([d,u])=>({pattern:d,headers:u}))}if(await fu(Z.join(tt,"headers.json"),JSON.stringify({default:Gr(Ws()),routes:a})),Jn||await Uh(tt,r),Jn||await ek(tt,o.dynamicRoutes??[]),s.pwa)try{await qd(tt,s.pwa),await Yx(tt,s.pwa),await Uh(tt,r)}catch(c){console.error("
|
|
12693
|
+
`;Un();import{pathToFileURL as ay}from"url";import{join as ra}from"path";function ta(e,t,n){let s=String(n("accept-language")??"").trim().toLowerCase(),r=t?.(e)??[];return r.length?[s,...r.map(i=>String(n(i)??"").trim())]:[s]}var na=[],qi=null;globalThis.__rosefcOnShutdown=Kd;globalThis.__rosefcRunShutdownHooks=sa;function Kd(e,t){let n={name:e,fn:t};return na.push(n),()=>{let s=na.indexOf(n);s!==-1&&na.splice(s,1)}}function sa(e){return qi||(qi=(async()=>{let t=[];for(let n of na.slice())try{await n.fn(),t.push({name:n.name,ok:!0})}catch(s){let r=s instanceof Error?s.message:String(s);t.push({name:n.name,ok:!1,error:r}),console.error(`[rosefc] shutdown hook ${n.name} failed (${e}):`,r)}return t})().finally(()=>{qi=null}),qi)}function ly(e){let t=e.method;if(t!=="POST"&&t!=="PUT"&&t!=="PATCH"&&t!=="DELETE")return null;let n=e.headers.get("origin");if(n){let r;try{r=new URL(n).host}catch{return new Response("Cross-site request blocked (unparsable Origin header)",{status:403})}return r===new URL(e.url).host?null:new Response("Cross-site request blocked (Origin does not match Host)",{status:403})}let s=e.headers.get("sec-fetch-site");return s&&s!=="same-origin"&&s!=="same-site"&&s!=="none"?new Response(`Cross-site request blocked (sec-fetch-site: ${s})`,{status:403}):null}var Zd=Promise.resolve(),cy=e=>{let t=Zd,n;return Zd=new Promise(s=>{n=s}),t.then(e).finally(n)};async function Xd(e,t){let n=t?.server??await import(ay(ra(e,"server.js")).href),s=null,r="";if(t&&"client"in t)s=t.client??null;else try{s=await(await import("fs/promises")).readFile(ra(e,"client.js"),"utf-8")}catch{s=null}s&&s.includes("chunks/")&&(s=null);let i=typeof n.sliceKeyFor=="function";i&&Xo("sliced");let o=d=>i?Ws(n.sliceKeyFor(d),e):s;if(t&&"styles"in t)r=t.styles??"";else try{r=await(await import("fs/promises")).readFile(ra(e,"styles.css"),"utf-8")}catch{r=""}let a=new Set;if(t&&"broken"in t)a=new Set(t.broken);else try{a=new Set(JSON.parse(await(await import("fs/promises")).readFile(ra(e,"broken.json"),"utf-8")))}catch{a=new Set}let c=(d,u="")=>{let l={};for(let[f,h]of Object.entries(Gr(o(d),u)))l[f.toLowerCase()]=h;l["cache-control"]||(l["cache-control"]="no-cache");let p=n.headersFor?.(d);if(p)for(let[f,h]of Object.entries(p))l[f.toLowerCase()]=h;return l};return async function(u){let l=ly(u);if(l)return l;let{pathname:p,searchParams:f}=new URL(u.url),h=p.replace(/\/+$/,"")||"/";return h!==p?new Response(null,{status:308,headers:{location:h+new URL(u.url).search}}):cy(async()=>{n.setQuery?.(Object.fromEntries(f));let g=n.hasRequestHooks||n.hasResponseHooks?{request:u,url:new URL(u.url),method:u.method,pathname:p,state:{}}:null;if(g){let C=await n.runRequestHooks(g);if(C)return n.runResponseHooks(g,C)}if(n.middleware){let C=await n.runMiddleware(u);if(C)return g?n.runResponseHooks(g,C):C}if(p==="/__rosefc/data"&&u.method==="GET"){let C=f.get("path")||"/";try{if(n.middleware){let R=await n.runMiddleware(new Request(new URL(C,u.url),{method:"GET",headers:u.headers}));if(R){let T=new Headers(R.headers);return T.set("access-control-allow-origin","*"),new Response(await R.arrayBuffer(),{status:R.status,headers:T})}}n.setQuery?.(Object.fromEntries(new URL("http://x"+C).searchParams));let x=await n.renderPage(C,void 0,{withState:!0}),A={};try{A=JSON.parse(x?.state||"{}")}catch{A={}}return new Response(JSON.stringify({path:C,status:x?.status??200,state:A}),{status:200,headers:{"content-type":"application/json; charset=utf-8","access-control-allow-origin":"*","cache-control":"no-store"}})}catch(x){return new Response(JSON.stringify({error:String(x?.message??x).slice(0,200)}),{status:500,headers:{"content-type":"application/json; charset=utf-8","access-control-allow-origin":"*"}})}}if(n.isApi(p)){if(u.method!=="GET"){let x=n.invalidateRenderCache;typeof x=="function"&&x()}let C=await n.handleApi(u.method,p,u);return g?n.runResponseHooks(g,C):C}let y=u.method==="POST"?await u.formData():void 0;if(y){let C=n.invalidateRenderCache;typeof C=="function"&&C()}if(!y&&!a.has(p)&&!n.isBuffered?.(p)&&n.canStream(p)&&!n.isNoJs(p)&&!u.headers.get("x-pjax")){let C=n.cspNonce?.(p)?Vi():"",x=new Response(null,{status:200,headers:{"content-type":"text/html; charset=utf-8",...c(p,C)}}),A=g?await n.runResponseHooks(g,x):x,R=new TextEncoder,T=new ReadableStream({async start(M){let F=n.docAttrs(p);await n.renderPageStream(p,I=>M.enqueue(R.encode(I)),Yo(r,F.lang,F.dir,!n.shellOff?.(p)),Ji(o(p),C)),M.close()}});return new Response(T,{status:A.status,headers:A.headers})}let m=u.headers.get("cookie")||"",b=f.toString(),$=ta(p,n.hotVaryFor,C=>u.headers.get(C)).join("\0"),v=(!y&&n.isCachedRoute?.(p)?n.peekRenderCache?.(p,m,b,$):null)??(n.renderPageCached&&!y?await n.renderPageCached(p,m,b,$):await n.renderPage(p,y)),_=n.cspNonce?.(p)?Vi():"";if(v.redirect){let C=v.redirect,x=new URL(C,u.url),A=`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${C}">${C}</a>.</p>`;return new Response(A,{status:v.status??302,headers:{"content-type":"text/html; charset=utf-8",location:x.pathname+x.search}})}let k=Xl(v.html,v.state,o(p),v.head,r,v.csr!==!1,v.lang,v.dir,_,v.shell!==!1);u.headers.get("x-pjax")&&(k=uy(k));let S=new Response(k,{status:v.status??200,headers:{"content-type":"text/html; charset=utf-8",...c(p,_)}});return g?n.runResponseHooks(g,S):S})}}function uy(e){let t=e.indexOf('<main id="sk-main"');if(t<0)return e;let n=e.indexOf("</main>",t);if(n<0)return e;let s=e.slice(t,n+7),r=e.match(/<title>([\s\S]*?)<\/title>/i);return(r?r[0]:"")+s}function Yd(e,t){let s=String(e.headers?.["x-forwarded-proto"]||"").split(",")[0].trim(),r=s==="https"||s==="http"?s:"http",o=String(e.headers?.["x-forwarded-host"]||"").split(",")[0].trim()||e.headers?.host||`localhost:${t}`;return`${r}://${o}`}import{createHash as dy}from"node:crypto";function py(e){return'W/"'+dy("sha1").update(e).digest("base64url").slice(0,24)+'"'}function Gi(e,t){return e.headers.get("etag")??py(t)}function Sr(e,t){if(!e)return!1;let n=t.startsWith("W/")?t.slice(2):t;for(let s of(Array.isArray(e)?e.join(","):e).split(",")){let r=s.trim();if(r&&(r==="*"||(r.startsWith("W/")?r.slice(2):r)===n))return!0}return!1}function dl(e){let t=e.headers["accept-encoding"]||"";return t.includes("br")?"br":t.includes("gzip")?"gzip":t.includes("deflate")?"deflate":null}function mi(e,t){let n=e.getHeader("vary"),r=(n==null?"":Array.isArray(n)?n.join(", "):String(n)).split(",").map(i=>i.trim()).filter(Boolean);r.some(i=>i.toLowerCase()===t.toLowerCase())||r.push(t),e.setHeader("Vary",r.join(", "))}var ml={[Ze.constants.BROTLI_PARAM_QUALITY]:5};function Lx(e,t){return e==="br"?Ze.brotliCompressSync(t,{params:ml}):e==="gzip"?Ze.gzipSync(t):Ze.deflateSync(t)}function Bx(e){return e==="br"?Ze.createBrotliCompress({params:ml}):e==="gzip"?Ze.createGzip():Ze.createDeflate()}var Ix=new Set([".png",".jpg",".jpeg",".webp",".avif",".gif",".ico",".woff",".woff2",".mp4",".webm",".mp3",".pdf",".zip",".gz",".br"]),Wx=new Set([".rose",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".json",".html",".svg"]);function Dx(e,t){return t==="br"?e.br??=Ze.brotliCompressSync(e.raw,{params:ml}):e.gzip??=Ze.gzipSync(e.raw)}function zx(e,t){try{let n=e+".br",s=K.statSync(n);return!s.isFile()||s.mtimeMs<t?null:K.readFileSync(n)}catch{return null}}var Hx=wu(Ze.gzip),Vx=wu(Ze.deflate);async function Yh(e,t){return e==="br"?eg(t,{params:ml}):e==="gzip"?Hx(t):Vx(t)}async function Jx(e,t,n,s,r){if(t.statusCode=n,t.setHeader("Content-Type","text/html; charset=utf-8"),Object.keys(r||{}).some(a=>a.toLowerCase()==="cache-control")||t.setHeader("Cache-Control","no-cache"),r)for(let[a,c]of Object.entries(r))t.setHeader(a,c);mi(t,"Accept-Encoding");let i='W/"'+Nx("sha1").update(s,"utf8").digest("base64url").slice(0,24)+'"';if(t.setHeader("ETag",i),Sr(e.headers["if-none-match"],i)){t.statusCode=304,t.end();return}let o=Jn?null:dl(e);o?(t.setHeader("Content-Encoding",o),t.end(await Yh(o,s))):t.end(s)}var Ux=new Set(["content-length","transfer-encoding","connection","keep-alive"]);function cl(e,t){let n=e.headers.getSetCookie?.()??[];e.headers.forEach((s,r)=>{n.length&&r.toLowerCase()==="set-cookie"||Ux.has(r.toLowerCase())||t.setHeader(r,s)}),n.length&&t.setHeader("set-cookie",n)}async function du(e,t,n){let s=Buffer.from(await t.arrayBuffer());if(cl(t,n),mi(n,"Accept-Encoding"),n.statusCode=t.status,s.length>0){let r=Gi(t,s);if(n.setHeader("ETag",r),e&&e.method==="GET"&&Sr(e.headers["if-none-match"],r)){n.statusCode=304,n.end();return}}n.end(s)}function qx(e){let t=e.indexOf('<main id="sk-main"');if(t<0)return e;let n=e.indexOf("</main>",t);if(n<0)return e;let s=e.slice(t,n+7),r=e.match(/<title>([\s\S]*?)<\/title>/i);return(r?r[0]:"")+s}function Gx(e){let t=e.headers;return t?!!(typeof t.get=="function"?t.get("x-pjax"):t["x-pjax"]):!1}async function Vh(e,t,n,s,r,i){let o=r.status??200;if(r.redirect){let u=`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${r.redirect}">${r.redirect}</a>.</p>`,l=fl(n,i,"");if(s){let p=await n.runResponseHooks(s,new Response(u,{status:o,headers:{"content-type":"text/html; charset=utf-8",location:r.redirect,...l}}));o=p.status,l=_o(p)}l.location=r.redirect,t.statusCode=o,t.setHeader("Content-Type","text/html; charset=utf-8"),t.setHeader("Location",r.redirect);for(let[p,f]of Object.entries(l))p!=="location"&&t.setHeader(p,f);mi(t,"Accept-Encoding"),t.end(u);return}let a=tg(n,i),c=ea(r.html,r.state,r.head,r.csr!==!1,r.lang,r.dir,a,r.shell!==!1,n.sliceKeyFor?.(i)??null);Gx(e)&&(c=qx(c));let d=fl(n,i,a);if(s){let u=await n.runResponseHooks(s,new Response(c,{status:o,headers:{"content-type":"text/html; charset=utf-8",...d}}));o=u.status,d=_o(u),c=u.bodyUsed?c:await u.text()}await Jx(e,t,o,c,d)}var gu=new Map,al=process.argv.find(e=>e==="--port"||e.startsWith("--port="));if(al){let e=al.includes("=")?al.slice(7):process.argv[process.argv.indexOf(al)+1];e&&Number(e)>0&&(process.env.PORT=e)}var ss=process.argv[3]&&!process.argv[3].startsWith("-")?Z.resolve(process.argv[3]):process.cwd(),tt=Z.join(process.cwd(),"dist"),pl=Number(process.env.PORT)||3e3,hr=null,Jh=-1,pu=0;function Qx(e){try{let t=K.readFileSync(Z.join(e,".env"),"utf-8");for(let n of t.split(/\r?\n/)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r<=0)continue;let i=s.slice(0,r).trim(),o=s.slice(r+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),i in process.env||(process.env[i]=o)}}catch{}}Qx(process.cwd());async function yi(){let e=Z.join(tt,"server.js"),t=K.statSync(e).mtimeMs;if(!hr||t!==Jh){Jh=t,pu++;let n=ul(e).href;if(Jn){let s=Z.join(ss,".rosefc-dev"),r=Z.join(s,`server-${process.pid}-${pu}.mjs`);await K.promises.mkdir(s,{recursive:!0}),await K.promises.copyFile(e,r),await K.promises.rm(Z.join(s,`server-${process.pid}-${pu-1}.mjs`),{force:!0}),n=ul(r).href}hr=await import(n)}return hr}async function fu(e,t){let n=null;try{n=await K.promises.readFile(e,"utf-8")}catch{}n!==t&&await K.promises.writeFile(e,t)}async function yl(){let e=!Jn&&!xo.includes("--no-minify"),{routes:t,bundle:n,config:s}=await Uo(ss,tt,{minify:e,incremental:Jn}),r=s.brotli?.quality??11;await fu(Z.join(tt,"package.json"),`{"type":"module"}
|
|
12694
|
+
`),Xo(n),Zl(s.csp?.connectSrc??"",s.csp?.imgSrc??"");let i=Jn?[]:await tk(t);await fu(Z.join(tt,"broken.json"),JSON.stringify(i));let o=await yi(),a=o.routeHeaders??[];if(n==="sliced"){let c=new Map;for(let d of a)c.set(d.pattern,{...d.headers});for(let d of t){let u=o.sliceKeyFor?.(d.routePath);if(!u)continue;let l=c.get(d.pattern)??{};Object.keys(l).some(f=>f.toLowerCase()==="content-security-policy")||c.set(d.pattern,{...l,"content-security-policy":Gr(Ws(u))["Content-Security-Policy"]})}a=[...c].map(([d,u])=>({pattern:d,headers:u}))}if(await fu(Z.join(tt,"headers.json"),JSON.stringify({default:Gr(Ws()),routes:a})),Jn||await Uh(tt,r),Jn||await ek(tt,o.dynamicRoutes??[]),s.pwa)try{await qd(tt,s.pwa),await Yx(tt,s.pwa),await Uh(tt,r)}catch(c){console.error("Rosefc: PWA generation failed:",c instanceof Error?c.message:String(c))}if(xo.includes("--static")){let c=o.dynamicRoutes??[],d=Object.entries(o.apiPrerender??{}).filter(([,p])=>!p).map(([p])=>p),u=t.filter(p=>p.paramNames.length>0&&!(o.routeParams??{})[p.routePath]).map(p=>p.routePath),l=[...new Set([...c,...d,...u,...i])];if(l.length>0){console.error("Rosefc: --static export refused - these routes need a server:");for(let p of l)console.error(` ${p}`);console.error("(getContext()/$store()/$query(), csp.nonce, buffer = true, an unbaked /api route, a param route with no export const params, or a route the middleware walled)"),console.error("drop --static to build the normal dist (the dynamic half renders on demand on Node/edge)"),process.exit(1)}console.log("Rosefc: static export verified - every route is a baked file, no server needed")}}var Kx=new Set([".html",".js",".css",".json",".svg",".txt"]),eg=wu(Ze.brotliCompress),Zx=8;function Xx(e,t){let n=`
|
|
12695
12695
|
const { parentPort, workerData } = require('node:worker_threads');
|
|
12696
12696
|
const zlib = require('node:zlib');
|
|
12697
12697
|
const fs = require('node:fs');
|
|
@@ -12703,21 +12703,21 @@ parentPort.on('message', (file) => {
|
|
|
12703
12703
|
} catch (e) { parentPort.postMessage(String((e && e.message) || e)); return; }
|
|
12704
12704
|
parentPort.postMessage(null);
|
|
12705
12705
|
});
|
|
12706
|
-
`,s=[],r=[],i=0,o=null,a=()=>{for(let d of s){if(r.length===0)break;c.has(d)||(c.add(d),i++,d.postMessage(r.shift()))}},c=new Set;for(let d=0;d<e;d++){let u=new Px(n,{eval:!0,workerData:{quality:t}});u.on("message",l=>{i--,c.delete(u),l&&(o=o??String(l)),a()}),u.on("error",l=>{o=o??String(l?.message??l),c.delete(u)}),s.push(u)}return{run:d=>{r.push(d),a()},done:async()=>{for(;(i>0||r.length>0)&&!o;)a(),await new Promise(d=>setTimeout(d,5));if(await Promise.all(s.map(d=>d.terminate())),o)throw new Error(o)}}}async function Uh(e,t=11){let n=[],s=async u=>{for(let l of await K.promises.readdir(u,{withFileTypes:!0})){let p=Z.join(u,l.name);l.isDirectory()?await s(p):Kx.has(Z.extname(l.name).toLowerCase())&&n.push(p)}};await s(e);let r=[],i=0;for(let u of n){let l=await K.promises.stat(u).catch(()=>null);if(!l)continue;let p=await K.promises.stat(u+".br").catch(()=>null);p&&p.mtimeMs>=l.mtimeMs||(r.push({file:u,size:l.size}),i+=l.size)}if(r.length===0)return;let o=Math.min(Math.max(2,Xh.cpus().length-1),12,Math.ceil(i/(4*1024*1024)));if(o>=2)try{let u=Xx(o,t);for(let{file:l}of r)u.run(l);await u.done();return}catch(u){console.warn(`
|
|
12706
|
+
`,s=[],r=[],i=0,o=null,a=()=>{for(let d of s){if(r.length===0)break;c.has(d)||(c.add(d),i++,d.postMessage(r.shift()))}},c=new Set;for(let d=0;d<e;d++){let u=new Px(n,{eval:!0,workerData:{quality:t}});u.on("message",l=>{i--,c.delete(u),l&&(o=o??String(l)),a()}),u.on("error",l=>{o=o??String(l?.message??l),c.delete(u)}),s.push(u)}return{run:d=>{r.push(d),a()},done:async()=>{for(;(i>0||r.length>0)&&!o;)a(),await new Promise(d=>setTimeout(d,5));if(await Promise.all(s.map(d=>d.terminate())),o)throw new Error(o)}}}async function Uh(e,t=11){let n=[],s=async u=>{for(let l of await K.promises.readdir(u,{withFileTypes:!0})){let p=Z.join(u,l.name);l.isDirectory()?await s(p):Kx.has(Z.extname(l.name).toLowerCase())&&n.push(p)}};await s(e);let r=[],i=0;for(let u of n){let l=await K.promises.stat(u).catch(()=>null);if(!l)continue;let p=await K.promises.stat(u+".br").catch(()=>null);p&&p.mtimeMs>=l.mtimeMs||(r.push({file:u,size:l.size}),i+=l.size)}if(r.length===0)return;let o=Math.min(Math.max(2,Xh.cpus().length-1),12,Math.ceil(i/(4*1024*1024)));if(o>=2)try{let u=Xx(o,t);for(let{file:l}of r)u.run(l);await u.done();return}catch(u){console.warn(`Rosefc: parallel precompression unavailable (${u instanceof Error?u.message:String(u)}), falling back to in-process`)}let a={[Ze.constants.BROTLI_PARAM_QUALITY]:t},c=0,d=async()=>{for(;c<r.length;){let u=r[c++].file,l=await K.promises.readFile(u);await K.promises.writeFile(u+".br",await eg(l,{params:a}))}};await Promise.all(Array.from({length:Math.min(Zx,r.length)},d))}async function Yx(e,t){let n=[],s=async r=>{for(let i of await K.promises.readdir(r,{withFileTypes:!0})){let o=Z.join(r,i.name);i.isDirectory()?await s(o):i.name.endsWith(".html")&&!i.name.endsWith(".br")&&n.push(o)}};await s(e);for(let r of n){let i=await K.promises.readFile(r,"utf8"),o=Gd(i,t);o!==i&&await K.promises.writeFile(r,o)}}async function ek(e,t){let n=[],s=async(a,c)=>{for(let d of await K.promises.readdir(a,{withFileTypes:!0})){if(d.isDirectory()){await s(Z.join(a,d.name),`${c}/${d.name}`);continue}if(!d.name.endsWith(".html"))continue;let u=Z.join(a,d.name),l=await K.promises.readFile(u),p=`${u}.br`;n.push({route:c||"/",raw:l.length,gzip:Ze.gzipSync(l,{level:9}).length,br:K.existsSync(p)?(await K.promises.stat(p)).size:0,js:/<script type="module"/.test(l.toString("utf8"))})}};await s(e,"");let r=a=>`${(a/1024).toFixed(1)} KB`,i=["Rosefc build analysis (measured from dist/; br = the precompressed bytes the Go binary serves):"];for(let a of n.sort((c,d)=>c.route<d.route?-1:1))i.push(` ${a.route.padEnd(16)}${r(a.raw).padStart(9)} raw ${r(a.gzip).padStart(8)} gzip ${r(a.br).padStart(8)} br ${a.js?"bundle inlined":"zero-JS"}`);let o=Z.join(e,"client.js");if(K.existsSync(o)){let a=await K.promises.readFile(o);i.push(` shared bundle ${r(a.length).padStart(9)} raw ${r(Ze.gzipSync(a,{level:9}).length).padStart(8)} gzip ${r(K.existsSync(`${o}.br`)?(await K.promises.stat(`${o}.br`)).size:0).padStart(8)} br inlined into every interactive document`)}t.length>0&&i.push(` dynamic (rendered per request, measured live by \`npm run benchmark\`): ${t.join(" ")}`);for(let a of i)console.log(a)}var qh=4,Gs=new Fx;function vu(e){e.installContextStore?.({getStore:()=>Gs.getStore(),run:(t,n)=>Gs.run(t,n)})}async function Gh(e,t){let n=0;await Promise.all(Array.from({length:Math.min(t,e.length)},async()=>{for(;n<e.length;)await e[n++]()}))}async function tk(e){let t=await yi();vu(t);let n=[],s=d=>d==="/"?Z.join(tt,"index.html"):Z.join(tt,d.slice(1),"index.html"),r=[];for(let d of e){if((t.prerenderSkipRoutes??[]).includes(d.routePath)){console.log(`dynamic route ${d.routePath}: per-request state (getContext/$store), rendered on demand`);continue}if(d.paramNames.length===0){r.push({routePath:d.routePath,file:s(d.routePath)});continue}try{let u=t.routeParams?.[d.routePath],l=typeof u=="function"?await u():u,p=nk(d.pattern,d.paramNames,l??{});for(let f of p)r.push({routePath:f,file:s(f)});p.length===0&&console.log(`dynamic route ${d.routePath}: no params export, rendered on demand`)}catch(u){console.error(`prerender skipped for ${d.routePath}: ${u instanceof Error?u.message:u}`),n.push(d.routePath)}}let i=new Set(r.map(({file:d})=>d)),o=t.apiPrerender??{},a=Object.entries(o).filter(([,d])=>d).map(([d])=>d);for(let d of a)i.add(Z.join(tt,d.slice(1)+".json"));i.add(Z.join(tt,"broken.json")),i.add(Z.join(tt,"headers.json")),i.add(Z.join(tt,"package.json")),await kl(tt,i);let c=async(d,u)=>{await Gs.run({},async()=>{if(await t.runMiddleware({method:"GET",url:d,headers:{}})){console.error(`prerender skipped for ${d}: the middleware short-circuits at build time`),n.push(d),await K.promises.rm(u,{force:!0});return}t.setQuery?.({});let p=await t.renderPage(d);if(p.status===500){console.error(`prerender skipped for ${d}: render failed, the error page rendered`),n.push(d),await K.promises.rm(u,{force:!0});return}let f=ea(p.html,p.state,p.head,p.csr!==!1,p.lang,p.dir,"",p.shell!==!1,t.sliceKeyFor?.(d)??null),h=null;try{h=await K.promises.readFile(u,"utf-8")}catch{}h!==f&&(await K.promises.mkdir(Z.dirname(u),{recursive:!0}),await K.promises.writeFile(u,f)),console.log(`prerendered ${d} -> ${Z.relative(process.cwd(),u)}`)})};return await Gh(r.map(({routePath:d,file:u})=>()=>c(d,u).catch(l=>{console.error(`prerender skipped for ${d}: ${l instanceof Error?l.message:l}`),n.push(d)})),qh),await Gh(a.map(d=>async()=>{try{await Gs.run({},async()=>{let u=await t.handleApi("GET",d,new Request("http://localhost"+d));if(u.status!==200){console.error(`api prerender skipped for ${d}: GET answered ${u.status}`);return}let l=await u.text(),p=Z.join(tt,d.slice(1)+".json"),f=null;try{f=await K.promises.readFile(p,"utf-8")}catch{}f!==l&&(await K.promises.mkdir(Z.dirname(p),{recursive:!0}),await K.promises.writeFile(p,l)),console.log(`prerendered api ${d} -> ${Z.relative(process.cwd(),p)}`)})}catch(u){console.error(`api prerender skipped for ${d}: ${u instanceof Error?u.message:u}`)}}),qh),n}function nk(e,t,n){let s=[[]];for(let r of t){let i=(Array.isArray(n[r])?n[r]:[]).map(o=>String(o));s=s.flatMap(o=>i.map(a=>[...o,a]))}return s.map(r=>{let i=0;return e.split("/").map(o=>o.startsWith(":")?encodeURIComponent(r[i++]):o.startsWith("*")?r[i++].split("/").map(encodeURIComponent).join("/"):o).join("/")})}var sk=new Set([".js",".css",".json",".png",".jpg",".jpeg",".gif",".svg",".ico",".webp",".woff",".woff2",".txt",".xml"]);function fl(e,t,n=""){let s={};for(let[i,o]of Object.entries(Gr(Ws(e.sliceKeyFor?.(t)??null),n)))s[i.toLowerCase()]=o;let r=e.headersFor?.(t);if(r)for(let[i,o]of Object.entries(r))s[i.toLowerCase()]=o;return s}function tg(e,t){return e.cspNonce?.(t)?Vi():""}var hu=new Set;function rk(e,t){hu.has(t)||(hu.add(t),(async()=>{try{let n=await yi();vu(n),await Gs.run({},async()=>{n.setQuery?.({});let s=await n.renderPage(e);s.status===200&&(await K.promises.writeFile(t,ea(s.html,s.state,s.head,s.csr!==!1,s.lang,s.dir,"",s.shell!==!1,n.sliceKeyFor?.(e)??null)),gu.delete(t),console.log(`Rosefc: revalidated ${e} in the background`))})}catch(n){console.error("Rosefc: background revalidation failed for",e,n instanceof Error?n.message:n)}finally{hu.delete(t)}})())}var Qh=Number(process.env.ROSEFC_MAX_BODY)||1024*1024;function Kh(e,t,n){let s=[],r=0,i=!1;e.on("data",o=>{if(!i){if(r+=o.length,r>Qh){i=!0,t.statusCode=413,t.setHeader("Content-Type","text/plain; charset=utf-8"),t.end(`Payload too large (limit ${Qh} bytes)`);return}s.push(o)}}),e.on("end",()=>{i||n(Buffer.concat(s))}),e.on("error",()=>{})}function ik(e){let t=e.method;if(t!=="POST"&&t!=="PUT"&&t!=="PATCH"&&t!=="DELETE")return null;let n=e.headers.origin;if(n){let r;try{r=new URL(n).host}catch{return{status:403,body:"Cross-site request blocked (unparsable Origin header)"}}return r===e.headers.host?null:{status:403,body:"Cross-site request blocked (Origin does not match Host)"}}let s=e.headers["sec-fetch-site"];return s&&s!=="same-origin"&&s!=="same-site"&&s!=="none"?{status:403,body:`Cross-site request blocked (sec-fetch-site: ${s})`}:null}function ng(e,t,n,s,r){let i=Number(process.hrtime.bigint()-(r??process.hrtime.bigint()))/1e6,o=i>=1?`${i.toFixed(3)}ms`:`${(i*1e3).toFixed(0)}us`;console.log(`${new Date().toISOString().slice(0,19)}Z${s?` [${s}]`:""} ${e.method} ${e.url} ${t.statusCode} ${n}B ${o}`)}function ok(e,t){return(n,s)=>{let r=process.hrtime.bigint(),i=0,o=s.write.bind(s),a=s.end.bind(s);s.write=(c,...d)=>(c&&(i+=Buffer.byteLength(c)),o(c,...d)),s.end=(c,...d)=>(c&&(i+=Buffer.byteLength(c)),a(c,...d)),s.on("finish",()=>ng(n,s,i,t,r)),e(n,s)}}async function ak(e){let t={};for(let[r,i]of Object.entries(e.headers))i!==void 0&&(t[r]=Array.isArray(i)?i.join(", "):String(i));let n=new Request(`http://${e.headers?.host||"localhost"}${e.url}`,{method:e.method||"GET",headers:t}),s=new URL(n.url);return{request:n,url:s,method:n.method,pathname:s.pathname,state:{}}}function _o(e){let t={},n=e.headers.getSetCookie?.()??[];return e.headers.forEach((s,r)=>{n.length&&r.toLowerCase()==="set-cookie"||(t[r]=s)}),n.length&&(t["set-cookie"]=n),t}var lk="<script>(function(){if(typeof EventSource==='undefined')return;var es=new EventSource('/__rosefc_reload');es.onmessage=function(m){if(m.data!=='rebuild')return;es.close();var s=window.__rosefc?window.__rosefc.state():null;if(s)fetch('/__rosefc_state',{method:'POST',body:s,headers:{'content-type':'application/json'}}).catch(function(){});setTimeout(function(){location.reload()},40)}})()</script>",mu=null,hl=new Set,Jn=!1;function ck(e,t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}),t.write(`: ok
|
|
12707
12707
|
|
|
12708
12708
|
`),hl.add(t),e.on("close",()=>hl.delete(t))}function uk(e,t){let n="";e.on("data",s=>{n+=s,n.length>1e6&&e.destroy()}),e.on("end",()=>{try{JSON.parse(n),mu=n}catch{}t.writeHead(204).end()})}function Zh(){for(let e of hl)try{e.write(`data: rebuild
|
|
12709
12709
|
|
|
12710
12710
|
`)}catch{hl.delete(e)}}var gi=null,Su=!1,gl=!1,sg=0;function _u(){return gi||(Su=!1,sg=Date.now(),gi=(async()=>{try{console.log("Rebuilding..."),await yl(),Zh(),Zh()}catch(e){console.error("Build failed (server still running):",e instanceof Error?e.message:String(e))}finally{gi=null,gl&&(gl=!1,_u())}})()),gi}function dk(){return!Jn||!gi&&!Su?null:_u()}var yu=null;function rg(e,t){t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"}),t.write(`: ok
|
|
12711
12711
|
|
|
12712
|
-
`),e.socket&&e.socket.setTimeout(0);let n=globalThis.
|
|
12712
|
+
`),e.socket&&e.socket.setTimeout(0);let n=globalThis.__rosefc_storeClients||(globalThis.__rosefc_storeClients=new Set);n.add(t);let s=setInterval(()=>{try{t.write(`: hb
|
|
12713
12713
|
|
|
12714
|
-
`)}catch{}},15e3),r=()=>{clearInterval(s),n.delete(t)};e.on("close",r),t.on("close",r)}function pk(e){return Jn=!0,(t,n)=>{let s=t.url||"/";if(s.startsWith("/
|
|
12714
|
+
`)}catch{}},15e3),r=()=>{clearInterval(s),n.delete(t)};e.on("close",r),t.on("close",r)}function pk(e){return Jn=!0,(t,n)=>{let s=t.url||"/";if(s.startsWith("/__rosefc_reload"))return ck(t,n);if(s.startsWith("/__rosefc_state")&&t.method==="POST")return uk(t,n);if(s.startsWith("/__rosefc_store"))return rg(t,n);let r=!1,i=mu;mu=null;let o=()=>String(n.getHeader("content-type")||"").includes("text/html"),a=u=>{if(r||!o())return u;let l=Buffer.isBuffer(u)?u.toString("utf8"):String(u),p=l.indexOf("<head>");if(p<0)return u;r=!0;let f=i?`<script>window.__rosefc_resume=${JSON.stringify(i).replace(/<\/script>/g,"")}</script>`:"",h=l.slice(0,p+6)+f+lk+l.slice(p+6);return Buffer.isBuffer(u)?Buffer.from(h,"utf8"):h},c=n.write.bind(n);n.write=(u,...l)=>c(a(u),...l);let d=n.end.bind(n);n.end=(u,...l)=>{!n.headersSent&&o()&&n.removeHeader("Content-Security-Policy"),d(u==null?u:a(u),...l)},e(t,n)}}function xu(e,t=!1,n=!1){return(s,r)=>{let i=ik(s);if(i){r.statusCode=i.status,r.setHeader("Content-Type","text/plain; charset=utf-8"),r.end(i.body);return}if(s.method==="POST"&&(s.url||"").startsWith("/__rosefc/revalidate")){let u=process.env.ROSEFC_REVALIDATE_TOKEN||"";if(!u){r.statusCode=404,r.end();return}if(s.headers["x-rosefc-token"]!==u){r.statusCode=403,r.setHeader("content-type","application/json"),r.end(JSON.stringify({error:"invalid token"}));return}let l="";s.on("data",p=>{l+=p,l.length>1e6&&s.destroy()}),s.on("end",()=>{try{let p=JSON.parse(l||"{}");yu&&yu(),r.setHeader("content-type","application/json"),r.end(JSON.stringify({revalidated:!0,scope:p.all?"all":"paths"}))}catch(p){r.statusCode=400,r.end(JSON.stringify({error:String(p).slice(0,120)}))}});return}let o=Bn(s.url||"/"),a=o.replace(/\/+$/,"")||"/";if(a!==o){let u="";try{u=new URL(s.url||"/","http://localhost").search}catch{}let l=a+u;r.statusCode=308,r.setHeader("Location",l),r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${l}">${l}</a>.</p>`);return}let c=dk();(c?c.then(()=>yi()):yi()).then(async u=>(vu(u),Gs.run({},async()=>{let l=Gs.getStore(),p=u.hasRequestHooks===!0||u.hasResponseHooks===!0?await ak(s):null;if(p){let A=await u.runRequestHooks(p);if(A){await du(s,await u.runResponseHooks(p,A),r);return}}let f=Bn(s.url);if(!(s.method==="POST"&&!u.isApi(f))&&u.middleware){let A=await u.runMiddleware(s);if(A){await du(s,p?await u.runResponseHooks(p,A):A,r);return}}if(Bn(s.url)==="/__rosefc/data"&&s.method==="GET"){let A="/";try{A=new URL(s.url||"/","http://localhost").searchParams.get("path")||"/"}catch{}let R=A.indexOf("?"),T=fk(R<0?A:A.slice(0,R)),M=R<0?"":A.slice(R),F=T+M;r.setHeader("content-type","application/json; charset=utf-8"),r.setHeader("access-control-allow-origin","*"),r.setHeader("cache-control","no-store");try{if(u.middleware){let P=await u.runMiddleware({url:F,method:"GET",headers:s.headers});if(P){cl(P,r),r.statusCode=P.status,P.headers.get("content-type")||r.setHeader("content-type","application/json; charset=utf-8"),r.end(Buffer.from(await P.arrayBuffer()));return}}u.setQuery?.(ll(F));let I=await u.renderPage(T,void 0,{withState:!0}),O={};try{O=JSON.parse(I?.state||"{}")}catch{O={}}r.statusCode=200,r.end(JSON.stringify({path:F,status:I?.status??200,state:O}))}catch(I){r.statusCode=500,r.end(JSON.stringify({error:String(I instanceof Error?I.message:I).slice(0,200)}))}return}let g=Bn(s.url);if(u.isApi(g)){Kh(s,r,async A=>Gs.run(l??{},async()=>{try{let R={};for(let[P,j]of Object.entries(s.headers))j!==void 0&&(R[P]=Array.isArray(j)?j.join(", "):String(j));let T=s.method||"GET",M=T!=="GET"&&T!=="HEAD",F=new Request(`http://${s.headers.host||"localhost"}${s.url}`,{method:T,headers:R,body:M&&A.length>0?A:void 0});u.setQuery?.(ll(s.url)),(s.method||"GET")!=="GET"&&u.invalidateRenderCache?.();let I=await u.handleApi(T,g,F),O=Buffer.from(await I.arrayBuffer());if(p){let P=await u.runResponseHooks(p,new Response(O,{status:I.status,headers:I.headers}));if(I=P,!P.bodyUsed){let j=Buffer.from(await P.arrayBuffer());if(cl(I,r),r.statusCode=I.status,j.length>0){let B=Gi(I,j);if(r.setHeader("ETag",B),(T==="GET"||T==="HEAD")&&Sr(s.headers["if-none-match"],B)){r.statusCode=304,r.end();return}}r.end(j);return}}if(cl(I,r),r.statusCode=I.status,O.length>0){let P=Gi(I,O);if(r.setHeader("ETag",P),(T==="GET"||T==="HEAD")&&Sr(s.headers["if-none-match"],P)){r.statusCode=304,r.end();return}}r.end(O)}catch(R){if(console.error(`Rosefc: ${s.method} ${s.url} api handler failed:`,R instanceof Error?R.stack??R.message:String(R)),r.headersSent){r.destroy();return}r.statusCode=500,r.setHeader("Content-Type","application/json"),r.end('{"error":"api handler failed"}')}}));return}if(s.method==="POST"){Kh(s,r,async A=>Gs.run(l??{},async()=>{try{let R=await new Response(A,{headers:{"content-type":s.headers["content-type"]||"application/x-www-form-urlencoded"}}).formData();if(u.middleware){let M=await u.runMiddleware(s,R);if(M){await du(s,p?await u.runResponseHooks(p,M):M,r);return}}u.setQuery?.(ll(s.url)),u.invalidateRenderCache?.();let T=await u.renderPage(Bn(s.url||"/"),R);await Vh(s,r,u,p,T,Bn(s.url||"/"))}catch(R){console.error(`Rosefc: POST ${Bn(s.url||"/")} failed:`,R instanceof Error?R.stack:R),r.headersSent||(r.statusCode=400,r.end("Bad request"))}}));return}let y=Z.normalize(Bn(s.url||"/")).replace(/^(\.\.(\/)?)+/,"");(y==="\\"||y==="/")&&(y="/");let m=Z.join(e,y);if(K.existsSync(m)&&K.statSync(m).isDirectory()&&(m=Z.join(m,"index.html")),/\.(?:br|gz)$/i.test(y)){let A=m.replace(/\.(?:br|gz)$/i,"");K.existsSync(A)&&(m=A)}let b=sk.has(Z.extname(y).toLowerCase()),$=!b&&u.dynamicRoutes?.includes(Bn(s.url)),w=Jn&&Z.extname(m).toLowerCase()===".html";if(!$&&!w&&K.existsSync(m)&&K.statSync(m).isFile()){let A=K.statSync(m),R=b?void 0:(u.revalidate||[]).find(j=>u.matchRoute(j.pattern,Bn(s.url)));t&&R&&Date.now()-A.mtimeMs>R.seconds*1e3&&rk(Bn(s.url),m);let T=gu.get(m);if(!T||T.mtimeMs!==A.mtimeMs){let j=K.readFileSync(m),B=j.length>1024&&!Ix.has(Z.extname(m).toLowerCase());T={mtimeMs:A.mtimeMs,raw:j,br:B?zx(m,A.mtimeMs)??void 0:void 0,gzip:void 0,compressible:B,etag:`W/"${A.size}-${A.mtimeMs}"`},gu.set(m,T)}let M=Z.extname(m),I={"Content-Type":{".html":"text/html",".js":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".svg":"image/svg+xml"}[M]||"application/octet-stream","Cache-Control":Jn?"no-cache":R?`public, max-age=0, stale-while-revalidate=${R.seconds}`:"public, max-age=3600",ETag:T.etag};M===".html"&&Object.assign(I,fl(u,Bn(s.url)));let O=200;if(p){let j=await u.runResponseHooks(p,new Response(null,{status:O,headers:I}));O=j.status;for(let[B,U]of Object.entries(_o(j)))r.setHeader(B,U)}else for(let[j,B]of Object.entries(I))r.setHeader(j,B);if(mi(r,"Accept-Encoding"),Sr(s.headers["if-none-match"],T.etag)){r.statusCode=304,r.end();return}let P=Jn?null:T.compressible?dl(s):null;r.statusCode=O,P?(r.setHeader("Content-Encoding",P),r.end(P==="deflate"?Lx("deflate",T.raw):Dx(T,P))):r.end(T.raw);return}let v=new Set;try{v=new Set(JSON.parse(K.readFileSync(Z.join(e,"broken.json"),"utf-8")))}catch{}let _=Bn(s.url||"/");u.setQuery?.(ll(s.url));let k=s.headers["if-none-match"],S=(Array.isArray(k)||typeof k=="string")&&k.length>0;if(!n&&!S&&!v.has(_)&&!u.isBuffered?.(_)&&u.canStream(_)&&!u.isNoJs(_)){let A=dl(s),R=200,T=tg(u,_),M=fl(u,_,T);if(p){let P=await u.runResponseHooks(p,new Response(null,{status:R,headers:M}));R=P.status,M=_o(P)}r.statusCode=R,r.setHeader("Content-Type","text/html; charset=utf-8");for(let[P,j]of Object.entries(M))r.setHeader(P,j);mi(r,"Accept-Encoding");let F,I;if(A){r.setHeader("Content-Encoding",A);let P=Bx(A);P.pipe(r);let j=!1;F=B=>{P.write(B),j||(j=!0,P.flush(Ze.constants.Z_FULL_FLUSH))},P.on("error",()=>r.destroy()),I=()=>P.end()}else F=P=>r.write(P),I=()=>r.end();let O=u.docAttrs(_);await u.renderPageStream(_,F,Yo(Hi(),O.lang,O.dir,!u.shellOff(_)),Ji(Ws(u.sliceKeyFor?.(_)??null),T)),I();return}let C=(s.url||"").includes("?"),x=s.method==="GET"&&!C&&u.renderPageCached?await u.renderPageCached(_,String(s.headers.cookie||""),"",ta(_,u.hotVaryFor,A=>s.headers[A]).join("\0")):await u.renderPage(_);await Vh(s,r,u,p,x,_)}))).catch(u=>{if(console.error(`Rosefc: ${s.method} ${s.url} failed:`,u instanceof Error?u.stack??u.message:u),r.headersSent){r.destroy();return}r.statusCode=500,r.setHeader("Content-Type","text/html; charset=utf-8");let l=u,p="";if(process.env.ROSEFC_DEV==="1"&&u){let f=u instanceof Error?(u.stack||"").split(`
|
|
12715
12715
|
`).slice(1,7).join(`
|
|
12716
|
-
`):"";p='<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word"><div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: '+vo(s.url||"")+'</div><div style="margin:10px 0 0;color:#ffd479">'+vo(u instanceof Error?u.message:u)+"</div>"+(l.file?'<div style="margin:6px 0 0;color:#9ad1ff">'+vo(l.file)+(l.line!=null?":"+l.line:"")+"</div>":"")+(l.hint?'<div style="margin:10px 0 0;color:#9fe8b0">Fix: '+vo(l.hint)+"</div>":"")+(f?'<pre style="margin:12px 0 0;color:#8f8f9a">'+vo(f)+"</pre>":"")+"</div>"}r.end("<h1>500</h1><p>Something went wrong rendering this page.</p>"+p)})}}function vo(e){return String(e??"").replace(/[<>&"]/g,t=>({"<":"<",">":">","&":"&",'"':"""})[t])}function Bn(e){try{return new URL(e||"/","http://localhost").pathname}catch{return(e||"/").split("?")[0]}}function ll(e){let t={};try{new URL(e||"/","http://localhost").searchParams.forEach((n,s)=>{s in t||(t[s]=n)})}catch{}return t}function fk(e){let t;try{t=new URL("/"+e.replace(/^\/+/,""),"http://localhost").pathname}catch{t=e.split("?")[0]}return t.startsWith("/")||(t="/"+t),t.replace(/\/+$/,"")||"/"}function ku(e,t,n){let s=r=>{let i=()=>{e.removeListener("error",o),e.removeListener("listening",a)},o=c=>{if(i(),c&&c.code==="EADDRINUSE"&&r-t<20){s(r+1);return}console.error(`
|
|
12717
|
-
`),K.writeFileSync(Z.join(e,"tsconfig.json"),JSON.stringify({compilerOptions:{target:"ES2022",module:"ESNext",moduleResolution:"bundler",lib:["ES2022","DOM","DOM.Iterable"],strict:!0,noEmit:!0,skipLibCheck:!0},include:["
|
|
12718
|
-
`)}function bk(e,t,n){let s=bu(),r=s?Z.resolve(s,t):"",i=K.existsSync(r)?r:Z.resolve(t);if(!K.existsSync(i)||!K.statSync(i).isDirectory()){let a=s?K.readdirSync(s).join(", "):"(none found)";console.error(`
|
|
12719
|
-
`)}ig(e),console.log(`\u{1F339}
|
|
12720
|
-
cd ${n}`),console.log(" npm install && npm run dev"),console.log(" npm run build # then deploy dist/")}async function $k(){let e=xo.slice(1),t=e.indexOf("--template"),n=t>=0?e[t+1]:null,s=e.find((o,a)=>!o.startsWith("-")&&a!==(t>=0?t+1:-1));if(!s||t>=0&&!n){let o=bu()?K.readdirSync(bu()).join(", "):"blog, api, admin, site";console.log(`Usage:
|
|
12716
|
+
`):"";p='<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word"><div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: '+vo(s.url||"")+'</div><div style="margin:10px 0 0;color:#ffd479">'+vo(u instanceof Error?u.message:u)+"</div>"+(l.file?'<div style="margin:6px 0 0;color:#9ad1ff">'+vo(l.file)+(l.line!=null?":"+l.line:"")+"</div>":"")+(l.hint?'<div style="margin:10px 0 0;color:#9fe8b0">Fix: '+vo(l.hint)+"</div>":"")+(f?'<pre style="margin:12px 0 0;color:#8f8f9a">'+vo(f)+"</pre>":"")+"</div>"}r.end("<h1>500</h1><p>Something went wrong rendering this page.</p>"+p)})}}function vo(e){return String(e??"").replace(/[<>&"]/g,t=>({"<":"<",">":">","&":"&",'"':"""})[t])}function Bn(e){try{return new URL(e||"/","http://localhost").pathname}catch{return(e||"/").split("?")[0]}}function ll(e){let t={};try{new URL(e||"/","http://localhost").searchParams.forEach((n,s)=>{s in t||(t[s]=n)})}catch{}return t}function fk(e){let t;try{t=new URL("/"+e.replace(/^\/+/,""),"http://localhost").pathname}catch{t=e.split("?")[0]}return t.startsWith("/")||(t="/"+t),t.replace(/\/+$/,"")||"/"}function ku(e,t,n){let s=r=>{let i=()=>{e.removeListener("error",o),e.removeListener("listening",a)},o=c=>{if(i(),c&&c.code==="EADDRINUSE"&&r-t<20){s(r+1);return}console.error(`Rosefc: cannot listen on port ${r}:`,c instanceof Error?c.message:c),process.exit(1)},a=()=>{i(),n(r)};e.once("error",o),e.once("listening",a),e.listen(r)};s(t)}async function hk(e){let t=await import("node:net");for(let n=e;n<e+20;n++)if(await new Promise(r=>{let i=t.createServer();i.once("error",()=>r(!1)),i.listen(n,()=>i.close(()=>r(!0)))}))return n;return e}function bi(){for(let e of["../FRAMEWORK_VERSION","../../FRAMEWORK_VERSION","../../package.json","../package.json"])try{let t=K.readFileSync($u(new URL(e,import.meta.url)),"utf-8"),n=e.endsWith("FRAMEWORK_VERSION")?t.trim():JSON.parse(t).version;if(n)return n}catch{}return"0.0.0"}function Ru(){try{let e=JSON.parse(K.readFileSync(Z.join(process.cwd(),"package.json"),"utf-8"));return!e.version||e.name==="rosefc"?"":` - project: ${e.name} v${e.version}`}catch{return""}}async function gk(){Jn=!0,process.env.ROSEFC_DEV="1",console.log(`\u{1F339} Rosefc v${bi()}${Ru()} dev server starting...`);try{await yl()}catch(s){console.error("Initial build failed (server still running):",s instanceof Error?s.message:s)}let e;K.watch(ss,{recursive:!0},(s,r)=>{if(!(r&&String(r).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase().split("/").filter(Boolean).some(a=>a==="dist"||a==="node_modules"||a===".git"||a===".rosefc"||a===".rosefc-build"||a===".rosefc-dev"))){if(gi){try{K.statSync(Z.join(ss,r)).mtimeMs>sg&&(gl=!0)}catch{let a=String(r??"").replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase().split("/").filter(Boolean);!a.some(d=>d==="dist"||d==="node_modules"||d===".git"||d===".rosefc"||d===".rosefc-build"||d===".rosefc-dev")&&Wx.has(Z.extname(a[a.length-1]??"").toLowerCase())&&(gl=!0)}return}Su=!0,clearTimeout(e),e=setTimeout(()=>{_u()},50)}});let n=(await import("http")).createServer(pk(xu(tt,!1,!0)));ku(n,pl,s=>{console.log("\u{1F339} http://localhost:"+s)})}async function mk(){await yl();let t=(await import("http")).createServer(xu(tt,!0));ku(t,pl,n=>{console.log(`\u{1F339} Rosefc v${bi()}${Ru()} preview at http://localhost:${n}`)})}async function yk(){K.existsSync(Z.join(tt,"server.js"))||(console.error(`Rosefc: ${tt} has no server.js - run rosefc build first`),process.exit(1));let e=(await import("node:cluster")).default;e.schedulingPolicy=e.SCHED_RR;let t=await import("node:os"),n=Math.max(1,Number(process.env.ROSEFC_WORKERS)||t.cpus().length);if(e.isPrimary){let f=await hk(Number(process.env.PORT)||3e3);for(let y=0;y<n;y++)e.fork({PORT:String(f)});e.on("message",(y,m)=>{if(!(!m||m.type!=="rosefc:store"))for(let b of Object.values(e.workers??{}))b&&b.id!==y.id&&b.send(m)});let h=n,g=()=>{for(let y of Object.values(e.workers??{}))y.kill();setTimeout(()=>process.exit(0),5e3).unref()};process.on("SIGTERM",g),process.on("SIGINT",g),e.on("exit",()=>{--h<=0&&process.exit(0)}),console.log(`\u{1F339} Rosefc v${bi()}${Ru()} serve: ${n} worker${n>1?"s":""} on http://localhost:${f} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);return}process.on("disconnect",()=>process.exit(0));let s=[];try{let f=await Jl(ss);Zl(f.csp?.connectSrc??"",f.csp?.imgSrc??""),s=f.plugins.filter(h=>h&&h.onServe)}catch(f){console.error("Rosefc: rosefc.config.js failed to load for the serve hooks:",f instanceof Error?f.message:String(f))}let r={install:f=>{try{hr?.__installStoreTransport?.(f)}catch{}},deliver:(f,h)=>{try{hr?.__deliverStorePatch?.(f,h)}catch{}}};try{let f=await yi();yu=()=>{try{f.invalidateRenderCache()}catch{}};try{f.__startNetwork?.()}catch(h){console.error("Rosefc: network listener start failed:",h instanceof Error?h.message:String(h))}}catch(f){console.error("Rosefc: dist/server.js failed to load for the serve hooks:",f instanceof Error?f.message:String(f))}let i=await import("node:http"),o=Xd(tt);o.then(async f=>{await ready;let h=(hr?.dynamicRoutes||[]).filter(y=>!y.includes(":")),g=0;await Promise.all(Array.from({length:Math.min(4,h.length)},async()=>{for(;g<h.length;){let y=h[g++];try{await(await f(new Request("http://localhost"+y))).arrayBuffer()}catch{}}}))}).catch(()=>{});let a=ok(xu(tt,!0),`w${process.pid}`),c=(()=>{try{let f=K.readFileSync(Z.join(tt,"index.html"),"utf8"),h=[];for(let g of f.matchAll(/<script[^>]+src="([^"]+)"/g)){let y=`<${g[1]}>; rel=preload; as=script`;h.includes(y)||h.push(y)}for(let g of f.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)){let y=/href="([^"]+)"/.exec(g[0])?.[1];if(y){let m=`<${y}>; rel=preload; as=style`;h.includes(m)||h.push(m)}}for(let g of f.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)){let y=`<${g[1]}>; rel=preload; as=style`;h.includes(y)||h.push(y)}return h}catch{return[]}})(),d=null,u=()=>{let f=hr?.dynamicRoutes||[];return(!d||d.size!==f.length)&&(d=new Set(f)),d},l=i.createServer(async(f,h)=>{let g=0,y=process.hrtime.bigint();if((f.url||"").startsWith("/__rosefc_store"))return rg(f,h);try{if((f.method==="GET"||f.method==="HEAD")&&u().has(Bn(f.url||"/"))){let m=await o;if(c.length&&f.method==="GET"&&String(f.headers.accept??"").includes("text/html"))try{h.writeEarlyHints({link:c})}catch{}let b=Yd(f,pl)+(f.url||"/"),$=await m(new Request(b,{method:f.method,headers:f.headers})),w=()=>ng(f,h,g,`w${process.pid}`,y);h.statusCode=$.status;let v=_o($);for(let[k,S]of Object.entries(v))h.setHeader(k,S);mi(h,"Accept-Encoding");let _=($.headers.get("content-type")??"").startsWith("text/html");if($.body){let k=Buffer.from(await $.arrayBuffer());if(k.length>0){let C=Gi($,k);if(h.setHeader("ETag",C),f.method==="GET"&&Sr(f.headers["if-none-match"],C)){h.statusCode=304,g=0,h.end(),w();return}}let S=_&&f.method==="GET"?dl(f):null;if(S){let C=await Yh(S,k);h.setHeader("Content-Encoding",S),h.setHeader("Content-Length",String(C.length)),h.end(C),g=C.length}else h.end(k),g=k.length;w()}else h.end(),g=0,w();return}}catch{}a(f,h)});l.requestTimeout=3e4,l.headersTimeout=65e3,l.keepAliveTimeout=5e3,ku(l,pl,async f=>{console.log(`\u{1F339} Rosefc worker ${process.pid} listening on http://localhost:${f}`);for(let h of s)try{await h.onServe({port:f,workers:n,store:r})}catch(g){console.error("Rosefc: plugin",h.name,"onServe failed:",g instanceof Error?g.message:String(g))}});let p=()=>{try{hr?.__stopNetwork?.()}catch{}for(let f of s)if(f.onShutdown)try{Promise.resolve(f.onShutdown()).catch(h=>{console.error("Rosefc: plugin",f.name,"onShutdown failed:",h instanceof Error?h.message:h)})}catch(h){console.error("Rosefc: plugin",f.name,"onShutdown failed:",h instanceof Error?h.message:h)}l.close(()=>{sa("worker signal").finally(()=>process.exit(0))}),l.closeIdleConnections?.(),setTimeout(()=>process.exit(0),5e3).unref()};process.on("SIGTERM",p),process.on("SIGINT",p)}function bu(){for(let e of["../../templates","../templates"]){let t=$u(new URL(e,import.meta.url));if(K.existsSync(t))return t}return null}function ig(e){K.writeFileSync(Z.join(e,"rosefc-env.d.ts"),`/// <reference types="rosefc" />
|
|
12717
|
+
`),K.writeFileSync(Z.join(e,"tsconfig.json"),JSON.stringify({compilerOptions:{target:"ES2022",module:"ESNext",moduleResolution:"bundler",lib:["ES2022","DOM","DOM.Iterable"],strict:!0,noEmit:!0,skipLibCheck:!0},include:["rosefc-env.d.ts","src/**/*.ts"]},null,2)+`
|
|
12718
|
+
`)}function bk(e,t,n){let s=bu(),r=s?Z.resolve(s,t):"",i=K.existsSync(r)?r:Z.resolve(t);if(!K.existsSync(i)||!K.statSync(i).isDirectory()){let a=s?K.readdirSync(s).join(", "):"(none found)";console.error(`Rosefc: no template '${t}' - available: ${a} (or pass a path to any project directory)`),process.exit(1)}K.cpSync(i,e,{recursive:!0,filter:a=>{let c=Z.relative(i,a);return c===""||!/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(c)}});let o=Z.join(e,"package.json");if(K.existsSync(o)){let a=JSON.parse(K.readFileSync(o,"utf8"));a.name=Z.basename(e),a.dependencies?.rosefc&&(a.dependencies.rosefc=`^${bi()}`),a.scripts={...a.scripts,check:"rosefc check"},a.devDependencies={...a.devDependencies,"@types/node":"^22.0.0",typescript:"^5.6.0"},K.writeFileSync(o,JSON.stringify(a,null,2)+`
|
|
12719
|
+
`)}ig(e),console.log(`\u{1F339} rosefc new: ${n}/ from the '${Z.basename(i)}' template`),console.log(`
|
|
12720
|
+
cd ${n}`),console.log(" npm install && npm run dev"),console.log(" npm run build # then deploy dist/")}async function $k(){let e=xo.slice(1),t=e.indexOf("--template"),n=t>=0?e[t+1]:null,s=e.find((o,a)=>!o.startsWith("-")&&a!==(t>=0?t+1:-1));if(!s||t>=0&&!n){let o=bu()?K.readdirSync(bu()).join(", "):"blog, api, admin, site";console.log(`Usage: rosefc new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${o} - or any project directory)`);return}let r=Z.resolve(s);if(K.existsSync(r)&&(console.error(`Rosefc: ${r} already exists - pick another name`),process.exit(1)),n){bk(r,n,s);return}let i=Z.join(r,"src","pages");K.mkdirSync(i,{recursive:!0}),K.writeFileSync(Z.join(r,"package.json"),JSON.stringify({name:Z.basename(r),private:!0,type:"module",scripts:{dev:"rosefc dev",build:"rosefc build",preview:"rosefc preview",serve:"rosefc serve",check:"rosefc check"},dependencies:{rosefc:`^${bi()}`},devDependencies:{typescript:"^5.6.0"}},null,2)+`
|
|
12721
12721
|
`),ig(r),K.writeFileSync(Z.join(i,"index.rose"),`<script>
|
|
12722
12722
|
|
|
12723
12723
|
interface Item { label: string }
|
|
@@ -12732,7 +12732,7 @@ parentPort.on('message', (file) => {
|
|
|
12732
12732
|
let first = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
|
|
12733
12733
|
</script>
|
|
12734
12734
|
|
|
12735
|
-
<h1>\u{1F339}
|
|
12735
|
+
<h1>\u{1F339} Rosefc</h1>
|
|
12736
12736
|
<p>Count: <strong>{count()}</strong> - first item: {first().label}</p>
|
|
12737
12737
|
<button on:click={increment}>Increment</button>
|
|
12738
12738
|
<button on:click={toggleList}>{showList() ? 'Hide' : 'Show'} the list</button>
|
|
@@ -12751,10 +12751,10 @@ parentPort.on('message', (file) => {
|
|
|
12751
12751
|
</style>
|
|
12752
12752
|
`),K.writeFileSync(Z.join(r,"README.md"),`# ${Z.basename(r)}
|
|
12753
12753
|
|
|
12754
|
-
A
|
|
12754
|
+
A Rosefc project. One file per route in \`src/pages/\`.
|
|
12755
12755
|
|
|
12756
12756
|
\`\`\`bash
|
|
12757
|
-
npm install # pulls the
|
|
12757
|
+
npm install # pulls the rosefc package (and typescript, for checking)
|
|
12758
12758
|
npm run dev # dev server with hot rebuild: http://localhost:3000
|
|
12759
12759
|
npm run build # compiles to dist/
|
|
12760
12760
|
npm run serve # production runner (cluster, access log, graceful shutdown)
|
|
@@ -12766,18 +12766,18 @@ Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
|
|
|
12766
12766
|
runs before every request, \`src/pages/api/*.rose\` answers JSON.
|
|
12767
12767
|
`),K.writeFileSync(Z.join(r,".gitignore"),`node_modules/
|
|
12768
12768
|
dist/
|
|
12769
|
-
`),console.log(`\u{1F339} Created ${r}`),console.log(" src/pages/index.rose - a typed page that builds and runs"),console.log("
|
|
12770
|
-
cd ${s}`),console.log(" npm install && npm run dev"),console.log(" npm run check # type-checks every .rose script")}async function wk(){let e=[...await Ye(ss),...await Ke(ss)];e.length===0&&(console.error(`
|
|
12771
|
-
`).length,k=vr($),S=Z.join(ss,".
|
|
12769
|
+
`),console.log(`\u{1F339} Created ${r}`),console.log(" src/pages/index.rose - a typed page that builds and runs"),console.log(" rosefc-env.d.ts + tsconfig.json - the script globals, typed"),console.log(`
|
|
12770
|
+
cd ${s}`),console.log(" npm install && npm run dev"),console.log(" npm run check # type-checks every .rose script")}async function wk(){let e=[...await Ye(ss),...await Ke(ss)];e.length===0&&(console.error(`Rosefc: no .rose pages found under ${Z.join(ss,"src","pages")} - run rosefc check from a project root, or pass one: rosefc check <dir>`),process.exit(1));let t=null;for(let b of[ul(Z.join(ss,"package.json")).href])try{let $=Mx(b),w=await import(ul($.resolve("typescript")).href),v=w&&w.ScriptTarget?w:w.default;if(v&&v.ScriptTarget&&v.createProgram){t=v;break}}catch{}t||(console.error("Rosefc: type checking needs typescript in this project - npm i -D typescript"),process.exit(1));let n=b=>b.map($=>$u(new URL($,import.meta.url))).find($=>K.existsSync($)),s=n(["../types/rosefc.d.ts","../src/types/rosefc.d.ts"]);s||(console.error("Rosefc: the type definitions (src/types/rosefc.d.ts) were not found next to the compiler"),process.exit(1));let r=n(["../runtime/index.ts","../src/runtime/index.ts"]),i=b=>Z.resolve(b).replace(/\\/g,"/"),o=new Map,a=0;for(let b of e){let $=await K.promises.readFile(b,"utf-8"),w=/<script>/.exec($);if(!vr($))continue;let _=$.slice(0,w.index+8).split(`
|
|
12771
|
+
`).length,k=vr($),S=Z.join(ss,".rosefc-build","check-flat");k=k.replace(/(from\s*['"])(\.{1,2}(?:\/[^'"]*)+)(['"])/g,(C,x,A,R)=>{let T=Z.resolve(S,A),M=[T,`${T}.ts`,`${T}.js`,`${T}.mjs`,Z.join(T,"index.ts"),Z.join(T,"index.js")].find(F=>K.existsSync(F));return!M&&r&&/(?:^|\/)runtime\.js$/.test(A)?x+i(r)+R:M?x+M.replace(/\\/g,"/")+R:C}),o.set(i(b),`
|
|
12772
12772
|
`.repeat(_-1)+k+`
|
|
12773
|
-
export {};`),a++}if(a===0){console.log("
|
|
12774
|
-
`)),u.add(v)}}let l={noEmit:!0,strict:!0,target:t.ScriptTarget.ES2022,module:t.ModuleKind.ESNext,moduleResolution:t.ModuleResolutionKind.Bundler,lib:["lib.es2022.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts"],allowNonTsExtensions:!0,allowImportingTsExtensions:!0,skipLibCheck:!0},p=t.createCompilerHost(l);p.getCurrentDirectory=()=>Z.resolve(ss);let f=p.readFile.bind(p),h=p.getSourceFile.bind(p);p.readFile=b=>o.get(i(b))??f(b),p.fileExists=b=>o.has(i(b))||t.sys.fileExists(b),p.getSourceFile=(b,$,w,v)=>{let _=o.get(i(b));return _?t.createSourceFile(b,_,$,!0):h(b,$,w,v)};let g=t.createProgram([...o.keys(),s],l,p),y=t.getPreEmitDiagnostics(g).filter(b=>b.file&&o.has(i(b.file.fileName)));if(y.length===0){console.log(`
|
|
12775
|
-
`),_=b.category===1?"error":"warning";console.error(`${w}: ${_} TS${b.code}: ${v}`)}let m=y.filter(b=>b.category===1).length;console.error(`
|
|
12776
|
-
`);return}console.log("
|
|
12777
|
-
Usage:
|
|
12778
|
-
`);return}let x=C.reduce((A,R)=>A+R.warnings,0);console.log(`
|
|
12779
|
-
${n()}`),process.exit(1));let o=r[2]&&!r[2].startsWith("-")?r[2]:".",a=Z.resolve(o),c=b=>{let $=r.findIndex(v=>v===b||v.startsWith(b+"="));if($<0)return;let w=r[$];return w.includes("=")?w.slice(w.indexOf("=")+1):r[$+1]},d=c("--api"),u=c("--out"),l=s[i];l.status!=="ready"&&(console.error(`
|
|
12773
|
+
export {};`),a++}if(a===0){console.log("Rosefc: no .rose scripts to check");return}let c=b=>b?/^['"`]/.test(b)?"string":/^-?\d+(\.\d+)?$/.test(b)?"number":/^(true|false)$/.test(b)?"boolean":"unknown":"unknown",d=/['"](\.[^'"]+\.rose)['"]/g,u=new Set;for(let b of[...o.keys()]){let $=vr(await K.promises.readFile(b,"utf-8").catch(()=>""));if($)for(let w of $.matchAll(d)){let v=i(Z.resolve(Z.dirname(b),w[1]));if(v===b||u.has(v))continue;let _=await K.promises.readFile(v,"utf-8").catch(()=>null);if(_===null)continue;let k=Qe(vr(_)??"").props;o.set(`${v}.d.ts`,[`declare function render(closes: unknown[], children: string, __props: { ${k.map(S=>`${S.name}?: ${c(S.def)}`).join("; ")} }, __slots?: Record<string, unknown>): string;`,"export default render;",""].join(`
|
|
12774
|
+
`)),u.add(v)}}let l={noEmit:!0,strict:!0,target:t.ScriptTarget.ES2022,module:t.ModuleKind.ESNext,moduleResolution:t.ModuleResolutionKind.Bundler,lib:["lib.es2022.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts"],allowNonTsExtensions:!0,allowImportingTsExtensions:!0,skipLibCheck:!0},p=t.createCompilerHost(l);p.getCurrentDirectory=()=>Z.resolve(ss);let f=p.readFile.bind(p),h=p.getSourceFile.bind(p);p.readFile=b=>o.get(i(b))??f(b),p.fileExists=b=>o.has(i(b))||t.sys.fileExists(b),p.getSourceFile=(b,$,w,v)=>{let _=o.get(i(b));return _?t.createSourceFile(b,_,$,!0):h(b,$,w,v)};let g=t.createProgram([...o.keys(),s],l,p),y=t.getPreEmitDiagnostics(g).filter(b=>b.file&&o.has(i(b.file.fileName)));if(y.length===0){console.log(`Rosefc: ${a} script${a===1?"":"s"} type-checked, no errors`);return}for(let b of y){let $=b.file?t.getLineAndCharacterOfPosition(b.file,b.start??0):null,w=b.file&&$?`${Z.relative(ss,b.file.fileName)}(${$.line+1},${$.character+1})`:"rosefc",v=t.flattenDiagnosticMessageText(b.messageText,`
|
|
12775
|
+
`),_=b.category===1?"error":"warning";console.error(`${w}: ${_} TS${b.code}: ${v}`)}let m=y.filter(b=>b.category===1).length;console.error(`Rosefc: ${m} type error${m===1?"":"s"} in ${a} script${a===1?"":"s"}`),process.exit(1)}async function vk(){let{exportProject:e,isTarget:t,targetList:n,TARGETS:s}=await Promise.resolve().then(()=>(Hh(),zh)),r=process.argv.slice(2),i=r[1];if(!i||i.startsWith("-")){let b=Object.values(s).map($=>({name:$.name,family:$.family,status:$.status,summary:$.summary}));if(So){process.stdout.write(`${JSON.stringify({ok:!0,targets:b})}
|
|
12776
|
+
`);return}console.log("Rosefc export targets:");for(let $ of b)console.log(` ${$.status==="ready"?"\u2713":"\xB7"} ${$.name.padEnd(10)} ${$.family.padEnd(13)} ${$.summary}`);console.log(`
|
|
12777
|
+
Usage: rosefc export <target|all> [dir] [--api <base>] [--out <dir>] [--json]`);return}if(i==="all"){let b=r[2]&&!r[2].startsWith("-")?r[2]:".",$=Z.resolve(b),w=A=>{let R=r.findIndex(M=>M===A||M.startsWith(A+"="));if(R<0)return;let T=r[R];return T.includes("=")?T.slice(T.indexOf("=")+1):r[R+1]},v=w("--out"),_=w("--api"),k=Date.now(),S=[],C=[];for(let A of Object.values(s)){if(A.status!=="ready")continue;let R=await e(A.name,$,{apiBase:_,outRoot:v});C.push({target:A.name,pages:R.pages.length,components:R.components.length,outDir:R.outDir,warnings:R.warnings.length}),So||console.log(` ${A.name.padEnd(10)} ${String(R.pages.length).padStart(3)} page(s) -> ${R.outDir}`),S.push(A.name)}if(So){process.stdout.write(`${JSON.stringify({ok:!0,targets:C,ms:Date.now()-k})}
|
|
12778
|
+
`);return}let x=C.reduce((A,R)=>A+R.warnings,0);console.log(`Rosefc exported ${S.length} targets in ${Date.now()-k}ms: ${S.join(", ")}`),x&&console.log(` ${x} warning(s) across targets - run one target to see them`);return}t(i)||(console.error(`rosefc export: unknown target "${i}"
|
|
12779
|
+
${n()}`),process.exit(1));let o=r[2]&&!r[2].startsWith("-")?r[2]:".",a=Z.resolve(o),c=b=>{let $=r.findIndex(v=>v===b||v.startsWith(b+"="));if($<0)return;let w=r[$];return w.includes("=")?w.slice(w.indexOf("=")+1):r[$+1]},d=c("--api"),u=c("--out"),l=s[i];l.status!=="ready"&&(console.error(`rosefc export: "${i}" (${l.summary}) is planned, not implemented yet.
|
|
12780
12780
|
Shipping targets today:
|
|
12781
12781
|
${n()}`),process.exit(1));let p=Date.now(),f=r.includes("--cloud"),h=c("--cloud-env"),g=await e(i,a,{apiBase:d,outRoot:u?Z.resolve(u):void 0,cloud:f?!0:void 0,cloudEnv:h});if(So){process.stdout.write(`${JSON.stringify({ok:!0,target:i,outDir:g.outDir,pages:g.pages,components:g.components,warnings:g.warnings,ms:Date.now()-p})}
|
|
12782
|
-
`);return}let y=Z.relative(process.cwd(),g.outDir)||g.outDir;console.log(`\u{1F339}
|
|
12783
|
-
`);else if(e instanceof ee){if(console.error(`
|
|
12782
|
+
`);return}let y=Z.relative(process.cwd(),g.outDir)||g.outDir;console.log(`\u{1F339} Rosefc v${bi()} export ${i} -> ${y}`),console.log(` ${g.pages.length} page(s), ${g.components.length} component(s) in ${Date.now()-p}ms`),g.pages.length&&console.log(` pages: ${g.pages.join(", ")}`);let m=new Map;for(let b of g.warnings){let $=b.replace(/^[a-z]+: /,"").replace(/[A-Za-z]:\\[^:]+?\.rose/g,"<file>").replace(/\b[\w./-]+\.rose\b/g,"<file>").replace(/load from GET \/__rosefc\/data \([^)]*\)/,"load from the data channel");m.set($,(m.get($)??0)+1)}if(m.size){console.log(` ${g.warnings.length} warning(s) - ${m.size} kind(s):`);let b=[...m.entries()].sort(($,w)=>w[1]-$[1]);for(let[$,w]of b.slice(0,8))console.log(` - ${$}${w>1?` (x${w})`:""}`);b.length>8&&console.log(` ... and ${b.length-8} more kind(s); pass --json for the full list`)}d||console.log(" note: no --api <base> given, so server actions and $data have no endpoint in the exported app")}var xo=process.argv.slice(2),fr=xo[0],So=xo.includes("--json");function Mr(e){if(So)process.stdout.write(`${JSON.stringify({ok:!1,errors:[Sl(e)]})}
|
|
12783
|
+
`);else if(e instanceof ee){if(console.error(`Rosefc: ${e.message}`),e.hint&&console.error(` hint: ${e.hint}`),e.file&&e.line)try{console.error(_l(K.readFileSync(e.file,"utf-8"),e.line))}catch{}let t=e.file?`${e.file}${e.line?`:${e.line}`:""}`:null;t&&console.error(` at ${t}`)}else console.error(e instanceof Error?e.stack??e.message:String(e));process.exit(1)}fr==="dev"?gk().catch(Mr):fr==="build"?yl().catch(Mr):fr==="preview"?mk().catch(Mr):fr==="serve"?yk().catch(Mr):fr==="new"?$k().catch(Mr):fr==="check"?wk().catch(Mr):fr==="export"?vk().catch(Mr):console.log(fr==="prompt"?Qd:"Usage: rosefc dev|build|preview|serve|new|check|export|prompt [dir] [--json] [--static] [--no-minify] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON; --static verifies the build is deployable with no server at all; --no-minify keeps server.js/prod.mjs unminified for debugging; `new <name> [--template blog|api|admin|site]` scaffolds a project; `export <target> [dir] [--api <base>] [--out <dir>]` compiles the same pages into a mini program today, with the native targets on the way)");
|