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,1021 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Native HTML Form Layer & Typed Form Handle
5
+ *
6
+ * Principles:
7
+ * - Built on native HTML <form action="/api/..." method="post" data-w-form="name"> semantics
8
+ * - Zero client JS required for standard form submission, validation error display, and fragment invalidation
9
+ * - Explicit, deterministic form-to-payload conversion rules
10
+ * - Starts with native constraint validation (`form.reportValidity()`); server validation remains authoritative
11
+ * - Accessible field error binding (`aria-invalid`, `aria-describedby`) and focus on first invalid field
12
+ * - Separation of `reset()` (restores initial default values) vs `clear()` (empties all controls)
13
+ * - Mutation success vs refresh failure separation: a refresh failure never puts a succeeded form into validation error state
14
+ */
15
+
16
+ let errorIdSeq = 0;
17
+
18
+ /**
19
+ * Check if a form control is disabled (either directly or via an ancestor <fieldset disabled>).
20
+ * Note: Per HTML spec, controls inside the first <legend> of a disabled <fieldset> remain enabled.
21
+ *
22
+ * @param {Element} el
23
+ * @returns {boolean}
24
+ */
25
+ function isControlDisabled(el) {
26
+ if (!el) return true;
27
+ if (el.disabled) return true;
28
+ let parent = el.parentElement;
29
+ while (parent) {
30
+ if (parent.tagName === 'FIELDSET' && parent.disabled) {
31
+ // Check if el is inside the first <legend> child of this fieldset
32
+ let firstLegend = null;
33
+ for (let i = 0; i < parent.children.length; i++) {
34
+ if (parent.children[i].tagName === 'LEGEND') {
35
+ firstLegend = parent.children[i];
36
+ break;
37
+ }
38
+ }
39
+ if (!firstLegend || !firstLegend.contains(el)) {
40
+ return true;
41
+ }
42
+ }
43
+ parent = parent.parentElement;
44
+ }
45
+ return false;
46
+ }
47
+
48
+ /**
49
+ * Coerce a single raw string value according to control type and `data-w-*` hints.
50
+ *
51
+ * @param {Element} el
52
+ * @param {string} rawValue
53
+ * @returns {unknown}
54
+ */
55
+ function coerceScalarControlValue(el, rawValue) {
56
+ const inputType = ((el.getAttribute && el.getAttribute('type')) || el.type || 'text').toLowerCase();
57
+ const dataType = ((el.getAttribute && el.getAttribute('data-w-type')) || '').toLowerCase();
58
+ const emptyMode = ((el.getAttribute && el.getAttribute('data-w-empty')) || '').toLowerCase();
59
+
60
+ if (rawValue === '') {
61
+ if (emptyMode === 'null') return null;
62
+ if (emptyMode === 'undefined' || emptyMode === 'omit') return undefined;
63
+ if (inputType === 'number' || inputType === 'range' || dataType === 'number') {
64
+ return null;
65
+ }
66
+ return '';
67
+ }
68
+
69
+ if (inputType === 'number' || inputType === 'range' || dataType === 'number') {
70
+ const num = Number(rawValue);
71
+ return Number.isNaN(num) ? rawValue : num;
72
+ }
73
+
74
+ if (dataType === 'boolean') {
75
+ if (rawValue === 'true' || rawValue === '1' || rawValue === 'on') return true;
76
+ if (rawValue === 'false' || rawValue === '0' || rawValue === 'off') return false;
77
+ return Boolean(rawValue);
78
+ }
79
+
80
+ return rawValue;
81
+ }
82
+
83
+ /**
84
+ * Parse a `<form>` element into a structured payload and transport descriptor.
85
+ *
86
+ * Explicit Coercion Rules:
87
+ * 1. `disabled` controls (including inside disabled `<fieldset>`) are excluded.
88
+ * 2. `submitter`: if a submit button with `name` triggered the submit and is not disabled, its `name`/`value` is included.
89
+ * 3. `checkbox`:
90
+ * - Single checkbox for a given `name`:
91
+ * - Boolean checkbox (no custom `value` attribute, or `value="true"|"on"`, or `data-w-type="boolean"`): `true` when checked, `false` when unchecked.
92
+ * - Custom value checkbox (e.g. `value="yes"`): `"yes"` when checked, `null` (or `data-w-unchecked` value) when unchecked.
93
+ * - Multiple checkboxes sharing the same `name` (or `name="tags[]"`): `Array` of checked values (`[]` when none checked).
94
+ * 4. `number` / `range`: coerced to `number` (`null` when empty, or `undefined` with `data-w-empty="undefined"`).
95
+ * 5. `empty string`: preserved as `""` for text controls unless `data-w-empty="null|undefined"` is specified.
96
+ * 6. `repeated field names`: collected into an `Array` in DOM order. Trailing `[]` in `name="tags[]"` is normalized to `tags`.
97
+ * 7. `select[multiple]`: always returns an `Array` of selected option values (`[]` when none selected).
98
+ * 8. `file`:
99
+ * - Empty file input (`files.length === 0` or single 0-byte unnamed file): omitted (`undefined`).
100
+ * - `input[ type="file" multiple ]`: `File[]`.
101
+ * - Single `input[type="file"]`: `File`.
102
+ * - When any non-empty `File` is present or `form.enctype === 'multipart/form-data'`, `isMultipart` is `true` and `formData` is populated.
103
+ *
104
+ * @param {HTMLFormElement} formEl
105
+ * @param {HTMLElement|null} [submitter]
106
+ * @returns {{ data: Record<string, unknown>, formData: FormData|null, isMultipart: boolean }}
107
+ */
108
+ function parseFormElement(formEl, submitterOrOptions = null) {
109
+ if (!formEl || typeof formEl.querySelectorAll !== 'function') {
110
+ return { data: {}, values: {}, formData: null, isMultipart: false };
111
+ }
112
+
113
+ const submitter =
114
+ submitterOrOptions &&
115
+ typeof submitterOrOptions === 'object' &&
116
+ !submitterOrOptions.nodeType &&
117
+ !('tagName' in submitterOrOptions) &&
118
+ 'submitter' in submitterOrOptions
119
+ ? submitterOrOptions.submitter
120
+ : submitterOrOptions;
121
+
122
+ const rawControls = Array.from(
123
+ formEl.querySelectorAll('input, select, textarea')
124
+ );
125
+
126
+ // Filter out disabled controls and button/submit/reset inputs (handled via submitter)
127
+ const controls = rawControls.filter((el) => {
128
+ if (isControlDisabled(el)) return false;
129
+ const rawName = el.getAttribute('name');
130
+ if (!rawName || !rawName.trim()) return false;
131
+ const type = (el.type || '').toLowerCase();
132
+ if (type === 'submit' || type === 'button' || type === 'reset' || type === 'image') {
133
+ return false;
134
+ }
135
+ return true;
136
+ });
137
+
138
+ // Count occurrences per normalized field name and per checkbox/radio group
139
+ const nameCounts = new Map();
140
+ const checkboxCounts = new Map();
141
+ const radioNames = new Set();
142
+
143
+ function normalizeFieldName(rawName) {
144
+ const trimmed = String(rawName || '').trim();
145
+ return trimmed.endsWith('[]') ? trimmed.slice(0, -2) : trimmed;
146
+ }
147
+
148
+ for (const el of controls) {
149
+ const rawName = el.getAttribute('name').trim();
150
+ const normName = normalizeFieldName(rawName);
151
+ const isExplicitArray = rawName.endsWith('[]');
152
+ const type = (el.type || '').toLowerCase();
153
+
154
+ if (type === 'checkbox') {
155
+ checkboxCounts.set(normName, (checkboxCounts.get(normName) || 0) + (isExplicitArray ? 2 : 1));
156
+ } else if (type === 'radio') {
157
+ radioNames.add(normName);
158
+ } else {
159
+ nameCounts.set(normName, (nameCounts.get(normName) || 0) + (isExplicitArray ? 2 : 1));
160
+ }
161
+ }
162
+
163
+ const data = {};
164
+ let hasBinaryFile = false;
165
+
166
+ function appendValue(normName, val, forceArray) {
167
+ if (val === undefined) return;
168
+ if (forceArray) {
169
+ if (!Array.isArray(data[normName])) {
170
+ data[normName] = [];
171
+ }
172
+ data[normName].push(val);
173
+ } else if (normName in data) {
174
+ if (!Array.isArray(data[normName])) {
175
+ data[normName] = [data[normName]];
176
+ }
177
+ data[normName].push(val);
178
+ } else {
179
+ data[normName] = val;
180
+ }
181
+ }
182
+
183
+ // Initialize multi-checkbox groups to [] and radio groups to null if none checked
184
+ for (const [normName, count] of checkboxCounts.entries()) {
185
+ if (count > 1) {
186
+ data[normName] = [];
187
+ }
188
+ }
189
+ for (const normName of radioNames) {
190
+ if (!(normName in data)) {
191
+ data[normName] = null;
192
+ }
193
+ }
194
+
195
+ for (const el of controls) {
196
+ const rawName = el.getAttribute('name').trim();
197
+ const normName = normalizeFieldName(rawName);
198
+ const isExplicitArray = rawName.endsWith('[]');
199
+ const tag = el.tagName;
200
+ const type = (el.type || '').toLowerCase();
201
+
202
+ if (tag === 'SELECT' && el.multiple) {
203
+ const selectedValues = [];
204
+ const options = Array.from(el.options || []);
205
+ for (const opt of options) {
206
+ if (opt.selected && !opt.disabled) {
207
+ selectedValues.push(coerceScalarControlValue(el, opt.value));
208
+ }
209
+ }
210
+ data[normName] = selectedValues;
211
+ continue;
212
+ }
213
+
214
+ if (type === 'checkbox') {
215
+ const totalCheckboxes = checkboxCounts.get(normName) || 1;
216
+ if (totalCheckboxes > 1 || isExplicitArray) {
217
+ if (el.checked) {
218
+ const valAttr = el.getAttribute('value');
219
+ const rawVal = valAttr !== null ? valAttr : 'on';
220
+ data[normName].push(coerceScalarControlValue(el, rawVal));
221
+ }
222
+ } else {
223
+ const valAttr = el.getAttribute('value');
224
+ const dataType = (el.getAttribute('data-w-type') || '').toLowerCase();
225
+ const isBooleanCheckbox =
226
+ dataType === 'boolean' ||
227
+ valAttr === null ||
228
+ valAttr === '' ||
229
+ valAttr === 'on' ||
230
+ valAttr === 'true';
231
+
232
+ if (isBooleanCheckbox) {
233
+ data[normName] = Boolean(el.checked);
234
+ } else if (el.checked) {
235
+ data[normName] = coerceScalarControlValue(el, valAttr);
236
+ } else {
237
+ const uncheckedAttr = el.getAttribute('data-w-unchecked');
238
+ data[normName] = uncheckedAttr !== null ? uncheckedAttr : null;
239
+ }
240
+ }
241
+ continue;
242
+ }
243
+
244
+ if (type === 'radio') {
245
+ if (el.checked) {
246
+ data[normName] = coerceScalarControlValue(el, el.value);
247
+ }
248
+ continue;
249
+ }
250
+
251
+ if (type === 'file') {
252
+ const files = el.files ? Array.from(el.files).filter((f) => f && (f.size > 0 || f.name)) : [];
253
+ if (files.length > 0) {
254
+ hasBinaryFile = true;
255
+ if (el.multiple || isExplicitArray || (nameCounts.get(normName) || 0) > 1) {
256
+ appendValue(normName, files.length === 1 && !el.multiple ? files[0] : files, !el.multiple);
257
+ if (el.multiple) {
258
+ data[normName] = files;
259
+ }
260
+ } else {
261
+ data[normName] = files[0];
262
+ }
263
+ }
264
+ continue;
265
+ }
266
+
267
+ const totalForName = nameCounts.get(normName) || 1;
268
+ const coerced = coerceScalarControlValue(el, el.value !== undefined ? String(el.value) : '');
269
+ appendValue(normName, coerced, totalForName > 1 || isExplicitArray);
270
+ }
271
+
272
+ // Include submitter name/value if provided and enabled
273
+ if (submitter && !isControlDisabled(submitter)) {
274
+ const subName = submitter.getAttribute ? submitter.getAttribute('name') : submitter.name;
275
+ if (subName && String(subName).trim()) {
276
+ const normSubName = normalizeFieldName(subName);
277
+ const subValue =
278
+ (submitter.getAttribute && submitter.getAttribute('value')) ??
279
+ submitter.value ??
280
+ '';
281
+ data[normSubName] = coerceScalarControlValue(submitter, String(subValue));
282
+ }
283
+ }
284
+
285
+ const enctype = ((formEl.getAttribute && formEl.getAttribute('enctype')) || formEl.enctype || '').toLowerCase();
286
+ const isMultipart = hasBinaryFile || enctype === 'multipart/form-data';
287
+
288
+ let formData = null;
289
+ if (isMultipart && typeof FormData !== 'undefined') {
290
+ formData = new FormData();
291
+ for (const [key, val] of Object.entries(data)) {
292
+ if (val === undefined) continue;
293
+ if (Array.isArray(val)) {
294
+ for (const item of val) {
295
+ if (item === undefined) continue;
296
+ if (typeof Blob !== 'undefined' && item instanceof Blob) {
297
+ formData.append(key, item);
298
+ } else if (item !== null) {
299
+ formData.append(key, String(item));
300
+ }
301
+ }
302
+ } else if (typeof Blob !== 'undefined' && val instanceof Blob) {
303
+ formData.append(key, val);
304
+ } else if (val === null) {
305
+ formData.append(key, '');
306
+ } else {
307
+ formData.append(key, String(val));
308
+ }
309
+ }
310
+ }
311
+
312
+ return { data, values: data, formData, isMultipart };
313
+ }
314
+
315
+ /**
316
+ * Snapshot initial default values on a form so `reset()` restores them accurately
317
+ * and `dirty` can compare current values against initial state.
318
+ */
319
+ function captureInitialFormSnapshot(formEl) {
320
+ const snapshot = new Map();
321
+ if (!formEl || typeof formEl.querySelectorAll !== 'function') return snapshot;
322
+ const controls = formEl.querySelectorAll('input, select, textarea');
323
+ for (let i = 0; i < controls.length; i++) {
324
+ const el = controls[i];
325
+ const type = (el.type || '').toLowerCase();
326
+ if (type === 'checkbox' || type === 'radio') {
327
+ snapshot.set(el, { checked: Boolean(el.checked) });
328
+ } else if (el.tagName === 'SELECT') {
329
+ const selectedIndices = [];
330
+ const opts = el.options || [];
331
+ for (let j = 0; j < opts.length; j++) {
332
+ if (opts[j].selected) selectedIndices.push(j);
333
+ }
334
+ snapshot.set(el, { selectedIndices, value: el.value });
335
+ } else if (type !== 'file') {
336
+ snapshot.set(el, { value: el.value !== undefined ? String(el.value) : '' });
337
+ }
338
+ }
339
+ return snapshot;
340
+ }
341
+
342
+ /**
343
+ * Check if any control in `formEl` differs from its captured initial snapshot.
344
+ */
345
+ function computeFormDirty(formEl, initialSnapshot) {
346
+ if (!formEl || typeof formEl.querySelectorAll !== 'function') return false;
347
+ const controls = formEl.querySelectorAll('input, select, textarea');
348
+ for (let i = 0; i < controls.length; i++) {
349
+ const el = controls[i];
350
+ const type = (el.type || '').toLowerCase();
351
+ if (type === 'submit' || type === 'button' || type === 'reset' || type === 'hidden') continue;
352
+ const init = initialSnapshot.get(el);
353
+ if (type === 'checkbox' || type === 'radio') {
354
+ const expected = init ? init.checked : Boolean(el.defaultChecked);
355
+ if (Boolean(el.checked) !== expected) return true;
356
+ } else if (el.tagName === 'SELECT') {
357
+ if (init) {
358
+ if (el.value !== init.value) return true;
359
+ }
360
+ } else if (type === 'file') {
361
+ if (el.files && el.files.length > 0) return true;
362
+ } else {
363
+ const expected = init ? init.value : (el.defaultValue || '');
364
+ if (String(el.value || '') !== expected) return true;
365
+ }
366
+ }
367
+ return false;
368
+ }
369
+
370
+ /**
371
+ * Create a Form Handle managing a `<form>` element's lifecycle, validation errors,
372
+ * accessibility attributes, pending lock, and submission.
373
+ *
374
+ * @param {HTMLFormElement} formEl
375
+ * @param {object} options
376
+ * @param {object} options.api - Typed API client instance
377
+ * @param {object} [options.datastar] - Datastar adapter for reactive signals
378
+ * @param {(url: string) => void} [options.navigate] - Navigation handler for explicit redirects
379
+ * @param {object} [options.debug] - Client debugger
380
+ */
381
+ function createFormHandle(formEl, options = {}) {
382
+ if (formEl && formEl.__wFormHandle) {
383
+ return formEl.__wFormHandle;
384
+ }
385
+
386
+ const api = options.api;
387
+ const debug = options.debug || null;
388
+ const formName =
389
+ (formEl && formEl.getAttribute && formEl.getAttribute('data-w-form')) ||
390
+ (formEl && formEl.getAttribute && formEl.getAttribute('name')) ||
391
+ 'form';
392
+
393
+ let initialSnapshot = captureInitialFormSnapshot(formEl);
394
+ let pending = false;
395
+ let dirty = false;
396
+ let fieldErrors = {};
397
+ let formError = null;
398
+ let lastData = null;
399
+
400
+ const successListeners = new Set();
401
+ const errorListeners = new Set();
402
+ const stateListeners = new Set();
403
+
404
+ function notifyStateChange() {
405
+ for (const fn of stateListeners) {
406
+ try {
407
+ fn(handle);
408
+ } catch (_e) {
409
+ // Ignore
410
+ }
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Render field errors and form-level error into the DOM with accessible ARIA bindings.
416
+ * Optionally focuses the first invalid control.
417
+ */
418
+ function syncErrorsToDom(focusFirstInvalid = false) {
419
+ if (!formEl || typeof formEl.querySelectorAll !== 'function') return;
420
+
421
+ // 1. Clear previous error elements and aria-invalid states
422
+ const errorSpans = formEl.querySelectorAll('[data-w-error]');
423
+ for (let i = 0; i < errorSpans.length; i++) {
424
+ const span = errorSpans[i];
425
+ const fieldName = span.getAttribute('data-w-error');
426
+ const msg = fieldName && fieldErrors[fieldName] ? String(fieldErrors[fieldName]) : '';
427
+ span.textContent = msg;
428
+ if (msg) {
429
+ span.removeAttribute('hidden');
430
+ if (!span.id) {
431
+ span.id = `w-err-${formName}-${fieldName}-${++errorIdSeq}`;
432
+ }
433
+ if (!span.getAttribute('role')) {
434
+ span.setAttribute('role', 'alert');
435
+ }
436
+ } else {
437
+ span.setAttribute('hidden', '');
438
+ }
439
+ }
440
+
441
+ // 2. Bind aria-invalid and aria-describedby on form controls, and find first invalid control
442
+ let firstInvalidControl = null;
443
+ const controls = formEl.querySelectorAll('input, select, textarea');
444
+ for (let i = 0; i < controls.length; i++) {
445
+ const ctrl = controls[i];
446
+ const rawName = ctrl.getAttribute('name');
447
+ if (!rawName) continue;
448
+ const normName = rawName.endsWith('[]') ? rawName.slice(0, -2) : rawName;
449
+ const errMsg = fieldErrors[normName] || fieldErrors[rawName];
450
+
451
+ if (errMsg) {
452
+ ctrl.setAttribute('aria-invalid', 'true');
453
+ const errSpan =
454
+ formEl.querySelector(`[data-w-error="${normName}"]`) ||
455
+ formEl.querySelector(`[data-w-error="${rawName}"]`);
456
+ if (errSpan && errSpan.id) {
457
+ ctrl.setAttribute('aria-describedby', errSpan.id);
458
+ }
459
+ if (!firstInvalidControl && typeof ctrl.focus === 'function' && !isControlDisabled(ctrl)) {
460
+ firstInvalidControl = ctrl;
461
+ }
462
+ } else {
463
+ ctrl.removeAttribute('aria-invalid');
464
+ const desc = ctrl.getAttribute('aria-describedby');
465
+ if (desc && desc.startsWith('w-err-')) {
466
+ ctrl.removeAttribute('aria-describedby');
467
+ }
468
+ }
469
+ }
470
+
471
+ // 3. Form-level error element `[data-w-form-error]`
472
+ const formErrorEl = formEl.querySelector('[data-w-form-error]');
473
+ if (formErrorEl) {
474
+ if (formError) {
475
+ formErrorEl.textContent = String(formError);
476
+ formErrorEl.removeAttribute('hidden');
477
+ if (!formErrorEl.getAttribute('role')) {
478
+ formErrorEl.setAttribute('role', 'alert');
479
+ }
480
+ } else {
481
+ formErrorEl.textContent = '';
482
+ formErrorEl.setAttribute('hidden', '');
483
+ }
484
+ }
485
+
486
+ if (focusFirstInvalid && firstInvalidControl) {
487
+ try {
488
+ firstInvalidControl.focus();
489
+ } catch (_e) {
490
+ // Ignore focus errors in headless environments
491
+ }
492
+ }
493
+ }
494
+
495
+ /**
496
+ * Toggle pending state on the form and submit buttons to prevent double submissions.
497
+ */
498
+ function setPendingState(nextPending, activeSubmitter = null) {
499
+ pending = Boolean(nextPending);
500
+ if (!formEl) return;
501
+
502
+ if (pending) {
503
+ formEl.setAttribute('aria-busy', 'true');
504
+ formEl.setAttribute('data-w-pending', 'true');
505
+ } else {
506
+ formEl.removeAttribute('aria-busy');
507
+ formEl.removeAttribute('data-w-pending');
508
+ }
509
+
510
+ const submitButtons = formEl.querySelectorAll
511
+ ? formEl.querySelectorAll('button[type="submit"], button:not([type]), input[type="submit"]')
512
+ : [];
513
+ for (let i = 0; i < submitButtons.length; i++) {
514
+ const btn = submitButtons[i];
515
+ if (btn.hasAttribute('data-w-disabled')) continue; // Managed by controller binding
516
+ if (pending) {
517
+ btn.__wWasDisabled = Boolean(btn.disabled);
518
+ btn.disabled = true;
519
+ } else if (!btn.__wWasDisabled) {
520
+ btn.disabled = false;
521
+ }
522
+ }
523
+ if (activeSubmitter && !activeSubmitter.hasAttribute('data-w-disabled')) {
524
+ activeSubmitter.disabled = pending;
525
+ }
526
+ notifyStateChange();
527
+ }
528
+
529
+ /**
530
+ * Reset form controls back to their initial default values (NOT emptying non-empty defaults).
531
+ */
532
+ function reset() {
533
+ if (!formEl) return;
534
+ if (typeof formEl.reset === 'function') {
535
+ formEl.reset();
536
+ }
537
+ // Restore exact captured initial snapshot
538
+ for (const [el, init] of initialSnapshot.entries()) {
539
+ const type = (el.type || '').toLowerCase();
540
+ if (type === 'checkbox' || type === 'radio') {
541
+ el.checked = init.checked;
542
+ } else if (el.tagName === 'SELECT') {
543
+ const opts = el.options || [];
544
+ for (let j = 0; j < opts.length; j++) {
545
+ opts[j].selected = init.selectedIndices.includes(j);
546
+ }
547
+ } else if (type !== 'file') {
548
+ el.value = init.value;
549
+ }
550
+ }
551
+ dirty = false;
552
+ fieldErrors = {};
553
+ formError = null;
554
+ syncErrorsToDom(false);
555
+ notifyStateChange();
556
+ }
557
+
558
+ /**
559
+ * Completely clear all user-editable controls to empty values (distinct from `reset()`).
560
+ */
561
+ function clear() {
562
+ if (!formEl || typeof formEl.querySelectorAll !== 'function') return;
563
+ const controls = formEl.querySelectorAll('input, select, textarea');
564
+ for (let i = 0; i < controls.length; i++) {
565
+ const el = controls[i];
566
+ const type = (el.type || '').toLowerCase();
567
+ if (type === 'submit' || type === 'button' || type === 'reset' || type === 'hidden') continue;
568
+ if (type === 'checkbox' || type === 'radio') {
569
+ el.checked = false;
570
+ } else if (el.tagName === 'SELECT') {
571
+ const opts = el.options || [];
572
+ for (let j = 0; j < opts.length; j++) {
573
+ opts[j].selected = false;
574
+ }
575
+ if (!el.multiple && opts.length > 0) {
576
+ el.value = '';
577
+ }
578
+ } else {
579
+ el.value = '';
580
+ }
581
+ }
582
+ dirty = computeFormDirty(formEl, initialSnapshot);
583
+ fieldErrors = {};
584
+ formError = null;
585
+ syncErrorsToDom(false);
586
+ notifyStateChange();
587
+ }
588
+
589
+ /**
590
+ * Programmatically fill form fields.
591
+ *
592
+ * @param {Record<string, unknown>} values - Object containing field name -> value mappings
593
+ * @param {object} [options]
594
+ * @param {boolean} [options.baseline=false] - If true, treats the filled values as the new baseline
595
+ * snapshot, clears `dirty`, and clears previous validation errors.
596
+ */
597
+ function fill(values = {}, options = {}) {
598
+ if (!formEl || typeof formEl.querySelectorAll !== 'function' || !values || typeof values !== 'object') {
599
+ return handle;
600
+ }
601
+
602
+ const isBaseline = Boolean(options.baseline);
603
+
604
+ for (const [key, val] of Object.entries(values)) {
605
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
606
+
607
+ const normKey = key.endsWith('[]') ? key.slice(0, -2) : key;
608
+ const matchingControls = Array.from(
609
+ formEl.querySelectorAll(`[name="${key}"], [name="${normKey}"], [name="${normKey}[]"]`)
610
+ );
611
+
612
+ for (const ctrl of matchingControls) {
613
+ if (!ctrl || ctrl.tagName === 'BUTTON') continue;
614
+ const type = (ctrl.type || '').toLowerCase();
615
+ if (type === 'file') continue; // Browser security prevents setting file input value
616
+
617
+ if (type === 'checkbox') {
618
+ if (Array.isArray(val)) {
619
+ ctrl.checked = val.map(String).includes(String(ctrl.value));
620
+ } else {
621
+ ctrl.checked = Boolean(val);
622
+ }
623
+ } else if (type === 'radio') {
624
+ ctrl.checked = String(val) === String(ctrl.value);
625
+ } else if (ctrl.tagName === 'SELECT') {
626
+ if (ctrl.multiple) {
627
+ const arr = Array.isArray(val) ? val.map(String) : [String(val)];
628
+ const opts = ctrl.options || [];
629
+ for (let j = 0; j < opts.length; j++) {
630
+ opts[j].selected = arr.includes(String(opts[j].value));
631
+ }
632
+ } else {
633
+ ctrl.value = val === null || val === undefined ? '' : String(val);
634
+ }
635
+ } else {
636
+ ctrl.value = val === null || val === undefined ? '' : String(val);
637
+ }
638
+
639
+ // Clear error for this field
640
+ delete fieldErrors[normKey];
641
+ delete fieldErrors[key];
642
+ }
643
+ }
644
+
645
+ if (isBaseline) {
646
+ initialSnapshot = captureInitialFormSnapshot(formEl);
647
+ dirty = false;
648
+ fieldErrors = {};
649
+ formError = null;
650
+ syncErrorsToDom(false);
651
+ } else {
652
+ dirty = computeFormDirty(formEl, initialSnapshot);
653
+ syncErrorsToDom(false);
654
+ }
655
+
656
+ notifyStateChange();
657
+ return handle;
658
+ }
659
+
660
+ function setAction(url) {
661
+ if (formEl && url) {
662
+ formEl.setAttribute('action', String(url));
663
+ }
664
+ return handle;
665
+ }
666
+
667
+ function setRouteParams(params = {}) {
668
+ if (!formEl || !params) return handle;
669
+ let action = formEl.getAttribute('action') || '';
670
+ for (const [k, v] of Object.entries(params)) {
671
+ action = action.replace(new RegExp(`\\[${k}\\]`, 'g'), encodeURIComponent(String(v)));
672
+ action = action.replace(new RegExp(`:${k}\\b`, 'g'), encodeURIComponent(String(v)));
673
+ }
674
+ formEl.setAttribute('action', action);
675
+ return handle;
676
+ }
677
+
678
+ let _manuallyDisabled = false;
679
+ function setDisabled(val) {
680
+ _manuallyDisabled = Boolean(val);
681
+ if (!formEl) return handle;
682
+ if (_manuallyDisabled) {
683
+ if (formEl.setAttribute) {
684
+ formEl.setAttribute('aria-disabled', 'true');
685
+ formEl.setAttribute('disabled', '');
686
+ }
687
+ } else {
688
+ if (formEl.removeAttribute) {
689
+ formEl.removeAttribute('aria-disabled');
690
+ formEl.removeAttribute('disabled');
691
+ }
692
+ }
693
+ const controls = formEl.querySelectorAll ? formEl.querySelectorAll('input, select, textarea, button') : [];
694
+ for (let i = 0; i < controls.length; i++) {
695
+ controls[i].disabled = _manuallyDisabled;
696
+ }
697
+ notifyStateChange();
698
+ return handle;
699
+ }
700
+
701
+ /**
702
+ * Execute form submission.
703
+ */
704
+ async function submit(eventOrOptions = null) {
705
+ let event = null;
706
+ let submitOptions = {};
707
+
708
+ if (eventOrOptions && typeof eventOrOptions.preventDefault === 'function') {
709
+ event = eventOrOptions;
710
+ event.preventDefault();
711
+ } else if (eventOrOptions && typeof eventOrOptions === 'object') {
712
+ submitOptions = eventOrOptions;
713
+ }
714
+
715
+ // Prevent double submit while pending
716
+ if (pending) {
717
+ return { submitted: false, reason: 'pending' };
718
+ }
719
+
720
+ // 1. Native HTML5 constraint validation first
721
+ if (
722
+ submitOptions.validate !== false &&
723
+ formEl &&
724
+ !formEl.noValidate &&
725
+ typeof formEl.reportValidity === 'function'
726
+ ) {
727
+ const isValid = formEl.reportValidity();
728
+ if (!isValid) {
729
+ return { submitted: false, reason: 'native-constraint-invalid' };
730
+ }
731
+ }
732
+
733
+ const submitter =
734
+ submitOptions.submitter || (event && event.submitter ? event.submitter : null);
735
+ const actionUrl =
736
+ submitOptions.action ||
737
+ (submitter && submitter.getAttribute && submitter.getAttribute('formaction')) ||
738
+ (formEl && formEl.getAttribute && formEl.getAttribute('action')) ||
739
+ (typeof window !== 'undefined' && window.location ? window.location.pathname : '/');
740
+ const rawMethod =
741
+ submitOptions.method ||
742
+ (submitter && submitter.getAttribute && submitter.getAttribute('formmethod')) ||
743
+ (formEl && formEl.getAttribute && formEl.getAttribute('method')) ||
744
+ 'POST';
745
+ const method = String(rawMethod).toUpperCase();
746
+
747
+ const { data: payloadData, formData, isMultipart } = parseFormElement(formEl, submitter);
748
+
749
+ // Clear previous errors before request starts
750
+ fieldErrors = {};
751
+ formError = null;
752
+ syncErrorsToDom(false);
753
+ setPendingState(true, submitter);
754
+
755
+ try {
756
+ let responseData;
757
+ const reqKey = `form:${formName}:${method}:${actionUrl}`;
758
+ if (method === 'GET') {
759
+ responseData = await api.get(actionUrl, payloadData, {
760
+ key: reqKey,
761
+ policy: 'latest',
762
+ });
763
+ } else {
764
+ const bodyToSend = isMultipart && formData ? formData : payloadData;
765
+ responseData = await api.request(method, actionUrl, bodyToSend, {
766
+ key: reqKey,
767
+ policy: 'drop',
768
+ });
769
+ }
770
+
771
+ lastData = responseData;
772
+ dirty = false;
773
+ fieldErrors = {};
774
+ formError = null;
775
+ syncErrorsToDom(false);
776
+
777
+ // Explicit reset / clear behavior on success
778
+ const resetAttr = formEl ? formEl.getAttribute('data-w-reset') : null;
779
+ const clearAttr = formEl ? formEl.getAttribute('data-w-clear') : null;
780
+ const shouldReset =
781
+ submitOptions.resetOnSuccess === true ||
782
+ options.resetOnSuccess === true ||
783
+ resetAttr === '' ||
784
+ resetAttr === 'true' ||
785
+ resetAttr === '1';
786
+ const shouldClear =
787
+ submitOptions.clearOnSuccess === true ||
788
+ options.clearOnSuccess === true ||
789
+ clearAttr === '' ||
790
+ clearAttr === 'true' ||
791
+ clearAttr === '1';
792
+
793
+ if (shouldClear) {
794
+ clear();
795
+ } else if (shouldReset) {
796
+ reset();
797
+ } else {
798
+ // Current state becomes the new clean baseline after successful save
799
+ initialSnapshot = captureInitialFormSnapshot(formEl);
800
+ }
801
+
802
+ // Invoke registered success hooks. Note: Any background fragment refresh failure
803
+ // is handled by the fragment coordinator and NEVER puts this form into validation error state!
804
+ for (const listener of successListeners) {
805
+ await listener(responseData, { values: payloadData, form: handle });
806
+ }
807
+
808
+ // Explicit redirect behavior
809
+ const redirectTarget =
810
+ submitOptions.redirectOnSuccess ||
811
+ (formEl && formEl.getAttribute('data-w-redirect')) ||
812
+ null;
813
+ if (redirectTarget) {
814
+ if (typeof options.navigate === 'function') {
815
+ options.navigate(redirectTarget);
816
+ } else if (typeof window !== 'undefined' && window.location) {
817
+ window.location.assign(redirectTarget);
818
+ }
819
+ }
820
+
821
+ let refreshOk = true;
822
+ let refreshError = null;
823
+ if (responseData && typeof responseData === 'object' && responseData.__refreshPromise) {
824
+ const refreshOutcome = await responseData.__refreshPromise;
825
+ if (refreshOutcome && refreshOutcome.ok === false) {
826
+ refreshOk = false;
827
+ refreshError = refreshOutcome.error || null;
828
+ }
829
+ }
830
+
831
+ return { ok: true, submitted: true, data: responseData, refreshOk, refreshError };
832
+ } catch (err) {
833
+ if (err && err.kind === 'validation') {
834
+ fieldErrors = { ...(err.fieldErrors || {}) };
835
+ formError = err.formError || (Object.keys(fieldErrors).length === 0 ? err.message : null);
836
+ syncErrorsToDom(true);
837
+ } else if (err && err.isCanceled) {
838
+ // Canceled or dropped duplicate submit — do not overwrite form with error
839
+ } else {
840
+ formError = err && err.message ? err.message : 'Form submission failed.';
841
+ syncErrorsToDom(false);
842
+ }
843
+
844
+ for (const listener of errorListeners) {
845
+ try {
846
+ await listener(err, { values: payloadData, form: handle });
847
+ } catch (_e) {
848
+ // Ignore
849
+ }
850
+ }
851
+
852
+ if (submitOptions.throwOnError) {
853
+ throw err;
854
+ }
855
+ return { ok: false, submitted: false, error: err };
856
+ } finally {
857
+ setPendingState(false, submitter);
858
+ }
859
+ }
860
+
861
+ // Listen to native submit and input/change events on `formEl`
862
+ const onDomInput = (evt) => {
863
+ dirty = computeFormDirty(formEl, initialSnapshot);
864
+ const target = evt && evt.target;
865
+ if (target && target.getAttribute) {
866
+ const rawName = target.getAttribute('name');
867
+ if (rawName) {
868
+ const norm = rawName.endsWith('[]') ? rawName.slice(0, -2) : rawName;
869
+ if (fieldErrors[norm] || fieldErrors[rawName]) {
870
+ delete fieldErrors[norm];
871
+ delete fieldErrors[rawName];
872
+ syncErrorsToDom(false);
873
+ }
874
+ }
875
+ }
876
+ notifyStateChange();
877
+ };
878
+
879
+ const onDomSubmit = (evt) => {
880
+ submit(evt);
881
+ };
882
+
883
+ const onDomReset = () => {
884
+ setTimeout(() => {
885
+ dirty = false;
886
+ fieldErrors = {};
887
+ formError = null;
888
+ syncErrorsToDom(false);
889
+ notifyStateChange();
890
+ }, 0);
891
+ };
892
+
893
+ if (formEl && typeof formEl.addEventListener === 'function') {
894
+ formEl.addEventListener('input', onDomInput);
895
+ formEl.addEventListener('change', onDomInput);
896
+ formEl.addEventListener('submit', onDomSubmit);
897
+ formEl.addEventListener('reset', onDomReset);
898
+ }
899
+
900
+ // Initialize hidden state on empty error placeholders
901
+ syncErrorsToDom(false);
902
+
903
+ const handle = {
904
+ name: formName,
905
+ el: formEl,
906
+ get pending() {
907
+ return pending;
908
+ },
909
+ get dirty() {
910
+ dirty = computeFormDirty(formEl, initialSnapshot);
911
+ return dirty;
912
+ },
913
+ get values() {
914
+ return parseFormElement(formEl).data;
915
+ },
916
+ get errors() {
917
+ return { ...fieldErrors };
918
+ },
919
+ get fieldErrors() {
920
+ return { ...fieldErrors };
921
+ },
922
+ get formError() {
923
+ return formError;
924
+ },
925
+ get lastData() {
926
+ return lastData;
927
+ },
928
+ get disabled() {
929
+ return _manuallyDisabled;
930
+ },
931
+ set disabled(val) {
932
+ setDisabled(val);
933
+ },
934
+ read(submitter) {
935
+ return parseFormElement(formEl, submitter).data;
936
+ },
937
+ getValues(submitter) {
938
+ return parseFormElement(formEl, submitter).data;
939
+ },
940
+ fill,
941
+ setAction,
942
+ setRouteParams,
943
+ setDisabled,
944
+ setFieldErrors(nextFieldErrors = {}, focusFirst = true) {
945
+ fieldErrors = { ...nextFieldErrors };
946
+ syncErrorsToDom(focusFirst);
947
+ notifyStateChange();
948
+ },
949
+ setFormError(message) {
950
+ formError = message ? String(message) : null;
951
+ syncErrorsToDom(false);
952
+ notifyStateChange();
953
+ },
954
+ clearErrors() {
955
+ fieldErrors = {};
956
+ formError = null;
957
+ syncErrorsToDom(false);
958
+ notifyStateChange();
959
+ },
960
+ reset,
961
+ clear,
962
+ submit,
963
+ onSuccess(fn) {
964
+ if (typeof fn === 'function') {
965
+ successListeners.add(fn);
966
+ return () => successListeners.delete(fn);
967
+ }
968
+ return () => {};
969
+ },
970
+ onError(fn) {
971
+ if (typeof fn === 'function') {
972
+ errorListeners.add(fn);
973
+ return () => errorListeners.delete(fn);
974
+ }
975
+ return () => {};
976
+ },
977
+ subscribe(fn) {
978
+ if (typeof fn === 'function') {
979
+ stateListeners.add(fn);
980
+ return () => stateListeners.delete(fn);
981
+ }
982
+ return () => {};
983
+ },
984
+ destroy() {
985
+ if (formEl && typeof formEl.removeEventListener === 'function') {
986
+ formEl.removeEventListener('input', onDomInput);
987
+ formEl.removeEventListener('change', onDomInput);
988
+ formEl.removeEventListener('submit', onDomSubmit);
989
+ formEl.removeEventListener('reset', onDomReset);
990
+ }
991
+ if (formEl) {
992
+ delete formEl.__wFormHandle;
993
+ }
994
+ successListeners.clear();
995
+ errorListeners.clear();
996
+ stateListeners.clear();
997
+ },
998
+ };
999
+
1000
+ if (formEl) {
1001
+ Object.defineProperty(formEl, '__wFormHandle', {
1002
+ value: handle,
1003
+ configurable: true,
1004
+ enumerable: false,
1005
+ });
1006
+ }
1007
+
1008
+ if (debug) {
1009
+ debug.recordEvent('form:bind', { name: formName });
1010
+ }
1011
+
1012
+ return handle;
1013
+ }
1014
+
1015
+ module.exports = {
1016
+ parseFormElement,
1017
+ isControlDisabled,
1018
+ coerceScalarControlValue,
1019
+ createFormHandle,
1020
+ };
1021
+