@stacksjs/stx 0.2.801 → 0.2.803

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 (196) hide show
  1. package/dist/{chunk-bbt09ebh.js → chunk-0ekdbagy.js} +3 -3
  2. package/dist/{chunk-brhas9mp.js → chunk-0rjcbqk3.js} +2 -2
  3. package/dist/{chunk-83myk906.js → chunk-0svj1nfa.js} +4 -4
  4. package/dist/chunk-0xqec4yj.js +2 -0
  5. package/dist/{chunk-k4nhwd9p.js → chunk-16362f43.js} +2 -2
  6. package/dist/chunk-19nnq90g.js +2 -0
  7. package/dist/{chunk-kydgndkt.js → chunk-1carv1dw.js} +1 -1
  8. package/dist/{chunk-enpx5t99.js → chunk-1ydz2w3t.js} +1 -1
  9. package/dist/{chunk-9gwhs0gk.js → chunk-2ws2qe1k.js} +2 -2
  10. package/dist/chunk-36zj3myn.js +2 -0
  11. package/dist/chunk-3e85etrf.js +2 -0
  12. package/dist/{chunk-8kvj2wz0.js → chunk-3ebwrpax.js} +6 -6
  13. package/dist/{chunk-sprgkk9j.js → chunk-3ec6jf9b.js} +30 -30
  14. package/dist/{chunk-9nbv6nk4.js → chunk-3es17qjn.js} +9 -9
  15. package/dist/{chunk-2vejgrj7.js → chunk-3k4xb05m.js} +5 -5
  16. package/dist/{chunk-b9d70mgr.js → chunk-3vpgr6nk.js} +3 -3
  17. package/dist/{chunk-dq87xd5c.js → chunk-3z0e637x.js} +3 -3
  18. package/dist/{chunk-qxt6hdat.js → chunk-427mhgje.js} +1 -1
  19. package/dist/{chunk-gqgcsgc3.js → chunk-4jrf6gsk.js} +1 -1
  20. package/dist/chunk-4mb75g61.js +2 -0
  21. package/dist/chunk-4n7yqb9w.js +2 -0
  22. package/dist/chunk-5eqna31h.js +2 -0
  23. package/dist/{chunk-zfzjn93c.js → chunk-5s31y4m0.js} +15 -15
  24. package/dist/{chunk-6162chg7.js → chunk-5vxk8bz9.js} +43 -43
  25. package/dist/chunk-69cphbrz.js +420 -0
  26. package/dist/chunk-6a97a9wk.js +2 -0
  27. package/dist/{chunk-dwydz68f.js → chunk-6dcc4ezx.js} +1 -1
  28. package/dist/{chunk-7yb82rm6.js → chunk-6s9bk98p.js} +2 -2
  29. package/dist/chunk-72cm91wm.js +2 -0
  30. package/dist/{chunk-s763dt8e.js → chunk-77a2hse0.js} +6 -6
  31. package/dist/{chunk-mt95md1e.js → chunk-7agp0wj2.js} +1 -1
  32. package/dist/{chunk-gctyy7r9.js → chunk-7v1pwjke.js} +9 -9
  33. package/dist/{chunk-y9bj3566.js → chunk-7xs45trj.js} +2 -2
  34. package/dist/chunk-85w7kf2j.js +2 -0
  35. package/dist/chunk-87g1ryzs.js +2 -0
  36. package/dist/chunk-8g3bgcac.js +2 -0
  37. package/dist/{chunk-2fh4wvtv.js → chunk-8je2zse3.js} +34 -34
  38. package/dist/chunk-8m5w99f3.js +2 -0
  39. package/dist/chunk-8wd83rnz.js +2 -0
  40. package/dist/chunk-97daxgfk.js +2 -0
  41. package/dist/{chunk-f52esq8m.js → chunk-9h72drk3.js} +1 -1
  42. package/dist/chunk-9wmjmas8.js +2 -0
  43. package/dist/{chunk-x82zksaj.js → chunk-a0r4dpzs.js} +2 -2
  44. package/dist/{chunk-s85s2kd3.js → chunk-amewvsn1.js} +2 -2
  45. package/dist/chunk-aqydav9y.js +2 -0
  46. package/dist/chunk-aznnh6cy.js +3 -0
  47. package/dist/{chunk-33vr7x2t.js → chunk-baj6w8ja.js} +3 -3
  48. package/dist/{chunk-j0bbr6ee.js → chunk-bejj0gra.js} +3 -3
  49. package/dist/{chunk-w0zayhmg.js → chunk-c5vzr1va.js} +2 -2
  50. package/dist/{chunk-ddhkhhc7.js → chunk-cfbpvm5e.js} +2 -2
  51. package/dist/{chunk-k3rcpnzm.js → chunk-cmnze7at.js} +2 -2
  52. package/dist/{chunk-61h00ba5.js → chunk-cwnx4rxk.js} +6 -6
  53. package/dist/chunk-cxahdpzz.js +2 -0
  54. package/dist/chunk-d3gncxq1.js +2 -0
  55. package/dist/{chunk-d8rcba53.js → chunk-d47m4qat.js} +2 -2
  56. package/dist/{chunk-t0qh1m5e.js → chunk-d98hgxky.js} +4 -4
  57. package/dist/chunk-da886asf.js +2 -0
  58. package/dist/{chunk-25q462jp.js → chunk-dc584r4z.js} +4 -4
  59. package/dist/{chunk-fw9dhsd9.js → chunk-dqa1g676.js} +2 -2
  60. package/dist/{chunk-9kadf7pv.js → chunk-dvbd5fxe.js} +1 -1
  61. package/dist/{chunk-t5vjt37c.js → chunk-e39nkbt4.js} +3 -3
  62. package/dist/chunk-e6snnz4t.js +2 -0
  63. package/dist/chunk-e848m5tj.js +2 -0
  64. package/dist/chunk-et8n16k2.js +2 -0
  65. package/dist/{chunk-gqdkvwjp.js → chunk-evmxrmjb.js} +50 -50
  66. package/dist/chunk-ewzdsksb.js +2 -0
  67. package/dist/chunk-fsjkavq5.js +2 -0
  68. package/dist/chunk-g4sdthck.js +2 -0
  69. package/dist/{chunk-56j2egg3.js → chunk-g9xx8qh1.js} +3 -3
  70. package/dist/{chunk-6n5cbyes.js → chunk-gb3tv53p.js} +2 -2
  71. package/dist/chunk-gebb12ak.js +72 -0
  72. package/dist/{chunk-e08hzdpw.js → chunk-gmme8c1s.js} +1 -1
  73. package/dist/{chunk-nn1f1h3q.js → chunk-gq5ffpq0.js} +1 -1
  74. package/dist/chunk-gzs0ertq.js +2 -0
  75. package/dist/chunk-h9yvb9qn.js +2 -0
  76. package/dist/{chunk-j2v9f2dk.js → chunk-hn2me1qx.js} +2 -2
  77. package/dist/{chunk-vzmkex8f.js → chunk-hpqrcpjb.js} +1 -1
  78. package/dist/{chunk-gjf8cjdt.js → chunk-hwcfgs3e.js} +3 -3
  79. package/dist/chunk-j49t3p7e.js +2 -0
  80. package/dist/chunk-jjcw2pa9.js +2 -0
  81. package/dist/{chunk-hzs3h76s.js → chunk-k4csq6pk.js} +4 -4
  82. package/dist/{chunk-hyz90d8w.js → chunk-k5xyb0dq.js} +2 -2
  83. package/dist/{chunk-8ey61ppd.js → chunk-k86573fe.js} +5 -5
  84. package/dist/chunk-kn84qg00.js +2 -0
  85. package/dist/{chunk-wz3gk8js.js → chunk-kq0cee7k.js} +3 -3
  86. package/dist/{chunk-vg3scf4d.js → chunk-m1mrq876.js} +9 -9
  87. package/dist/chunk-m5cdkb11.js +2 -0
  88. package/dist/{chunk-akcyaxwv.js → chunk-m7hfcxt3.js} +2 -2
  89. package/dist/{chunk-r32pqvpq.js → chunk-mmh2k7ab.js} +5 -5
  90. package/dist/chunk-mrc7hc4a.js +2 -0
  91. package/dist/{chunk-t0bcbhvs.js → chunk-ncptqa8v.js} +5 -5
  92. package/dist/{chunk-sxee2rxz.js → chunk-ncyjaxyz.js} +1 -1
  93. package/dist/chunk-nmc1vj8f.js +2 -0
  94. package/dist/chunk-nrqv8s48.js +2 -0
  95. package/dist/{chunk-gzfvj15b.js → chunk-nsxjt6h3.js} +1 -1
  96. package/dist/{chunk-hcwjdpzv.js → chunk-p8wq37hd.js} +2 -2
  97. package/dist/chunk-pr6nrg6x.js +2 -0
  98. package/dist/{chunk-jce3scvg.js → chunk-ps5by9sq.js} +16 -16
  99. package/dist/{chunk-v47yfe9k.js → chunk-qeyzgyhk.js} +1 -1
  100. package/dist/{chunk-8xx1yf34.js → chunk-qm3hkrcw.js} +4 -4
  101. package/dist/{chunk-hp9e8nz6.js → chunk-r1vkk7qp.js} +2 -2
  102. package/dist/{chunk-2yxva96k.js → chunk-r9e0r6jx.js} +2 -2
  103. package/dist/chunk-rmpgtyqh.js +2 -0
  104. package/dist/chunk-rnz6g3xv.js +2 -0
  105. package/dist/{chunk-gvnfb6s2.js → chunk-rpen41w3.js} +2 -2
  106. package/dist/{chunk-x8m28yea.js → chunk-rssxm2jw.js} +2 -2
  107. package/dist/chunk-s1k2sc69.js +2 -0
  108. package/dist/chunk-s3z8jtfj.js +2 -0
  109. package/dist/{chunk-q3dsjk2b.js → chunk-s9xs2ff4.js} +6 -6
  110. package/dist/{chunk-znx5m1jv.js → chunk-sphc7xzx.js} +1 -1
  111. package/dist/chunk-syvsj91a.js +2 -0
  112. package/dist/{chunk-x8h81amr.js → chunk-t4j2rw91.js} +2 -2
  113. package/dist/chunk-tdcgskyy.js +2 -0
  114. package/dist/chunk-tzb0n60s.js +2 -0
  115. package/dist/chunk-va9w63nh.js +2 -0
  116. package/dist/{chunk-qpvwxppw.js → chunk-vbc8a8fh.js} +4 -4
  117. package/dist/{chunk-s9b6abkb.js → chunk-vkn133cs.js} +2 -2
  118. package/dist/chunk-w3dsj0a6.js +3 -0
  119. package/dist/chunk-w5xq1217.js +2 -0
  120. package/dist/{chunk-hrrrf46j.js → chunk-w6n4y2xg.js} +2 -2
  121. package/dist/chunk-wwbng2jf.js +2 -0
  122. package/dist/chunk-x2hc3zth.js +2 -0
  123. package/dist/chunk-x7qctqj2.js +2 -0
  124. package/dist/{chunk-c1bsagbe.js → chunk-xrd1md4j.js} +6 -6
  125. package/dist/{chunk-1htxem27.js → chunk-y2q46m8b.js} +3 -3
  126. package/dist/{chunk-2yb1rwmy.js → chunk-y7sf7aj0.js} +1 -1
  127. package/dist/{chunk-t65tn8ee.js → chunk-ybjfr7e8.js} +2 -2
  128. package/dist/{chunk-8adf5x29.js → chunk-ycr9bkww.js} +1 -1
  129. package/dist/{chunk-xtwcz8dg.js → chunk-yhfrs6yn.js} +7 -7
  130. package/dist/chunk-yjezsy4p.js +2 -0
  131. package/dist/{chunk-3ajbbtqx.js → chunk-zmckz1eq.js} +7 -7
  132. package/dist/cli.js +19 -19
  133. package/dist/client-parameter-bindings.js +10 -6
  134. package/dist/client-script.js +11 -10
  135. package/dist/craft-entry.js +2 -2
  136. package/dist/craft.js +2 -2
  137. package/dist/native/compiler/inline-style.js +51 -28
  138. package/dist/native/runtime/craft-bridge.js +37 -4
  139. package/dist/performance-utils.d.ts +255 -115
  140. package/dist/pwa.js +3 -3
  141. package/dist/safe-evaluator.js +28 -3
  142. package/dist/ssg.js +5 -5
  143. package/package.json +5 -5
  144. package/dist/chunk-1yhrq2nx.js +0 -2
  145. package/dist/chunk-1zy94dxs.js +0 -2
  146. package/dist/chunk-26505qjh.js +0 -2
  147. package/dist/chunk-2ehn5r6d.js +0 -2
  148. package/dist/chunk-3gcdq401.js +0 -2
  149. package/dist/chunk-3rgb6kc1.js +0 -2
  150. package/dist/chunk-5fzvcr9v.js +0 -2
  151. package/dist/chunk-6b10096c.js +0 -2
  152. package/dist/chunk-6fq522rd.js +0 -2
  153. package/dist/chunk-6mdvx2bf.js +0 -2
  154. package/dist/chunk-6q0c9j7p.js +0 -2
  155. package/dist/chunk-77v7g18n.js +0 -2
  156. package/dist/chunk-7m4eesp0.js +0 -2
  157. package/dist/chunk-92te36hf.js +0 -2
  158. package/dist/chunk-9736003n.js +0 -2
  159. package/dist/chunk-9sgzv5ze.js +0 -2
  160. package/dist/chunk-acwqb3ys.js +0 -2
  161. package/dist/chunk-amc8xdcz.js +0 -2
  162. package/dist/chunk-b3b9tfpx.js +0 -2
  163. package/dist/chunk-bb3y1g34.js +0 -2
  164. package/dist/chunk-bf3va62c.js +0 -2
  165. package/dist/chunk-c2x9wea0.js +0 -2
  166. package/dist/chunk-cas0vn5m.js +0 -2
  167. package/dist/chunk-d1c1qggs.js +0 -2
  168. package/dist/chunk-dd1vqndp.js +0 -2
  169. package/dist/chunk-ef8p88as.js +0 -2
  170. package/dist/chunk-ej8q3kyc.js +0 -2
  171. package/dist/chunk-eszpqrxy.js +0 -2
  172. package/dist/chunk-fn4jk05k.js +0 -2
  173. package/dist/chunk-h72d9174.js +0 -2
  174. package/dist/chunk-jn6g5n02.js +0 -2
  175. package/dist/chunk-kdhsev5v.js +0 -3
  176. package/dist/chunk-nm20k22y.js +0 -2
  177. package/dist/chunk-nq4d91zm.js +0 -2
  178. package/dist/chunk-nv0n2hjg.js +0 -431
  179. package/dist/chunk-p9j909eq.js +0 -2
  180. package/dist/chunk-pmf53mgj.js +0 -2
  181. package/dist/chunk-ps9fcjyg.js +0 -2
  182. package/dist/chunk-pxxhhaaw.js +0 -3
  183. package/dist/chunk-q38vjqv2.js +0 -2
  184. package/dist/chunk-q78jxqnr.js +0 -2
  185. package/dist/chunk-qkck7zx0.js +0 -2
  186. package/dist/chunk-se44tmvx.js +0 -61
  187. package/dist/chunk-shag9bcm.js +0 -2
  188. package/dist/chunk-t4yy48dh.js +0 -2
  189. package/dist/chunk-t55nk8sw.js +0 -2
  190. package/dist/chunk-tkb335d7.js +0 -2
  191. package/dist/chunk-vse4ewax.js +0 -2
  192. package/dist/chunk-vy92xwbg.js +0 -2
  193. package/dist/chunk-whq40bdm.js +0 -2
  194. package/dist/chunk-wqt2hep2.js +0 -2
  195. package/dist/chunk-ys46rqxg.js +0 -2
  196. package/dist/chunk-zhz8er14.js +0 -2
@@ -283,21 +283,20 @@ export function parseNativeStyleLayers(inputs, inheritedVariables, report) {
283
283
  const layers = Array(inputs.length);
284
284
  let empty = !0;
285
285
  for (let i = 0;i < inputs.length; i++) {
286
- const input = inputs[i];
287
- if (input && typeof input === "object" && !Array.isArray(input) || typeof input === "string" && input) {
288
- const key = typeof input === "string" ? standaloneStyleText(input) : standaloneStyleKey(input), kept = key === void 0 ? void 0 : rememberedStyles.get(key);
289
- if (kept) {
290
- (known ??= Array(inputs.length))[i] = kept;
291
- layers[i] = NO_ENTRIES;
292
- empty = !1;
293
- continue;
294
- }
295
- if (key !== void 0)
296
- (keys ??= Array(inputs.length))[i] = key;
297
- }
298
- layers[i] = styleEntries(input, report);
299
- if (layers[i].length)
300
- empty = !1;
286
+ const entries = snapshotStructuredEntries(styleEntries(inputs[i], report));
287
+ layers[i] = entries;
288
+ if (!entries.length)
289
+ continue;
290
+ empty = !1;
291
+ const key = standaloneStyleKey(entries);
292
+ if (key === void 0)
293
+ continue;
294
+ const kept = rememberedStyles.get(key);
295
+ if (kept) {
296
+ (known ??= Array(inputs.length))[i] = kept;
297
+ layers[i] = NO_ENTRIES;
298
+ } else
299
+ (keys ??= Array(inputs.length))[i] = key;
301
300
  }
302
301
  if (empty)
303
302
  return { variables: inheritedVariables ?? NO_STYLE_VARIABLES, styles: layers.map(() => ({})) };
@@ -327,20 +326,44 @@ export function parseNativeStyleLayers(inputs, inheritedVariables, report) {
327
326
  }
328
327
  return { variables: computed, styles };
329
328
  }
330
- const NO_ENTRIES = [], rememberedStyles = new Map;
331
- function standaloneStyleText(text) {
332
- return text.includes("var(") || text.includes("--") ? void 0 : `\x03${text}`;
329
+ const rememberedStyles = new Map, NO_ENTRIES = [], INVALID_STRUCTURED_STYLE = Symbol("invalid native structured style");
330
+ function normalizedProperty(rawProperty) {
331
+ return STYLE_KEYS.has(rawProperty) || rawProperty.trim().startsWith("--") ? rawProperty : rawProperty.trim().toLowerCase().replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
333
332
  }
334
- function standaloneStyleKey(input) {
335
- let text;
336
- try {
337
- text = JSON.stringify(input);
338
- } catch {
339
- return;
333
+ function snapshotStructuredEntries(entries) {
334
+ let snapshots;
335
+ for (let i = 0;i < entries.length; i++) {
336
+ const [name, raw] = entries[i];
337
+ if (!raw || typeof raw !== "object")
338
+ continue;
339
+ const property = normalizedProperty(name);
340
+ if (property !== "shadowOffset" && property !== "transform")
341
+ continue;
342
+ snapshots ??= entries.slice();
343
+ snapshots[i] = [name, structuredStyle(property, raw) ?? INVALID_STRUCTURED_STYLE];
344
+ }
345
+ return snapshots ?? entries;
346
+ }
347
+ function cacheableValue(name, value) {
348
+ if (value == null || typeof value === "string" || typeof value === "boolean")
349
+ return !0;
350
+ if (typeof value === "number")
351
+ return finite(value) && !Object.is(value, -0);
352
+ const property = normalizedProperty(name);
353
+ if (property === "shadowOffset" && value && typeof value === "object" && !Array.isArray(value))
354
+ return Object.values(value).every((part) => finite(part) && !Object.is(part, -0));
355
+ if (property === "transform" && Array.isArray(value))
356
+ return value.every((step) => Object.values(step).every((part) => typeof part === "string" || finite(part) && !Object.is(part, -0)));
357
+ return !1;
358
+ }
359
+ function standaloneStyleKey(entries) {
360
+ for (const [name, value] of entries) {
361
+ if (name.trim().startsWith("--") || typeof value === "string" && /var\(/i.test(value))
362
+ return;
363
+ if (!cacheableValue(name, value))
364
+ return;
340
365
  }
341
- if (typeof text !== "string" || text.includes("var(") || text.includes('"--'))
342
- return;
343
- return text;
366
+ return JSON.stringify(entries);
344
367
  }
345
368
  function parseEntries(entries, variables, report) {
346
369
  const style = {}, declarationNames = [];
@@ -349,7 +372,7 @@ function parseEntries(entries, variables, report) {
349
372
  declarationNames.push(rawProperty.trim());
350
373
  continue;
351
374
  }
352
- const property = STYLE_KEYS.has(rawProperty) || rawProperty.trim().startsWith("--") ? rawProperty : rawProperty.trim().toLowerCase().replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
375
+ const property = normalizedProperty(rawProperty);
353
376
  if (!STYLE_KEYS.has(property)) {
354
377
  report({ kind: "unknown-style", name: property });
355
378
  continue;
@@ -656,23 +656,56 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
656
656
  removeAll: () => scheduled("removeAll")
657
657
  };
658
658
  }
659
- if (capabilities.has("media"))
659
+ if (capabilities.has("media")) {
660
+ const cacheKeys = capabilities.has("media-cache-key"), cacheOptions = (options) => {
661
+ if (options.cacheKey === void 0)
662
+ return {};
663
+ if (!cacheKeys)
664
+ throw Error("This host does not support media cache keys");
665
+ if (typeof options.cacheKey !== "string" || !options.cacheKey || options.cacheKey.length > 256)
666
+ throw TypeError("A media cache key must contain 1 to 256 characters");
667
+ return { cacheKey: options.cacheKey };
668
+ };
660
669
  craft.media = {
670
+ cacheKeys,
661
671
  keep: (url, options = {}) => {
662
672
  if (typeof url !== "string" || !url)
663
673
  return Promise.reject(TypeError("media.keep needs a URL"));
674
+ let identity;
675
+ try {
676
+ identity = cacheOptions(options);
677
+ } catch (error) {
678
+ return Promise.reject(error);
679
+ }
664
680
  const headers = {}, given = options.headers;
665
681
  if (given && typeof given === "object")
666
682
  Object.keys(given).forEach((name) => {
667
683
  headers[name] = String(given[name]);
668
684
  });
669
- return ask("Media", "keep", [url, options.cellular === !1 ? { headers, cellular: !1 } : { headers }]);
685
+ return ask("Media", "keep", [url, { headers, ...identity, ...options.cellular === !1 ? { cellular: !1 } : {} }]);
686
+ },
687
+ path: (url, options = {}) => {
688
+ let identity;
689
+ try {
690
+ identity = cacheOptions(options);
691
+ } catch (error) {
692
+ return Promise.reject(error);
693
+ }
694
+ return typeof url === "string" && url ? request("Media", "path", Object.keys(identity).length ? [url, identity] : [url]).then((path) => typeof path === "string" ? path : null) : Promise.resolve(null);
695
+ },
696
+ prune: (sources = []) => {
697
+ let keep;
698
+ try {
699
+ keep = (Array.isArray(sources) ? sources : []).filter((source) => typeof source === "string" || source && typeof source === "object" && typeof source.url === "string").map((source) => typeof source === "string" ? source : { url: source.url, ...cacheOptions(source) });
700
+ } catch (error) {
701
+ return Promise.reject(error);
702
+ }
703
+ return request("Media", "prune", [keep]);
670
704
  },
671
- path: (url) => typeof url === "string" && url ? request("Media", "path", [url]).then((path) => typeof path === "string" ? path : null) : Promise.resolve(null),
672
- prune: (urls = []) => request("Media", "prune", [(Array.isArray(urls) ? urls : []).filter((url) => typeof url === "string")]),
673
705
  clear: () => request("Media", "clear", []),
674
706
  usage: () => request("Media", "usage", [])
675
707
  };
708
+ }
676
709
  if (capabilities.has("files")) {
677
710
  craft.files = {
678
711
  pickVideo: (options = {}) => ask("Files", "pickVideo", [{
@@ -1,3 +1,82 @@
1
+ /**
2
+ * Performance optimization utilities for stx
3
+ */
4
+ /**
5
+ * Generic LRU (Least Recently Used) cache implementation
6
+ * Automatically evicts least recently used items when capacity is reached
7
+ */
8
+ /**
9
+ * How a cache measures what it is holding, when entry count is not enough.
10
+ *
11
+ * A count-bounded cache assumes entries are roughly one size. That holds for
12
+ * the caches here that store paths or small fragments, and stops holding as
13
+ * soon as the values are rendered output: one entry can be tens of kilobytes
14
+ * and another a few bytes, so `maxSize` stops describing the footprint at all
15
+ * (stacksjs/stx#1945). Passing `sizeOf` and `maxBytes` bounds the bytes as
16
+ * well, which is the number a memory-constrained host actually has to budget.
17
+ */
18
+ export interface LRUCacheOptions<V> {
19
+ /** Bytes this cache may retain across all entries. */
20
+ maxBytes: number;
21
+ /** What one value costs. Called once per `set`, so keep it cheap. */
22
+ sizeOf: (value: V) => number;
23
+ }
24
+ export declare class LRUCache<K, V> {
25
+ private cache;
26
+ private readonly maxSize;
27
+ private options;
28
+ private sizes;
29
+ private bytes;
30
+ constructor(maxSize?: number, options?: LRUCacheOptions<V>);
31
+ /** Bytes currently retained. Zero unless the cache is byte-bounded. */
32
+ get byteSize(): number;
33
+ /**
34
+ * Change the byte budget, evicting immediately down to the new one.
35
+ *
36
+ * The caches here are module state, built when the module loads and so before
37
+ * any config has been read. A host that wants a different ceiling -- or none
38
+ * at all -- can only say so afterwards, and it should take effect on what is
39
+ * already held rather than only on what arrives next: a container that has
40
+ * just told stx to keep 4MB is not helped by a cache that keeps its current
41
+ * 32MB until the entries happen to age out.
42
+ *
43
+ * A no-op on a cache built without a budget: giving one bytes it never
44
+ * measured would evict against a total that is always zero.
45
+ */
46
+ setMaxBytes(maxBytes: number): void;
47
+ /**
48
+ * Get a value from the cache, moving it to most recently used
49
+ */
50
+ get(key: K): V | undefined;
51
+ /**
52
+ * Set a value in the cache
53
+ */
54
+ set(key: K, value: V): void;
55
+ /**
56
+ * Check if key exists in cache
57
+ */
58
+ has(key: K): boolean;
59
+ /**
60
+ * Delete a key from the cache
61
+ */
62
+ delete(key: K): boolean;
63
+ /**
64
+ * Clear all entries from the cache
65
+ */
66
+ clear(): void;
67
+ /**
68
+ * Get the current size of the cache
69
+ */
70
+ get size(): number;
71
+ /**
72
+ * Get all keys in the cache (oldest to newest)
73
+ */
74
+ keys(): IterableIterator<K>;
75
+ /**
76
+ * Get all values in the cache (oldest to newest)
77
+ */
78
+ values(): IterableIterator<V>;
79
+ }
1
80
  /**
2
81
  * Get a cached regex pattern or compile and cache it.
3
82
  *
@@ -23,6 +102,39 @@ export declare function getCachedRegex(pattern: string, flags?: string): RegExp;
23
102
  * Clear the regex cache (useful for testing)
24
103
  */
25
104
  export declare function clearRegexCache(): void;
105
+ /**
106
+ * Cache for template processing results
107
+ */
108
+ export declare class TemplateCache {
109
+ private cache;
110
+ private maxSize;
111
+ private ttl;
112
+ constructor(maxSize?: number, ttl?: number);
113
+ /**
114
+ * Get cached result if available and not expired
115
+ */
116
+ get(key: string): string | null;
117
+ /**
118
+ * Store result in cache
119
+ */
120
+ set(key: string, result: string, dependencies?: Set<string>): void;
121
+ /**
122
+ * Invalidate cache entries that depend on a specific file
123
+ */
124
+ invalidateDependency(filePath: string): number;
125
+ /**
126
+ * Clear all cached entries
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Get cache statistics
131
+ */
132
+ getStats(): {
133
+ size: number;
134
+ maxSize: number;
135
+ hitRate?: number;
136
+ };
137
+ }
26
138
  /**
27
139
  * Debounce function calls to avoid excessive processing
28
140
  */
@@ -40,139 +152,167 @@ export declare function memoize<T extends (...args: any[]) => any>(func: T, maxC
40
152
  */
41
153
  export declare function optimizedReplace(text: string, pattern: string | RegExp, replacement: string | ((match: string, ...args: any[]) => string), flags?: string): string;
42
154
  /**
43
- * Get the global performance monitor instance (lazy-loaded)
44
- * This avoids instantiating the monitor until it's actually needed
45
- */
46
- export declare function getPerformanceMonitor(): PerformanceMonitor;
47
- /**
48
- * Apply default performance budgets to the monitor
49
- */
50
- export declare function applyDefaultBudgets(monitor?: PerformanceMonitor): void;
51
- /**
52
- * Reset the performance monitor instance (useful for testing)
53
- */
54
- export declare function resetPerformanceMonitor(): void;
55
- // Global expression evaluator pool
56
- export declare const expressionEvaluatorPool: ExpressionEvaluatorPool;
57
- /**
58
- * Default performance budgets for common operations
59
- * @defaultValue
60
- * ```ts
61
- * {
62
- * processDirectives: { maxTime: 500, warnThreshold: 0.8, action: 'warn' },
63
- * processTemplate: { maxTime: 200, warnThreshold: 0.8, action: 'warn' },
64
- * processIncludes: { maxTime: 100, warnThreshold: 0.8, action: 'warn' },
65
- * processLoops: { maxTime: 50, warnThreshold: 0.8, action: 'warn' },
66
- * processConditionals: { maxTime: 50, warnThreshold: 0.8, action: 'warn' },
67
- * processExpressions: { maxTime: 100, warnThreshold: 0.8, action: 'warn' },
68
- * renderComponent: { maxTime: 150, warnThreshold: 0.8, action: 'warn' },
69
- * buildWebComponents: { maxTime: 1000, warnThreshold: 0.8, action: 'warn' }
70
- * }
71
- * ```
72
- */
73
- export declare const defaultPerformanceBudgets: Record<string, PerformanceBudget>;
74
- /**
75
- * Global performance monitor instance
76
- * @deprecated Use getPerformanceMonitor() for lazy loading
77
- */
78
- export declare const performanceMonitor: PerformanceMonitor;
79
- /* eslint-disable prefer-const, style/max-statements-per-line, no-super-linear-backtracking, regexp/no-unused-capturing-group, pickier/no-unused-vars */
80
- /**
81
- * Performance optimization utilities for stx
82
- */
83
- /**
84
- * Generic LRU (Least Recently Used) cache implementation
85
- * Automatically evicts least recently used items when capacity is reached
86
- */
87
- /**
88
- * How a cache measures what it is holding, when entry count is not enough.
89
- *
90
- * A count-bounded cache assumes entries are roughly one size. That holds for
91
- * the caches here that store paths or small fragments, and stops holding as
92
- * soon as the values are rendered output: one entry can be tens of kilobytes
93
- * and another a few bytes, so `maxSize` stops describing the footprint at all
94
- * (stacksjs/stx#1945). Passing `sizeOf` and `maxBytes` bounds the bytes as
95
- * well, which is the number a memory-constrained host actually has to budget.
155
+ * Pool of worker contexts to avoid creating new Function instances
96
156
  */
97
- export declare interface LRUCacheOptions<V> {
98
- maxBytes: number
99
- sizeOf: (value: V) => number
157
+ declare class ExpressionEvaluatorPool {
158
+ private pool;
159
+ private maxPoolSize;
160
+ private fnCache;
161
+ private fnCacheMaxSize;
162
+ getEvaluator(contextKeys: string[]): (...args: any[]) => any;
163
+ clear(): void;
100
164
  }
165
+ export declare const expressionEvaluatorPool: ExpressionEvaluatorPool;
101
166
  /**
102
167
  * Performance budget configuration
103
168
  */
104
- export declare interface PerformanceBudget {
105
- maxTime: number
106
- warnThreshold?: number
107
- action?: 'log' | 'warn' | 'error' | 'throw'
169
+ export interface PerformanceBudget {
170
+ /** Maximum allowed time in milliseconds */
171
+ maxTime: number;
172
+ /** Warning threshold (percentage of maxTime, e.g., 0.8 = 80%) */
173
+ warnThreshold?: number;
174
+ /** Action to take on budget violation: 'log', 'warn', 'error', 'throw' */
175
+ action?: 'log' | 'warn' | 'error' | 'throw';
108
176
  }
109
177
  /**
110
178
  * Performance budget violation event
111
179
  */
112
- export declare interface BudgetViolation {
113
- label: string
114
- actualTime: number
115
- budgetTime: number
116
- exceedancePercent: number
117
- timestamp: Date
118
- isWarning: boolean
180
+ export interface BudgetViolation {
181
+ label: string;
182
+ actualTime: number;
183
+ budgetTime: number;
184
+ exceedancePercent: number;
185
+ timestamp: Date;
186
+ isWarning: boolean;
119
187
  }
120
188
  /**
121
189
  * Performance budget violation handler type
122
190
  */
123
- // eslint-disable-next-line pickier/no-unused-vars
124
191
  export type BudgetViolationHandler = (violation: BudgetViolation) => void;
125
- export declare class LRUCache<K, V> {
126
- constructor(maxSize?: number, options?: LRUCacheOptions<V>);
127
- get byteSize(): number;
128
- setMaxBytes(maxBytes: number): void;
129
- get(key: K): V | undefined;
130
- set(key: K, value: V): void;
131
- has(key: K): boolean;
132
- delete(key: K): boolean;
133
- clear(): void;
134
- get size(): number;
135
- keys(): IterableIterator<K>;
136
- values(): IterableIterator<V>;
137
- }
138
192
  /**
139
- * Cache for template processing results
193
+ * Performance monitor for tracking processing times with budget support
140
194
  */
141
- export declare class TemplateCache {
142
- constructor(maxSize?: number, ttl?: number);
143
- get(key: string): string | null;
144
- set(key: string, result: string, dependencies?: Set<string>): void;
145
- invalidateDependency(filePath: string): number;
146
- clear(): void;
147
- getStats(): { size: number, maxSize: number, hitRate?: number };
195
+ export declare class PerformanceMonitor {
196
+ private metrics;
197
+ private budgets;
198
+ private violations;
199
+ private maxViolations;
200
+ private violationHandlers;
201
+ private enabled;
202
+ /**
203
+ * Enable or disable performance monitoring
204
+ */
205
+ setEnabled(enabled: boolean): void;
206
+ /**
207
+ * Check if monitoring is enabled
208
+ */
209
+ isEnabled(): boolean;
210
+ /**
211
+ * Set a performance budget for a specific operation
212
+ *
213
+ * @param label - Operation label
214
+ * @param budget - Budget configuration
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * performanceMonitor.setBudget('processDirectives', {
219
+ * maxTime: 100, // 100ms max
220
+ * warnThreshold: 0.8, // warn at 80ms
221
+ * action: 'warn'
222
+ * })
223
+ * ```
224
+ */
225
+ setBudget(label: string, budget: PerformanceBudget): void;
226
+ /**
227
+ * Set multiple performance budgets at once
228
+ */
229
+ setBudgets(budgets: Record<string, PerformanceBudget>): void;
230
+ /**
231
+ * Remove a performance budget
232
+ */
233
+ removeBudget(label: string): void;
234
+ /**
235
+ * Get all configured budgets
236
+ */
237
+ getBudgets(): Record<string, PerformanceBudget>;
238
+ /**
239
+ * Add a handler for budget violations
240
+ */
241
+ onViolation(handler: BudgetViolationHandler): void;
242
+ /**
243
+ * Remove a violation handler
244
+ */
245
+ offViolation(handler: BudgetViolationHandler): void;
246
+ /**
247
+ * Time a function execution
248
+ */
249
+ time<T>(label: string, fn: () => T): T;
250
+ /**
251
+ * Time an async function execution
252
+ */
253
+ timeAsync<T>(label: string, fn: () => Promise<T>): Promise<T>;
254
+ /**
255
+ * Check if a duration violates the budget
256
+ */
257
+ private checkBudget;
258
+ /**
259
+ * Record a timing measurement
260
+ */
261
+ recordTime(label: string, duration: number): void;
262
+ /**
263
+ * Get performance statistics
264
+ */
265
+ getStats(label?: string): Record<string, any>;
266
+ /**
267
+ * Get all budget violations
268
+ */
269
+ getViolations(label?: string): BudgetViolation[];
270
+ /**
271
+ * Get violation statistics
272
+ */
273
+ getViolationStats(): {
274
+ total: number;
275
+ byLabel: Record<string, number>;
276
+ warnings: number;
277
+ errors: number;
278
+ };
279
+ /**
280
+ * Clear all metrics
281
+ */
282
+ clear(): void;
283
+ /**
284
+ * Clear all violations
285
+ */
286
+ clearViolations(): void;
287
+ /**
288
+ * Clear budgets
289
+ */
290
+ clearBudgets(): void;
291
+ /**
292
+ * Reset everything (metrics, violations, budgets)
293
+ */
294
+ reset(): void;
148
295
  }
149
296
  /**
150
- * Pool of worker contexts to avoid creating new Function instances
297
+ * Default performance budgets for common operations
151
298
  */
152
- declare class ExpressionEvaluatorPool {
153
- getEvaluator(contextKeys: string[]): (...args: any[]) => any;
154
- clear(): void;
155
- }
299
+ export declare const defaultPerformanceBudgets: Record<string, PerformanceBudget>;
156
300
  /**
157
- * Performance monitor for tracking processing times with budget support
301
+ * Get the global performance monitor instance (lazy-loaded)
302
+ * This avoids instantiating the monitor until it's actually needed
158
303
  */
159
- export declare class PerformanceMonitor {
160
- setEnabled(enabled: boolean): void;
161
- isEnabled(): boolean;
162
- setBudget(label: string, budget: PerformanceBudget): void;
163
- setBudgets(budgets: Record<string, PerformanceBudget>): void;
164
- removeBudget(label: string): void;
165
- getBudgets(): Record<string, PerformanceBudget>;
166
- onViolation(handler: BudgetViolationHandler): void;
167
- offViolation(handler: BudgetViolationHandler): void;
168
- time<T>(label: string, fn: () => T): T;
169
- timeAsync<T>(label: string, fn: () => Promise<T>): Promise<T>;
170
- recordTime(label: string, duration: number): void;
171
- getStats(label?: string): Record<string, any>;
172
- getViolations(label?: string): BudgetViolation[];
173
- getViolationStats(): { total: number, byLabel: Record<string, number>, warnings: number, errors: number };
174
- clear(): void;
175
- clearViolations(): void;
176
- clearBudgets(): void;
177
- reset(): void;
178
- }
304
+ export declare function getPerformanceMonitor(): PerformanceMonitor;
305
+ /**
306
+ * Global performance monitor instance
307
+ * @deprecated Use getPerformanceMonitor() for lazy loading
308
+ */
309
+ export declare const performanceMonitor: PerformanceMonitor;
310
+ /**
311
+ * Apply default performance budgets to the monitor
312
+ */
313
+ export declare function applyDefaultBudgets(monitor?: PerformanceMonitor): void;
314
+ /**
315
+ * Reset the performance monitor instance (useful for testing)
316
+ */
317
+ export declare function resetPerformanceMonitor(): void;
318
+ export {};
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{eo,Ht,Sl,Cg}from"./chunk-83myk906.js";import{Qs,Ii,Sg,kg,_g}from"./chunk-t5vjt37c.js";import{wl,vl,xl,vg,xg}from"./chunk-d8rcba53.js";import{Ue,Tn,Oi}from"./chunk-y9bj3566.js";import{Eg,Tg,$g,Rg,to,dy}from"./chunk-gqjb1y7c.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-acwqb3ys.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{eo,Ht,xl,Cg}from"./chunk-0svj1nfa.js";import{Qs,Pi,Sg,kg,_g}from"./chunk-e39nkbt4.js";import{bl,wl,vl,vg,xg}from"./chunk-d47m4qat.js";import{Ue,Tn,Ii}from"./chunk-7xs45trj.js";import{Eg,Tg,$g,Rg,to,dy}from"./chunk-gqjb1y7c.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-0xqec4yj.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=Ue(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=eo(n,t);if(a){let s=Ht(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 Ii(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,vl as auditBuildOutput,wl as auditConfig,re as buildPwaAssets,xl as calculateAuditResult,xg as formatAuditResult,Oi as formatSize,j as generateManifest,_ as generateManifestJson,kg as generateManifestLink,F as generateOfflinePage,Ue as generatePrecacheManifest,Tn as generatePrecacheManifestJs,M as generatePwaIcons,Qs as generatePwaTags,eo as generateServiceWorker,Cg as generateServiceWorkerAuto,Sg as generateSwRegistrationScript,_g as generateThemeColorMeta,N as getExpectedIconPaths,Ht as getServiceWorkerFileName,Ii as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,Sl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,to as pwaDirectives,Eg as pwaInstallDirective,$g as pwaOfflineDirective,Rg as pwaPushDirective,Tg as pwaUpdateDirective,dy as registerPwaDirectives,vg 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=Ue(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=eo(n,t);if(a){let s=Ht(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 Pi(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,wl as auditBuildOutput,bl as auditConfig,re as buildPwaAssets,vl as calculateAuditResult,xg as formatAuditResult,Ii as formatSize,j as generateManifest,_ as generateManifestJson,kg as generateManifestLink,F as generateOfflinePage,Ue as generatePrecacheManifest,Tn as generatePrecacheManifestJs,M as generatePwaIcons,Qs as generatePwaTags,eo as generateServiceWorker,Cg as generateServiceWorkerAuto,Sg as generateSwRegistrationScript,_g as generateThemeColorMeta,N as getExpectedIconPaths,Ht as getServiceWorkerFileName,Pi as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,xl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,to as pwaDirectives,Eg as pwaInstallDirective,$g as pwaOfflineDirective,Rg as pwaPushDirective,Tg as pwaUpdateDirective,dy as registerPwaDirectives,vg as runPwaAudit,D as validateManifest};