webspresso 0.0.108 → 0.0.109

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 (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -3
  3. package/bin/commands/add-esbuild.js +7 -3
  4. package/bin/commands/add-tailwind.js +9 -5
  5. package/bin/commands/build.js +20 -4
  6. package/bin/commands/dev.js +57 -7
  7. package/bin/commands/doctor.js +42 -1
  8. package/bin/commands/favicon-generate.js +10 -3
  9. package/bin/commands/new.js +8 -3
  10. package/bin/commands/start.js +3 -1
  11. package/bin/utils/add-command.js +16 -0
  12. package/core/app.js +45 -3
  13. package/core/auth/authenticate.js +3 -3
  14. package/core/auth/hash.js +167 -43
  15. package/core/auth/index.js +13 -1
  16. package/core/auth/jwt.js +21 -2
  17. package/core/auth/manager.js +63 -14
  18. package/core/auth/middleware.js +4 -2
  19. package/core/auth/oauth.js +5 -1
  20. package/core/auth/tokens.js +7 -2
  21. package/core/auth/totp.js +42 -6
  22. package/core/auth/user-agent.js +2 -0
  23. package/core/client/adapter/datastar.js +1254 -0
  24. package/core/client/api.js +1033 -0
  25. package/core/client/controller.js +1081 -0
  26. package/core/client/debug.js +367 -0
  27. package/core/client/forms.js +1021 -0
  28. package/core/client/fragments.js +738 -0
  29. package/core/client/index.d.ts +40 -0
  30. package/core/client/index.js +347 -0
  31. package/core/client/lite.js +164 -0
  32. package/core/client/server-fragments.js +859 -0
  33. package/core/client/utils.js +144 -0
  34. package/core/compression/middleware.js +277 -26
  35. package/core/context/app-context.js +25 -3
  36. package/core/context/request.js +32 -4
  37. package/core/errors/middleware.js +14 -0
  38. package/core/events/dispatcher.js +33 -0
  39. package/core/forms/flash.js +136 -102
  40. package/core/health/middleware.js +36 -6
  41. package/core/http/pipeline.js +45 -6
  42. package/core/index.js +21 -7
  43. package/core/kernel/view.js +41 -10
  44. package/core/metrics/middleware.js +30 -6
  45. package/core/metrics/registry.js +13 -5
  46. package/core/orm/cache/fingerprint.js +32 -11
  47. package/core/orm/cache/layer.js +19 -2
  48. package/core/orm/hidden.js +145 -0
  49. package/core/orm/model.js +48 -2
  50. package/core/orm/query-builder.js +343 -6
  51. package/core/orm/query-filters.js +14 -2
  52. package/core/orm/repository.js +64 -13
  53. package/core/orm/schema-helpers.js +9 -6
  54. package/core/orm/transaction.js +50 -6
  55. package/core/orm/types.js +4 -0
  56. package/core/queue/adapters/database.js +184 -2
  57. package/core/queue/adapters/memory.js +153 -5
  58. package/core/queue/adapters/redis.js +59 -4
  59. package/core/queue/job.js +14 -1
  60. package/core/queue/manager.js +115 -0
  61. package/core/resilience/circuit-breaker.js +27 -8
  62. package/core/services/builtins/exchange.js +174 -7
  63. package/core/services/builtins/file-manager.js +36 -0
  64. package/core/services/builtins/mail.js +27 -0
  65. package/core/services/builtins/queue.js +144 -0
  66. package/core/services/builtins/security.js +118 -0
  67. package/core/services/builtins/webhook.js +110 -0
  68. package/core/services/executor.js +38 -16
  69. package/core/services/index.js +4 -1
  70. package/core/sse/stream.js +28 -5
  71. package/core/utils/timeout.js +8 -1
  72. package/core/validation/compiler.js +10 -7
  73. package/index.d.ts +1127 -71
  74. package/index.js +124 -8
  75. package/package.json +75 -26
  76. package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
  77. package/plugins/admin-panel/index.js +19 -8
  78. package/plugins/csrf/index.js +3 -3
  79. package/plugins/data-exchange/export.js +214 -0
  80. package/plugins/data-exchange/import.js +48 -5
  81. package/plugins/data-exchange/index.js +70 -28
  82. package/plugins/data-exchange/preview.js +266 -0
  83. package/plugins/data-exchange/template.js +242 -0
  84. package/plugins/email/admin-component.js +783 -141
  85. package/plugins/email/api-handlers.js +51 -1
  86. package/plugins/email/index.js +5 -0
  87. package/plugins/email/service.js +48 -0
  88. package/plugins/file-manager/admin-component.js +1546 -70
  89. package/plugins/file-manager/api-handlers.js +166 -1
  90. package/plugins/file-manager/core.js +598 -8
  91. package/plugins/file-manager/index.js +8 -0
  92. package/plugins/index.js +7 -0
  93. package/plugins/mcp/auth.js +3 -3
  94. package/plugins/oauth/index.js +36 -3
  95. package/plugins/queue/admin-component.js +1092 -0
  96. package/plugins/queue/api-handlers.js +248 -0
  97. package/plugins/queue/index.js +69 -0
  98. package/plugins/rest-resources/index.js +7 -2
  99. package/plugins/security/admin-component.js +689 -0
  100. package/plugins/security/api-handlers.js +169 -0
  101. package/plugins/security/audit.js +153 -0
  102. package/plugins/security/bruteforce.js +244 -0
  103. package/plugins/security/firewall.js +459 -0
  104. package/plugins/security/headers.js +214 -0
  105. package/plugins/security/honeypot.js +234 -0
  106. package/plugins/security/incident-recorder.js +137 -0
  107. package/plugins/security/index.js +211 -0
  108. package/plugins/seo-checker/analyzer.js +20 -7
  109. package/plugins/upload/index.js +36 -0
  110. package/plugins/webhooks/admin-component.js +702 -175
  111. package/plugins/webhooks/api-handlers.js +75 -1
  112. package/plugins/webhooks/dispatcher.js +290 -11
  113. package/plugins/webhooks/index.js +37 -2
  114. package/plugins/webhooks/sender.js +56 -0
  115. package/plugins/xlsx/engine.js +19 -4
  116. package/src/api/api-loader.js +19 -1
  117. package/src/bundle/index.js +443 -17
  118. package/src/client-runtime/mount.js +9 -2
  119. package/src/dev/api-typegen.js +1300 -0
  120. package/src/dev/banner.js +10 -1
  121. package/src/dev/colors.js +1 -1
  122. package/src/dev/index.js +7 -1
  123. package/src/dev/typegen.js +173 -17
  124. package/src/dev-reload/index.js +1 -1
  125. package/src/discovery/file-route-parser.js +17 -3
  126. package/src/discovery/scan-routes.js +4 -1
  127. package/src/file-router.js +249 -69
  128. package/src/helpers.js +46 -26
  129. package/src/njk-frontmatter.js +30 -4
  130. package/src/routing/cascading.js +26 -8
  131. package/src/routing/mount-discovered-routes.js +69 -0
  132. package/src/server.js +237 -66
  133. package/.agents/ADMIN.md +0 -426
  134. package/.agents/AGENTS.md +0 -96
  135. package/.agents/ARCHITECTURE.md +0 -163
  136. package/.agents/AUTH.md +0 -581
  137. package/.agents/CACHE.md +0 -148
  138. package/.agents/CLI.md +0 -649
  139. package/.agents/COMPRESSION.md +0 -59
  140. package/.agents/CONTEXT.md +0 -152
  141. package/.agents/CONVENTIONS.md +0 -50
  142. package/.agents/EARLY_HINTS.md +0 -120
  143. package/.agents/EMAIL.md +0 -223
  144. package/.agents/ERRORS.md +0 -260
  145. package/.agents/EVENTS.md +0 -179
  146. package/.agents/FLAGS.md +0 -118
  147. package/.agents/HEALTH.md +0 -118
  148. package/.agents/LIMITS.md +0 -109
  149. package/.agents/LOGGING.md +0 -93
  150. package/.agents/MCP.md +0 -103
  151. package/.agents/METRICS.md +0 -127
  152. package/.agents/MIGRATION_JOBS.md +0 -95
  153. package/.agents/ORM.md +0 -700
  154. package/.agents/PLUGINS.md +0 -729
  155. package/.agents/QUEUE.md +0 -290
  156. package/.agents/RATE_LIMIT.md +0 -147
  157. package/.agents/REALTIME.md +0 -213
  158. package/.agents/RESILIENCE.md +0 -235
  159. package/.agents/ROUTING.md +0 -605
  160. package/.agents/SCALE_OUT.md +0 -109
  161. package/.agents/SECRETS.md +0 -117
  162. package/.agents/SERVICES.md +0 -341
  163. package/.agents/SHUTDOWN.md +0 -74
  164. package/.agents/STREAMING.md +0 -108
  165. package/.agents/WORKFLOW.md +0 -27
  166. package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
  167. package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
  168. package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
  169. package/.agents/skills/webspresso-framework/SKILL.md +0 -89
  170. package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
  171. package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
  172. package/.agents/skills/webspresso-services/SKILL.md +0 -134
  173. package/.cursorrules +0 -14
  174. package/AGENTS.md +0 -203
  175. package/CLAUDE.md +0 -54
  176. package/core/kernel/run-demo.js +0 -58
  177. package/plugins/admin-panel/styles.js +0 -9
  178. package/plugins/data-exchange/export-xlsx.js +0 -119
@@ -0,0 +1,1254 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Datastar Adapter
5
+ *
6
+ * Isolates all direct interaction with @starfederation/datastar (v1.0.0-beta.11, MIT).
7
+ * Uses Datastar's public extension APIs:
8
+ * - load(...plugins), apply(), PluginType, Requirement, DATASTAR_SIGNAL_EVENT
9
+ * - InitContext: { signals (SignalsRoot), effect, applyToElement }
10
+ * - CustomEvent('datastar-sse', { detail: { type: 'datastar-merge-fragments', ... } })
11
+ *
12
+ * Architectural notes on public API boundaries:
13
+ * 1. Datastar's built-in attribute plugins evaluate arbitrary JS expressions against a single
14
+ * global signal store and Datastar's backend actions (@get/@post) serialize all global signals
15
+ * into requests by default.
16
+ * 2. To satisfy Webspresso's strict requirements (per-controller isolated state scope, zero naive
17
+ * regex expression rewriting, and strict separation between JSON API payloads and HTML/signal
18
+ * patches), we register Webspresso's `data-w-*` bindings via Datastar's public AttributePlugin
19
+ * interface (`PluginType.Attribute`) when `@starfederation/datastar` is present, and resolve
20
+ * property paths directly against each controller instance's isolated signal namespace
21
+ * (`__w_inst_<id>.*`) inside Datastar's `signals` (`SignalsRoot`) + `effect()`.
22
+ * 3. Because `@starfederation/datastar` is an optional peerDependency, this adapter includes a
23
+ * 100% contract-compatible signal/effect/plugin engine and DOM morphing implementation when the
24
+ * external package is not installed in `node_modules`.
25
+ */
26
+
27
+ const { getByPath, setByPath } = require('../utils');
28
+
29
+ const PluginType = {
30
+ Attribute: 1,
31
+ Watcher: 2,
32
+ Action: 3,
33
+ };
34
+
35
+ const Requirement = {
36
+ Allowed: 0,
37
+ Must: 1,
38
+ Denied: 2,
39
+ Exclusive: 3,
40
+ };
41
+
42
+ const DATASTAR_SIGNAL_EVENT = 'datastar-signals';
43
+ const DATASTAR_SSE_EVENT = 'datastar-sse';
44
+
45
+ /**
46
+ * Attempt to resolve @starfederation/datastar if installed or provided on globalThis.
47
+ *
48
+ * @param {object} [injectedDatastar]
49
+ * @returns {object|null}
50
+ */
51
+ function resolveExternalDatastar(injectedDatastar) {
52
+ if (injectedDatastar && typeof injectedDatastar.load === 'function') {
53
+ return injectedDatastar;
54
+ }
55
+ if (typeof globalThis !== 'undefined' && globalThis.__WEBSPRESSO_DATASTAR__) {
56
+ return globalThis.__WEBSPRESSO_DATASTAR__;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // Datastar-compatible Signal & Effect Engine (matches Datastar SignalsRoot API)
63
+ // ---------------------------------------------------------------------------
64
+
65
+ function createSignalsEngine() {
66
+ let activeEffect = null;
67
+ const effectStack = [];
68
+
69
+ class SignalNode {
70
+ constructor(initialValue) {
71
+ this._value = initialValue;
72
+ this._subs = new Set();
73
+ }
74
+
75
+ get value() {
76
+ if (activeEffect) {
77
+ this._subs.add(activeEffect);
78
+ activeEffect.deps.add(this._subs);
79
+ }
80
+ return this._value;
81
+ }
82
+
83
+ set value(nextValue) {
84
+ if (Object.is(this._value, nextValue)) return;
85
+ this._value = nextValue;
86
+ const subscribers = Array.from(this._subs);
87
+ for (const sub of subscribers) {
88
+ if (!sub.disposed) {
89
+ sub.run();
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ function effect(fn) {
96
+ const runner = {
97
+ disposed: false,
98
+ deps: new Set(),
99
+ cleanup() {
100
+ for (const depSet of this.deps) {
101
+ depSet.delete(this);
102
+ }
103
+ this.deps.clear();
104
+ },
105
+ run() {
106
+ if (this.disposed) return;
107
+ this.cleanup();
108
+ effectStack.push(this);
109
+ activeEffect = this;
110
+ try {
111
+ fn();
112
+ } finally {
113
+ effectStack.pop();
114
+ activeEffect = effectStack[effectStack.length - 1] || null;
115
+ }
116
+ },
117
+ };
118
+
119
+ runner.run();
120
+
121
+ return function stopEffect() {
122
+ runner.disposed = true;
123
+ runner.cleanup();
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Implements Datastar's public `SignalsRoot` contract:
129
+ * exists(path), signal(path), value(path), setValue(path, val),
130
+ * upsertIfMissing(path, val), remove(...paths), merge(obj, onlyIfMissing),
131
+ * subset(...keys), values(onlyPublic)
132
+ */
133
+ class CompatibleSignalsRoot {
134
+ constructor() {
135
+ this._nodes = new Map();
136
+ }
137
+
138
+ _normalizePath(path) {
139
+ return String(path || '').trim().replace(/^\.+|\.+$/g, '');
140
+ }
141
+
142
+ exists(path) {
143
+ const p = this._normalizePath(path);
144
+ return this._nodes.has(p);
145
+ }
146
+
147
+ signal(path) {
148
+ const p = this._normalizePath(path);
149
+ if (!this._nodes.has(p)) {
150
+ this._nodes.set(p, new SignalNode(undefined));
151
+ }
152
+ return this._nodes.get(p);
153
+ }
154
+
155
+ value(path) {
156
+ const p = this._normalizePath(path);
157
+ return this.signal(p).value;
158
+ }
159
+
160
+ setValue(path, val) {
161
+ const p = this._normalizePath(path);
162
+ this.signal(p).value = val;
163
+ }
164
+
165
+ upsertIfMissing(path, val) {
166
+ const p = this._normalizePath(path);
167
+ if (!this._nodes.has(p)) {
168
+ this._nodes.set(p, new SignalNode(val));
169
+ }
170
+ return this._nodes.get(p);
171
+ }
172
+
173
+ remove(...paths) {
174
+ for (const rawPath of paths) {
175
+ const prefix = this._normalizePath(rawPath);
176
+ if (!prefix) continue;
177
+ this._nodes.delete(prefix);
178
+ const dotPrefix = `${prefix}.`;
179
+ for (const key of Array.from(this._nodes.keys())) {
180
+ if (key.startsWith(dotPrefix)) {
181
+ this._nodes.delete(key);
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ subset(...keys) {
188
+ const out = {};
189
+ for (const prefix of keys) {
190
+ const norm = this._normalizePath(prefix);
191
+ const dotPrefix = `${norm}.`;
192
+ for (const [k, node] of this._nodes.entries()) {
193
+ if (k === norm) {
194
+ out[norm] = node.value;
195
+ } else if (k.startsWith(dotPrefix)) {
196
+ const subKey = k.slice(dotPrefix.length);
197
+ out[subKey] = node.value;
198
+ }
199
+ }
200
+ }
201
+ return out;
202
+ }
203
+
204
+ values() {
205
+ const out = {};
206
+ for (const [k, node] of this._nodes.entries()) {
207
+ out[k] = node.value;
208
+ }
209
+ return out;
210
+ }
211
+ }
212
+
213
+ return {
214
+ signals: new CompatibleSignalsRoot(),
215
+ effect,
216
+ };
217
+ }
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // Safe Expression Evaluator (NO Regex Rewriting, NO eval / new Function)
221
+ // ---------------------------------------------------------------------------
222
+
223
+ /**
224
+ * Parse a literal token (string, number, boolean, null, undefined) or resolve as state path.
225
+ */
226
+ function resolveOperand(state, token) {
227
+ const t = token.trim();
228
+ if (t === 'true') return true;
229
+ if (t === 'false') return false;
230
+ if (t === 'null') return null;
231
+ if (t === 'undefined') return undefined;
232
+ if ((t.startsWith("'") && t.endsWith("'")) || (t.startsWith('"') && t.endsWith('"'))) {
233
+ return t.slice(1, -1);
234
+ }
235
+ if (/^-?\d+(\.\d+)?$/.test(t)) {
236
+ return Number(t);
237
+ }
238
+ return getByPath(state, t);
239
+ }
240
+
241
+ /**
242
+ * Safely evaluate a declarative binding expression against controller state without
243
+ * naive regex transformations or `eval`/`new Function`.
244
+ *
245
+ * Supported declarative syntax:
246
+ * - Property path: `count`, `user.name`, `items.length`
247
+ * - Negation: `!pending`, `!!error`
248
+ * - Simple comparisons: `status === 'active'`, `count > 0`, `step !== 1`
249
+ *
250
+ * @param {object} state
251
+ * @param {string} rawExpr
252
+ * @returns {unknown}
253
+ */
254
+ function evaluateStateExpression(state, rawExpr) {
255
+ if (typeof rawExpr !== 'string') return undefined;
256
+ const expr = rawExpr.trim();
257
+ if (!expr) return undefined;
258
+
259
+ // Check simple comparison operators in precedence order
260
+ const operators = ['===', '!==', '==', '!=', '>=', '<=', '>', '<'];
261
+ for (const op of operators) {
262
+ const idx = expr.indexOf(op);
263
+ if (idx > 0) {
264
+ const leftRaw = expr.slice(0, idx).trim();
265
+ const rightRaw = expr.slice(idx + op.length).trim();
266
+ if (leftRaw && rightRaw) {
267
+ const left = resolveOperand(state, leftRaw);
268
+ const right = resolveOperand(state, rightRaw);
269
+ switch (op) {
270
+ case '===':
271
+ case '==':
272
+ return left === right;
273
+ case '!==':
274
+ case '!=':
275
+ return left !== right;
276
+ case '>=':
277
+ return Number(left) >= Number(right);
278
+ case '<=':
279
+ return Number(left) <= Number(right);
280
+ case '>':
281
+ return Number(left) > Number(right);
282
+ case '<':
283
+ return Number(left) < Number(right);
284
+ }
285
+ }
286
+ }
287
+ }
288
+
289
+ if (expr.startsWith('!!')) {
290
+ return Boolean(evaluateStateExpression(state, expr.slice(2)));
291
+ }
292
+ if (expr.startsWith('!')) {
293
+ return !Boolean(evaluateStateExpression(state, expr.slice(1)));
294
+ }
295
+
296
+ return resolveOperand(state, expr);
297
+ }
298
+
299
+ // ---------------------------------------------------------------------------
300
+ // Isolated Scoped Reactive State per Controller Instance
301
+ // ---------------------------------------------------------------------------
302
+
303
+ /**
304
+ * Creates an isolated reactive state Proxy for a single controller instance,
305
+ * backed by Datastar's `signals` store under namespace `__w_inst_<instanceId>`.
306
+ *
307
+ * @param {object} engine - { signals, effect }
308
+ * @param {string} instanceId
309
+ * @param {object} initialState
310
+ * @param {() => boolean} isConnected - Guard preventing disconnected instances from mutating state
311
+ * @param {object} [debug]
312
+ * @returns {{ state: object, dispose: () => void, snapshot: () => object }}
313
+ */
314
+ function createIsolatedControllerState(
315
+ engine,
316
+ instanceId,
317
+ initialState = {},
318
+ isConnected = () => true,
319
+ debug = null,
320
+ computedDefs = {},
321
+ getContext = () => ({})
322
+ ) {
323
+ const namespace = `__w_inst_${instanceId}`;
324
+ const rawStore = {};
325
+ const proxyCache = new WeakMap();
326
+
327
+ // Validate that no property is defined in both state and computed
328
+ if (computedDefs && typeof computedDefs === 'object') {
329
+ for (const key of Object.keys(computedDefs)) {
330
+ if (initialState && Object.prototype.hasOwnProperty.call(initialState, key)) {
331
+ throw new TypeError(
332
+ `Cannot define "${key}" as both a state and computed property for instance "${instanceId}".`
333
+ );
334
+ }
335
+ }
336
+ }
337
+
338
+ function signalKeyFor(path) {
339
+ return path ? `${namespace}.${path}` : namespace;
340
+ }
341
+
342
+ let isEvaluatingComputed = false;
343
+ let activeComputedKey = null;
344
+ const computedValues = new Map();
345
+ const computedDisposers = [];
346
+
347
+ function wrapReactive(target, basePath) {
348
+ if (target === null || typeof target !== 'object') {
349
+ return target;
350
+ }
351
+ if (proxyCache.has(target)) {
352
+ return proxyCache.get(target);
353
+ }
354
+
355
+ const proxy = new Proxy(target, {
356
+ get(obj, prop, receiver) {
357
+ if (prop === '__isWebspressoState') return true;
358
+ if (prop === '__raw') return obj;
359
+ if (typeof prop === 'symbol') {
360
+ return Reflect.get(obj, prop, receiver);
361
+ }
362
+
363
+ // Allow accessing tasks on root state
364
+ if (!basePath && prop === 'tasks') {
365
+ const ctx = getContext();
366
+ return ctx && ctx.tasks ? ctx.tasks : undefined;
367
+ }
368
+
369
+ // Check if accessing a root-level computed property
370
+ if (!basePath && computedDefs && Object.prototype.hasOwnProperty.call(computedDefs, prop)) {
371
+ engine.signals.value(signalKeyFor(String(prop)));
372
+ return computedValues.get(prop);
373
+ }
374
+
375
+ const path = basePath ? `${basePath}.${String(prop)}` : String(prop);
376
+ // Track signal dependency in Datastar signals store
377
+ engine.signals.value(signalKeyFor(path));
378
+ // If accessing array length or methods, also subscribe to the array path itself
379
+ if (Array.isArray(obj) && basePath) {
380
+ engine.signals.value(signalKeyFor(basePath));
381
+ }
382
+ const val = Reflect.get(obj, prop, receiver);
383
+ if (val !== null && typeof val === 'object') {
384
+ return wrapReactive(val, path);
385
+ }
386
+ return val;
387
+ },
388
+
389
+ set(obj, prop, nextValue, receiver) {
390
+ if (typeof prop === 'symbol') {
391
+ return Reflect.set(obj, prop, nextValue, receiver);
392
+ }
393
+ if (isEvaluatingComputed) {
394
+ throw new Error(
395
+ `Cannot mutate state property "${String(prop)}" inside computed property "${activeComputedKey}". Computed getters must be side-effect free.`
396
+ );
397
+ }
398
+ if (!basePath && computedDefs && Object.prototype.hasOwnProperty.call(computedDefs, prop)) {
399
+ throw new TypeError(
400
+ `Cannot assign to read-only computed property "${String(prop)}".`
401
+ );
402
+ }
403
+ if (!isConnected()) {
404
+ if (debug && typeof debug.trackDiscardedResponse === 'function') {
405
+ debug.trackDiscardedResponse({
406
+ source: 'controller-state',
407
+ instanceId,
408
+ key: String(prop),
409
+ reason: 'instance-disconnected',
410
+ });
411
+ }
412
+ return true;
413
+ }
414
+ const rawNext = nextValue && nextValue.__raw ? nextValue.__raw : nextValue;
415
+ const prevValue = obj[prop];
416
+ const path = basePath ? `${basePath}.${String(prop)}` : String(prop);
417
+
418
+ if (Object.is(prevValue, rawNext) && !Array.isArray(obj)) {
419
+ return true;
420
+ }
421
+
422
+ Reflect.set(obj, prop, rawNext, receiver);
423
+
424
+ // Seed nested keys if setting an object
425
+ if (rawNext !== null && typeof rawNext === 'object' && !Array.isArray(rawNext)) {
426
+ for (const [k, v] of Object.entries(rawNext)) {
427
+ engine.signals.setValue(signalKeyFor(`${path}.${k}`), v);
428
+ }
429
+ }
430
+ engine.signals.setValue(signalKeyFor(path), rawNext);
431
+ if (basePath) {
432
+ engine.signals.setValue(signalKeyFor(basePath), Array.isArray(obj) ? [...obj] : { ...obj });
433
+ }
434
+ return true;
435
+ },
436
+
437
+ deleteProperty(obj, prop) {
438
+ if (isEvaluatingComputed) {
439
+ throw new Error(
440
+ `Cannot delete state property "${String(prop)}" inside computed property "${activeComputedKey}".`
441
+ );
442
+ }
443
+ if (!basePath && computedDefs && Object.prototype.hasOwnProperty.call(computedDefs, prop)) {
444
+ throw new TypeError(
445
+ `Cannot delete read-only computed property "${String(prop)}".`
446
+ );
447
+ }
448
+ if (!isConnected()) return true;
449
+ const path = basePath ? `${basePath}.${String(prop)}` : String(prop);
450
+ const res = Reflect.deleteProperty(obj, prop);
451
+ engine.signals.remove(signalKeyFor(path));
452
+ return res;
453
+ },
454
+ });
455
+
456
+ proxyCache.set(target, proxy);
457
+ return proxy;
458
+ }
459
+
460
+ // Initialize signals from initialState
461
+ if (initialState && typeof initialState === 'object') {
462
+ for (const [key, val] of Object.entries(initialState)) {
463
+ const cloned =
464
+ val !== null && typeof val === 'object'
465
+ ? Array.isArray(val)
466
+ ? [...val]
467
+ : { ...val }
468
+ : val;
469
+ rawStore[key] = cloned;
470
+ engine.signals.setValue(signalKeyFor(key), cloned);
471
+ if (cloned !== null && typeof cloned === 'object' && !Array.isArray(cloned)) {
472
+ for (const [subKey, subVal] of Object.entries(cloned)) {
473
+ engine.signals.setValue(signalKeyFor(`${key}.${subKey}`), subVal);
474
+ }
475
+ }
476
+ }
477
+ }
478
+
479
+ const stateProxy = wrapReactive(rawStore, '');
480
+
481
+ // Initialize and track computed properties
482
+ if (computedDefs && typeof computedDefs === 'object') {
483
+ for (const [compKey, getter] of Object.entries(computedDefs)) {
484
+ if (typeof getter !== 'function') continue;
485
+
486
+ // Seed initial signal slot
487
+ engine.signals.setValue(signalKeyFor(compKey), undefined);
488
+
489
+ const stopEffect = engine.effect(() => {
490
+ if (!isConnected()) return;
491
+ isEvaluatingComputed = true;
492
+ activeComputedKey = compKey;
493
+ try {
494
+ const ctx = typeof getContext === 'function' ? getContext() : null;
495
+ const computedVal = getter({
496
+ state: stateProxy,
497
+ tasks: (ctx && ctx.tasks) || {},
498
+ el: (ctx && ctx.el) || null,
499
+ });
500
+ computedValues.set(compKey, computedVal);
501
+ engine.signals.setValue(signalKeyFor(compKey), computedVal);
502
+ } finally {
503
+ isEvaluatingComputed = false;
504
+ activeComputedKey = null;
505
+ }
506
+ });
507
+
508
+ computedDisposers.push(stopEffect);
509
+ }
510
+ }
511
+
512
+ return {
513
+ state: stateProxy,
514
+ dispose() {
515
+ for (let i = 0; i < computedDisposers.length; i++) {
516
+ try {
517
+ computedDisposers[i]();
518
+ } catch (_e) {
519
+ // Ignore
520
+ }
521
+ }
522
+ computedDisposers.length = 0;
523
+ engine.signals.remove(namespace);
524
+ },
525
+ snapshot() {
526
+ return JSON.parse(JSON.stringify(rawStore));
527
+ },
528
+ };
529
+ }
530
+
531
+ // ---------------------------------------------------------------------------
532
+ // Ownership Check & In-Place DOM Morphing (Focus, Form Draft & Controller Preservation)
533
+ // ---------------------------------------------------------------------------
534
+
535
+ const CLIENT_OWNED_TEXT_ATTR = 'data-w-text';
536
+ const CLIENT_OWNED_SHOW_ATTR = 'data-w-show';
537
+ const CLIENT_OWNED_DISABLED_ATTR = 'data-w-disabled';
538
+ const CLIENT_OWNED_MODEL_ATTR = 'data-w-model';
539
+
540
+ /**
541
+ * Determine whether a node has client bindings owning specific DOM properties.
542
+ */
543
+ function getClientOwnership(el) {
544
+ if (!el || typeof el.hasAttribute !== 'function') {
545
+ return { text: false, show: false, disabled: false, model: false };
546
+ }
547
+ return {
548
+ text: el.hasAttribute(CLIENT_OWNED_TEXT_ATTR),
549
+ show: el.hasAttribute(CLIENT_OWNED_SHOW_ATTR),
550
+ disabled: el.hasAttribute(CLIENT_OWNED_DISABLED_ATTR),
551
+ model: el.hasAttribute(CLIENT_OWNED_MODEL_ATTR),
552
+ };
553
+ }
554
+
555
+ /**
556
+ * Check if a form element currently holds unsaved draft values.
557
+ */
558
+ function isFormDirtyOrPreserved(formEl) {
559
+ if (!formEl) return false;
560
+ if (formEl.hasAttribute && formEl.hasAttribute('data-w-preserve-draft')) return true;
561
+ if (formEl.__wFormHandle && formEl.__wFormHandle.dirty) return true;
562
+ const controls = formEl.querySelectorAll ? formEl.querySelectorAll('input, textarea, select') : [];
563
+ for (let i = 0; i < controls.length; i++) {
564
+ const ctrl = controls[i];
565
+ const type = (ctrl.type || '').toLowerCase();
566
+ if (type === 'submit' || type === 'button' || type === 'reset' || type === 'hidden') continue;
567
+ if (type === 'checkbox' || type === 'radio') {
568
+ if (ctrl.checked !== ctrl.defaultChecked) return true;
569
+ } else if (ctrl.tagName === 'SELECT') {
570
+ const options = ctrl.options || [];
571
+ for (let j = 0; j < options.length; j++) {
572
+ if (options[j].selected !== options[j].defaultSelected) return true;
573
+ }
574
+ } else if (ctrl.value !== ctrl.defaultValue) {
575
+ return true;
576
+ }
577
+ }
578
+ return false;
579
+ }
580
+
581
+ /**
582
+ * Compute a matching key for DOM morphing so keyed items, fragments, forms,
583
+ * and controller roots preserve their identity across refreshes.
584
+ */
585
+ function getMorphNodeKey(node) {
586
+ if (!node || node.nodeType !== 1) return null;
587
+ if (node.id) return `id:${node.id}`;
588
+ const wKey = node.getAttribute('data-w-key');
589
+ if (wKey) return `wkey:${wKey}`;
590
+ const fragId = node.getAttribute('data-w-fragment-id');
591
+ if (fragId) return `frag:${fragId}`;
592
+ const formName = node.getAttribute('data-w-form');
593
+ if (formName) return `form:${formName}:${node.getAttribute('action') || ''}`;
594
+ const ctrlName = node.getAttribute('data-w-controller');
595
+ if (ctrlName) {
596
+ const instKey = node.getAttribute('data-w-id') || '';
597
+ if (instKey) return `ctrl:${ctrlName}:${instKey}`;
598
+ }
599
+ const nameAttr = node.getAttribute('name');
600
+ if (nameAttr && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA' || node.tagName === 'SELECT')) {
601
+ return `input:${node.tagName}:${ node.getAttribute('type') || '' }:${nameAttr}`;
602
+ }
603
+ return null;
604
+ }
605
+
606
+ /**
607
+ * Sync attributes from `fromEl` onto `toEl` while respecting client-owned properties
608
+ * and preserving active focus / form draft states.
609
+ */
610
+ function syncElementAttributes(toEl, fromEl, ownership) {
611
+ const fromAttrs = fromEl.attributes;
612
+ const toAttrs = Array.from(toEl.attributes);
613
+
614
+ // Remove attributes no longer present on server HTML, except client-managed runtime state
615
+ for (let i = 0; i < toAttrs.length; i++) {
616
+ const attrName = toAttrs[i].name;
617
+ if (ownership.disabled && attrName === 'disabled') continue;
618
+ if (ownership.show && attrName === 'hidden') continue;
619
+ if (attrName.startsWith('data-w-bound-')) continue;
620
+ if (
621
+ attrName === 'data-w-fragment-input' ||
622
+ attrName === 'data-w-fragment-id' ||
623
+ attrName === 'data-w-fragment-page'
624
+ ) {
625
+ continue;
626
+ }
627
+ if (!fromEl.hasAttribute(attrName)) {
628
+ toEl.removeAttribute(attrName);
629
+ }
630
+ }
631
+
632
+ // Set updated attributes from server HTML
633
+ for (let i = 0; i < fromAttrs.length; i++) {
634
+ const attr = fromAttrs[i];
635
+ if (ownership.disabled && attr.name === 'disabled') continue;
636
+ if (ownership.show && attr.name === 'hidden') continue;
637
+ if (toEl.getAttribute(attr.name) !== attr.value) {
638
+ toEl.setAttribute(attr.name, attr.value);
639
+ }
640
+ }
641
+ }
642
+
643
+ /**
644
+ * Sync form control state without clobbering active focus, selection range,
645
+ * client `data-w-model`, or dirty form drafts.
646
+ */
647
+ function syncFormControlValue(toEl, fromEl, ownership, preserveDraft) {
648
+ if (ownership.model) return; // Owned by client data-w-model binding
649
+ const isFocused =
650
+ typeof document !== 'undefined' &&
651
+ document.activeElement &&
652
+ document.activeElement === toEl;
653
+
654
+ if (isFocused || preserveDraft) {
655
+ return;
656
+ }
657
+
658
+ const tag = toEl.tagName;
659
+ if (tag === 'INPUT') {
660
+ const type = (toEl.type || '').toLowerCase();
661
+ if (type === 'checkbox' || type === 'radio') {
662
+ toEl.checked = fromEl.checked;
663
+ toEl.defaultChecked = fromEl.defaultChecked;
664
+ } else if (type !== 'file') {
665
+ toEl.value = fromEl.value;
666
+ toEl.defaultValue = fromEl.defaultValue;
667
+ }
668
+ } else if (tag === 'TEXTAREA') {
669
+ toEl.value = fromEl.value;
670
+ toEl.defaultValue = fromEl.defaultValue;
671
+ } else if (tag === 'SELECT') {
672
+ toEl.value = fromEl.value;
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Morph `toNode` in-place to match `fromNode` while preserving:
678
+ * - Active element focus and selection cursor
679
+ * - Dirty `<form>` drafts (`data-w-form` / user-edited inputs)
680
+ * - Existing `[data-w-controller]` instances and their local state on preserved roots
681
+ * - Client-owned bindings (`data-w-text`, `data-w-show`, `data-w-disabled`, `data-w-model`)
682
+ *
683
+ * @param {Element} toEl
684
+ * @param {Element} fromEl
685
+ * @param {object} [ctx]
686
+ * @param {boolean} [ctx.insideDirtyForm=false]
687
+ * @param {(removedEl: Element) => void} [ctx.onBeforeNodeRemove]
688
+ * @param {(addedEl: Element) => void} [ctx.onNodeAdded]
689
+ */
690
+ function morphDomTrees(toEl, fromEl, ctx = {}) {
691
+ if (!toEl || !fromEl) return toEl;
692
+
693
+ const ownership = getClientOwnership(toEl);
694
+ const isForm = toEl.tagName === 'FORM';
695
+ const insideDirtyForm = Boolean(ctx.insideDirtyForm || (isForm && isFormDirtyOrPreserved(toEl)));
696
+
697
+ syncElementAttributes(toEl, fromEl, ownership);
698
+
699
+ if (toEl.tagName === 'INPUT' || toEl.tagName === 'TEXTAREA' || toEl.tagName === 'SELECT') {
700
+ syncFormControlValue(toEl, fromEl, ownership, insideDirtyForm);
701
+ if (toEl.tagName !== 'SELECT') {
702
+ return toEl;
703
+ }
704
+ }
705
+
706
+ // If `toEl` has `data-w-text`, client state owns its textContent; do not overwrite from server HTML
707
+ if (ownership.text) {
708
+ return toEl;
709
+ }
710
+
711
+ // Morph childNodes
712
+ const existingChildren = Array.from(toEl.childNodes);
713
+ const newChildren = Array.from(fromEl.childNodes);
714
+
715
+ // Index existing element children by key
716
+ const keyedExisting = new Map();
717
+ for (let i = 0; i < existingChildren.length; i++) {
718
+ const child = existingChildren[i];
719
+ const key = getMorphNodeKey(child);
720
+ if (key && !keyedExisting.has(key)) {
721
+ keyedExisting.set(key, child);
722
+ }
723
+ }
724
+
725
+ const usedExisting = new Set();
726
+ let unkeyedCursor = 0;
727
+
728
+ for (let i = 0; i < newChildren.length; i++) {
729
+ const newChild = newChildren[i];
730
+ let match = null;
731
+
732
+ if (newChild.nodeType === 1) {
733
+ const key = getMorphNodeKey(newChild);
734
+ if (key && keyedExisting.has(key)) {
735
+ const candidate = keyedExisting.get(key);
736
+ if (!usedExisting.has(candidate) && candidate.tagName === newChild.tagName) {
737
+ match = candidate;
738
+ }
739
+ }
740
+
741
+ if (!match) {
742
+ // Look ahead for a compatible unkeyed element with the same tagName and controller attribute
743
+ for (let j = unkeyedCursor; j < existingChildren.length; j++) {
744
+ const cand = existingChildren[j];
745
+ if (usedExisting.has(cand)) continue;
746
+ if (cand.nodeType === 1 && !getMorphNodeKey(cand)) {
747
+ const candCtrl = cand.getAttribute('data-w-controller') || '';
748
+ const newCtrl = newChild.getAttribute('data-w-controller') || '';
749
+ if (cand.tagName === newChild.tagName && candCtrl === newCtrl) {
750
+ match = cand;
751
+ unkeyedCursor = j + 1;
752
+ break;
753
+ }
754
+ }
755
+ }
756
+ }
757
+
758
+ if (match) {
759
+ usedExisting.add(match);
760
+ const currentAtPos = toEl.childNodes[i];
761
+ if (currentAtPos !== match) {
762
+ toEl.insertBefore(match, currentAtPos || null);
763
+ }
764
+ morphDomTrees(match, newChild, {
765
+ ...ctx,
766
+ insideDirtyForm,
767
+ });
768
+ } else {
769
+ const imported = toEl.ownerDocument
770
+ ? toEl.ownerDocument.importNode(newChild, true)
771
+ : newChild.cloneNode(true);
772
+ const currentAtPos = toEl.childNodes[i];
773
+ toEl.insertBefore(imported, currentAtPos || null);
774
+ if (typeof ctx.onNodeAdded === 'function') {
775
+ ctx.onNodeAdded(imported);
776
+ }
777
+ }
778
+ } else if (newChild.nodeType === 3 || newChild.nodeType === 8) {
779
+ // Text or Comment node
780
+ let matchedText = null;
781
+ for (let j = unkeyedCursor; j < existingChildren.length; j++) {
782
+ const cand = existingChildren[j];
783
+ if (usedExisting.has(cand)) continue;
784
+ if (cand.nodeType === newChild.nodeType) {
785
+ matchedText = cand;
786
+ unkeyedCursor = j + 1;
787
+ break;
788
+ }
789
+ }
790
+ if (matchedText) {
791
+ usedExisting.add(matchedText);
792
+ const currentAtPos = toEl.childNodes[i];
793
+ if (currentAtPos !== matchedText) {
794
+ toEl.insertBefore(matchedText, currentAtPos || null);
795
+ }
796
+ if (matchedText.nodeValue !== newChild.nodeValue) {
797
+ matchedText.nodeValue = newChild.nodeValue;
798
+ }
799
+ } else {
800
+ const clonedText = newChild.cloneNode(false);
801
+ const currentAtPos = toEl.childNodes[i];
802
+ toEl.insertBefore(clonedText, currentAtPos || null);
803
+ }
804
+ }
805
+ }
806
+
807
+ // Remove leftover existing children that were not matched
808
+ for (let i = 0; i < existingChildren.length; i++) {
809
+ const oldChild = existingChildren[i];
810
+ if (!usedExisting.has(oldChild) && oldChild.parentNode === toEl) {
811
+ if (oldChild.nodeType === 1 && typeof ctx.onBeforeNodeRemove === 'function') {
812
+ ctx.onBeforeNodeRemove(oldChild);
813
+ }
814
+ toEl.removeChild(oldChild);
815
+ }
816
+ }
817
+
818
+ return toEl;
819
+ }
820
+
821
+ /**
822
+ * Parse an HTML string into a temporary container and return its root Element.
823
+ *
824
+ * @param {string} html
825
+ * @param {Document} [doc]
826
+ * @returns {Element|null}
827
+ */
828
+ function parseHtmlFragment(html, doc) {
829
+ const targetDoc = doc || (typeof document !== 'undefined' ? document : null);
830
+ if (!targetDoc || typeof html !== 'string') return null;
831
+ const trimmed = html.trim();
832
+ if (!trimmed) return null;
833
+
834
+ const template = targetDoc.createElement('template');
835
+ template.innerHTML = trimmed;
836
+ if (template.content && template.content.firstElementChild) {
837
+ return template.content.firstElementChild;
838
+ }
839
+ // Fallback for environments where <template>.content is limited
840
+ const wrapper = targetDoc.createElement('div');
841
+ wrapper.innerHTML = trimmed;
842
+ return wrapper.firstElementChild;
843
+ }
844
+
845
+ // ---------------------------------------------------------------------------
846
+ // Datastar Adapter Factory
847
+ // ---------------------------------------------------------------------------
848
+
849
+ /**
850
+ * Create a Datastar adapter instance.
851
+ *
852
+ * @param {object} [options]
853
+ * @param {object} [options.datastar] - Optional explicit @starfederation/datastar module
854
+ * @param {object} [options.debug] - Optional client debugger
855
+ */
856
+ function createDatastarAdapter(options = {}) {
857
+ const externalDatastar = resolveExternalDatastar(options.datastar);
858
+ const fallbackEngine = createSignalsEngine();
859
+
860
+ let datastarInitCtx = null;
861
+
862
+ // If official @starfederation/datastar is present, capture its InitContext via a public AttributePlugin
863
+ if (externalDatastar && typeof externalDatastar.load === 'function') {
864
+ try {
865
+ externalDatastar.load({
866
+ type: externalDatastar.PluginType ? externalDatastar.PluginType.Attribute : PluginType.Attribute,
867
+ name: 'wBridge',
868
+ onGlobalInit(ctx) {
869
+ datastarInitCtx = ctx;
870
+ },
871
+ onLoad() {},
872
+ });
873
+ if (typeof externalDatastar.apply === 'function' && typeof document !== 'undefined' && document.body) {
874
+ externalDatastar.apply();
875
+ }
876
+ } catch (_err) {
877
+ datastarInitCtx = null;
878
+ }
879
+ }
880
+
881
+ const engine = {
882
+ get isExternalDatastar() {
883
+ return Boolean(datastarInitCtx);
884
+ },
885
+ get signals() {
886
+ return datastarInitCtx && datastarInitCtx.signals ? datastarInitCtx.signals : fallbackEngine.signals;
887
+ },
888
+ effect(fn) {
889
+ if (datastarInitCtx && typeof datastarInitCtx.effect === 'function') {
890
+ return datastarInitCtx.effect(fn);
891
+ }
892
+ return fallbackEngine.effect(fn);
893
+ },
894
+ };
895
+
896
+ /**
897
+ * Bind the V1 declarative attribute surface (`data-w-text`, `data-w-show`,
898
+ * `data-w-disabled`, `data-w-model`, `data-w-on*`) within a controller's DOM scope.
899
+ *
900
+ * Enforces:
901
+ * - Scoped strictly to `rootEl` (never crosses into nested `[data-w-controller]` elements)
902
+ * - Single binding per element/attribute per instance (`WeakMap` guard)
903
+ * - All effects & listeners returned in a single cleanup function
904
+ */
905
+ const boundElementsByInstance = new Map(); // instanceId -> WeakSet<Element>
906
+
907
+ function isWithinControllerScope(rootEl, candidateEl) {
908
+ if (candidateEl === rootEl) return true;
909
+ let cur = candidateEl.parentElement;
910
+ while (cur && cur !== rootEl) {
911
+ if (cur.hasAttribute && cur.hasAttribute('data-w-controller')) {
912
+ return false;
913
+ }
914
+ cur = cur.parentElement;
915
+ }
916
+ return cur === rootEl;
917
+ }
918
+
919
+ function collectScopedElements(rootEl) {
920
+ const result = [rootEl];
921
+ if (!rootEl || typeof rootEl.querySelectorAll !== 'function') return result;
922
+ const all = rootEl.querySelectorAll('*');
923
+ for (let i = 0; i < all.length; i++) {
924
+ if (isWithinControllerScope(rootEl, all[i])) {
925
+ result.push(all[i]);
926
+ }
927
+ }
928
+ return result;
929
+ }
930
+
931
+ /**
932
+ * Parse `data-w-on` or `data-w-on:<event>` attributes on an element.
933
+ * Supports:
934
+ * - `data-w-on:click="save"`
935
+ * - `data-w-on:submit.prevent="save"`
936
+ * - `data-w-on="click->save; keydown->onKey"`
937
+ * - `data-w-click="save"` (shorthand for click)
938
+ */
939
+ function extractEventBindings(el) {
940
+ const bindings = [];
941
+ if (!el || !el.attributes) return bindings;
942
+
943
+ for (let i = 0; i < el.attributes.length; i++) {
944
+ const attr = el.attributes[i];
945
+ const name = attr.name;
946
+ const val = (attr.value || '').trim();
947
+ if (!val) continue;
948
+
949
+ if (name.startsWith('data-w-on:')) {
950
+ const rawSpec = name.slice('data-w-on:'.length);
951
+ const parts = rawSpec.split('.');
952
+ const eventName = parts[0];
953
+ const modifiers = new Set(parts.slice(1));
954
+ if (eventName) {
955
+ bindings.push({ eventName, actionName: val, modifiers });
956
+ }
957
+ } else if (name === 'data-w-on') {
958
+ const clauses = val.split(';').map((s) => s.trim()).filter(Boolean);
959
+ for (const clause of clauses) {
960
+ const arrowIdx = clause.indexOf('->');
961
+ if (arrowIdx > 0) {
962
+ const rawEvent = clause.slice(0, arrowIdx).trim();
963
+ const actionName = clause.slice(arrowIdx + 2).trim();
964
+ const parts = rawEvent.split('.');
965
+ const eventName = parts[0];
966
+ const modifiers = new Set(parts.slice(1));
967
+ if (eventName && actionName) {
968
+ bindings.push({ eventName, actionName, modifiers });
969
+ }
970
+ }
971
+ }
972
+ } else if (name === 'data-w-click') {
973
+ bindings.push({ eventName: 'click', actionName: val, modifiers: new Set() });
974
+ }
975
+ }
976
+
977
+ return bindings;
978
+ }
979
+
980
+ /**
981
+ * Bind V1 declarative attributes inside `rootEl` for a controller instance.
982
+ */
983
+ function bindControllerDom({ instanceId, rootEl, state, invokeAction, isConnected }) {
984
+ if (!boundElementsByInstance.has(instanceId)) {
985
+ boundElementsByInstance.set(instanceId, new WeakSet());
986
+ }
987
+ const boundSet = boundElementsByInstance.get(instanceId);
988
+ const disposers = [];
989
+
990
+ const elements = collectScopedElements(rootEl);
991
+
992
+ for (let i = 0; i < elements.length; i++) {
993
+ const el = elements[i];
994
+ if (boundSet.has(el)) continue;
995
+ boundSet.add(el);
996
+
997
+ // 1. data-w-text
998
+ if (el.hasAttribute('data-w-text')) {
999
+ const expr = el.getAttribute('data-w-text');
1000
+ const stop = engine.effect(() => {
1001
+ if (!isConnected()) return;
1002
+ const val = evaluateStateExpression(state, expr);
1003
+ const text = val === null || val === undefined ? '' : String(val);
1004
+ if (el.textContent !== text) {
1005
+ el.textContent = text;
1006
+ }
1007
+ });
1008
+ disposers.push(stop);
1009
+ }
1010
+
1011
+ // 2. data-w-show
1012
+ if (el.hasAttribute('data-w-show')) {
1013
+ const expr = el.getAttribute('data-w-show');
1014
+ const initialDisplay = el.style && el.style.display && el.style.display !== 'none' ? el.style.display : '';
1015
+ const stop = engine.effect(() => {
1016
+ if (!isConnected()) return;
1017
+ const visible = Boolean(evaluateStateExpression(state, expr));
1018
+ if (visible) {
1019
+ el.removeAttribute('hidden');
1020
+ if (el.style && el.style.display === 'none') {
1021
+ el.style.display = initialDisplay;
1022
+ }
1023
+ } else {
1024
+ el.setAttribute('hidden', '');
1025
+ if (el.style) {
1026
+ el.style.display = 'none';
1027
+ }
1028
+ }
1029
+ });
1030
+ disposers.push(stop);
1031
+ }
1032
+
1033
+ // 3. data-w-disabled
1034
+ if (el.hasAttribute('data-w-disabled')) {
1035
+ const expr = el.getAttribute('data-w-disabled');
1036
+ const stop = engine.effect(() => {
1037
+ if (!isConnected()) return;
1038
+ const disabled = Boolean(evaluateStateExpression(state, expr));
1039
+ if ('disabled' in el) {
1040
+ el.disabled = disabled;
1041
+ }
1042
+ if (disabled) {
1043
+ el.setAttribute('disabled', '');
1044
+ el.setAttribute('aria-disabled', 'true');
1045
+ } else {
1046
+ el.removeAttribute('disabled');
1047
+ el.removeAttribute('aria-disabled');
1048
+ }
1049
+ });
1050
+ disposers.push(stop);
1051
+ }
1052
+
1053
+ // 4. data-w-model (two-way binding between input/select/textarea and controller state)
1054
+ if (el.hasAttribute('data-w-model')) {
1055
+ const modelPath = (el.getAttribute('data-w-model') || '').trim();
1056
+ const type = (el.type || '').toLowerCase();
1057
+
1058
+ // Security & DOM standard: Never bind file inputs to programmatic value bindings
1059
+ if (modelPath && type !== 'file') {
1060
+ // Binding initialization: determine value ownership
1061
+ // If state defines the value (even if null, false, 0, or empty string), state owns it.
1062
+ // Only if state is undefined, seed from the DOM control's initial value.
1063
+ const initialStateVal = getByPath(state, modelPath);
1064
+ if (initialStateVal === undefined) {
1065
+ if (type === 'checkbox') {
1066
+ setByPath(state, modelPath, Boolean(el.checked));
1067
+ } else if (type === 'number' || type === 'range') {
1068
+ setByPath(state, modelPath, el.value === '' ? null : (Number.isNaN(Number(el.value)) ? null : Number(el.value)));
1069
+ } else if (el.tagName === 'SELECT' && el.multiple) {
1070
+ const selected = [];
1071
+ const opts = el.options || [];
1072
+ for (let j = 0; j < opts.length; j++) {
1073
+ if (opts[j].selected) selected.push(opts[j].value);
1074
+ }
1075
+ setByPath(state, modelPath, selected);
1076
+ } else {
1077
+ setByPath(state, modelPath, el.value !== undefined ? el.value : '');
1078
+ }
1079
+ }
1080
+
1081
+ // Track IME composition state so typing during composition doesn't jump or corrupt input
1082
+ let isComposing = false;
1083
+ const onCompositionStart = () => {
1084
+ isComposing = true;
1085
+ };
1086
+ const onCompositionEnd = () => {
1087
+ isComposing = false;
1088
+ onModelInput();
1089
+ };
1090
+ el.addEventListener('compositionstart', onCompositionStart);
1091
+ el.addEventListener('compositionend', onCompositionEnd);
1092
+ disposers.push(() => {
1093
+ try {
1094
+ el.removeEventListener('compositionstart', onCompositionStart);
1095
+ el.removeEventListener('compositionend', onCompositionEnd);
1096
+ } catch (_e) {}
1097
+ });
1098
+
1099
+ // State -> DOM effect (synchronizes changes in state to the DOM control)
1100
+ const stopModelEffect = engine.effect(() => {
1101
+ if (!isConnected() || isComposing) return;
1102
+ const currentVal = getByPath(state, modelPath);
1103
+
1104
+ if (type === 'checkbox') {
1105
+ if (Array.isArray(currentVal)) {
1106
+ el.checked = currentVal.map(String).includes(String(el.value));
1107
+ } else {
1108
+ el.checked = Boolean(currentVal);
1109
+ }
1110
+ } else if (type === 'radio') {
1111
+ el.checked = String(currentVal) === String(el.value);
1112
+ } else if (el.tagName === 'SELECT' && el.multiple) {
1113
+ const arr = Array.isArray(currentVal) ? currentVal.map(String) : [];
1114
+ const opts = el.options || [];
1115
+ for (let j = 0; j < opts.length; j++) {
1116
+ opts[j].selected = arr.includes(String(opts[j].value));
1117
+ }
1118
+ } else {
1119
+ const formatted = currentVal === null || currentVal === undefined ? '' : String(currentVal);
1120
+ if (el.value !== formatted) {
1121
+ el.value = formatted;
1122
+ }
1123
+ }
1124
+ });
1125
+ disposers.push(stopModelEffect);
1126
+
1127
+ // DOM -> State listener (synchronizes user interactions to state)
1128
+ const evtType =
1129
+ type === 'checkbox' || type === 'radio' || el.tagName === 'SELECT'
1130
+ ? 'change'
1131
+ : 'input';
1132
+
1133
+ const onModelInput = () => {
1134
+ if (!isConnected() || isComposing) return;
1135
+
1136
+ if (type === 'checkbox') {
1137
+ const cur = getByPath(state, modelPath);
1138
+ if (Array.isArray(cur)) {
1139
+ const next = el.checked
1140
+ ? Array.from(new Set([...cur, el.value]))
1141
+ : cur.filter((item) => String(item) !== String(el.value));
1142
+ setByPath(state, modelPath, next);
1143
+ } else {
1144
+ setByPath(state, modelPath, Boolean(el.checked));
1145
+ }
1146
+ } else if (type === 'radio') {
1147
+ if (el.checked) {
1148
+ setByPath(state, modelPath, el.value);
1149
+ }
1150
+ } else if (type === 'number' || type === 'range') {
1151
+ // Explicit empty number behavior: empty string converts to null, never 0!
1152
+ setByPath(state, modelPath, el.value === '' ? null : (Number.isNaN(Number(el.value)) ? null : Number(el.value)));
1153
+ } else if (el.tagName === 'SELECT' && el.multiple) {
1154
+ const selected = [];
1155
+ const opts = el.options || [];
1156
+ for (let j = 0; j < opts.length; j++) {
1157
+ if (opts[j].selected) selected.push(opts[j].value);
1158
+ }
1159
+ setByPath(state, modelPath, selected);
1160
+ } else {
1161
+ setByPath(state, modelPath, el.value);
1162
+ }
1163
+ };
1164
+
1165
+ el.addEventListener(evtType, onModelInput);
1166
+ disposers.push(() => el.removeEventListener(evtType, onModelInput));
1167
+ }
1168
+ }
1169
+
1170
+ // 5. Event bindings (data-w-on:<event>, data-w-on, data-w-click)
1171
+ const eventBindings = extractEventBindings(el);
1172
+ for (const binding of eventBindings) {
1173
+ const listener = (event) => {
1174
+ if (!isConnected()) return;
1175
+ if (binding.modifiers.has('prevent')) event.preventDefault();
1176
+ if (binding.modifiers.has('stop')) event.stopPropagation();
1177
+ invokeAction(binding.actionName, event, el);
1178
+ };
1179
+ el.addEventListener(binding.eventName, listener);
1180
+ disposers.push(() => el.removeEventListener(binding.eventName, listener));
1181
+ }
1182
+ }
1183
+
1184
+ return function unbindInstanceDom() {
1185
+ for (let i = 0; i < disposers.length; i++) {
1186
+ try {
1187
+ disposers[i]();
1188
+ } catch (_err) {
1189
+ // Ignore individual unbind errors
1190
+ }
1191
+ }
1192
+ };
1193
+ }
1194
+
1195
+ /**
1196
+ * Morph a fragment element in place using the Datastar-compatible morph engine.
1197
+ */
1198
+ function patchFragmentElement(targetEl, htmlString, lifecycleCallbacks = {}) {
1199
+ if (!targetEl || typeof htmlString !== 'string') return targetEl;
1200
+ const parsed = parseHtmlFragment(htmlString, targetEl.ownerDocument);
1201
+ if (!parsed) return targetEl;
1202
+
1203
+ const morphed = morphDomTrees(targetEl, parsed, {
1204
+ onBeforeNodeRemove: lifecycleCallbacks.onBeforeNodeRemove,
1205
+ onNodeAdded: lifecycleCallbacks.onNodeAdded,
1206
+ });
1207
+
1208
+ // If external @starfederation/datastar is active, notify apply() on updated subtree
1209
+ if (externalDatastar && typeof externalDatastar.apply === 'function') {
1210
+ try {
1211
+ externalDatastar.apply();
1212
+ } catch (_err) {
1213
+ // Ignore
1214
+ }
1215
+ }
1216
+
1217
+ return morphed;
1218
+ }
1219
+
1220
+ return {
1221
+ PluginType,
1222
+ Requirement,
1223
+ DATASTAR_SIGNAL_EVENT,
1224
+ DATASTAR_SSE_EVENT,
1225
+ engine,
1226
+ createIsolatedControllerState: (instanceId, initialState, isConnected, debug, computedDefs, getContext) =>
1227
+ createIsolatedControllerState(engine, instanceId, initialState, isConnected, debug, computedDefs, getContext),
1228
+ bindControllerDom,
1229
+ patchFragmentElement,
1230
+ patchElements: patchFragmentElement,
1231
+ morphDomTrees,
1232
+ parseHtmlFragment,
1233
+ evaluateStateExpression,
1234
+ getByPath,
1235
+ setByPath,
1236
+ isWithinControllerScope,
1237
+ collectScopedElements,
1238
+ };
1239
+ }
1240
+
1241
+ module.exports = {
1242
+ PluginType,
1243
+ Requirement,
1244
+ DATASTAR_SIGNAL_EVENT,
1245
+ DATASTAR_SSE_EVENT,
1246
+ createDatastarAdapter,
1247
+ createSignalsEngine,
1248
+ evaluateStateExpression,
1249
+ getByPath,
1250
+ setByPath,
1251
+ morphDomTrees,
1252
+ parseHtmlFragment,
1253
+ };
1254
+