@stacksjs/stx 0.2.800 → 0.2.802

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 (148) hide show
  1. package/dist/{chunk-gzfvj15b.js → chunk-06hc6rs6.js} +1 -1
  2. package/dist/{chunk-rq5s1hc6.js → chunk-077dwzpp.js} +1 -1
  3. package/dist/{chunk-fes0t0js.js → chunk-0vztrb90.js} +32 -32
  4. package/dist/chunk-1338vj5g.js +2 -0
  5. package/dist/chunk-14qhn86r.js +2 -0
  6. package/dist/{chunk-kydgndkt.js → chunk-1pz11ez9.js} +1 -1
  7. package/dist/{chunk-szkmxk09.js → chunk-24x7s0x5.js} +3 -3
  8. package/dist/chunk-27p6cxa2.js +2 -0
  9. package/dist/chunk-2jwmtbsj.js +2 -0
  10. package/dist/{chunk-akcyaxwv.js → chunk-2vqpz4qv.js} +2 -2
  11. package/dist/{chunk-6c50nsgz.js → chunk-3dtp59r9.js} +1 -1
  12. package/dist/{chunk-95k6shcv.js → chunk-3j9zzpbd.js} +2 -2
  13. package/dist/{chunk-70j06zqt.js → chunk-3vfxn6g5.js} +1 -1
  14. package/dist/{chunk-rp9xzzmt.js → chunk-4gf3khd9.js} +2 -2
  15. package/dist/{chunk-s1eb3b3x.js → chunk-4q2fh4r4.js} +1 -1
  16. package/dist/{chunk-2ehn5r6d.js → chunk-50be1xy0.js} +1 -1
  17. package/dist/{chunk-48914p88.js → chunk-5hgghq24.js} +1 -1
  18. package/dist/chunk-6cgak0k1.js +2 -0
  19. package/dist/{chunk-et40w1wx.js → chunk-7j4tf0ba.js} +1 -1
  20. package/dist/{chunk-xa3xk823.js → chunk-7tkxshah.js} +8 -8
  21. package/dist/{chunk-jg4xvn1f.js → chunk-8fnhv8jq.js} +1 -1
  22. package/dist/{chunk-j0bbr6ee.js → chunk-8fvgsd9v.js} +3 -3
  23. package/dist/chunk-8hm4a8p2.js +2 -0
  24. package/dist/{chunk-2sgrapfw.js → chunk-9767yz39.js} +1 -1
  25. package/dist/{chunk-7z5ga45f.js → chunk-a0xxm3eh.js} +1 -1
  26. package/dist/{chunk-2yb1rwmy.js → chunk-a5byhf8f.js} +1 -1
  27. package/dist/{chunk-ssr3h26v.js → chunk-aj5na3d3.js} +1 -1
  28. package/dist/{chunk-9kadf7pv.js → chunk-antc6crh.js} +1 -1
  29. package/dist/chunk-b22yj5j5.js +2 -0
  30. package/dist/{chunk-dpctjkac.js → chunk-b29x9hsz.js} +1 -1
  31. package/dist/{chunk-sprgkk9j.js → chunk-bs02d6mm.js} +8 -8
  32. package/dist/{chunk-czsagff5.js → chunk-byatzyvf.js} +2 -2
  33. package/dist/chunk-bz3papjy.js +2 -0
  34. package/dist/{chunk-d47z4fky.js → chunk-c36bj74x.js} +1 -1
  35. package/dist/{chunk-04eq8yhz.js → chunk-casq5t61.js} +1 -1
  36. package/dist/{chunk-k3rcpnzm.js → chunk-cmnze7at.js} +2 -2
  37. package/dist/{chunk-8qhdbch9.js → chunk-cs38hg43.js} +8 -8
  38. package/dist/chunk-d3gncxq1.js +2 -0
  39. package/dist/{chunk-j2v9f2dk.js → chunk-dbbc84mj.js} +2 -2
  40. package/dist/{chunk-r32pqvpq.js → chunk-ddk34ppv.js} +5 -5
  41. package/dist/chunk-dwn8ye99.js +2 -0
  42. package/dist/{chunk-0gvrpg5x.js → chunk-dxemdr58.js} +41 -41
  43. package/dist/{chunk-xd8w1vf4.js → chunk-e1g3ns8y.js} +2 -2
  44. package/dist/{chunk-ysyh69a7.js → chunk-e5fszb5z.js} +1 -1
  45. package/dist/chunk-e88bsw36.js +2 -0
  46. package/dist/{chunk-ddhkhhc7.js → chunk-eayewa2s.js} +2 -2
  47. package/dist/{chunk-q3dsjk2b.js → chunk-esm9sdyf.js} +3 -3
  48. package/dist/chunk-ewhkvqce.js +72 -0
  49. package/dist/chunk-fq1dw4ph.js +3 -0
  50. package/dist/{chunk-2fkzsmcr.js → chunk-fsfj0s13.js} +6 -6
  51. package/dist/{chunk-qa358n74.js → chunk-fy6sdbak.js} +48 -48
  52. package/dist/{chunk-chgchzd9.js → chunk-g02jnsz5.js} +1 -1
  53. package/dist/chunk-g4sdthck.js +2 -0
  54. package/dist/chunk-gabw11g3.js +2 -0
  55. package/dist/{chunk-5h32se25.js → chunk-gk214p91.js} +2 -2
  56. package/dist/{chunk-dd1vqndp.js → chunk-gxrpf87x.js} +1 -1
  57. package/dist/{chunk-dwydz68f.js → chunk-h1dwth11.js} +1 -1
  58. package/dist/{chunk-4zv5vfv0.js → chunk-hzhsg5j7.js} +6 -6
  59. package/dist/chunk-j0jgc426.js +2 -0
  60. package/dist/{chunk-qkck7zx0.js → chunk-jdjv5x6q.js} +1 -1
  61. package/dist/chunk-jkn9garq.js +2 -0
  62. package/dist/chunk-jy9qmwpm.js +2 -0
  63. package/dist/chunk-krqj3cx9.js +2 -0
  64. package/dist/chunk-kzny87pz.js +2 -0
  65. package/dist/{chunk-p1d6hwty.js → chunk-kzt46v41.js} +1 -1
  66. package/dist/{chunk-8adf5x29.js → chunk-m0c64sna.js} +1 -1
  67. package/dist/{chunk-f4a6sbnt.js → chunk-m4w61tyq.js} +2 -2
  68. package/dist/{chunk-nm20k22y.js → chunk-md55r6zp.js} +1 -1
  69. package/dist/chunk-mv9k42dn.js +2 -0
  70. package/dist/{chunk-8ey61ppd.js → chunk-mz1kffvs.js} +2 -2
  71. package/dist/{chunk-33vr7x2t.js → chunk-n7arptzc.js} +3 -3
  72. package/dist/chunk-nhfksrce.js +3 -0
  73. package/dist/{chunk-cas0vn5m.js → chunk-ntwgk0tf.js} +1 -1
  74. package/dist/{chunk-7q0y6qg5.js → chunk-nya33asw.js} +3 -3
  75. package/dist/{chunk-83myk906.js → chunk-p4aaxpaw.js} +1 -1
  76. package/dist/{chunk-hcwjdpzv.js → chunk-p8wq37hd.js} +2 -2
  77. package/dist/{chunk-d5bhtsb5.js → chunk-pamtcna7.js} +1 -1
  78. package/dist/{chunk-gvnfb6s2.js → chunk-q7zwv88b.js} +2 -2
  79. package/dist/{chunk-aqf0kt1w.js → chunk-qx5jhe7h.js} +5 -5
  80. package/dist/{chunk-2yxva96k.js → chunk-r9e0r6jx.js} +2 -2
  81. package/dist/chunk-r9eyepbk.js +21 -0
  82. package/dist/{chunk-7tjw0mpm.js → chunk-rs0ejvjm.js} +1 -1
  83. package/dist/{chunk-t5vjt37c.js → chunk-rxhymzj8.js} +1 -1
  84. package/dist/{chunk-mb2d9spg.js → chunk-s81y1dw3.js} +4 -4
  85. package/dist/chunk-sfvdj9dj.js +2 -0
  86. package/dist/chunk-szma9dby.js +2 -0
  87. package/dist/{chunk-x8h81amr.js → chunk-t4j2rw91.js} +2 -2
  88. package/dist/chunk-txyyvtdp.js +2 -0
  89. package/dist/{chunk-8nsn1mkz.js → chunk-v18816jj.js} +8 -8
  90. package/dist/chunk-ved3r01r.js +420 -0
  91. package/dist/chunk-vxd3akt4.js +2 -0
  92. package/dist/{chunk-hp9e8nz6.js → chunk-we6jnjjp.js} +1 -1
  93. package/dist/{chunk-99jzhp6x.js → chunk-wes7vsze.js} +2 -2
  94. package/dist/chunk-wf6vjd41.js +2 -0
  95. package/dist/{chunk-ps9fcjyg.js → chunk-wghv9vr6.js} +1 -1
  96. package/dist/{chunk-w0zayhmg.js → chunk-wpendr22.js} +2 -2
  97. package/dist/{chunk-r1t4978q.js → chunk-wvnzq8w8.js} +3 -3
  98. package/dist/{chunk-qxt6hdat.js → chunk-wy0gghvh.js} +1 -1
  99. package/dist/{chunk-qph9n5vc.js → chunk-x0ttkvr7.js} +2 -2
  100. package/dist/chunk-xbvx8j82.js +2 -0
  101. package/dist/{chunk-e0vrayws.js → chunk-xndhzwdj.js} +5 -5
  102. package/dist/{chunk-dq87xd5c.js → chunk-xrvdef6x.js} +3 -3
  103. package/dist/{chunk-pfygdsms.js → chunk-yxsrerew.js} +1 -1
  104. package/dist/chunk-z0kx564w.js +2 -0
  105. package/dist/{chunk-y87whqd5.js → chunk-zwptpjjt.js} +16 -16
  106. package/dist/cli.js +13 -13
  107. package/dist/client-parameter-bindings.js +10 -6
  108. package/dist/craft-entry.js +1 -1
  109. package/dist/craft.js +1 -1
  110. package/dist/native/compiler/inline-style.js +51 -28
  111. package/dist/native/runtime/craft-bridge.js +37 -4
  112. package/dist/performance-utils.d.ts +255 -115
  113. package/dist/pwa.js +2 -2
  114. package/dist/safe-evaluator.js +28 -3
  115. package/dist/signal-processing.js +20 -41
  116. package/dist/ssg.js +3 -3
  117. package/package.json +5 -5
  118. package/dist/chunk-09vge2qv.js +0 -21
  119. package/dist/chunk-0h07bnrc.js +0 -2
  120. package/dist/chunk-0tbf7n5v.js +0 -2
  121. package/dist/chunk-2dmytnfq.js +0 -3
  122. package/dist/chunk-2f1kqrdc.js +0 -2
  123. package/dist/chunk-2g21c65w.js +0 -2
  124. package/dist/chunk-4q5y2b0z.js +0 -2
  125. package/dist/chunk-5fzvcr9v.js +0 -2
  126. package/dist/chunk-7m4eesp0.js +0 -2
  127. package/dist/chunk-b3b9tfpx.js +0 -2
  128. package/dist/chunk-baryfj93.js +0 -2
  129. package/dist/chunk-cn6cmy23.js +0 -2
  130. package/dist/chunk-eszpqrxy.js +0 -2
  131. package/dist/chunk-ex43dwnv.js +0 -431
  132. package/dist/chunk-f13yn6xw.js +0 -2
  133. package/dist/chunk-faqzszzs.js +0 -3
  134. package/dist/chunk-h2xrfjh8.js +0 -2
  135. package/dist/chunk-jfq3nwe0.js +0 -2
  136. package/dist/chunk-ktxatzbd.js +0 -2
  137. package/dist/chunk-m6a8mftb.js +0 -2
  138. package/dist/chunk-nq4d91zm.js +0 -2
  139. package/dist/chunk-q38vjqv2.js +0 -2
  140. package/dist/chunk-q78jxqnr.js +0 -2
  141. package/dist/chunk-qftr9bm2.js +0 -2
  142. package/dist/chunk-rp831mk8.js +0 -2
  143. package/dist/chunk-se44tmvx.js +0 -61
  144. package/dist/chunk-tmr6ey5s.js +0 -2
  145. package/dist/chunk-tq5mqv8d.js +0 -2
  146. package/dist/chunk-xqe2jt3f.js +0 -2
  147. package/dist/chunk-ys46rqxg.js +0 -2
  148. package/dist/chunk-zxm9hkqb.js +0 -2
@@ -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-tmr6ey5s.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,Sl,Cg}from"./chunk-p4aaxpaw.js";import{Qs,Ii,Sg,kg,_g}from"./chunk-rxhymzj8.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-mv9k42dn.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">
@@ -1,3 +1,4 @@
1
+ import { LRUCache } from "./performance-utils.js";
1
2
  const defaultConfig = {
2
3
  maxSanitizeDepth: 10,
3
4
  allowBracketNotation: !1
@@ -5,9 +6,11 @@ const defaultConfig = {
5
6
  let currentConfig = { ...defaultConfig };
6
7
  export function configureSafeEvaluator(config) {
7
8
  currentConfig = { ...currentConfig, ...config };
9
+ expressionPlans.clear();
8
10
  }
9
11
  export function resetSafeEvaluatorConfig() {
10
12
  currentConfig = { ...defaultConfig };
13
+ expressionPlans.clear();
11
14
  }
12
15
  export function getSafeEvaluatorConfig() {
13
16
  return { ...currentConfig };
@@ -482,7 +485,21 @@ const VALID_PARAM_IDENT = /^[A-Za-z_$][\w$]*$/;
482
485
  export function isUsableParamName(name) {
483
486
  return VALID_PARAM_IDENT.test(name) && !RESERVED_PARAM_NAMES.has(name);
484
487
  }
488
+ const expressionPlans = new LRUCache(2000, {
489
+ maxBytes: 2097152,
490
+ sizeOf: (plan) => plan.sourceBytes
491
+ });
485
492
  export function createSafeFunction(expression, contextKeys, onMissingIdentifier) {
493
+ const key = JSON.stringify([expression, contextKeys]);
494
+ let plan = expressionPlans.get(key);
495
+ if (!plan) {
496
+ plan = prepareFunctionPlan(expression, [...contextKeys]);
497
+ plan.sourceBytes += key.length * 2;
498
+ expressionPlans.set(key, plan);
499
+ }
500
+ return guardDynamicKeys(bindProjection(plan.buildFunc, plan.filteredKeys, plan.contextKeys, plan.validEntries, plan.validIndices, onMissingIdentifier), plan.contextKeys, plan.dynamicKeys);
501
+ }
502
+ function prepareFunctionPlan(expression, contextKeys) {
486
503
  const { source: sanitizedExpr, usesSafeConstructors, dynamicKeys } = prepareExpression(expression), validEntries = [];
487
504
  for (let i = 0;i < contextKeys.length; i++) {
488
505
  if (!isUsableParamName(contextKeys[i]))
@@ -503,14 +520,22 @@ catch (e) {
503
520
  }
504
521
  throw e;
505
522
  }
506
- `;
507
- return guardDynamicKeys(bindProjection(usesSafeConstructors ? (extraParams) => {
523
+ `, buildFunc = usesSafeConstructors ? (extraParams) => {
508
524
  const compiled = compileFunctionBody([SAFE_CTOR_PARAM, "Object", ...SHADOWED_GLOBAL_NAMES, ...filteredKeys, ...extraParams], body);
509
525
  return (...args) => compiled(SAFE_CONSTRUCTORS, SAFE_OBJECT, ...SHADOWED_GLOBAL_VALUES, ...args);
510
526
  } : (extraParams) => {
511
527
  const compiled = compileFunctionBody(["Object", ...SHADOWED_GLOBAL_NAMES, ...filteredKeys, ...extraParams], body);
512
528
  return (...args) => compiled(SAFE_OBJECT, ...SHADOWED_GLOBAL_VALUES, ...args);
513
- }, filteredKeys, contextKeys, validEntries, validIndices, onMissingIdentifier), contextKeys, dynamicKeys);
529
+ }, initialFunc = buildFunc([]);
530
+ return {
531
+ sourceBytes: expression.length * 2 + contextKeys.reduce((bytes, key) => bytes + key.length * 2, 0),
532
+ contextKeys,
533
+ filteredKeys,
534
+ validEntries,
535
+ validIndices,
536
+ dynamicKeys,
537
+ buildFunc: (extraParams) => extraParams.length === 0 ? initialFunc : buildFunc(extraParams)
538
+ };
514
539
  }
515
540
  function guardDynamicKeys(evaluate, contextKeys, dynamicKeys) {
516
541
  if (dynamicKeys.length === 0)
@@ -819,46 +819,25 @@ function dedupeTopLevelDeclarations(code) {
819
819
  return out.join("");
820
820
  }
821
821
  const SETUP_MARKER_SKIP_TAGS = new Set(["script", "style", "html", "head", "meta", "link", "title", "!doctype"]);
822
- function overlapsSignalScript(start, end, ranges) {
823
- for (const range of ranges) {
824
- if (range.start >= end)
825
- return !1;
826
- if (range.end > start)
827
- return !0;
828
- }
829
- return !1;
830
- }
831
- function hasTextOutsideSignalScripts(template, text, ranges) {
832
- let from = 0;
833
- while (from < template.length) {
834
- const index = template.indexOf(text, from);
835
- if (index === -1)
836
- return !1;
837
- if (!overlapsSignalScript(index, index + text.length, ranges))
838
- return !0;
839
- from = index + text.length;
840
- }
841
- return !1;
842
- }
843
- function findSetupMarkerInsertion(template, ranges) {
844
- if (hasTextOutsideSignalScripts(template, "<body", ranges)) {
845
- const bodyTagRe = new RegExp(`<body(${TAG_ATTR_RUN})>`, "g");
846
- let match;
847
- while ((match = bodyTagRe.exec(template)) !== null)
848
- if (!overlapsSignalScript(match.index, match.index + match[0].length, ranges))
849
- return match.index + match[0].length - 1;
850
- return null;
851
- }
852
- const openingTagRe = new RegExp(`<([a-zA-Z][a-zA-Z0-9-]*)\\b(${TAG_ATTR_RUN})>`, "gi");
853
- let match;
854
- while ((match = openingTagRe.exec(template)) !== null) {
855
- if (overlapsSignalScript(match.index, match.index + match[0].length, ranges))
856
- continue;
857
- if (SETUP_MARKER_SKIP_TAGS.has(match[1].toLowerCase()))
858
- continue;
859
- return match.index + match[0].length - 1;
860
- }
861
- return null;
822
+ function findSetupMarkerInsertion(template) {
823
+ const openingTagRe = new RegExp(`<([a-zA-Z][a-zA-Z0-9-]*)\\b(${TAG_ATTR_RUN})>`, "iy");
824
+ let first = null, body = null;
825
+ scanAtElementPosition(template, (html, index) => {
826
+ openingTagRe.lastIndex = index;
827
+ const match = openingTagRe.exec(html);
828
+ if (!match)
829
+ return -1;
830
+ const tag = match[1].toLowerCase();
831
+ if (tag === "script" || tag === "style")
832
+ return -1;
833
+ const insertion = index + match[0].length - 1;
834
+ if (tag === "body" && body === null)
835
+ body = insertion;
836
+ if (first === null && !SETUP_MARKER_SKIP_TAGS.has(tag))
837
+ first = insertion;
838
+ return index + match[0].length;
839
+ });
840
+ return body ?? first;
862
841
  }
863
842
  function rebuildSetupOwner(template, ranges, markerAt, setupFnName) {
864
843
  const chunks = [], marker = ` data-stx="${setupFnName}"`;
@@ -929,7 +908,7 @@ ${escapeScriptBody(`${bridge}${mergedContent}`)}
929
908
  }
930
909
  window.__stx_latestSetup=${setupFnName};
931
910
  if(window.stx)window.stx._latestSetup=${setupFnName};
932
- </script>`, markerAt = findSetupMarkerInsertion(template, signalScripts);
911
+ </script>`, markerAt = findSetupMarkerInsertion(template);
933
912
  return { output: rebuildSetupOwner(template, signalScripts, markerAt, setupFnName), setupCode };
934
913
  }
935
914
  export async function processSignals(template, options, filePath, serverData) {