@stacksjs/stx 0.2.463 → 0.2.465

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.
Files changed (116) hide show
  1. package/dist/chunk-0880qx3m.js +2 -0
  2. package/dist/{chunk-krsdcjxk.js → chunk-0avd5kkb.js} +20 -20
  3. package/dist/chunk-0zf49qxk.js +2 -0
  4. package/dist/{chunk-sprx02g0.js → chunk-1bazr47z.js} +1 -1
  5. package/dist/{chunk-2tn3dkcy.js → chunk-1byqqwgm.js} +2 -2
  6. package/dist/chunk-1tsz7v68.js +2 -0
  7. package/dist/{chunk-bp53x03f.js → chunk-27k24mk0.js} +1 -1
  8. package/dist/{chunk-jmhhv817.js → chunk-2e4pegf1.js} +1 -1
  9. package/dist/chunk-2mv3wh0s.js +2 -0
  10. package/dist/{chunk-3ar8gdyd.js → chunk-2nvnd83c.js} +1 -1
  11. package/dist/{chunk-rgwvqmhh.js → chunk-32kk8y2r.js} +1 -1
  12. package/dist/{chunk-skjwh35r.js → chunk-3q3174cn.js} +2 -2
  13. package/dist/{chunk-nwwzf7h1.js → chunk-4acykd9n.js} +1 -1
  14. package/dist/chunk-4wjef6d8.js +18 -0
  15. package/dist/{chunk-raqqq3mm.js → chunk-4xcypfmg.js} +1 -1
  16. package/dist/{chunk-cfk3skk4.js → chunk-5e6p2ndj.js} +1 -1
  17. package/dist/{chunk-wvxj6r2a.js → chunk-5mmqe3hj.js} +1 -1
  18. package/dist/{chunk-5yn0gpcj.js → chunk-5zaj400e.js} +10 -10
  19. package/dist/{chunk-d9360m89.js → chunk-6bwe6vsc.js} +1 -1
  20. package/dist/chunk-6ry01675.js +2 -0
  21. package/dist/{chunk-a35c060g.js → chunk-769t2y70.js} +1 -1
  22. package/dist/{chunk-k9sbgax8.js → chunk-7knc20mz.js} +1 -1
  23. package/dist/{chunk-tsg7bj9p.js → chunk-7xckcy9x.js} +1 -1
  24. package/dist/chunk-97ezbs97.js +2 -0
  25. package/dist/chunk-99qf5fff.js +2 -0
  26. package/dist/{chunk-z80d9dd2.js → chunk-9g339c7b.js} +2 -2
  27. package/dist/chunk-a201b6rx.js +2 -0
  28. package/dist/{chunk-r5gyx7ch.js → chunk-abb9xmdg.js} +1 -1
  29. package/dist/{chunk-dqdggvq4.js → chunk-ag1v2tkm.js} +2101 -2101
  30. package/dist/chunk-aqdkct70.js +2 -0
  31. package/dist/{chunk-627af18j.js → chunk-azcvytqc.js} +1 -1
  32. package/dist/chunk-bb7p822h.js +2 -0
  33. package/dist/chunk-bj31r6sj.js +2 -0
  34. package/dist/chunk-c1gp4xjy.js +2 -0
  35. package/dist/chunk-c8z3fghp.js +2 -0
  36. package/dist/{chunk-y9j2kf3k.js → chunk-cstvhr0r.js} +1297 -1297
  37. package/dist/{chunk-xbm2gcb6.js → chunk-en3e0y6m.js} +1 -1
  38. package/dist/chunk-esc6fahf.js +2 -0
  39. package/dist/chunk-f2rh0zhs.js +2 -0
  40. package/dist/{chunk-39q77svv.js → chunk-gasb5fhy.js} +2 -2
  41. package/dist/{chunk-y36av1ac.js → chunk-gj90pnre.js} +7 -7
  42. package/dist/{chunk-d2zw2e5m.js → chunk-gjrbnzap.js} +3 -3
  43. package/dist/{chunk-8efg91ak.js → chunk-gm6g6gar.js} +2 -2
  44. package/dist/chunk-h5k0c1jp.js +2 -0
  45. package/dist/chunk-hqfgbtsy.js +30 -0
  46. package/dist/chunk-j2pdtq0d.js +2 -0
  47. package/dist/{chunk-ptek61ts.js → chunk-j9y50qt9.js} +1 -1
  48. package/dist/{chunk-ng61wjke.js → chunk-jbdqs7t6.js} +1 -1
  49. package/dist/chunk-kewh1a68.js +2 -0
  50. package/dist/{chunk-t61vdbje.js → chunk-ktvr45qg.js} +6 -6
  51. package/dist/chunk-kvfcm30m.js +2 -0
  52. package/dist/{chunk-1sdtg9np.js → chunk-n003eq8w.js} +2 -2
  53. package/dist/{chunk-etjw0he9.js → chunk-n6p2at6g.js} +1 -1
  54. package/dist/chunk-nahzfs7d.js +2 -0
  55. package/dist/{chunk-hhsynd7c.js → chunk-nmk9en1n.js} +6 -6
  56. package/dist/{chunk-qr15ksz9.js → chunk-nmnbdtsq.js} +6 -6
  57. package/dist/{chunk-v83bpj84.js → chunk-p7j2g8y2.js} +4 -4
  58. package/dist/{chunk-ynvce0q6.js → chunk-pfm6cfph.js} +2 -2
  59. package/dist/{chunk-tesmv3m9.js → chunk-pxmbee61.js} +5 -5
  60. package/dist/{chunk-02e24cym.js → chunk-qc7zybaa.js} +1 -1
  61. package/dist/chunk-s1075erh.js +2 -0
  62. package/dist/chunk-s2fpethy.js +2 -0
  63. package/dist/{chunk-544e2jvd.js → chunk-se9qddyx.js} +4 -4
  64. package/dist/{chunk-0v5dpk7r.js → chunk-sgbgwezf.js} +1 -1
  65. package/dist/chunk-tps20cx5.js +2 -0
  66. package/dist/chunk-ts3jftxq.js +2 -0
  67. package/dist/{chunk-z990jtmx.js → chunk-vvb3wq2p.js} +1 -1
  68. package/dist/chunk-wfmy7a0b.js +2 -0
  69. package/dist/{chunk-e15a8txv.js → chunk-x9a5a282.js} +2 -2
  70. package/dist/{chunk-nkxa7men.js → chunk-xsdj6k6c.js} +1 -1
  71. package/dist/{chunk-ccy6avqe.js → chunk-xt4990k8.js} +1 -1
  72. package/dist/{chunk-74j18qk0.js → chunk-y8h823cb.js} +28 -28
  73. package/dist/{chunk-2cqymwe8.js → chunk-yc4hf2ea.js} +2 -2
  74. package/dist/chunk-yn2d8x8m.js +3 -0
  75. package/dist/{chunk-eegxyqk3.js → chunk-ysptfks9.js} +1 -1
  76. package/dist/chunk-z14y48en.js +17 -0
  77. package/dist/cli.js +43 -43
  78. package/dist/client-script-bundler.d.ts +10 -0
  79. package/dist/client-script-bundler.js +9 -3
  80. package/dist/composable-loader.js +5 -2
  81. package/dist/craft-entry.js +2 -2
  82. package/dist/craft.js +2 -2
  83. package/dist/database.js +2 -2
  84. package/dist/native/runtime/native-host.js +2 -1
  85. package/dist/pwa.js +3 -3
  86. package/dist/ssg.js +2 -2
  87. package/package.json +5 -5
  88. package/dist/chunk-0fvz8wad.js +0 -2
  89. package/dist/chunk-0yba08sr.js +0 -2
  90. package/dist/chunk-1p5ge6fq.js +0 -2
  91. package/dist/chunk-4yjtwjrw.js +0 -2
  92. package/dist/chunk-7fjatz47.js +0 -2
  93. package/dist/chunk-7j1cpa9d.js +0 -2
  94. package/dist/chunk-938g2a3d.js +0 -2
  95. package/dist/chunk-ajqwjevt.js +0 -2
  96. package/dist/chunk-cg8hg6cs.js +0 -3
  97. package/dist/chunk-d1x5r4p6.js +0 -2
  98. package/dist/chunk-dcv6absa.js +0 -2
  99. package/dist/chunk-jr3g08vs.js +0 -2
  100. package/dist/chunk-kdk0jy1h.js +0 -17
  101. package/dist/chunk-kmb9qrdg.js +0 -2
  102. package/dist/chunk-mfxf378k.js +0 -18
  103. package/dist/chunk-mxt11ejx.js +0 -2
  104. package/dist/chunk-mxtah7y5.js +0 -2
  105. package/dist/chunk-q316y302.js +0 -2
  106. package/dist/chunk-qyq7j8hp.js +0 -2
  107. package/dist/chunk-raeyd6e5.js +0 -2
  108. package/dist/chunk-rjm3n62n.js +0 -2
  109. package/dist/chunk-tkakxkbx.js +0 -2
  110. package/dist/chunk-txkfp4v5.js +0 -2
  111. package/dist/chunk-tzjqtweb.js +0 -2
  112. package/dist/chunk-vhdemrec.js +0 -2
  113. package/dist/chunk-xek78ez1.js +0 -2
  114. package/dist/chunk-xjb0yzvq.js +0 -2
  115. package/dist/chunk-y8mx0hab.js +0 -30
  116. package/dist/chunk-zhexga43.js +0 -2
@@ -290,8 +290,8 @@ export function queueClientBundleBuild(task) {
290
290
  return result;
291
291
  }
292
292
  export async function bundleClientScript(code, filePath, options = {}) {
293
- const projectRoot = options.projectRoot || process.cwd(), serverApi = (await loadStxConfig(projectRoot)).serverApi, minify = options.minify ?? !1, externalizeUserModules = options.externalizeUserModules ?? !0, cacheDir = options.cacheDir || stateDir(projectRoot, "bundle-cache"), hasher = new Bun.CryptoHasher("md5");
294
- hasher.update(`${BUNDLE_CACHE_VERSION}\x00${cacheEngineFingerprint()}\x00${JSON.stringify(serverApi ?? !1)}\x00${externalizeUserModules ? "registry" : "inline"}\x00${code}\x00${filePath}`);
293
+ const projectRoot = options.projectRoot || process.cwd(), serverApi = (await loadStxConfig(projectRoot)).serverApi, minify = options.minify ?? !1, externalizeUserModules = options.externalizeUserModules ?? !0, expose = options.expose?.length ? [...new Set(options.expose)].sort() : void 0, cacheDir = options.cacheDir || stateDir(projectRoot, "bundle-cache"), hasher = new Bun.CryptoHasher("md5");
294
+ hasher.update(`${BUNDLE_CACHE_VERSION}\x00${cacheEngineFingerprint()}\x00${JSON.stringify(serverApi ?? !1)}\x00${externalizeUserModules ? "registry" : "inline"}\x00${expose ? expose.join(",") : "*"}\x00${code}\x00${filePath}`);
295
295
  const hash = hasher.digest("hex").slice(0, 12), cachePath = path.join(cacheDir, `${hash}.js`), remembered = bundleMemo.get(cachePath);
296
296
  if (remembered) {
297
297
  if (depsUnchanged(remembered.files) && remembered.files.every((dep) => !isPrivateClientSource(dep.path, projectRoot, serverApi))) {
@@ -342,7 +342,7 @@ export async function bundleClientScript(code, filePath, options = {}) {
342
342
  options.collectInputs.push(...(bundleMemo.get(cachePath)?.files ?? []).map((dep) => dep.path));
343
343
  return shared;
344
344
  }
345
- const build = queueClientBundleBuild(() => buildBundle(code, filePath, { projectRoot, minify, cacheDir, hash, cachePath, depsPath, collectInputs: options.collectInputs, externalizeUserModules, serverApi }));
345
+ const build = queueClientBundleBuild(() => buildBundle(code, filePath, { projectRoot, minify, cacheDir, hash, cachePath, depsPath, collectInputs: options.collectInputs, externalizeUserModules, serverApi, expose }));
346
346
  inFlightBundles.set(hash, build);
347
347
  try {
348
348
  return await build;
@@ -451,6 +451,12 @@ export { ${[...declNames].join(", ")} }` : "";
451
451
  if (/^[A-Za-z_$][\w$]*$/.test(name))
452
452
  exposedBindings.push([name, name]);
453
453
  }
454
+ if (options.expose) {
455
+ const wanted = new Set(options.expose);
456
+ for (let i = exposedBindings.length - 1;i >= 0; i--)
457
+ if (!wanted.has(exposedBindings[i][0]))
458
+ exposedBindings.splice(i, 1);
459
+ }
454
460
  const registryReads = [];
455
461
  bundled = rewriteRegistryImports(normalizeRegistrySpecifiers(bundled, registrySpecifiers), registryReads);
456
462
  const externalImports = bundled.match(/^\s*import\s+[^;]+;?\s*$/gm) || [];
@@ -154,14 +154,17 @@ export async function getComposableScript(composablesDir, pageSource, extraSourc
154
154
  for (const match of code.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))
155
155
  if (match[1])
156
156
  declaredNames.add(match[1]);
157
+ const ownExports = [];
157
158
  try {
158
159
  for (const name of transpiler.scan(code).exports)
159
- if (name !== "default")
160
+ if (name !== "default") {
160
161
  exportedNames.add(name);
162
+ ownExports.push(name);
163
+ }
161
164
  } catch {}
162
165
  code = transformStoreImports(code);
163
166
  if (hasUserImports(code)) {
164
- code = await bundleClientScript(code, file, { projectRoot: process.cwd(), externalizeUserModules: !1 });
167
+ code = await bundleClientScript(code, file, { projectRoot: process.cwd(), externalizeUserModules: !1, expose: ownExports });
165
168
  code = stripStxRuntimeImports(code);
166
169
  }
167
170
  code = stripModuleImports(code);
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Br,$o,Eo}from"./chunk-2tn3dkcy.js";import"./chunk-ynvce0q6.js";import"./chunk-2n5pjbw9.js";import"./chunk-88px183j.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import"./chunk-dqdggvq4.js";import"./chunk-v83bpj84.js";import"./chunk-y36av1ac.js";import"./chunk-zydg3wgt.js";import"./chunk-ng61wjke.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{lu,bo,uu,du,wo,jr,vo,pu,xo,fu,gu,So,ko,Co}from"./chunk-krsdcjxk.js";import"./chunk-mfxf378k.js";import"./chunk-d2zw2e5m.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import{Br,$o,Eo}from"./chunk-1byqqwgm.js";import"./chunk-pfm6cfph.js";import"./chunk-2n5pjbw9.js";import"./chunk-88px183j.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import"./chunk-ag1v2tkm.js";import"./chunk-p7j2g8y2.js";import"./chunk-gj90pnre.js";import"./chunk-zydg3wgt.js";import"./chunk-jbdqs7t6.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{ld,bo,dd,ud,wo,jr,vo,pd,xo,fd,gd,So,ko,Co}from"./chunk-0avd5kkb.js";import"./chunk-4wjef6d8.js";import"./chunk-gjrbnzap.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
6
6
  `),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
7
7
  <script data-craft-hydration>
8
8
  window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
9
- </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{lu as CRAFT_BRIDGE_SCRIPT,jr as CRAFT_COMPONENTS,pu as CRAFT_COMPONENT_RUNTIME,vo as CRAFT_COMPONENT_STYLES,Br as NATIVE_COMPONENTS,So as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,$o as compileToNative,Eo as createHotReloadServer,bo as generateCraftBridgeScript,V as generateCraftOptimizations,Co as getAvailableFormats,ko as getAvailableTargets,gu as getCraftComponents,G as getSSRCacheStats,wo as injectCraftBridge,uu as isCraftEnvironment,Y as prerenderForCraft,xo as processCraftComponents,du as processCraftDirective,fu as registerCraftComponent,Q as renderSSR};
9
+ </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{ld as CRAFT_BRIDGE_SCRIPT,jr as CRAFT_COMPONENTS,pd as CRAFT_COMPONENT_RUNTIME,vo as CRAFT_COMPONENT_STYLES,Br as NATIVE_COMPONENTS,So as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,$o as compileToNative,Eo as createHotReloadServer,bo as generateCraftBridgeScript,V as generateCraftOptimizations,Co as getAvailableFormats,ko as getAvailableTargets,gd as getCraftComponents,G as getSSRCacheStats,wo as injectCraftBridge,dd as isCraftEnvironment,Y as prerenderForCraft,xo as processCraftComponents,ud as processCraftDirective,fd as registerCraftComponent,Q as renderSSR};
package/dist/craft.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Br,$o,Eo}from"./chunk-2tn3dkcy.js";import"./chunk-ynvce0q6.js";import"./chunk-2n5pjbw9.js";import"./chunk-88px183j.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import"./chunk-dqdggvq4.js";import"./chunk-v83bpj84.js";import"./chunk-y36av1ac.js";import"./chunk-zydg3wgt.js";import"./chunk-ng61wjke.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{lu,bo,uu,du,wo,jr,vo,pu,xo,fu,gu,So,ko,Co}from"./chunk-krsdcjxk.js";import"./chunk-mfxf378k.js";import"./chunk-d2zw2e5m.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import{Br,$o,Eo}from"./chunk-1byqqwgm.js";import"./chunk-pfm6cfph.js";import"./chunk-2n5pjbw9.js";import"./chunk-88px183j.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import"./chunk-ag1v2tkm.js";import"./chunk-p7j2g8y2.js";import"./chunk-gj90pnre.js";import"./chunk-zydg3wgt.js";import"./chunk-jbdqs7t6.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{ld,bo,dd,ud,wo,jr,vo,pd,xo,fd,gd,So,ko,Co}from"./chunk-0avd5kkb.js";import"./chunk-4wjef6d8.js";import"./chunk-gjrbnzap.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
6
6
  `),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
7
7
  <script data-craft-hydration>
8
8
  window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
9
- </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{lu as CRAFT_BRIDGE_SCRIPT,jr as CRAFT_COMPONENTS,pu as CRAFT_COMPONENT_RUNTIME,vo as CRAFT_COMPONENT_STYLES,Br as NATIVE_COMPONENTS,So as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,$o as compileToNative,Eo as createHotReloadServer,bo as generateCraftBridgeScript,V as generateCraftOptimizations,Co as getAvailableFormats,ko as getAvailableTargets,gu as getCraftComponents,G as getSSRCacheStats,wo as injectCraftBridge,uu as isCraftEnvironment,Y as prerenderForCraft,xo as processCraftComponents,du as processCraftDirective,fu as registerCraftComponent,Q as renderSSR};
9
+ </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{ld as CRAFT_BRIDGE_SCRIPT,jr as CRAFT_COMPONENTS,pd as CRAFT_COMPONENT_RUNTIME,vo as CRAFT_COMPONENT_STYLES,Br as NATIVE_COMPONENTS,So as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,$o as compileToNative,Eo as createHotReloadServer,bo as generateCraftBridgeScript,V as generateCraftOptimizations,Co as getAvailableFormats,ko as getAvailableTargets,gd as getCraftComponents,G as getSSRCacheStats,wo as injectCraftBridge,dd as isCraftEnvironment,Y as prerenderForCraft,xo as processCraftComponents,ud as processCraftDirective,fd as registerCraftComponent,Q as renderSSR};
package/dist/database.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},k={},C={},f=new Map,P=[];function z(t){u={...u,...t}}function V(){return{...u}}function G(){u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let t of Object.keys(k))delete k[t];f.clear(),P.length=0}function X(t,e){k[t]=e}function g(t){let e=t||u.default;if(k[e])return k[e];let r=u.connections[e];if(!r)throw Error(`Database connection "${e}" not configured`);let s=N(r);return k[e]=s,s}function N(t){switch(t.driver){case"sqlite":return D(t);case"postgres":return S(t);case"mysql":return L(t);default:throw Error(`Unsupported database driver: ${t.driver}`)}}function D(t){let e=null,r=!1;return{async connect(){if(r)return;let{Database:s}=await import("bun:sqlite");e=new s(t.database,{create:!0,readwrite:!0}),r=!0},async disconnect(){if(e)e.close(),e=null,r=!1},async query(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).all(...n);if(u.logging)y(s,n,performance.now()-i);return o}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.lastInsertRowid}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.changes}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!r)await this.connect();e.run("BEGIN TRANSACTION")},async commit(){e.run("COMMIT")},async rollback(){e.run("ROLLBACK")},isConnected(){return r}}}function S(t){let e=!1,r=null;return{async connect(){if(e)return;try{let{Client:s}=await import("pg");r=new s({host:t.host||"localhost",port:t.port||5432,database:t.database,user:t.username,password:t.password,ssl:t.ssl}),await r.connect(),e=!0}catch(s){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rows}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(`${s} RETURNING id`,n);if(u.logging)y(s,n,performance.now()-i);return a.rows[0]?.id}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rowCount||0}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();await r.query("BEGIN")},async commit(){await r.query("COMMIT")},async rollback(){await r.query("ROLLBACK")},isConnected(){return e}}}function L(t){let e=!1,r=null;return{async connect(){if(e)return;try{let s=await import("mysql2/promise");r=s.createPool({host:t.host||"localhost",port:t.port||3306,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:t.poolSize||10,queueLimit:0}),e=!0}catch(s){throw Error(`MySQL connection failed. Install 'mysql2' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.insertId}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.affectedRows||0}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();let s=await r.getConnection();return await s.beginTransaction(),s},async commit(){await r.execute("COMMIT")},async rollback(){await r.execute("ROLLBACK")},isConnected(){return e}}}class x{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(t){if(t)this._table=t}table(t){return this._table=t,this}from(t){return this.table(t)}connection(t){return this._connection=t,this}select(...t){return this._columns=t.length>0?t:["*"],this}addSelect(...t){if(this._columns[0]==="*")this._columns=t;else this._columns.push(...t);return this}distinct(){return this._distinct=!0,this}where(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"and"}),this}orWhere(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"or"}),this}whereIn(t,e){return this._wheres.push({column:t,operator:"in",value:e,boolean:"and"}),this}whereNotIn(t,e){return this._wheres.push({column:t,operator:"not in",value:e,boolean:"and"}),this}whereNull(t){return this._wheres.push({column:t,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(t){return this._wheres.push({column:t,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(t,e,r){return this._wheres.push({column:t,operator:"between",value:[e,r],boolean:"and"}),this}whereLike(t,e){return this._wheres.push({column:t,operator:"like",value:e,boolean:"and"}),this}join(t,e,r,s){return this._joins.push({type:"inner",table:t,first:e,operator:r,second:s}),this}leftJoin(t,e,r,s){return this._joins.push({type:"left",table:t,first:e,operator:r,second:s}),this}rightJoin(t,e,r,s){return this._joins.push({type:"right",table:t,first:e,operator:r,second:s}),this}orderBy(t,e="asc"){return this._orders.push({column:t,direction:e}),this}orderByDesc(t){return this.orderBy(t,"desc")}groupBy(...t){return this._groupBy.push(...t),this}having(t,e,r){return this._having.push({column:t,operator:e,value:r,boolean:"and"}),this}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}async get(){let{sql:t,bindings:e}=this.toSql();if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e),i=Q(n);if(i!==void 0)return i}let s=await g(this._connection).query(t,e);if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e);B(n,s,u.cacheTTL)}return s}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let t=await this.first();if(!t)throw Error("No results found");return t}async find(t,e="id"){return this.where(e,t).first()}async value(t){let e=await this.select(t).first();return e?e[t]:null}async pluck(t){return(await this.select(t).get()).map((r)=>r[t])}async exists(){return(await this.select(_("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(t="*"){let e=await this.select(_(`COUNT(${t}) as count`)).first();return Number(e?.count||0)}async max(t){return(await this.select(_(`MAX(${t}) as max`)).first())?.max}async min(t){return(await this.select(_(`MIN(${t}) as min`)).first())?.min}async sum(t){let e=await this.select(_(`SUM(${t}) as sum`)).first();return Number(e?.sum||0)}async avg(t){return(await this.select(_(`AVG(${t}) as avg`)).first())?.avg}async insert(t){let e=Object.keys(t),r=e.map(()=>"?").join(", "),s=Object.values(t),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES (${r})`,i=g(this._connection);return T(this._table),i.insert(n,s)}async insertAll(t){if(t.length===0)return;let e=Object.keys(t[0]),r=t.map(()=>`(${e.map(()=>"?").join(", ")})`).join(", "),s=t.flatMap((a)=>Object.values(a)),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES ${r}`,i=g(this._connection);T(this._table),await i.execute(n,s)}async update(t){this._bindings=[];let e=this.buildWhereClause(),r=[...this._bindings],s=Object.keys(t).map((o)=>`${o} = ?`).join(", "),n=[...Object.values(t),...r],i=`UPDATE ${this._table} SET ${s}${e}`,a=g(this._connection);return T(this._table),a.execute(i,n)}async increment(t,e=1){this._bindings=[];let r=this.buildWhereClause(),s=`UPDATE ${this._table} SET ${t} = ${t} + ?${r}`,n=g(this._connection);return T(this._table),n.execute(s,[e,...this._bindings])}async decrement(t,e=1){return this.increment(t,-e)}async delete(){this._bindings=[];let t=this.buildWhereClause(),e=`DELETE FROM ${this._table}${t}`,r=g(this._connection);return T(this._table),r.execute(e,this._bindings)}async truncate(){let t=g(this._connection);T(this._table),await t.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let t="SELECT ";if(this._distinct)t+="DISTINCT ";t+=this._columns.map((e)=>{if(typeof e==="object"&&e.__raw)return e.sql;return e}).join(", "),t+=` FROM ${this._table}`;for(let e of this._joins)t+=` ${e.type.toUpperCase()} JOIN ${e.table} ON ${e.first} ${e.operator} ${e.second}`;if(t+=this.buildWhereClause(),this._groupBy.length>0)t+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let e=this._having.map((r,s)=>{let n=s===0?"":` ${r.boolean.toUpperCase()} `;return this._bindings.push(r.value),`${n}${r.column} ${r.operator} ?`});t+=` HAVING ${e.join("")}`}if(this._orders.length>0)t+=` ORDER BY ${this._orders.map((e)=>`${e.column} ${e.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)t+=` LIMIT ${this._limit}`;if(this._offset!==void 0)t+=` OFFSET ${this._offset}`;return{sql:t,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((e,r)=>{let s=r===0?" WHERE ":` ${e.boolean.toUpperCase()} `;switch(e.operator){case"in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} IN (${i})`}case"not in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} NOT IN (${i})`}case"between":{let[n,i]=e.value;return this._bindings.push(n,i),`${s}${e.column} BETWEEN ? AND ?`}case"is null":return`${s}${e.column} IS NULL`;case"is not null":return`${s}${e.column} IS NOT NULL`;default:return this._bindings.push(e.value),`${s}${e.column} ${e.operator} ?`}}).join("")}getCacheKey(t,e){return`${this._table}:${t}:${JSON.stringify(e)}`}clone(){let t=new x(this._table);return t._columns=[...this._columns],t._wheres=[...this._wheres],t._orders=[...this._orders],t._joins=[...this._joins],t._groupBy=[...this._groupBy],t._having=[...this._having],t._limit=this._limit,t._offset=this._offset,t._distinct=this._distinct,t._connection=this._connection,t}}function l(t){return new x(t)}function Y(t){return l(t)}function _(t,e=[]){return{__raw:!0,sql:t,bindings:e}}function H(t,e){let r=e.primaryKey||"id",s={name:t,definition:e,async find(n){let i=await l(e.table).where(r,n).first();return i?b(s,i):null},async findOrFail(n){let i=await this.find(n);if(!i)throw Error(`${t} not found with ${r} = ${n}`);return i},async all(){return(await l(e.table).get()).map((i)=>b(s,i))},async create(n){let i={...e.defaults,...n},a=e.fillable?Object.fromEntries(Object.entries(i).filter(([c])=>e.fillable.includes(c))):i;if(e.timestamps!==!1){let c=new Date().toISOString(),h=typeof e.timestamps==="object"?e.timestamps.createdAt||"created_at":"created_at",p=typeof e.timestamps==="object"?e.timestamps.updatedAt||"updated_at":"updated_at";a[h]=c,a[p]=c}let o=await l(e.table).insert(a);return this.findOrFail(o)},async update(n){return l(e.table).update(n)},async destroy(n){let i=Array.isArray(n)?n:[n];return l(e.table).whereIn(r,i).delete()},query(){return l(e.table)},where(n,i,a){return this.query().where(n,i,a)},async first(){let n=await this.query().first();return n?b(s,n):null},async get(){return(await this.query().get()).map((i)=>b(s,i))},async count(){return this.query().count()}};return C[t]=s,s}function v(t){let e=C[t];if(!e)throw Error(`Model "${t}" not defined. Use defineModel() first.`);return e}function Z(t){return t in C}function b(t,e){let{definition:r}=t,s=r.primaryKey||"id",n={...e},i={...e};if(r.casts){for(let[o,c]of Object.entries(r.casts))if(o in i)i[o]=q(i[o],c)}let a={exists:!0,original:n,attributes:i,get(o){return i[o]},set(o,c){i[o]=c},toJSON(){let o={...i};if(r.hidden)for(let c of r.hidden)delete o[c];return o},async save(){let o={};for(let c of Object.keys(i))if(i[c]!==n[c])o[c]=i[c];if(Object.keys(o).length>0){if(r.timestamps!==!1){let c=typeof r.timestamps==="object"?r.timestamps.updatedAt||"updated_at":"updated_at";o[c]=new Date().toISOString()}await l(r.table).where(s,n[s]).update(o),Object.assign(n,o)}},async delete(){if(r.softDeletes){let o=typeof r.softDeletes==="string"?r.softDeletes:"deleted_at";await l(r.table).where(s,n[s]).update({[o]:new Date().toISOString()})}else await l(r.table).where(s,n[s]).delete();a.exists=!1},async refresh(){let o=await l(r.table).where(s,n[s]).first();if(o)Object.assign(n,o),Object.assign(i,o)},isDirty(o){if(o)return i[o]!==n[o];return Object.keys(i).some((c)=>i[c]!==n[c])}};if(r.relationships)for(let[o,c]of Object.entries(r.relationships))Object.defineProperty(a,o,{value:async()=>j(a,c,t),enumerable:!1});return new Proxy(a,{get(o,c){if(c in o)return o[c];return i[c]},set(o,c,h){if(c in o)o[c]=h;else i[c]=h;return!0}})}async function j(t,e,r){let s=v(e.model),n=r.definition.primaryKey||"id";switch(e.type){case"hasOne":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`,a=await l(s.definition.table).where(i,t.get(n)).first();return a?b(s,a):null}case"hasMany":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`;return(await l(s.definition.table).where(i,t.get(n)).get()).map((o)=>b(s,o))}case"belongsTo":{let i=e.foreignKey||`${e.model.toLowerCase()}_id`,a=e.localKey||"id",o=await l(s.definition.table).where(a,t.get(i)).first();return o?b(s,o):null}case"belongsToMany":{let i=e.pivotTable||[r.name,e.model].sort().join("_").toLowerCase(),a=e.pivotForeignKey||`${r.name.toLowerCase()}_id`,o=e.pivotRelatedKey||`${e.model.toLowerCase()}_id`,c=s.definition.primaryKey||"id";return(await l(s.definition.table).join(i,`${s.definition.table}.${c}`,"=",`${i}.${o}`).where(`${i}.${a}`,t.get(n)).get()).map((p)=>b(s,p))}default:return null}}function q(t,e){if(t===null||t===void 0)return t;switch(e){case"string":return String(t);case"number":return Number(t);case"boolean":return Boolean(t);case"date":return new Date(t);case"json":case"array":return typeof t==="string"?JSON.parse(t):t;default:return t}}async function tt(t,e){let r=g(e);await r.beginTransaction();try{let s=await t();return await r.commit(),s}catch(s){throw await r.rollback(),s}}function Q(t){let e=f.get(t);if(!e)return;if(Date.now()-e.timestamp>e.ttl*1000){f.delete(t);return}return e.result}function B(t,e,r){if(f.size>=(u.maxCacheSize||1000)){let s=f.keys().next().value;if(s)f.delete(s)}f.set(t,{result:e,timestamp:Date.now(),ttl:r})}function T(t){for(let e of f.keys())if(e.startsWith(`${t}:`))f.delete(e)}function et(){f.clear()}function nt(){return{size:f.size,keys:[...f.keys()]}}function y(t,e,r){if(P.push({sql:t,bindings:e,duration:r,timestamp:new Date}),P.length>1000)P.shift()}function rt(){return[...P]}function st(){P.length=0}function it(t=!0){u.logging=t}class m extends Error{sql;bindings;constructor(t,e,r){super(t);this.sql=e;this.bindings=r;this.name="DatabaseError"}}async function K(t,e,r,s){let n=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p]=o;try{let d=await W(h,p),w=`$${h}`;e[w]=d,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- DB Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function U(t,e,r,s){let n=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p]=o;try{let d=v(h),w=await J(d,p),E=`$${h.toLowerCase()}`;e[E]=w,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- Model Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function F(t,e,r,s){let n=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p,d]=o;try{let w=p?JSON.parse(p):[],A=await g().query(h,w);e[`$${d}`]=A,i=i.replace(c,"")}catch(w){i=i.replace(c,`<!-- Query Error: ${w instanceof Error?w.message:String(w)} -->`)}}return i}async function W(t,e){let r=l(t),s=/->(\w+)\(([^)]*)\)/g,n=[...e.matchAll(s)],i=r;for(let[,a,o]of n){let c=O(o);if(typeof i[a]==="function"){if(i=i[a](...c),i instanceof Promise){i=await i;break}}}if(i instanceof x)i=await i.get();return i}async function J(t,e){let r=/->(\w+)\(([^)]*)\)/g,s=[...e.matchAll(r)],n=t;for(let[,i,a]of s){let o=O(a);if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}else if(n instanceof x){if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}}}if(n instanceof x)n=await n.get();return n}function O(t){if(!t.trim())return[];let e=[],r="",s=0,n=!1,i="";for(let a=0;a<t.length;a++){let o=t[a];if(!n&&(o==='"'||o==="'"))n=!0,i=o,r+=o;else if(n&&o===i)n=!1,r+=o;else if(!n&&(o==="["||o==="{"||o==="("))s++,r+=o;else if(!n&&(o==="]"||o==="}"||o===")"))s--,r+=o;else if(!n&&s===0&&o===",")e.push(R(r.trim())),r="";else r+=o}if(r.trim())e.push(R(r.trim()));return e}function R(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let e=Number(t);if(!Number.isNaN(e))return e;try{return JSON.parse(t)}catch{return t}}async function ot(t,e,r,s){let n=t;return n=await F(n,e,r,s),n=await U(n,e,r,s),n=await K(n,e,r,s),n}class I{_connection;connection(t){return this._connection=t,this}async create(t,e){let r=new M(t);e(r);let s=r.toCreateSQL();await g(this._connection).execute(s)}async drop(t){await g(this._connection).execute(`DROP TABLE IF EXISTS ${t}`)}async rename(t,e){await g(this._connection).execute(`ALTER TABLE ${t} RENAME TO ${e}`)}async hasTable(t){let e=g(this._connection);try{return await e.query(`SELECT 1 FROM ${t} LIMIT 1`),!0}catch{return!1}}}class M{table;columns=[];indices=[];constructor(t){this.table=t}id(t="id"){return this.columns.push(`${t} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(t,e=255){return this.columns.push(`${t} VARCHAR(${e})`),this}text(t){return this.columns.push(`${t} TEXT`),this}integer(t){return this.columns.push(`${t} INTEGER`),this}boolean(t){return this.columns.push(`${t} BOOLEAN DEFAULT 0`),this}datetime(t){return this.columns.push(`${t} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(t){return this.columns.push(`${t} TEXT`),this}foreignId(t){return this.columns.push(`${t} INTEGER`),this}index(t){let e=Array.isArray(t)?t:[t],r=`idx_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}unique(t){let e=Array.isArray(t)?t:[t],r=`uniq_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
2
+ var u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},k={},C={},f=new Map,P=[];function z(t){u={...u,...t}}function V(){return{...u}}function G(){u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let t of Object.keys(k))delete k[t];f.clear(),P.length=0}function X(t,e){k[t]=e}function g(t){let e=t||u.default;if(k[e])return k[e];let r=u.connections[e];if(!r)throw Error(`Database connection "${e}" not configured`);let s=N(r);return k[e]=s,s}function N(t){switch(t.driver){case"sqlite":return D(t);case"postgres":return S(t);case"mysql":return L(t);default:throw Error(`Unsupported database driver: ${t.driver}`)}}function D(t){let e=null,r=!1;return{async connect(){if(r)return;let{Database:s}=await import("bun:sqlite");e=new s(t.database,{create:!0,readwrite:!0}),r=!0},async disconnect(){if(e)e.close(),e=null,r=!1},async query(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).all(...n);if(u.logging)y(s,n,performance.now()-i);return o}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.lastInsertRowid}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.changes}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!r)await this.connect();e.run("BEGIN TRANSACTION")},async commit(){e.run("COMMIT")},async rollback(){e.run("ROLLBACK")},isConnected(){return r}}}function S(t){let e=!1,r=null;return{async connect(){if(e)return;try{let{Client:s}=await import("pg");r=new s({host:t.host||"localhost",port:t.port||5432,database:t.database,user:t.username,password:t.password,ssl:t.ssl}),await r.connect(),e=!0}catch(s){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rows}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(`${s} RETURNING id`,n);if(u.logging)y(s,n,performance.now()-i);return a.rows[0]?.id}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rowCount||0}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();await r.query("BEGIN")},async commit(){await r.query("COMMIT")},async rollback(){await r.query("ROLLBACK")},isConnected(){return e}}}function L(t){let e=!1,r=null;return{async connect(){if(e)return;try{let s=await import("mysql2/promise");r=s.createPool({host:t.host||"localhost",port:t.port||3306,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:t.poolSize||10,queueLimit:0}),e=!0}catch(s){throw Error(`MySQL connection failed. Install 'mysql2' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.insertId}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.affectedRows||0}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();let s=await r.getConnection();return await s.beginTransaction(),s},async commit(){await r.execute("COMMIT")},async rollback(){await r.execute("ROLLBACK")},isConnected(){return e}}}class x{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(t){if(t)this._table=t}table(t){return this._table=t,this}from(t){return this.table(t)}connection(t){return this._connection=t,this}select(...t){return this._columns=t.length>0?t:["*"],this}addSelect(...t){if(this._columns[0]==="*")this._columns=t;else this._columns.push(...t);return this}distinct(){return this._distinct=!0,this}where(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"and"}),this}orWhere(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"or"}),this}whereIn(t,e){return this._wheres.push({column:t,operator:"in",value:e,boolean:"and"}),this}whereNotIn(t,e){return this._wheres.push({column:t,operator:"not in",value:e,boolean:"and"}),this}whereNull(t){return this._wheres.push({column:t,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(t){return this._wheres.push({column:t,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(t,e,r){return this._wheres.push({column:t,operator:"between",value:[e,r],boolean:"and"}),this}whereLike(t,e){return this._wheres.push({column:t,operator:"like",value:e,boolean:"and"}),this}join(t,e,r,s){return this._joins.push({type:"inner",table:t,first:e,operator:r,second:s}),this}leftJoin(t,e,r,s){return this._joins.push({type:"left",table:t,first:e,operator:r,second:s}),this}rightJoin(t,e,r,s){return this._joins.push({type:"right",table:t,first:e,operator:r,second:s}),this}orderBy(t,e="asc"){return this._orders.push({column:t,direction:e}),this}orderByDesc(t){return this.orderBy(t,"desc")}groupBy(...t){return this._groupBy.push(...t),this}having(t,e,r){return this._having.push({column:t,operator:e,value:r,boolean:"and"}),this}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}async get(){let{sql:t,bindings:e}=this.toSql();if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e),i=Q(n);if(i!==void 0)return i}let s=await g(this._connection).query(t,e);if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e);B(n,s,u.cacheTTL)}return s}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let t=await this.first();if(!t)throw Error("No results found");return t}async find(t,e="id"){return this.where(e,t).first()}async value(t){let e=await this.select(t).first();return e?e[t]:null}async pluck(t){return(await this.select(t).get()).map((r)=>r[t])}async exists(){return(await this.select(_("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(t="*"){let e=await this.select(_(`COUNT(${t}) as count`)).first();return Number(e?.count||0)}async max(t){return(await this.select(_(`MAX(${t}) as max`)).first())?.max}async min(t){return(await this.select(_(`MIN(${t}) as min`)).first())?.min}async sum(t){let e=await this.select(_(`SUM(${t}) as sum`)).first();return Number(e?.sum||0)}async avg(t){return(await this.select(_(`AVG(${t}) as avg`)).first())?.avg}async insert(t){let e=Object.keys(t),r=e.map(()=>"?").join(", "),s=Object.values(t),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES (${r})`,i=g(this._connection);return T(this._table),i.insert(n,s)}async insertAll(t){if(t.length===0)return;let e=Object.keys(t[0]),r=t.map(()=>`(${e.map(()=>"?").join(", ")})`).join(", "),s=t.flatMap((a)=>Object.values(a)),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES ${r}`,i=g(this._connection);T(this._table),await i.execute(n,s)}async update(t){this._bindings=[];let e=this.buildWhereClause(),r=[...this._bindings],s=Object.keys(t).map((o)=>`${o} = ?`).join(", "),n=[...Object.values(t),...r],i=`UPDATE ${this._table} SET ${s}${e}`,a=g(this._connection);return T(this._table),a.execute(i,n)}async increment(t,e=1){this._bindings=[];let r=this.buildWhereClause(),s=`UPDATE ${this._table} SET ${t} = ${t} + ?${r}`,n=g(this._connection);return T(this._table),n.execute(s,[e,...this._bindings])}async decrement(t,e=1){return this.increment(t,-e)}async delete(){this._bindings=[];let t=this.buildWhereClause(),e=`DELETE FROM ${this._table}${t}`,r=g(this._connection);return T(this._table),r.execute(e,this._bindings)}async truncate(){let t=g(this._connection);T(this._table),await t.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let t="SELECT ";if(this._distinct)t+="DISTINCT ";t+=this._columns.map((e)=>{if(typeof e==="object"&&e.__raw)return e.sql;return e}).join(", "),t+=` FROM ${this._table}`;for(let e of this._joins)t+=` ${e.type.toUpperCase()} JOIN ${e.table} ON ${e.first} ${e.operator} ${e.second}`;if(t+=this.buildWhereClause(),this._groupBy.length>0)t+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let e=this._having.map((r,s)=>{let n=s===0?"":` ${r.boolean.toUpperCase()} `;return this._bindings.push(r.value),`${n}${r.column} ${r.operator} ?`});t+=` HAVING ${e.join("")}`}if(this._orders.length>0)t+=` ORDER BY ${this._orders.map((e)=>`${e.column} ${e.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)t+=` LIMIT ${this._limit}`;if(this._offset!==void 0)t+=` OFFSET ${this._offset}`;return{sql:t,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((e,r)=>{let s=r===0?" WHERE ":` ${e.boolean.toUpperCase()} `;switch(e.operator){case"in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} IN (${i})`}case"not in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} NOT IN (${i})`}case"between":{let[n,i]=e.value;return this._bindings.push(n,i),`${s}${e.column} BETWEEN ? AND ?`}case"is null":return`${s}${e.column} IS NULL`;case"is not null":return`${s}${e.column} IS NOT NULL`;default:return this._bindings.push(e.value),`${s}${e.column} ${e.operator} ?`}}).join("")}getCacheKey(t,e){return`${this._table}:${t}:${JSON.stringify(e)}`}clone(){let t=new x(this._table);return t._columns=[...this._columns],t._wheres=[...this._wheres],t._orders=[...this._orders],t._joins=[...this._joins],t._groupBy=[...this._groupBy],t._having=[...this._having],t._limit=this._limit,t._offset=this._offset,t._distinct=this._distinct,t._connection=this._connection,t}}function l(t){return new x(t)}function Y(t){return l(t)}function _(t,e=[]){return{__raw:!0,sql:t,bindings:e}}function H(t,e){let r=e.primaryKey||"id",s={name:t,definition:e,async find(n){let i=await l(e.table).where(r,n).first();return i?b(s,i):null},async findOrFail(n){let i=await this.find(n);if(!i)throw Error(`${t} not found with ${r} = ${n}`);return i},async all(){return(await l(e.table).get()).map((i)=>b(s,i))},async create(n){let i={...e.defaults,...n},a=e.fillable?Object.fromEntries(Object.entries(i).filter(([c])=>e.fillable.includes(c))):i;if(e.timestamps!==!1){let c=new Date().toISOString(),h=typeof e.timestamps==="object"?e.timestamps.createdAt||"created_at":"created_at",m=typeof e.timestamps==="object"?e.timestamps.updatedAt||"updated_at":"updated_at";a[h]=c,a[m]=c}let o=await l(e.table).insert(a);return this.findOrFail(o)},async update(n){return l(e.table).update(n)},async destroy(n){let i=Array.isArray(n)?n:[n];return l(e.table).whereIn(r,i).delete()},query(){return l(e.table)},where(n,i,a){return this.query().where(n,i,a)},async first(){let n=await this.query().first();return n?b(s,n):null},async get(){return(await this.query().get()).map((i)=>b(s,i))},async count(){return this.query().count()}};return C[t]=s,s}function v(t){let e=C[t];if(!e)throw Error(`Model "${t}" not defined. Use defineModel() first.`);return e}function Z(t){return t in C}function b(t,e){let{definition:r}=t,s=r.primaryKey||"id",n={...e},i={...e};if(r.casts){for(let[o,c]of Object.entries(r.casts))if(o in i)i[o]=q(i[o],c)}let a={exists:!0,original:n,attributes:i,get(o){return i[o]},set(o,c){i[o]=c},toJSON(){let o={...i};if(r.hidden)for(let c of r.hidden)delete o[c];return o},async save(){let o={};for(let c of Object.keys(i))if(i[c]!==n[c])o[c]=i[c];if(Object.keys(o).length>0){if(r.timestamps!==!1){let c=typeof r.timestamps==="object"?r.timestamps.updatedAt||"updated_at":"updated_at";o[c]=new Date().toISOString()}await l(r.table).where(s,n[s]).update(o),Object.assign(n,o)}},async delete(){if(r.softDeletes){let o=typeof r.softDeletes==="string"?r.softDeletes:"deleted_at";await l(r.table).where(s,n[s]).update({[o]:new Date().toISOString()})}else await l(r.table).where(s,n[s]).delete();a.exists=!1},async refresh(){let o=await l(r.table).where(s,n[s]).first();if(o)Object.assign(n,o),Object.assign(i,o)},isDirty(o){if(o)return i[o]!==n[o];return Object.keys(i).some((c)=>i[c]!==n[c])}};if(r.relationships)for(let[o,c]of Object.entries(r.relationships))Object.defineProperty(a,o,{value:async()=>j(a,c,t),enumerable:!1});return new Proxy(a,{get(o,c){if(c in o)return o[c];return i[c]},set(o,c,h){if(c in o)o[c]=h;else i[c]=h;return!0}})}async function j(t,e,r){let s=v(e.model),n=r.definition.primaryKey||"id";switch(e.type){case"hasOne":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`,a=await l(s.definition.table).where(i,t.get(n)).first();return a?b(s,a):null}case"hasMany":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`;return(await l(s.definition.table).where(i,t.get(n)).get()).map((o)=>b(s,o))}case"belongsTo":{let i=e.foreignKey||`${e.model.toLowerCase()}_id`,a=e.localKey||"id",o=await l(s.definition.table).where(a,t.get(i)).first();return o?b(s,o):null}case"belongsToMany":{let i=e.pivotTable||[r.name,e.model].sort().join("_").toLowerCase(),a=e.pivotForeignKey||`${r.name.toLowerCase()}_id`,o=e.pivotRelatedKey||`${e.model.toLowerCase()}_id`,c=s.definition.primaryKey||"id";return(await l(s.definition.table).join(i,`${s.definition.table}.${c}`,"=",`${i}.${o}`).where(`${i}.${a}`,t.get(n)).get()).map((m)=>b(s,m))}default:return null}}function q(t,e){if(t===null||t===void 0)return t;switch(e){case"string":return String(t);case"number":return Number(t);case"boolean":return Boolean(t);case"date":return new Date(t);case"json":case"array":return typeof t==="string"?JSON.parse(t):t;default:return t}}async function tt(t,e){let r=g(e);await r.beginTransaction();try{let s=await t();return await r.commit(),s}catch(s){throw await r.rollback(),s}}function Q(t){let e=f.get(t);if(!e)return;if(Date.now()-e.timestamp>e.ttl*1000){f.delete(t);return}return e.result}function B(t,e,r){if(f.size>=(u.maxCacheSize||1000)){let s=f.keys().next().value;if(s)f.delete(s)}f.set(t,{result:e,timestamp:Date.now(),ttl:r})}function T(t){for(let e of f.keys())if(e.startsWith(`${t}:`))f.delete(e)}function et(){f.clear()}function nt(){return{size:f.size,keys:[...f.keys()]}}function y(t,e,r){if(P.push({sql:t,bindings:e,duration:r,timestamp:new Date}),P.length>1000)P.shift()}function rt(){return[...P]}function st(){P.length=0}function it(t=!0){u.logging=t}class p extends Error{sql;bindings;constructor(t,e,r){super(t);this.sql=e;this.bindings=r;this.name="DatabaseError"}}async function K(t,e,r,s){let n=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m]=o;try{let d=await W(h,m),w=`$${h}`;e[w]=d,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- DB Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function U(t,e,r,s){let n=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m]=o;try{let d=v(h),w=await J(d,m),E=`$${h.toLowerCase()}`;e[E]=w,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- Model Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function F(t,e,r,s){let n=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m,d]=o;try{let w=m?JSON.parse(m):[],A=await g().query(h,w);e[`$${d}`]=A,i=i.replace(c,"")}catch(w){i=i.replace(c,`<!-- Query Error: ${w instanceof Error?w.message:String(w)} -->`)}}return i}async function W(t,e){let r=l(t),s=/->(\w+)\(([^)]*)\)/g,n=[...e.matchAll(s)],i=r;for(let[,a,o]of n){let c=O(o);if(typeof i[a]==="function"){if(i=i[a](...c),i instanceof Promise){i=await i;break}}}if(i instanceof x)i=await i.get();return i}async function J(t,e){let r=/->(\w+)\(([^)]*)\)/g,s=[...e.matchAll(r)],n=t;for(let[,i,a]of s){let o=O(a);if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}else if(n instanceof x){if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}}}if(n instanceof x)n=await n.get();return n}function O(t){if(!t.trim())return[];let e=[],r="",s=0,n=!1,i="";for(let a=0;a<t.length;a++){let o=t[a];if(!n&&(o==='"'||o==="'"))n=!0,i=o,r+=o;else if(n&&o===i)n=!1,r+=o;else if(!n&&(o==="["||o==="{"||o==="("))s++,r+=o;else if(!n&&(o==="]"||o==="}"||o===")"))s--,r+=o;else if(!n&&s===0&&o===",")e.push(R(r.trim())),r="";else r+=o}if(r.trim())e.push(R(r.trim()));return e}function R(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let e=Number(t);if(!Number.isNaN(e))return e;try{return JSON.parse(t)}catch{return t}}async function ot(t,e,r,s){let n=t;return n=await F(n,e,r,s),n=await U(n,e,r,s),n=await K(n,e,r,s),n}class I{_connection;connection(t){return this._connection=t,this}async create(t,e){let r=new M(t);e(r);let s=r.toCreateSQL();await g(this._connection).execute(s)}async drop(t){await g(this._connection).execute(`DROP TABLE IF EXISTS ${t}`)}async rename(t,e){await g(this._connection).execute(`ALTER TABLE ${t} RENAME TO ${e}`)}async hasTable(t){let e=g(this._connection);try{return await e.query(`SELECT 1 FROM ${t} LIMIT 1`),!0}catch{return!1}}}class M{table;columns=[];indices=[];constructor(t){this.table=t}id(t="id"){return this.columns.push(`${t} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(t,e=255){return this.columns.push(`${t} VARCHAR(${e})`),this}text(t){return this.columns.push(`${t} TEXT`),this}integer(t){return this.columns.push(`${t} INTEGER`),this}boolean(t){return this.columns.push(`${t} BOOLEAN DEFAULT 0`),this}datetime(t){return this.columns.push(`${t} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(t){return this.columns.push(`${t} TEXT`),this}foreignId(t){return this.columns.push(`${t} INTEGER`),this}index(t){let e=Array.isArray(t)?t:[t],r=`idx_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}unique(t){let e=Array.isArray(t)?t:[t],r=`uniq_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
3
3
  ${this.columns.join(`,
4
4
  `)}
5
- )`}getIndexSQL(){return this.indices}}function at(){return new I}export{M as Blueprint,m as DatabaseError,x as QueryBuilder,I as SchemaBuilder,et as clearQueryCache,st as clearQueryLog,z as configureDatabase,H as defineModel,it as enableQueryLogging,g as getAdapter,V as getDatabaseConfig,v as getModel,nt as getQueryCacheStats,rt as getQueryLog,Z as hasModel,ot as processDatabaseDirectives,K as processDbDirective,U as processModelDirective,F as processQueryDirective,l as query,_ as raw,X as registerAdapter,G as resetDatabaseConfig,at as schema,Y as table,tt as transaction};
5
+ )`}getIndexSQL(){return this.indices}}function at(){return new I}export{M as Blueprint,p as DatabaseError,x as QueryBuilder,I as SchemaBuilder,et as clearQueryCache,st as clearQueryLog,z as configureDatabase,H as defineModel,it as enableQueryLogging,g as getAdapter,V as getDatabaseConfig,v as getModel,nt as getQueryCacheStats,rt as getQueryLog,Z as hasModel,ot as processDatabaseDirectives,K as processDbDirective,U as processModelDirective,F as processQueryDirective,l as query,_ as raw,X as registerAdapter,G as resetDatabaseConfig,at as schema,Y as table,tt as transaction};
@@ -92,6 +92,7 @@ export function createNativeHost(options) {
92
92
  const record = records.get(node.__stxId);
93
93
  if (!record)
94
94
  return;
95
+ record.materialized = !1;
95
96
  node.__stxDetachedRecord = record;
96
97
  record.children.forEach(retainDetachedDescriptors);
97
98
  records.delete(node.__stxId);
@@ -216,7 +217,7 @@ export function createNativeHost(options) {
216
217
  function setConnected(node, connected) {
217
218
  if ("isConnected" in node)
218
219
  node.isConnected = connected;
219
- records.get(node.__stxId)?.children.forEach((child) => setConnected(child, connected));
220
+ descriptorOf(node)?.children.forEach((child) => setConnected(child, connected));
220
221
  }
221
222
  function removeFromBindingParent(node) {
222
223
  const owner = node.__stxOwner;
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Pn,Ie,Oo,Ma}from"./chunk-d3mpxr3s.js";import{An,Fr,Ia,Da,Oa}from"./chunk-tpvc8xnk.js";import{Po,Io,Do,Aa,Pa}from"./chunk-v3yqeh15.js";import{oe,ft,zr}from"./chunk-vg7wfkt5.js";import{jc,Bc,Fc,zc,ur,od}from"./chunk-e15a8txv.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-rjm3n62n.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
2
+ import{Pn,Ie,Oo,Ma}from"./chunk-d3mpxr3s.js";import{An,Fr,Ia,Da,Oa}from"./chunk-tpvc8xnk.js";import{Po,Io,Do,Aa,Pa}from"./chunk-v3yqeh15.js";import{oe,ft,zr}from"./chunk-vg7wfkt5.js";import{jc,Bc,Fc,zc,dr,ou}from"./chunk-x9a5a282.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-s2fpethy.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -233,4 +233,4 @@ Icon generation requires the sharp package for image processing.`),e.success=!1,
233
233
  }, 5000);
234
234
  </script>
235
235
  </body>
236
- </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=oe(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=Pn(n,t);if(a){let s=Ie(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Fr(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,Io as auditBuildOutput,Po as auditConfig,re as buildPwaAssets,Do as calculateAuditResult,Pa as formatAuditResult,zr as formatSize,j as generateManifest,_ as generateManifestJson,Da as generateManifestLink,F as generateOfflinePage,oe as generatePrecacheManifest,ft as generatePrecacheManifestJs,M as generatePwaIcons,An as generatePwaTags,Pn as generateServiceWorker,Ma as generateServiceWorkerAuto,Ia as generateSwRegistrationScript,Oa as generateThemeColorMeta,N as getExpectedIconPaths,Ie as getServiceWorkerFileName,Fr as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,Oo as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,ur as pwaDirectives,jc as pwaInstallDirective,Fc as pwaOfflineDirective,zc as pwaPushDirective,Bc as pwaUpdateDirective,od as registerPwaDirectives,Aa as runPwaAudit,D as validateManifest};
236
+ </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=oe(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=Pn(n,t);if(a){let s=Ie(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Fr(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,Io as auditBuildOutput,Po as auditConfig,re as buildPwaAssets,Do as calculateAuditResult,Pa as formatAuditResult,zr as formatSize,j as generateManifest,_ as generateManifestJson,Da as generateManifestLink,F as generateOfflinePage,oe as generatePrecacheManifest,ft as generatePrecacheManifestJs,M as generatePwaIcons,An as generatePwaTags,Pn as generateServiceWorker,Ma as generateServiceWorkerAuto,Ia as generateSwRegistrationScript,Oa as generateThemeColorMeta,N as getExpectedIconPaths,Ie as getServiceWorkerFileName,Fr as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,Oo as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,dr as pwaDirectives,jc as pwaInstallDirective,Fc as pwaOfflineDirective,zc as pwaPushDirective,Bc as pwaUpdateDirective,ou as registerPwaDirectives,Aa as runPwaAudit,D as validateManifest};
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunk-ynvce0q6.js";import"./chunk-2n5pjbw9.js";import{Qe,et,tt,nt,rt,st}from"./chunk-88px183j.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import{f,je,N,K,n,o}from"./chunk-dqdggvq4.js";import"./chunk-v83bpj84.js";import{Qn}from"./chunk-y36av1ac.js";import"./chunk-zydg3wgt.js";import"./chunk-ng61wjke.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import"./chunk-39q77svv.js";import{ie,gt,mt}from"./chunk-kdk0jy1h.js";import{To,Ro,Ao}from"./chunk-5j5msbks.js";import{pt,Gt,Jt}from"./chunk-5pjsc9zv.js";import"./chunk-d2zw2e5m.js";import{a}from"./chunk-7tt84v1y.js";import x from"fs";import g from"path";import{createHash as $t}from"crypto";function Dt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Rt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function kt(t){return Bun.hash(t).toString(16)}function lt(t,i={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,r=t.replace(Rt,(e,l,w,y)=>{let h=y.trim();if(!h)return e;if(/\bdata-stx-src=/.test(w))return e;if(i.minify)h=Dt(h);let S=kt(h);if(!s.has(S))s.set(S,h);let P=i.integrity?` data-stx-integrity="sha384-${$t("sha384").update(h).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${l}" data-stx-src="/_stx/islands/${S}.js"${P}${w}></script>`}),c=Array.from(s,([e,l])=>({hash:e,code:l}));return{html:r,chunks:c}}var Ct=new Set(["visible","idle"]);function ut(t){if(!t.includes("data-stx-src="))return t;let i=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,r;while((r=s.exec(t))!==null)i.set(r[1],r[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,l;while((l=e.exec(t))!==null)if(Ct.has(i.get(l[1])||""))c.add(l[2]);let w=t.lastIndexOf("</head>");if(c.size===0||w===-1)return t;let y=Array.from(c).filter((h)=>!t.includes(`rel="prefetch" href="${h}"`)).map((h)=>`<link rel="prefetch" href="${h}" as="script">`).join("");if(!y)return t;return t.slice(0,w)+y+t.slice(w)}var Et=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function q(t){let i=t.trim();if(!i)return null;let s=/^https?:\/\//i.test(i)?i:`https://${i}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function It(t){for(let i of Et){let s=t[i];if(!s)continue;let r=q(s);if(r)return{url:r,source:"env",via:i}}return null}function dt(t){if(!t||typeof t!=="object")return null;let i=t,s=i.site?.url??i.url??i.app?.url;return typeof s==="string"?q(s):null}async function Bt(t){let{existsSync:i}=await import("fs"),s=await import("path");for(let r of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(t,r);if(!i(c))continue;try{let e=await import(c),l=dt(e.default??e);if(l)return l}catch{}}return null}async function ht(t={}){let i=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let l=q(t.explicit);if(l)return{url:l,source:"option"}}let r=dt(t.stxConfig);if(r)return{url:r,source:"stx.config",via:"site.url"};let c=await Bt(i);if(c)return{url:c,source:"site.config",via:"url"};let e=It(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function ft(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
2
+ import"./chunk-pfm6cfph.js";import"./chunk-2n5pjbw9.js";import{Qe,et,tt,nt,rt,st}from"./chunk-88px183j.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import{f,je,N,K,n,o}from"./chunk-ag1v2tkm.js";import"./chunk-p7j2g8y2.js";import{Qn}from"./chunk-gj90pnre.js";import"./chunk-zydg3wgt.js";import"./chunk-jbdqs7t6.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import"./chunk-gasb5fhy.js";import{ie,gt,mt}from"./chunk-z14y48en.js";import{To,Ro,Ao}from"./chunk-5j5msbks.js";import{pt,Gt,Jt}from"./chunk-5pjsc9zv.js";import"./chunk-gjrbnzap.js";import{a}from"./chunk-7tt84v1y.js";import x from"fs";import g from"path";import{createHash as $t}from"crypto";function Dt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Rt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function kt(t){return Bun.hash(t).toString(16)}function lt(t,i={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,r=t.replace(Rt,(e,l,w,y)=>{let h=y.trim();if(!h)return e;if(/\bdata-stx-src=/.test(w))return e;if(i.minify)h=Dt(h);let S=kt(h);if(!s.has(S))s.set(S,h);let P=i.integrity?` data-stx-integrity="sha384-${$t("sha384").update(h).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${l}" data-stx-src="/_stx/islands/${S}.js"${P}${w}></script>`}),c=Array.from(s,([e,l])=>({hash:e,code:l}));return{html:r,chunks:c}}var Ct=new Set(["visible","idle"]);function ut(t){if(!t.includes("data-stx-src="))return t;let i=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,r;while((r=s.exec(t))!==null)i.set(r[1],r[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,l;while((l=e.exec(t))!==null)if(Ct.has(i.get(l[1])||""))c.add(l[2]);let w=t.lastIndexOf("</head>");if(c.size===0||w===-1)return t;let y=Array.from(c).filter((h)=>!t.includes(`rel="prefetch" href="${h}"`)).map((h)=>`<link rel="prefetch" href="${h}" as="script">`).join("");if(!y)return t;return t.slice(0,w)+y+t.slice(w)}var Et=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function q(t){let i=t.trim();if(!i)return null;let s=/^https?:\/\//i.test(i)?i:`https://${i}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function It(t){for(let i of Et){let s=t[i];if(!s)continue;let r=q(s);if(r)return{url:r,source:"env",via:i}}return null}function dt(t){if(!t||typeof t!=="object")return null;let i=t,s=i.site?.url??i.url??i.app?.url;return typeof s==="string"?q(s):null}async function Bt(t){let{existsSync:i}=await import("fs"),s=await import("path");for(let r of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(t,r);if(!i(c))continue;try{let e=await import(c),l=dt(e.default??e);if(l)return l}catch{}}return null}async function ht(t={}){let i=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let l=q(t.explicit);if(l)return{url:l,source:"option"}}let r=dt(t.stxConfig);if(r)return{url:r,source:"stx.config",via:"site.url"};let c=await Bt(i);if(c)return{url:c,source:"site.config",via:"url"};let e=It(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function ft(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
3
  `)}class wt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,i=""){this.cacheDir=t,this.salt=i}async load(){if(this.loaded)return;let t=g.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let i=JSON.parse(await Bun.file(t).text());for(let[s,r]of Object.entries(i))this.cache.set(s,r)}catch{}this.loaded=!0}async save(){await x.promises.mkdir(this.cacheDir,{recursive:!0});let t=g.join(this.cacheDir,"build-cache.json"),i={};for(let[s,r]of this.cache)i[s]=r;await Bun.write(t,JSON.stringify(i))}getHash(t,i){let s=x.statSync(t),r=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of i)if(x.existsSync(e)){let l=x.statSync(e);r+=`:${e}:${l.mtimeMs}`}let c=0;for(let e=0;e<r.length;e++){let l=r.charCodeAt(e);c=(c<<5)-c+l,c=c&c}return Math.abs(c).toString(36)}get(t,i){let s=this.cache.get(t);if(!s)return null;let r=this.getHash(i,s.dependencies??[]);if(s.hash!==r)return this.cache.delete(t),null;return s.html}set(t,i,s,r){let c=this.getHash(i,s);this.cache.set(t,{hash:c,html:r,generatedAt:Date.now(),dependencies:s})}}class yt{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let i=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return g.join(this.cacheDir,"isr",i)}async get(t){let i=this.getFilePath(t);if(!await Bun.file(i).exists())return null;try{return JSON.parse(await Bun.file(i).text())}catch{return null}}async set(t,i){let s=this.getFilePath(t);await x.promises.mkdir(g.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(i))}async invalidate(t){let i=this.getFilePath(t);if(await Bun.file(i).exists())await x.promises.unlink(i)}async invalidatePattern(t){let i=g.join(this.cacheDir,"isr");if(!x.existsSync(i))return;let s=await x.promises.readdir(i);for(let r of s){let c=r.replace(/_/g,"/").replace(".json","");if(t.test(c))await x.promises.unlink(g.join(i,r))}}async needsRevalidation(t){let i=await this.get(t);if(!i)return!0;return Date.now()>i.revalidateAfter}}async function jt(t){try{let s=(await Bun.file(t).text()).match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return null;let r=s[1];if(!r.includes("getStaticPaths"))return null;let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticPaths\s*\([^)]*\)\s*\{([\s\S]*?)\n[\t ]*\}/);if(!c)return null;return await Function(`
4
4
  return (async function getStaticPaths() {
5
5
  ${c[1]}
@@ -41,7 +41,7 @@ ${t.map((r)=>{let c=new URL(r.loc,i).href,e=` <url>
41
41
  ${s.join(`
42
42
  `)}
43
43
  </channel>
44
- </rss>`}async function zt(t={}){let i=Date.now();mt();let s=await o(process.cwd()),r=s.build||{},c=await ht({explicit:t.domain||r.domain,stxConfig:s});if(c.source==="fallback"&&(t.sitemap??r.sitemap??!0))console.warn(ft());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||r.pagesDir||"pages",outputDir:t.outputDir||r.outputDir||"dist",baseUrl:t.baseUrl||r.baseUrl||"/",domain:c.url,revalidate:t.revalidate??r.revalidate??!1,sitemap:t.sitemap??r.sitemap??!0,sitemapExclude:t.sitemapExclude||r.sitemapExclude||[],robots:t.robots??r.robots??!0,rss:t.rss??r.rss??!1,concurrency:t.concurrency||r.concurrency||10,cache:t.cache??r.cache??!0,cacheDir:t.cacheDir||r.cacheDir||a(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??r.minify??!0,generate404:t.generate404??r.generate404??!0,publicDir:t.publicDir||r.publicDir||"public",trailingSlash:t.trailingSlash??r.trailingSlash??!1,cleanOutput:t.cleanOutput??r.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},l={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},w=new Set,y=0,h={},S={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&x.existsSync(e.outputDir))await x.promises.rm(e.outputDir,{recursive:!0});await x.promises.mkdir(e.outputDir,{recursive:!0});let D=e.cacheSalt;if(!D){let{resolveUserCssConfig:u,fingerprintConfig:m}=await import("./chunk-mxt11ejx.js");try{D=m(await u(process.cwd()))}catch{}}let{prepareImageDelivery:p}=await import("./chunk-ajqwjevt.js"),b=await p(e.publicDir,e.outputDir);if(b.count>0)console.log(`Optimized ${b.count} image(s) for responsive delivery`),D=[D,b.fingerprint].filter(Boolean).join(":");let B=new wt(e.cacheDir,D);if(e.cache)await B.load();try{let{generateCss:u}=await import("./chunk-mxt11ejx.js");await u('<div class="bg-black"></div>')}catch{}Qe();let xt=s?.routeMiddleware?.dir||"middleware";await tt(process.cwd(),xt);let H=et();if(H.length>0)console.log(`Loaded ${H.length} middleware: ${H.join(", ")}`);let vt=s?.routeMiddleware?.global||[];Ao(s?.layoutsDir,a(process.cwd()));let V=N(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${V.length} routes`);let _=[];for(let u of V){let m=await Ft(u);for(let v of m)_.push({route:u,url:v.url,params:v.params,props:v.props,revalidate:v.revalidate??e.revalidate})}l.totalPages=_.length,console.log(`Generating ${l.totalPages} pages...`);let A=[],X=[];for(let u=0;u<_.length;u+=e.concurrency)X.push(_.slice(u,u+e.concurrency));for(let u of X)await Promise.all(u.map(async(m)=>{let{route:v,url:d,params:L,props:bt,revalidate:Q}=m;try{await e.hooks.onPageStart?.(d);let j=await Bun.file(v.filePath).text(),F=Vt(j),Pt=F?.middleware?Array.isArray(F.middleware)?F.middleware:[F.middleware]:[],it=[...vt,...Pt];if(it.length>0){let C=nt(d,L,F||{}),O=rt(C,null,void 0,{isServer:!0}),E=await st(it,O);if(E.redirect){let R=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,U=Kt(String(R),d),T=Xt(d,e);await x.promises.mkdir(g.dirname(T),{recursive:!0}),await Bun.write(T,U),l.successCount++,l.pages.push({route:d,outputPath:T,size:Buffer.byteLength(U),cached:!1}),A.push({loc:d,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${d} \u2192 redirect to ${R}`);return}if(E.abort){let R=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${d} \u2014 middleware aborted: ${R}`);return}}let at=j.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(at)try{if(!await Function("route",`
44
+ </rss>`}async function zt(t={}){let i=Date.now();mt();let s=await o(process.cwd()),r=s.build||{},c=await ht({explicit:t.domain||r.domain,stxConfig:s});if(c.source==="fallback"&&(t.sitemap??r.sitemap??!0))console.warn(ft());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||r.pagesDir||"pages",outputDir:t.outputDir||r.outputDir||"dist",baseUrl:t.baseUrl||r.baseUrl||"/",domain:c.url,revalidate:t.revalidate??r.revalidate??!1,sitemap:t.sitemap??r.sitemap??!0,sitemapExclude:t.sitemapExclude||r.sitemapExclude||[],robots:t.robots??r.robots??!0,rss:t.rss??r.rss??!1,concurrency:t.concurrency||r.concurrency||10,cache:t.cache??r.cache??!0,cacheDir:t.cacheDir||r.cacheDir||a(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??r.minify??!0,generate404:t.generate404??r.generate404??!0,publicDir:t.publicDir||r.publicDir||"public",trailingSlash:t.trailingSlash??r.trailingSlash??!1,cleanOutput:t.cleanOutput??r.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},l={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},w=new Set,y=0,h={},S={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&x.existsSync(e.outputDir))await x.promises.rm(e.outputDir,{recursive:!0});await x.promises.mkdir(e.outputDir,{recursive:!0});let D=e.cacheSalt;if(!D){let{resolveUserCssConfig:u,fingerprintConfig:m}=await import("./chunk-99qf5fff.js");try{D=m(await u(process.cwd()))}catch{}}let{prepareImageDelivery:p}=await import("./chunk-nahzfs7d.js"),b=await p(e.publicDir,e.outputDir);if(b.count>0)console.log(`Optimized ${b.count} image(s) for responsive delivery`),D=[D,b.fingerprint].filter(Boolean).join(":");let B=new wt(e.cacheDir,D);if(e.cache)await B.load();try{let{generateCss:u}=await import("./chunk-99qf5fff.js");await u('<div class="bg-black"></div>')}catch{}Qe();let xt=s?.routeMiddleware?.dir||"middleware";await tt(process.cwd(),xt);let H=et();if(H.length>0)console.log(`Loaded ${H.length} middleware: ${H.join(", ")}`);let vt=s?.routeMiddleware?.global||[];Ao(s?.layoutsDir,a(process.cwd()));let V=N(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${V.length} routes`);let _=[];for(let u of V){let m=await Ft(u);for(let v of m)_.push({route:u,url:v.url,params:v.params,props:v.props,revalidate:v.revalidate??e.revalidate})}l.totalPages=_.length,console.log(`Generating ${l.totalPages} pages...`);let A=[],X=[];for(let u=0;u<_.length;u+=e.concurrency)X.push(_.slice(u,u+e.concurrency));for(let u of X)await Promise.all(u.map(async(m)=>{let{route:v,url:d,params:L,props:bt,revalidate:Q}=m;try{await e.hooks.onPageStart?.(d);let j=await Bun.file(v.filePath).text(),F=Vt(j),Pt=F?.middleware?Array.isArray(F.middleware)?F.middleware:[F.middleware]:[],it=[...vt,...Pt];if(it.length>0){let C=nt(d,L,F||{}),O=rt(C,null,void 0,{isServer:!0}),E=await st(it,O);if(E.redirect){let R=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,U=Kt(String(R),d),T=Xt(d,e);await x.promises.mkdir(g.dirname(T),{recursive:!0}),await Bun.write(T,U),l.successCount++,l.pages.push({route:d,outputPath:T,size:Buffer.byteLength(U),cached:!1}),A.push({loc:d,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${d} \u2192 redirect to ${R}`);return}if(E.abort){let R=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${d} \u2014 middleware aborted: ${R}`);return}}let at=j.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(at)try{if(!await Function("route",`
45
45
  const validate = ${at[1]};
46
46
  return validate(route);
47
47
  `)({params:L})){console.warn(`Validation failed for ${d}, skipping...`);return}}catch{}let k=null,ot=!1;if(e.cache){if(k=B.get(d,v.filePath),k)ot=!0,l.cachedCount++}if(!k){let C=await St(v,L,bt,e,s);if(k=C.html,e.failOnIncludeError&&C.includeFailures.length>0)throw Error(`${C.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/stx",
3
3
  "type": "module",
4
- "version": "0.2.463",
4
+ "version": "0.2.465",
5
5
  "description": "A performant UI Framework. Powered by Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -122,12 +122,12 @@
122
122
  "dependencies": {
123
123
  "@stacksjs/ts-css": "^0.3.2",
124
124
  "@stacksjs/clapp": "^0.2.16",
125
- "@stacksjs/desktop": "0.2.463",
126
- "@stacksjs/sanitizer": "0.2.463",
125
+ "@stacksjs/desktop": "0.2.465",
126
+ "@stacksjs/sanitizer": "0.2.465",
127
127
  "@stacksjs/ts-i18n": "^0.1.11",
128
- "bun-plugin-stx": "0.2.463",
128
+ "bun-plugin-stx": "0.2.465",
129
129
  "bunfig": "^0.15.19",
130
- "stx-router": "0.2.463",
130
+ "stx-router": "0.2.465",
131
131
  "ts-broadcasting": "^0.0.11",
132
132
  "ts-images": "^0.2.22",
133
133
  "ts-syntax-highlighter": "^0.2.1"
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Yi,dl,Zi,Qi,pl,fl}from"./chunk-skjwh35r.js";import"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{fl as applySlots,pl as extractSlotContent,dl as parseSlotElement,Yi as parseSlots,Qi as processSlots,Zi as renderSlot};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Ct,cc,lc,uc,dc,pc,d,fc,ls,gc,ri,si}from"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{Ct as STX_ENGINE_BINDING_NAMES,ls as convertToCommonJS,ri as extractScriptFromTemplate,d as extractVariables,si as hasVariables,fc as isCompleteImport,pc as isMissingBindingFailure,uc as isModuleResolutionFailure,dc as isSyntaxFailure,gc as splitDeclaration,cc as stripTypeScript,lc as withoutStxReferrer};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Ql,yo,_a,eu,tu,nu,ru,su,Ta,Ra,ou,iu,au,cu}from"./chunk-qr15ksz9.js";import"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{_a as SUSPENSE_RESOLVER_RUNTIME,yo as buildSuspenseResolveScript,su as createStreamRenderer,nu as extractStreamBoundaries,cu as generateHydrationRuntime,Ra as islandDirective,iu as processSectionDirectives,tu as processStreamDirectives,ou as registerStreamingDirectives,eu as renderStreamingPage,Ql as streamTemplate,ru as streamTemplateSimple,au as streamToResponse,Ta as streamingSuspenseDirective};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Or,bl,wl}from"./chunk-5yn0gpcj.js";import"./chunk-kdk0jy1h.js";import"./chunk-39q77svv.js";import"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{wl as clearComposableCache,bl as getComposableScript,Or as listComposableModules};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ks,Cs,$s,Es,Yn,Zn,Vu,Uu,Wu,qu,Qn,Ku}from"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";export{Ku as generateDefaultRobotsTxt,Qn as generateRobotsTxt,Uu as generateSitemap,Wu as generateSitemapIndex,Es as injectSeoTags,Yn as metaDirective,ks as processMetaDirectives,$s as processSeoDirective,Cs as processStructuredData,Vu as registerSeoDirectives,qu as scanForSitemapEntries,Zn as structuredDataDirective};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Ts,Xu,Gu,vi,pe,Tc,nr,Ju,Yu,Zu,Qu,ed,td,nd,rd,sd}from"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";export{td as applyHead,Ju as definePageMeta,Ts as getHead,Xu as getPageMeta,pe as mergeHeadConfigs,nd as processHeadDirective,sd as processMetaDirective,rd as processTitleDirective,ed as renderBodyAttrs,Zu as renderHead,Qu as renderHtmlAttrs,Gu as resetHead,nr as seoMetaToHeadConfig,vi as useHead,Yu as usePageTitle,Tc as useSeoMeta,Yu as useTitle};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Jc}from"./chunk-eegxyqk3.js";import"./chunk-y8mx0hab.js";import"./chunk-hhsynd7c.js";import"./chunk-39q77svv.js";import"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{Jc as buildForProduction};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Zr,Qr,es,Mu,jn,Nu}from"./chunk-dqdggvq4.js";export{jn as clearImageDeliveryCatalog,Mu as deliveredImage,es as efficientDeliverySources,Zr as getImageDelivery,Qr as isTransparentImage,Nu as prepareImageDelivery};
@@ -1,3 +0,0 @@
1
- // @bun
2
- var u=import.meta.require;
3
- export{u};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Me,Ga,$u,Eu,_u,Tu,Ja,Ya,Ru,Au,Ho,Pu,Qt,en,Mn}from"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{Tu as __setSignalsGeneratorsForTest,Me as cacheEngineFingerprint,en as cacheTemplate,Qt as checkCache,Pu as clearDevCaches,Ya as getCachedRouterScript,Ja as getCachedSignalsRuntime,Ru as getServeClientAsset,Ho as getServeModuleBundle,Mn as hashFilePath,Eu as invalidateFileCache,_u as invalidateFileCacheByDir,$u as readFileCached,Au as registerServeModuleBundle,Ga as templateCache};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ll}from"./chunk-xbm2gcb6.js";import"./chunk-y8mx0hab.js";import"./chunk-39q77svv.js";import"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{ll as startProductionServer};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{nn,sc,ss}from"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import{ve}from"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{ve as freeIdentifiers,ss as processComponents,sc as processESImports,nn as rendersAsElement};
@@ -1,17 +0,0 @@
1
- // @bun
2
- import{m,Zt,w,Me,o,R}from"./chunk-dqdggvq4.js";import{Wr}from"./chunk-39q77svv.js";import{s,be}from"./chunk-y3cqh2jv.js";import{a}from"./chunk-7tt84v1y.js";import g from"path";import v from"fs";function pe(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.message==="string"&&(t.name==="BuildMessage"||t.name==="ResolveMessage"||("position"in t))}function fe(e){if(e&&typeof e==="object"&&Array.isArray(e.errors))return e.errors;return[e]}function J(e,t){let r=[];for(let l of fe(e)){if(pe(l)){let u=l.position||void 0;r.push({file:t||u?.file,line:u?.line,column:u?.column,message:l.message??"",lineText:u?.lineText});continue}r.push({file:t,message:l instanceof Error?l.message:String(l)})}return r}function De(e,t){return J(e,t).map((r)=>{let l=r.file?`${r.file}${r.line?`:${r.line}${r.column?`:${r.column}`:""}`:""}`:"",u=r.lineText?`
3
- ${r.lineText.trim()}`:"";return l?`${l}: ${r.message}${u}`:`${r.message}${u}`}).join(`
4
- `)}var me=10;function P(e,t,r){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(g.basename(e))||Wr(e,t,r)}var re=1,se=new Map,W=600,ge=100,G=new Map;async function he(e){let t=G.get(e)??0;if(t>0&&t<ge){G.set(e,t+1);return}G.set(e,1);try{let r=(await v.promises.readdir(e)).filter((p)=>p.endsWith(".js"));if(r.length<=W)return;let u=(await Promise.all(r.map(async(p)=>{try{return{name:p,at:(await v.promises.stat(g.join(e,p))).mtimeMs}}catch{return null}}))).filter((p)=>p!==null);u.sort((p,d)=>d.at-p.at);for(let p of u.slice(W)){let d=p.name.slice(0,-3);await v.promises.rm(g.join(e,`${d}.js`),{force:!0}),await v.promises.rm(g.join(e,`${d}.deps.json`),{force:!0})}D("pruned bundle cache to",W,"entries")}catch{}}function ie(e){return se.get(e)??[]}function q(e,t){if(e)se.set(e,t)}function Na(e=process.env){return e.STX_DEBUG==="true"||e.STX_DEBUG==="1"}function D(...e){if(Na())console.log("[stx:bundler]",...e)}var Y=[];function Mo(e,t,r){Y.push({filePath:e||"<inline>",message:t,details:r})}function gt(){return Y.slice()}function mt(){Y.length=0}var H;function yu(e){H=e}function No(){if(H)return H;try{let e=R.strict;return typeof e==="object"&&e!==null?e.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Z=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function ht(e){let t=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,r;while((r=t.exec(e))!==null){let u=r[1];if(!Z.some((d)=>d.test(u)))return D("detected user import:",u),!0}let l=/^[ \t]*import[ \t]+['"]([^'"]+)['"]/gm;while((r=l.exec(e))!==null){let u=r[1];if(/\.css(?:\?.*)?$/.test(u))continue;if(!Z.some((d)=>d.test(u)))return D("detected side-effect import:",u),!0}return!1}var Yt="stx-module:",xe=/\.(?:[cm]?[jt]sx?|json)$/i;function La(e,t){return g.relative(e,t).split(g.sep).join("/")}function ja(e,t){if(t.size===0)return e;return e.replace(/^([ \t]*import\s+(?:[^;"']*?\s+from\s+)?)(["'])([^"']+)\2/gm,(r,l,u,p)=>{let d=t.get(p);return d&&!p.startsWith(Yt)?`${l}${u}${d}${u}`:r})}function Ba(e,t){let r=0,l=(p)=>{let d=`__stxMod${r++}`,y=JSON.stringify(p);return t.push(`var ${d} = globalThis.__stxModules && globalThis.__stxModules[${y}];`,`if (${d} === undefined) throw new Error("[stx] module " + ${JSON.stringify(y)} + " is not registered on this page (#1957)");`),d},u=(p,d)=>{for(let y of p.split(",")){let F=y.trim();if(!F)continue;let c=F.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!c)continue;let n=c[1].startsWith('"')?JSON.parse(c[1]):c[1],i=c[2]??n;t.push(`var ${i} = ${d}[${JSON.stringify(n)}];`)}};return e=e.replace(/^[ \t]*import\s+([^;"']*?)\s+from\s+["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(p,d,y)=>{let F=y.slice(Yt.length),c=l(F),n=d.trim(),i=n.match(/^([\w$]+)\s*(?:,\s*|$)/);if(i&&!n.startsWith("{")&&!n.startsWith("*"))t.push(`var ${i[1]} = ${c}.default;`),n=n.slice(i[0].length).trim();let f=n.match(/^\*\s*as\s+([\w$]+)$/);if(f)t.push(`var ${f[1]} = ${c};`);else if(n.startsWith("{"))u(n.replace(/^\{|\}$/g,""),c);return""}),e=e.replace(/^[ \t]*import\s+["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(p,d)=>(l(d.slice(Yt.length)),"")),e}function te(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.mjs`,`${e}.jsx`,g.join(e,"index.ts"),g.join(e,"index.tsx"),g.join(e,"index.js"),g.join(e,"index.mjs")];for(let r of t)try{if(v.existsSync(r)&&v.statSync(r,{throwIfNoEntry:!1})?.isFile())return r}catch{}return}function $e(e,t,r,l,u,p=new Map,d){let y=(c,n,i)=>{if(P(n,e,d))return null;if(!u||c!==r||!xe.test(n))return null;try{if(!v.statSync(n,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}l.add(n);let f=`${Yt}${La(process.cwd(),n)}`;return p.set(i,f),{path:f,external:!0}},F=(c,n)=>{let i=c===r?t:g.dirname(c),f=g.resolve(i,n);return te(f)??f};return{name:"stx-client-bundle",setup(c){if(c.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(n)=>({path:n.path,external:!0})),c.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(n)=>({path:n.path,external:!0})),c.onResolve({filter:/^\//},(n)=>{let i=te(n.path);if(i){let f=y(n.importer,i,n.path);if(f)return f;if(i!==r)l.add(i);return{path:i}}return{path:n.path,external:!0}}),c.onResolve({filter:/^\.\.?\//},(n)=>{let i=F(n.importer,n.path),f=y(n.importer,i,n.path);if(f)return f;return l.add(i),{path:i}}),c.onResolve({filter:/^[@~]\//},(n)=>{let i=g.resolve(e,n.path.slice(2)),f=[i,`${i}.ts`,`${i}.tsx`,`${i}.js`,`${i}.mjs`,`${i}.jsx`,g.join(i,"index.ts"),g.join(i,"index.tsx"),g.join(i,"index.js"),g.join(i,"index.mjs")];for(let S of f)if(v.existsSync(S)&&v.statSync(S,{throwIfNoEntry:!1})?.isFile()){let k=y(n.importer,S,n.path);if(k)return k;return D(`resolved ${n.path[0]}/ import:`,n.path,"\u2192",S),l.add(S),{path:S}}return console.warn(`[stx:bundler] could not resolve ${n.path[0]}/ import:`,n.path),{path:i}}),u)c.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(n)=>{if(n.importer!==r)return;let i=`${Yt}npm:${n.path}`;return p.set(n.path,i),{path:i,external:!0}});c.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(n)=>{if(P(n.path,e,d))throw Error(`Server-only API source cannot be imported by a client script: ${n.path}`);let i=g.extname(n.path).toLowerCase(),f=i===".json"?"json":i===".tsx"?"tsx":i===".jsx"?"jsx":i===".ts"||i===".mts"||i===".cts"?"ts":"js";if(n.path!==r)l.add(n.path);return{contents:v.readFileSync(n.path,"utf8"),loader:f}})}}}var X=new Map,U=m(64),ne=Symbol.for("stx.client-bundle-build-queue");function Fa(e){let t=globalThis,l=(t[ne]??Promise.resolve()).then(e,e);return t[ne]=l.then(()=>{return},()=>{return}),l}async function yt(e,t,r={}){let l=r.projectRoot||process.cwd(),u=(await o(l)).serverApi,p=r.minify??!1,d=r.externalizeUserModules??!0,y=r.cacheDir||a(l,"bundle-cache"),F=new Bun.CryptoHasher("md5");F.update(`${me}\x00${Me()}\x00${JSON.stringify(u??!1)}\x00${d?"registry":"inline"}\x00${e}\x00${t}`);let c=F.digest("hex").slice(0,12),n=g.join(y,`${c}.js`),i=U.get(n);if(i){if(Zt(i.files)&&i.files.every((_)=>!P(_.path,l,u))){D("memo hit:",c);let _=i.files.map((A)=>A.path);return q(t,_),r.collectInputs?.push(..._),i.code}U.delete(n),D("memo invalidated by dep change:",c)}let f=g.join(y,`${c}.deps.json`),S=Bun.file(n);if(await S.exists()){let _=Bun.file(f),A=!1,E=null;if(await _.exists())try{let N=JSON.parse(await _.text());if(N.metadataVersion!==re||!Array.isArray(N.files))A=!1;else E=N.files,A=!0;if(E&&(!Zt(E)||E.some((T)=>P(T.path,l,u))))A=!1}catch{A=!1}if(A){if(D("cache hit:",c),E)q(t,E.map((T)=>T.path)),r.collectInputs?.push(...E.map((T)=>T.path));let N=await S.text();if(E)U.set(n,{code:N,files:E});return N}D("cache invalidated by dep change:",c)}let k=X.get(c);if(k){let _=await k;if(r.collectInputs)r.collectInputs.push(...(U.get(n)?.files??[]).map((A)=>A.path));return _}let M=Fa(()=>ye(e,t,{projectRoot:l,minify:p,cacheDir:y,hash:c,cachePath:n,depsPath:f,collectInputs:r.collectInputs,externalizeUserModules:d,serverApi:u}));X.set(c,M);try{return await M}finally{X.delete(c)}}var we=0;function za(e){return`${e}-${process.pid}-${++we}`}async function ye(e,t,r){let{projectRoot:l,minify:u,cacheDir:p,hash:d,cachePath:y,depsPath:F,externalizeUserModules:c}=r,n=a(l,"bundle-tmp"),i=za(d),f=g.join(n,`${i}.ts`),S=g.join(n,"out",i);v.mkdirSync(n,{recursive:!0}),v.mkdirSync(S,{recursive:!0});let k=g.dirname(t),M=new Set,_=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,A=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,E=s(e),{depths:N,balanced:T}=be(E),V=(B)=>!T||N[B]===0,x;while((x=_.exec(E))!==null){if(x[1])continue;if(!V(x.index))continue;if(x[2])x[2].split(",").forEach((B)=>{let h=Be(B);if(h)M.add(h)});else if(x[3])M.add(x[3])}while((x=A.exec(E))!==null){if(x[1])continue;if(!V(x.index))continue;M.add(x[2])}let oe=/^[ \t]*import\s+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((x=oe.exec(E))!==null){if(!V(x.index))continue;let B=/^\s*['"]([^'"]+)['"]/.exec(e.slice(x.index+x[0].length))?.[1];if(B&&Z.some((h)=>h.test(B)))continue;if(x[1])M.add(x[1]);if(x[2])M.add(x[2]);for(let h of(x[3]??"").split(",")){let j=h.trim();if(!j||/^type\s/.test(j))continue;let L=/\bas\s+(\w+)\s*$/.exec(j)?.[1]??/^\w+$/.exec(j)?.[0];if(L)M.add(L)}}for(let B of E.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let h of B[1].split(",")){let j=/\bas\s+(\w+)\s*$/.exec(h)?.[1]??/^\s*(\w+)\s*$/.exec(h)?.[1];if(j)M.delete(j)}let le=M.size>0?`
5
- export { ${[...M].join(", ")} }`:"";await Bun.write(f,e+le),D("bundling:",d,"from:",g.basename(t));let Q=new Set,K=new Map;try{let B=await Bun.build({entrypoints:[f],outdir:S,target:"browser",format:"esm",minify:u,plugins:[$e(l,k,f,Q,c,K,r.serverApi)],define:{"process.env.NODE_ENV":u?'"production"':'"development"',...w()},root:l});if(!B.success){let I=B.logs.filter((C)=>C.level==="error").map((C)=>C.message).join(", ")||`Unable to bundle ${g.basename(t)}`,O=J(B.logs,t||void 0);if(console.warn("[stx:bundler] build failed:",I),Mo(t||"",I,O),No()==="error")throw Error(I);return e}let h="";for(let b of B.outputs){h=await b.text();break}let j=[];for(let b of h.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let I of b[1].split(",")){let O=I.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(O){j.push([O[2],O[1]]);continue}let C=I.trim();if(/^[A-Za-z_$][\w$]*$/.test(C))j.push([C,C])}let L=[];h=Ba(ja(h,K),L);let ae=h.match(/^\s*import\s+[^;]+;?\s*$/gm)||[];h=h.replace(/^\s*import\s+[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim();let ee=`__stxBundle_${d}`,ce=j.map(([b,I])=>`${JSON.stringify(b)}: ${I}`).join(", "),ue=j.map(([b])=>`var ${b} = undefined;`).join(`
6
- `),de=j.map(([b])=>`${b} = ${ee}[${JSON.stringify(b)}];`).join(`
7
- `);if(h=`${ae.join(`
8
- `)}
9
- ${ue}
10
- var ${ee} = (function() {
11
- ${L.join(`
12
- `)}
13
- ${h}
14
- return { ${ce} };
15
- })();
16
- ${de}`.trim(),D("bundled:",d,"output:",h.length,"bytes"),M.size>0&&j.length===0)return console.warn(`[stx:bundler] dropped every binding for ${g.basename(t)} (${d}); serving the unbundled source and not caching this result`),e;v.mkdirSync(p,{recursive:!0}),await Bun.write(y,h);let z=Array.from(Q).map((b)=>{try{return{path:b,mtimeMs:v.statSync(b).mtimeMs}}catch{return null}}).filter((b)=>b!==null);return await Bun.write(F,JSON.stringify({metadataVersion:re,files:z})),q(t,z.map((b)=>b.path)),r.collectInputs?.push(...z.map((b)=>b.path)),U.set(y,{code:h,files:z}),await he(p),h}catch(B){let h=J(B,t||void 0),j=De(B,t||void 0);if(console.warn(`[stx:bundler] error: ${j}`),Mo(t||"",j,h),No()==="error")throw B;return e}finally{try{v.rmSync(f,{force:!0}),v.rmSync(S,{recursive:!0,force:!0})}catch{}}}function Be(e){let t=e.trim();if(!t)return null;let r=t.indexOf("=");if(r!==-1)t=t.slice(0,r).trim();let l=t.indexOf(":");if(l!==-1)t=t.slice(l+1).trim();if(t.startsWith("..."))t=t.slice(3).trim();return/^[A-Za-z_$][\w$]*$/.test(t)?t:null}
17
- export{De,ie,Na,Mo,gt,mt,yu,No,ht,Yt,La,ja,Ba,Fa,yt,za};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{kt,us,oi,mc}from"./chunk-dqdggvq4.js";import"./chunk-d2zw2e5m.js";import"./chunk-2n5pjbw9.js";import"./chunk-0trfbqa7.js";import"./chunk-ng61wjke.js";import"./chunk-zydg3wgt.js";import"./chunk-y36av1ac.js";import"./chunk-v83bpj84.js";import"./chunk-ynvce0q6.js";import"./chunk-pf0d8y9n.js";import"./chunk-2jbyks2t.js";import"./chunk-88px183j.js";import"./chunk-jz7pvh7b.js";export{mc as declareBareLoopHead,kt as parseLoopBinding,oi as processLoops,us as reportDeferredLoopWarnings};
@@ -1,18 +0,0 @@
1
- // @bun
2
- import{In,Oe,Ne,me,Wo,Ln,Z,K,rn,d,n,I}from"./chunk-dqdggvq4.js";import{dirname as C,resolve as R}from"path";function h(o){return o.endsWith(".md")||o.endsWith(".markdown")}function _(o){let e=[];m(/<pre\b[^>]*>[\s\S]*?<\/pre>/gi);let r=[...e];m(/<code\b[^>]*>[\s\S]*?<\/code>/gi,r);function m(s,p){let u;while((u=s.exec(o))!==null){let t=u.index,i=t+u[0].length;if(p?.some((l)=>t>=l.start&&i<=l.end))continue;e.push({start:t,end:i})}}if(e.length===0)return o;e.sort((s,p)=>s.start-p.start);let a="",c=0;for(let s of e){if(s.start<c)continue;a+=o.slice(c,s.start),a+=`@raw${o.slice(s.start,s.end)}@endraw`,c=s.end}return a+=o.slice(c),a}async function b(o,e={}){let{data:r,content:m}=In(o),c=await(e.renderer??((s)=>Oe(s)))(m);return{html:_(c),frontmatter:r??{}}}function k(o){let e=o,r=Z(o);if(r)e=r.content.trim();let m=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,a=[],c=[],s=[],p=(i)=>/\b(?:state|derived|effect|batch)\s*(?:<[^<>()]*>)?\s*\(/.test(i),u;while((u=m.exec(o))!==null){let i=u[1],l=u[2],f=u[0],g=i.includes("server");if(p(l))s.push(f);else if(g)c.push(l);else a.push(f)}let t=e;{let i=/<script\b(?![^>]*\b(?:client|type\s*=\s*["']module["']|src\s*=))[^>]*>/gi,l,f=[];while((l=i.exec(t))!==null){let g=l.index+l[0].length,x=t.indexOf("</script>",g);if(x===-1)continue;f.push({start:l.index,end:x+9}),i.lastIndex=x+9}for(let g=f.length-1;g>=0;g--)t=t.substring(0,f[g].start)+t.substring(f[g].end)}for(let i of a)t=t.replace(i,"");return{templateContent:t,serverScripts:c,clientScripts:a,signalsScripts:s}}function v(o,e){return`<!DOCTYPE html>
3
- <html lang="en">
4
- <head>
5
- <meta charset="UTF-8">
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
- <title>${(e||"stx").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}</title>
8
- </head>
9
- <body>
10
- ${o}
11
- </body>
12
- </html>`}async function _o(o,e={}){let r=R(o),m=Bun.file(r);if(!await m.exists())throw Error(`Template file not found: ${r}`);let a=await m.text(),c=null;if(h(r)){let s=await b(a,{renderer:e.markdownRenderer});a=s.html,c=s.frontmatter}if(c)e={...e,context:{...c,...e.context||{}}};if(e.layout){let s=R(e.layout),p=Bun.file(s);if(!await p.exists())throw Error(`Layout template not found: ${s}`);let{layout:u,injectCSS:t,...i}=e,l={...e.context||{}};rn(l);let f=await S(a,r,{...i,context:{...l,__stx_defer_server_data:!0},injectCSS:!1}),g=await p.text(),x={...l,content:f},w={...i,context:x,injectCSS:t};return S(g,s,w)}return S(a,r,e)}async function S(o,e,r={}){let{templateContent:m,serverScripts:a,clientScripts:c}=k(o),s={...I,...r.options},p={__filename:e,__dirname:C(e),__stx:{},__stx_options:s,__stx_sfc_mode:!0,__stx_inject_css:r.injectCSS===!0,__stxServeContext:void 0,...Ln(r.context??{}),definePageMeta:()=>{},...r.context||{}};for(let i of a)await d(i,p,e);let u=new Set,t=m;if(t=await n(t,p,e,s,u),Wo(p,r.context),r.templateOnly){if(t=t.replace(/<script data-stx-scoped>[\s\S]*?<\/script>\s*/gi,""),t=t.replace(/<!-- stx SEO Tags -->[\s\S]*?(?=<)/i,""),c.length>0)t+=`
13
- ${c.join(`
14
- `)}`}else{if(r.processClientScripts!==!1&&c.length>0){let i=p.__stx_event_bindings||[],l=Ne(p),g=(await Promise.all(c.map(async(w)=>{let y=w.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!y)return w;return await me(y[1],{eventBindings:i,templateContent:t,serverData:l,filePath:e})}))).join(`
15
- `);if(t.match(/(<\/body>)/i))t=t.replace(/(<\/body>)/i,`${g}
16
- $1`);else t+=`
17
- ${g}`}t=await K(t)}if(r.wrapInDocument){if(!t.trim().toLowerCase().startsWith("<!doctype")&&!t.trim().toLowerCase().startsWith("<html"))t=v(t,r.title)}if(r.injectCSS)try{let{injectCss:i}=await import("./chunk-mxt11ejx.js");t=await i(t)}catch{}return t}
18
- export{_o};