@marvalt/madapter 1.0.14

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 (37) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +422 -0
  3. package/dist/client/mautic-client.d.ts +88 -0
  4. package/dist/client/mautic-client.d.ts.map +1 -0
  5. package/dist/data/mautic-data-store.d.ts +84 -0
  6. package/dist/data/mautic-data-store.d.ts.map +1 -0
  7. package/dist/generators/mautic-generator.d.ts +48 -0
  8. package/dist/generators/mautic-generator.d.ts.map +1 -0
  9. package/dist/index.cjs +3199 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +770 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.esm.js +3141 -0
  14. package/dist/index.esm.js.map +1 -0
  15. package/dist/react/components/MauticForm.d.ts +31 -0
  16. package/dist/react/components/MauticForm.d.ts.map +1 -0
  17. package/dist/react/components/MauticTracking.d.ts +42 -0
  18. package/dist/react/components/MauticTracking.d.ts.map +1 -0
  19. package/dist/react/hooks/useMautic.d.ts +98 -0
  20. package/dist/react/hooks/useMautic.d.ts.map +1 -0
  21. package/dist/react/providers/MauticProvider.d.ts +42 -0
  22. package/dist/react/providers/MauticProvider.d.ts.map +1 -0
  23. package/dist/service/mautic-service.d.ts +40 -0
  24. package/dist/service/mautic-service.d.ts.map +1 -0
  25. package/dist/setupTests.d.ts +18 -0
  26. package/dist/setupTests.d.ts.map +1 -0
  27. package/dist/types/config.d.ts +46 -0
  28. package/dist/types/config.d.ts.map +1 -0
  29. package/dist/types/mautic.d.ts +108 -0
  30. package/dist/types/mautic.d.ts.map +1 -0
  31. package/dist/types/static-data.d.ts +59 -0
  32. package/dist/types/static-data.d.ts.map +1 -0
  33. package/dist/utils/config.d.ts +54 -0
  34. package/dist/utils/config.d.ts.map +1 -0
  35. package/dist/utils/validation.d.ts +58 -0
  36. package/dist/utils/validation.d.ts.map +1 -0
  37. package/package.json +90 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,3199 @@
1
+ 'use strict';
2
+
3
+ var reactQuery = require('@tanstack/react-query');
4
+ var fs = require('fs');
5
+ var path = require('path');
6
+ var React = require('react');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ /**
10
+ * @license GPL-3.0-or-later
11
+ *
12
+ * This file is part of the MarVAlt Open SDK.
13
+ * Copyright (c) 2025 Vibune Pty Ltd.
14
+ *
15
+ * This program is free software: you can redistribute it and/or modify
16
+ * it under the terms of the GNU General Public License as published by
17
+ * the Free Software Foundation, either version 3 of the License, or
18
+ * (at your option) any later version.
19
+ *
20
+ * This program is distributed in the hope that it will be useful,
21
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23
+ * See the GNU General Public License for more details.
24
+ */
25
+ class MauticClient {
26
+ constructor(config) {
27
+ this.config = config;
28
+ if (config.authMode === 'cloudflare_proxy' && config.cloudflareWorkerUrl && config.appId && config.workerSecret) {
29
+ // Cloudflare Worker proxy (recommended - uses Secrets Store)
30
+ this.proxyUrl = config.cloudflareWorkerUrl;
31
+ this.appId = config.appId;
32
+ this.workerSecret = config.workerSecret;
33
+ this.useProxy = true;
34
+ this.isConfigured = true;
35
+ }
36
+ else if (config.authMode === 'direct' && config.apiUrl) {
37
+ // Direct Mautic API access (legacy - for local development only)
38
+ this.baseUrl = config.apiUrl;
39
+ this.useProxy = false;
40
+ this.isConfigured = true;
41
+ }
42
+ else {
43
+ // Fallback or error state
44
+ this.useProxy = false;
45
+ this.isConfigured = false;
46
+ }
47
+ }
48
+ validateConfiguration() {
49
+ if (!this.isConfigured) {
50
+ throw new Error('Mautic service not properly configured. Check your configuration.');
51
+ }
52
+ }
53
+ getAuthHeaders() {
54
+ if (this.useProxy) {
55
+ return {
56
+ 'x-app-id': this.appId || '',
57
+ 'x-app-secret': this.workerSecret || '',
58
+ };
59
+ }
60
+ else {
61
+ return {};
62
+ }
63
+ }
64
+ async makeRequest(endpoint, options = {}) {
65
+ this.validateConfiguration();
66
+ let url;
67
+ if (this.useProxy) {
68
+ // Use Cloudflare Worker proxy
69
+ const proxyEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
70
+ url = `${this.proxyUrl}?endpoint=${encodeURIComponent(proxyEndpoint)}`;
71
+ }
72
+ else {
73
+ // Use direct Mautic API
74
+ // Determine if this is a form submission endpoint (should not use /api prefix)
75
+ const isFormSubmission = endpoint.startsWith('/form/submit') ||
76
+ (endpoint.startsWith('/forms/') && endpoint.includes('/submit'));
77
+ if (isFormSubmission) {
78
+ // Form submissions go directly to the form endpoint, not the API
79
+ url = `${this.baseUrl}${endpoint}`;
80
+ }
81
+ else {
82
+ // API calls use the /api prefix
83
+ url = `${this.baseUrl}/api${endpoint}`;
84
+ }
85
+ }
86
+ const isFormSubmission = endpoint.startsWith('/form/submit') ||
87
+ (endpoint.startsWith('/forms/') && endpoint.includes('/submit'));
88
+ const headers = {
89
+ ...this.getAuthHeaders(),
90
+ ...options.headers,
91
+ };
92
+ // Default JSON only for non-form submissions when a body exists and no explicit content-type provided
93
+ const hasBody = options.body != null && options.body !== undefined;
94
+ if (!isFormSubmission && hasBody && !('Content-Type' in headers)) {
95
+ headers['Content-Type'] = 'application/json';
96
+ }
97
+ try {
98
+ const response = await fetch(url, {
99
+ ...options,
100
+ headers,
101
+ });
102
+ // Determine if this was a form submission based on the original endpoint
103
+ const wasFormSubmission = endpoint.startsWith('/form/submit') ||
104
+ (endpoint.startsWith('/forms/') && endpoint.includes('/submit'));
105
+ if (!response.ok) {
106
+ // For form submissions, some Mautic setups respond with an HTML 404 after a successful submit.
107
+ // Do not treat this as an error; let the frontend handle success/redirect messaging.
108
+ const isRedirect = response.status >= 300 && response.status < 400;
109
+ const isHtmlLike = (response.headers.get('content-type') || '').includes('text/html');
110
+ if (!(wasFormSubmission && (isRedirect || response.status === 404 || isHtmlLike))) {
111
+ throw new Error(`Mautic API request failed: ${response.status} ${response.statusText}`);
112
+ }
113
+ }
114
+ const responseText = await response.text();
115
+ // Handle empty responses
116
+ if (!responseText) {
117
+ return [];
118
+ }
119
+ // For Mautic form submissions, the response may be HTML. Try JSON first, fallback to text.
120
+ try {
121
+ return JSON.parse(responseText);
122
+ }
123
+ catch {
124
+ return responseText;
125
+ }
126
+ }
127
+ catch (error) {
128
+ const message = error instanceof Error ? error.message : String(error);
129
+ console.error('Mautic API request error:', message);
130
+ throw new Error(message);
131
+ }
132
+ }
133
+ /**
134
+ * Submit a form to Mautic
135
+ */
136
+ async submitForm(formId, submission) {
137
+ const endpoint = `/form/submit?formId=${formId}`;
138
+ // Encode as application/x-www-form-urlencoded to match Mautic expectations
139
+ const formParams = new URLSearchParams();
140
+ // Add fields
141
+ Object.entries(submission.fields || {}).forEach(([alias, value]) => {
142
+ if (Array.isArray(value)) {
143
+ value.forEach((v) => formParams.append(`mauticform[${alias}]`, String(v)));
144
+ }
145
+ else if (typeof value === 'boolean') {
146
+ formParams.append(`mauticform[${alias}]`, value ? '1' : '0');
147
+ }
148
+ else if (value != null) {
149
+ formParams.append(`mauticform[${alias}]`, String(value));
150
+ }
151
+ });
152
+ // Required hidden fields
153
+ formParams.append('mauticform[formId]', String(formId));
154
+ // Prevent Mautic from attempting a redirect; frontend will handle any redirect
155
+ formParams.append('mauticform[return]', '');
156
+ // Mautic submit flag similar to native form button name/value
157
+ formParams.append('mauticform[submit]', '1');
158
+ // Include formName only if provided (derived from cachedHtml)
159
+ if (submission.formName) {
160
+ formParams.append('mauticform[formName]', submission.formName);
161
+ }
162
+ return this.makeRequest(endpoint, {
163
+ method: 'POST',
164
+ headers: {
165
+ 'Content-Type': 'application/x-www-form-urlencoded'
166
+ },
167
+ body: formParams.toString(),
168
+ });
169
+ }
170
+ /**
171
+ * Create a new contact in Mautic
172
+ */
173
+ async createContact(contact) {
174
+ return this.makeRequest('/contacts/new', {
175
+ method: 'POST',
176
+ body: JSON.stringify(contact),
177
+ });
178
+ }
179
+ /**
180
+ * Update an existing contact in Mautic
181
+ */
182
+ async updateContact(contactId, contact) {
183
+ return this.makeRequest(`/contacts/${contactId}/edit`, {
184
+ method: 'PATCH',
185
+ body: JSON.stringify(contact),
186
+ });
187
+ }
188
+ /**
189
+ * Get a contact by email
190
+ */
191
+ async getContactByEmail(email) {
192
+ return this.makeRequest(`/contacts?search=email:${encodeURIComponent(email)}`);
193
+ }
194
+ /**
195
+ * Get all forms from Mautic
196
+ */
197
+ async getForms() {
198
+ const response = await this.makeRequest('/forms');
199
+ return response.forms || [];
200
+ }
201
+ /**
202
+ * Get a specific form by ID
203
+ */
204
+ async getForm(formId) {
205
+ return this.makeRequest(`/forms/${formId}`);
206
+ }
207
+ /**
208
+ * Track an event in Mautic
209
+ */
210
+ async trackEvent(eventName, eventData = {}) {
211
+ return this.makeRequest('/events', {
212
+ method: 'POST',
213
+ body: JSON.stringify({
214
+ eventName,
215
+ eventData,
216
+ }),
217
+ });
218
+ }
219
+ /**
220
+ * Add tags to a contact
221
+ */
222
+ async addTagToContact(contactId, tags) {
223
+ return this.makeRequest(`/contacts/${contactId}/tags`, {
224
+ method: 'POST',
225
+ body: JSON.stringify({ tags }),
226
+ });
227
+ }
228
+ /**
229
+ * Remove tags from a contact
230
+ */
231
+ async removeTagFromContact(contactId, tags) {
232
+ return this.makeRequest(`/contacts/${contactId}/tags`, {
233
+ method: 'DELETE',
234
+ body: JSON.stringify({ tags }),
235
+ });
236
+ }
237
+ /**
238
+ * Get contact tags
239
+ */
240
+ async getContactTags(contactId) {
241
+ return this.makeRequest(`/contacts/${contactId}/tags`);
242
+ }
243
+ /**
244
+ * Get all tags
245
+ */
246
+ async getTags() {
247
+ return this.makeRequest('/tags');
248
+ }
249
+ /**
250
+ * Get segments
251
+ */
252
+ async getSegments() {
253
+ return this.makeRequest('/segments');
254
+ }
255
+ /**
256
+ * Add contact to segment
257
+ */
258
+ async addContactToSegment(contactId, segmentId) {
259
+ return this.makeRequest(`/contacts/${contactId}/segments`, {
260
+ method: 'POST',
261
+ body: JSON.stringify({ segmentId }),
262
+ });
263
+ }
264
+ /**
265
+ * Remove contact from segment
266
+ */
267
+ async removeContactFromSegment(contactId, segmentId) {
268
+ return this.makeRequest(`/contacts/${contactId}/segments`, {
269
+ method: 'DELETE',
270
+ body: JSON.stringify({ segmentId }),
271
+ });
272
+ }
273
+ }
274
+
275
+ /**
276
+ * @license GPL-3.0-or-later
277
+ *
278
+ * This file is part of the MarVAlt Open SDK.
279
+ * Copyright (c) 2025 Vibune Pty Ltd.
280
+ *
281
+ * This program is free software: you can redistribute it and/or modify
282
+ * it under the terms of the GNU General Public License as published by
283
+ * the Free Software Foundation, either version 3 of the License, or
284
+ * (at your option) any later version.
285
+ *
286
+ * This program is distributed in the hope that it will be useful,
287
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
288
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
289
+ * See the GNU General Public License for more details.
290
+ */
291
+ /**
292
+ * Create Mautic configuration from environment variables
293
+ */
294
+ const createMauticConfig = (overrides = {}) => {
295
+ // Use import.meta.env for Vite compatibility in browser
296
+ const getEnvVar = (key) => {
297
+ // Check for Vite environment (browser)
298
+ if (typeof window !== 'undefined' && window.import?.meta?.env) {
299
+ return window.import.meta.env[key];
300
+ }
301
+ // Check for direct import.meta (Vite)
302
+ try {
303
+ // @ts-ignore - import.meta is a Vite-specific global
304
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) }) !== 'undefined' && undefined) {
305
+ // @ts-ignore
306
+ return undefined[key];
307
+ }
308
+ }
309
+ catch (e) {
310
+ // import.meta not available
311
+ }
312
+ // Fallback for Node.js environments
313
+ if (typeof process !== 'undefined' && process.env) {
314
+ return process.env[key];
315
+ }
316
+ return undefined;
317
+ };
318
+ const merged = {
319
+ authMode: getEnvVar('VITE_AUTH_MODE') || getEnvVar('VITE_MAUTIC_AUTH_MODE') || 'cloudflare_proxy',
320
+ apiUrl: getEnvVar('VITE_MAUTIC_URL'),
321
+ cloudflareWorkerUrl: getEnvVar('VITE_MAUTIC_PROXY_URL'),
322
+ appId: getEnvVar('VITE_FRONTEND_ID'),
323
+ workerSecret: getEnvVar('VITE_FRONTEND_SECRET'),
324
+ timeout: parseInt(getEnvVar('VITE_MAUTIC_TIMEOUT') || '30000'),
325
+ retries: parseInt(getEnvVar('VITE_MAUTIC_RETRIES') || '3'),
326
+ ...overrides,
327
+ };
328
+ // Enforce required fields depending on authMode
329
+ const errors = [];
330
+ if (merged.authMode === 'cloudflare_proxy') {
331
+ if (!merged.cloudflareWorkerUrl)
332
+ errors.push('cloudflareWorkerUrl is required for cloudflare_proxy mode');
333
+ if (!merged.appId)
334
+ errors.push('appId is required for cloudflare_proxy mode');
335
+ if (!merged.workerSecret)
336
+ errors.push('workerSecret is required for cloudflare_proxy mode');
337
+ }
338
+ if (merged.authMode === 'direct') {
339
+ if (!merged.apiUrl)
340
+ errors.push('apiUrl is required for direct mode');
341
+ }
342
+ if (errors.length) {
343
+ throw new Error(`Invalid Mautic configuration: ${errors.join('; ')}`);
344
+ }
345
+ return merged;
346
+ };
347
+ /**
348
+ * Validate Mautic configuration
349
+ */
350
+ const validateMauticConfig = (config) => {
351
+ const errors = [];
352
+ if (!config.authMode) {
353
+ errors.push('authMode is required');
354
+ }
355
+ if (config.authMode === 'cloudflare_proxy') {
356
+ if (!config.cloudflareWorkerUrl) {
357
+ errors.push('cloudflareWorkerUrl is required for cloudflare_proxy mode');
358
+ }
359
+ if (!config.appId) {
360
+ errors.push('appId is required for cloudflare_proxy mode');
361
+ }
362
+ if (!config.workerSecret) {
363
+ errors.push('workerSecret is required for cloudflare_proxy mode');
364
+ }
365
+ }
366
+ else if (config.authMode === 'direct') {
367
+ if (!config.apiUrl) {
368
+ errors.push('apiUrl is required for direct mode');
369
+ }
370
+ }
371
+ if (config.timeout && config.timeout < 1000) {
372
+ errors.push('timeout must be at least 1000ms');
373
+ }
374
+ if (config.retries && config.retries < 0) {
375
+ errors.push('retries must be non-negative');
376
+ }
377
+ return {
378
+ isValid: errors.length === 0,
379
+ errors,
380
+ };
381
+ };
382
+ /**
383
+ * Get default Mautic configuration
384
+ */
385
+ const getDefaultMauticConfig = () => {
386
+ return {
387
+ authMode: 'cloudflare_proxy',
388
+ timeout: 30000,
389
+ retries: 3,
390
+ };
391
+ };
392
+ /**
393
+ * Merge Mautic configurations
394
+ */
395
+ const mergeMauticConfig = (base, overrides) => {
396
+ return {
397
+ ...base,
398
+ ...overrides,
399
+ };
400
+ };
401
+ /**
402
+ * Check if Mautic is enabled based on configuration
403
+ */
404
+ const isMauticEnabled = (config) => {
405
+ if (config.authMode === 'cloudflare_proxy') {
406
+ return !!(config.cloudflareWorkerUrl && config.appId && config.workerSecret);
407
+ }
408
+ else if (config.authMode === 'direct') {
409
+ return !!config.apiUrl;
410
+ }
411
+ return false;
412
+ };
413
+ /**
414
+ * Get Mautic configuration summary (for debugging)
415
+ */
416
+ const getMauticConfigSummary = (config) => {
417
+ return {
418
+ authMode: config.authMode,
419
+ hasApiUrl: !!config.apiUrl,
420
+ hasCloudflareWorkerUrl: !!config.cloudflareWorkerUrl,
421
+ hasAppId: !!config.appId,
422
+ hasWorkerSecret: !!config.workerSecret,
423
+ timeout: config.timeout,
424
+ retries: config.retries,
425
+ isEnabled: isMauticEnabled(config),
426
+ };
427
+ };
428
+
429
+ /**
430
+ * @license GPL-3.0-or-later
431
+ *
432
+ * This file is part of the MarVAlt Open SDK.
433
+ * Copyright (c) 2025 Vibune Pty Ltd.
434
+ *
435
+ * This program is free software: you can redistribute it and/or modify
436
+ * it under the terms of the GNU General Public License as published by
437
+ * the Free Software Foundation, either version 3 of the License, or
438
+ * (at your option) any later version.
439
+ *
440
+ * This program is distributed in the hope that it will be useful,
441
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
442
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
443
+ * See the GNU General Public License for more details.
444
+ */
445
+ // Create a default client instance (will be overridden by provider)
446
+ let defaultClient = null;
447
+ /**
448
+ * Set the default Mautic client for hooks
449
+ */
450
+ const setMauticClient = (client) => {
451
+ defaultClient = client;
452
+ };
453
+ /**
454
+ * Get the current Mautic client
455
+ */
456
+ const getMauticClient = () => {
457
+ if (!defaultClient) {
458
+ // Lazy initialize the client from environment if not set by provider/service
459
+ const config = createMauticConfig();
460
+ defaultClient = new MauticClient(config);
461
+ }
462
+ return defaultClient;
463
+ };
464
+ /**
465
+ * Custom hook for submitting forms to Mautic
466
+ */
467
+ const useMauticFormSubmission = () => {
468
+ const queryClient = reactQuery.useQueryClient();
469
+ return reactQuery.useMutation({
470
+ mutationFn: (submission) => {
471
+ const client = getMauticClient();
472
+ return client.submitForm(submission.formId, submission);
473
+ },
474
+ onSuccess: (data, variables) => {
475
+ if (undefined?.DEV) {
476
+ console.log('Mautic form submission successful:', data);
477
+ }
478
+ // Invalidate related queries
479
+ queryClient.invalidateQueries({ queryKey: ['mautic-contacts'] });
480
+ // Track the submission event
481
+ if (variables.contact?.email) {
482
+ const client = getMauticClient();
483
+ client.trackEvent('form_submission', {
484
+ formId: variables.formId,
485
+ email: variables.contact.email
486
+ }).catch(console.error);
487
+ }
488
+ },
489
+ onError: (error) => {
490
+ console.error('Mautic form submission failed:', error);
491
+ },
492
+ });
493
+ };
494
+ /**
495
+ * Custom hook for creating Mautic contacts
496
+ */
497
+ const useMauticCreateContact = () => {
498
+ const queryClient = reactQuery.useQueryClient();
499
+ return reactQuery.useMutation({
500
+ mutationFn: (contact) => {
501
+ const client = getMauticClient();
502
+ return client.createContact(contact);
503
+ },
504
+ onSuccess: (data, variables) => {
505
+ if (undefined?.DEV) {
506
+ console.log('Mautic contact created:', data);
507
+ }
508
+ // Invalidate contacts queries
509
+ queryClient.invalidateQueries({ queryKey: ['mautic-contacts'] });
510
+ queryClient.invalidateQueries({ queryKey: ['mautic-contact', variables.email] });
511
+ },
512
+ onError: (error) => {
513
+ console.error('Failed to create Mautic contact:', error);
514
+ },
515
+ });
516
+ };
517
+ /**
518
+ * Custom hook for updating Mautic contacts
519
+ */
520
+ const useMauticUpdateContact = () => {
521
+ const queryClient = reactQuery.useQueryClient();
522
+ return reactQuery.useMutation({
523
+ mutationFn: ({ contactId, contact }) => {
524
+ const client = getMauticClient();
525
+ return client.updateContact(contactId, contact);
526
+ },
527
+ onSuccess: (data, variables) => {
528
+ if (undefined?.DEV) {
529
+ console.log('Mautic contact updated:', data);
530
+ }
531
+ // Invalidate related queries
532
+ queryClient.invalidateQueries({ queryKey: ['mautic-contacts'] });
533
+ queryClient.invalidateQueries({ queryKey: ['mautic-contact', variables.contactId] });
534
+ },
535
+ onError: (error) => {
536
+ console.error('Failed to update Mautic contact:', error);
537
+ },
538
+ });
539
+ };
540
+ /**
541
+ * Custom hook for fetching Mautic contact by email
542
+ */
543
+ const useMauticContactByEmail = (email) => {
544
+ return reactQuery.useQuery({
545
+ queryKey: ['mautic-contact', email],
546
+ queryFn: () => {
547
+ const client = getMauticClient();
548
+ return client.getContactByEmail(email);
549
+ },
550
+ enabled: !!email && email.includes('@'),
551
+ staleTime: 5 * 60 * 1000, // 5 minutes
552
+ gcTime: 10 * 60 * 1000,
553
+ });
554
+ };
555
+ /**
556
+ * Custom hook for fetching Mautic forms
557
+ */
558
+ const useMauticForms = () => {
559
+ return reactQuery.useQuery({
560
+ queryKey: ['mautic-forms'],
561
+ queryFn: () => {
562
+ const client = getMauticClient();
563
+ return client.getForms();
564
+ },
565
+ staleTime: 30 * 60 * 1000, // Forms don't change often
566
+ gcTime: 60 * 60 * 1000,
567
+ });
568
+ };
569
+ /**
570
+ * Custom hook for fetching a specific Mautic form
571
+ */
572
+ const useMauticForm = (formId) => {
573
+ return reactQuery.useQuery({
574
+ queryKey: ['mautic-form', formId],
575
+ queryFn: () => {
576
+ const client = getMauticClient();
577
+ return client.getForm(formId);
578
+ },
579
+ enabled: !!formId,
580
+ staleTime: 30 * 60 * 1000,
581
+ gcTime: 60 * 60 * 1000,
582
+ });
583
+ };
584
+ /**
585
+ * Custom hook for tracking Mautic events
586
+ */
587
+ const useMauticEventTracking = () => {
588
+ return reactQuery.useMutation({
589
+ mutationFn: ({ email, eventName, eventData }) => {
590
+ const client = getMauticClient();
591
+ return client.trackEvent(eventName, {
592
+ email,
593
+ ...(eventData || {})
594
+ });
595
+ },
596
+ onSuccess: (data, variables) => {
597
+ if (undefined?.DEV) {
598
+ console.log('Mautic event tracked successfully:', variables.eventName);
599
+ }
600
+ },
601
+ onError: (error, variables) => {
602
+ console.error('Failed to track Mautic event:', variables.eventName, error);
603
+ },
604
+ });
605
+ };
606
+ /**
607
+ * Custom hook for adding tags to contacts
608
+ */
609
+ const useMauticAddTags = () => {
610
+ const queryClient = reactQuery.useQueryClient();
611
+ return reactQuery.useMutation({
612
+ mutationFn: ({ contactId, tags }) => {
613
+ const client = getMauticClient();
614
+ return client.addTagToContact(contactId, tags);
615
+ },
616
+ onSuccess: (data, variables) => {
617
+ if (undefined?.DEV) {
618
+ console.log('Tags added to Mautic contact:', variables.tags);
619
+ }
620
+ // Invalidate contact queries
621
+ queryClient.invalidateQueries({ queryKey: ['mautic-contact', variables.contactId] });
622
+ },
623
+ onError: (error) => {
624
+ console.error('Failed to add tags to Mautic contact:', error);
625
+ },
626
+ });
627
+ };
628
+ /**
629
+ * Custom hook for removing tags from contacts
630
+ */
631
+ const useMauticRemoveTags = () => {
632
+ const queryClient = reactQuery.useQueryClient();
633
+ return reactQuery.useMutation({
634
+ mutationFn: ({ contactId, tags }) => {
635
+ const client = getMauticClient();
636
+ return client.removeTagFromContact(contactId, tags);
637
+ },
638
+ onSuccess: (data, variables) => {
639
+ if (undefined?.DEV) {
640
+ console.log('Tags removed from Mautic contact:', variables.tags);
641
+ }
642
+ // Invalidate contact queries
643
+ queryClient.invalidateQueries({ queryKey: ['mautic-contact', variables.contactId] });
644
+ },
645
+ onError: (error) => {
646
+ console.error('Failed to remove tags from Mautic contact:', error);
647
+ },
648
+ });
649
+ };
650
+ /**
651
+ * Custom hook for getting contact tags
652
+ */
653
+ const useMauticContactTags = (contactId) => {
654
+ return reactQuery.useQuery({
655
+ queryKey: ['mautic-contact-tags', contactId],
656
+ queryFn: () => {
657
+ const client = getMauticClient();
658
+ return client.getContactTags(contactId);
659
+ },
660
+ enabled: !!contactId,
661
+ staleTime: 5 * 60 * 1000,
662
+ gcTime: 10 * 60 * 1000,
663
+ });
664
+ };
665
+ /**
666
+ * Custom hook for getting all tags
667
+ */
668
+ const useMauticTags = () => {
669
+ return reactQuery.useQuery({
670
+ queryKey: ['mautic-tags'],
671
+ queryFn: () => {
672
+ const client = getMauticClient();
673
+ return client.getTags();
674
+ },
675
+ staleTime: 30 * 60 * 1000,
676
+ gcTime: 60 * 60 * 1000,
677
+ });
678
+ };
679
+ /**
680
+ * Custom hook for getting segments
681
+ */
682
+ const useMauticSegments = () => {
683
+ return reactQuery.useQuery({
684
+ queryKey: ['mautic-segments'],
685
+ queryFn: () => {
686
+ const client = getMauticClient();
687
+ return client.getSegments();
688
+ },
689
+ staleTime: 30 * 60 * 1000,
690
+ gcTime: 60 * 60 * 1000,
691
+ });
692
+ };
693
+ /**
694
+ * Custom hook for adding contact to segment
695
+ */
696
+ const useMauticAddToSegment = () => {
697
+ const queryClient = reactQuery.useQueryClient();
698
+ return reactQuery.useMutation({
699
+ mutationFn: ({ contactId, segmentId }) => {
700
+ const client = getMauticClient();
701
+ return client.addContactToSegment(contactId, segmentId);
702
+ },
703
+ onSuccess: (data, variables) => {
704
+ if (undefined?.DEV) {
705
+ console.log('Contact added to segment:', variables.segmentId);
706
+ }
707
+ // Invalidate contact queries
708
+ queryClient.invalidateQueries({ queryKey: ['mautic-contact', variables.contactId] });
709
+ },
710
+ onError: (error) => {
711
+ console.error('Failed to add contact to segment:', error);
712
+ },
713
+ });
714
+ };
715
+ /**
716
+ * Custom hook for removing contact from segment
717
+ */
718
+ const useMauticRemoveFromSegment = () => {
719
+ const queryClient = reactQuery.useQueryClient();
720
+ return reactQuery.useMutation({
721
+ mutationFn: ({ contactId, segmentId }) => {
722
+ const client = getMauticClient();
723
+ return client.removeContactFromSegment(contactId, segmentId);
724
+ },
725
+ onSuccess: (data, variables) => {
726
+ if (undefined?.DEV) {
727
+ console.log('Contact removed from segment:', variables.segmentId);
728
+ }
729
+ // Invalidate contact queries
730
+ queryClient.invalidateQueries({ queryKey: ['mautic-contact', variables.contactId] });
731
+ },
732
+ onError: (error) => {
733
+ console.error('Failed to remove contact from segment:', error);
734
+ },
735
+ });
736
+ };
737
+
738
+ /**
739
+ * @license GPL-3.0-or-later
740
+ *
741
+ * This file is part of the MarVAlt Open SDK.
742
+ * Copyright (c) 2025 Vibune Pty Ltd.
743
+ *
744
+ * This program is free software: you can redistribute it and/or modify
745
+ * it under the terms of the GNU General Public License as published by
746
+ * the Free Software Foundation, either version 3 of the License, or
747
+ * (at your option) any later version.
748
+ *
749
+ * This program is distributed in the hope that it will be useful,
750
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
751
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
752
+ * See the GNU General Public License for more details.
753
+ */
754
+ class MauticService {
755
+ constructor() {
756
+ // Create configuration from environment variables
757
+ const config = createMauticConfig();
758
+ this.client = new MauticClient(config);
759
+ }
760
+ // Check if Mautic is configured
761
+ isServiceConfigured() {
762
+ try {
763
+ // The client will throw if not configured
764
+ return true;
765
+ }
766
+ catch {
767
+ return false;
768
+ }
769
+ }
770
+ // Form Submissions
771
+ async submitForm(formId, formData) {
772
+ return this.client.submitForm(formId, formData);
773
+ }
774
+ // Enhanced Forms Management - Core functionality for frontend rendering
775
+ async getForms() {
776
+ return this.client.getForms();
777
+ }
778
+ async getForm(formId) {
779
+ return this.client.getForm(formId);
780
+ }
781
+ // NEW: Get complete form configuration with fields and actions
782
+ async getFormConfig(formId) {
783
+ return this.client.getForm(formId);
784
+ }
785
+ // NEW: Get form fields with validation and properties
786
+ async getFormFields(formId) {
787
+ const form = await this.client.getForm(formId);
788
+ return form.fields || [];
789
+ }
790
+ // NEW: Get form actions (what happens after submission)
791
+ async getFormActions(formId) {
792
+ const form = await this.client.getForm(formId);
793
+ return form.actions || [];
794
+ }
795
+ // NEW: Get form validation rules
796
+ async getFormValidation(formId) {
797
+ const fields = await this.getFormFields(formId);
798
+ const validation = {};
799
+ fields.forEach(field => {
800
+ if (field.properties?.validation) {
801
+ validation[field.alias] = field.properties.validation;
802
+ }
803
+ });
804
+ return validation;
805
+ }
806
+ // Contact Management (basic functionality for form submissions)
807
+ async createContact(contact) {
808
+ return this.client.createContact(contact);
809
+ }
810
+ async updateContact(contactId, contact) {
811
+ return this.client.updateContact(contactId, contact);
812
+ }
813
+ async getContact(contactId) {
814
+ const response = await this.client.getContactByEmail(''); // This needs to be updated
815
+ return response;
816
+ }
817
+ async getContactByEmail(email) {
818
+ try {
819
+ const response = await this.client.getContactByEmail(email);
820
+ return response.data || null;
821
+ }
822
+ catch (error) {
823
+ console.error('Error fetching contact by email:', error);
824
+ return null;
825
+ }
826
+ }
827
+ // Tags (basic functionality for form actions)
828
+ async addTagToContact(contactId, tags) {
829
+ return this.client.addTagToContact(contactId, tags);
830
+ }
831
+ async removeTagFromContact(contactId, tags) {
832
+ return this.client.removeTagFromContact(contactId, tags);
833
+ }
834
+ // Tracking (basic functionality)
835
+ async trackEvent(eventName, eventData) {
836
+ return this.client.trackEvent(eventName, eventData);
837
+ }
838
+ }
839
+ // Export configured instance
840
+ const mauticService = new MauticService();
841
+ setMauticClient(mauticService['client']);
842
+
843
+ /**
844
+ * @license GPL-3.0-or-later
845
+ *
846
+ * This file is part of the MarVAlt Open SDK.
847
+ * Copyright (c) 2025 Vibune Pty Ltd.
848
+ *
849
+ * This program is free software: you can redistribute it and/or modify
850
+ * it under the terms of the GNU General Public License as published by
851
+ * the Free Software Foundation, either version 3 of the License, or
852
+ * (at your option) any later version.
853
+ *
854
+ * This program is distributed in the hope that it will be useful,
855
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
856
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
857
+ * See the GNU General Public License for more details.
858
+ */
859
+ class MauticGenerator {
860
+ constructor(config) {
861
+ this.config = config;
862
+ this.client = new MauticClient({
863
+ authMode: config.authMode,
864
+ apiUrl: config.apiUrl,
865
+ cloudflareWorkerUrl: config.cloudflareWorkerUrl,
866
+ appId: config.appId,
867
+ workerSecret: config.workerSecret,
868
+ timeout: config.timeout,
869
+ retries: config.retries,
870
+ });
871
+ }
872
+ /**
873
+ * Generate static data for Mautic forms
874
+ */
875
+ async generateStaticData() {
876
+ console.log('🔄 Generating Mautic forms JSON data...');
877
+ try {
878
+ const allForms = await this.fetchMauticFormsList();
879
+ console.log(`📝 Found ${allForms.length} forms`);
880
+ const forms = [];
881
+ for (const formSummary of allForms) {
882
+ const formId = formSummary.id?.toString();
883
+ if (!formId) {
884
+ console.warn(`⚠️ Form summary missing ID:`, formSummary);
885
+ continue;
886
+ }
887
+ try {
888
+ const formDetails = await this.fetchMauticForm(formId);
889
+ if (!formDetails) {
890
+ console.warn(`⚠️ No form details returned for form ${formId}`);
891
+ continue;
892
+ }
893
+ // Extract the form data with proper structure
894
+ const formData = {
895
+ id: formId,
896
+ name: formDetails.name || formSummary.name || `Form ${formId}`,
897
+ description: formDetails.description,
898
+ isPublished: formDetails.isPublished || formSummary.isPublished || false,
899
+ // Include post-submission behavior configuration
900
+ postAction: formDetails.postAction || 'message',
901
+ postActionProperty: formDetails.postActionProperty || 'Thank you for your submission!',
902
+ // Include other important form properties
903
+ formType: formDetails.formType || 'standalone',
904
+ // Extract fields with validation and properties
905
+ fields: (formDetails.fields || []).map(field => ({
906
+ id: field.id,
907
+ label: field.label,
908
+ alias: field.alias,
909
+ type: field.type,
910
+ isRequired: field.isRequired || false,
911
+ validationMessage: field.validationMessage,
912
+ defaultValue: field.defaultValue,
913
+ properties: {
914
+ placeholder: field.properties?.placeholder,
915
+ cssClass: field.properties?.cssClass,
916
+ validation: field.properties?.validation,
917
+ options: field.properties?.options,
918
+ helpText: field.properties?.helpText,
919
+ size: field.properties?.size,
920
+ ...field.properties
921
+ }
922
+ })),
923
+ // Extract actions
924
+ actions: (formDetails.actions || []).map(action => ({
925
+ id: action.id,
926
+ name: action.name,
927
+ type: action.type,
928
+ properties: action.properties || {}
929
+ })),
930
+ // Include styling and behavior
931
+ cssClass: formDetails.cssClass,
932
+ submitAction: formDetails.submitAction,
933
+ // Keep the details for reference
934
+ ...formSummary
935
+ };
936
+ forms.push(formData);
937
+ console.log(`✅ Processed form: ${formData.name} (ID: ${formId})`);
938
+ }
939
+ catch (error) {
940
+ const message = error instanceof Error ? error.message : String(error);
941
+ console.error(`❌ Error processing form ${formId}:`, message);
942
+ // Continue with other forms
943
+ }
944
+ }
945
+ const staticData = {
946
+ generated_at: new Date().toISOString(),
947
+ total_forms: forms.length,
948
+ forms: forms.map(form => ({
949
+ id: parseInt(form.id),
950
+ name: form.name,
951
+ alias: form.alias || form.name.toLowerCase().replace(/\s+/g, '-'),
952
+ description: form.description,
953
+ isPublished: form.isPublished,
954
+ fields: form.fields,
955
+ actions: form.actions,
956
+ cssClass: form.cssClass,
957
+ submitAction: form.submitAction,
958
+ postAction: form.postAction,
959
+ postActionProperty: form.postActionProperty,
960
+ formType: form.formType,
961
+ }))
962
+ };
963
+ console.log(`✅ Generated static data for ${forms.length} forms`);
964
+ return staticData;
965
+ }
966
+ catch (error) {
967
+ const message = error instanceof Error ? error.message : String(error);
968
+ console.error('❌ Error generating Mautic static data:', message);
969
+ throw new Error(message);
970
+ }
971
+ }
972
+ /**
973
+ * Write static data to file
974
+ */
975
+ async writeStaticData(staticData) {
976
+ const outputPath = path.resolve(this.config.outputPath);
977
+ const outputDir = path.dirname(outputPath);
978
+ // Ensure output directory exists
979
+ if (!fs.existsSync(outputDir)) {
980
+ fs.mkdirSync(outputDir, { recursive: true });
981
+ }
982
+ // Write the static data
983
+ fs.writeFileSync(outputPath, JSON.stringify(staticData, null, 2));
984
+ console.log(`📁 Static data written to: ${outputPath}`);
985
+ }
986
+ /**
987
+ * Generate and write static data
988
+ */
989
+ async generateAndWrite() {
990
+ const staticData = await this.generateStaticData();
991
+ await this.writeStaticData(staticData);
992
+ return staticData;
993
+ }
994
+ /**
995
+ * Fetch list of forms from Mautic
996
+ */
997
+ async fetchMauticFormsList() {
998
+ const baseUrl = this.config.cloudflareWorkerUrl;
999
+ if (!baseUrl)
1000
+ throw new Error('VITE_MAUTIC_PROXY_URL not configured');
1001
+ const url = `${baseUrl}?endpoint=/forms`;
1002
+ const headers = {
1003
+ 'Content-Type': 'application/json',
1004
+ };
1005
+ if (this.config.appId) {
1006
+ headers['x-app-id'] = this.config.appId;
1007
+ }
1008
+ if (this.config.workerSecret) {
1009
+ headers['x-app-secret'] = this.config.workerSecret;
1010
+ }
1011
+ const response = await fetch(url, { headers });
1012
+ if (!response.ok) {
1013
+ throw new Error(`Failed to fetch forms list: ${response.status} ${response.statusText}`);
1014
+ }
1015
+ const data = await response.json().catch(() => ({}));
1016
+ const forms = data.forms;
1017
+ return Array.isArray(forms) ? forms : [];
1018
+ }
1019
+ /**
1020
+ * Fetch individual form details from Mautic
1021
+ */
1022
+ async fetchMauticForm(formId) {
1023
+ const baseUrl = this.config.cloudflareWorkerUrl;
1024
+ if (!baseUrl)
1025
+ throw new Error('VITE_MAUTIC_PROXY_URL not configured');
1026
+ const url = `${baseUrl}?endpoint=/forms/${formId}`;
1027
+ const headers = {
1028
+ 'Content-Type': 'application/json',
1029
+ };
1030
+ if (this.config.appId) {
1031
+ headers['x-app-id'] = this.config.appId;
1032
+ }
1033
+ if (this.config.workerSecret) {
1034
+ headers['x-app-secret'] = this.config.workerSecret;
1035
+ }
1036
+ const response = await fetch(url, { headers });
1037
+ if (!response.ok) {
1038
+ throw new Error(`Failed to fetch form ${formId}: ${response.status} ${response.statusText}`);
1039
+ }
1040
+ return response.json().catch(() => ({}));
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Generate Mautic static data with configuration
1045
+ */
1046
+ async function generateMauticData(config) {
1047
+ const generator = new MauticGenerator(config);
1048
+ return generator.generateAndWrite();
1049
+ }
1050
+
1051
+ var jsxRuntime = {exports: {}};
1052
+
1053
+ var reactJsxRuntime_production_min = {};
1054
+
1055
+ /**
1056
+ * @license React
1057
+ * react-jsx-runtime.production.min.js
1058
+ *
1059
+ * Copyright (c) Facebook, Inc. and its affiliates.
1060
+ *
1061
+ * This source code is licensed under the MIT license found in the
1062
+ * LICENSE file in the root directory of this source tree.
1063
+ */
1064
+
1065
+ var hasRequiredReactJsxRuntime_production_min;
1066
+
1067
+ function requireReactJsxRuntime_production_min () {
1068
+ if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
1069
+ hasRequiredReactJsxRuntime_production_min = 1;
1070
+ var f=React,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:true,ref:true,__self:true,__source:true};
1071
+ function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a) void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
1072
+ return reactJsxRuntime_production_min;
1073
+ }
1074
+
1075
+ var reactJsxRuntime_development = {};
1076
+
1077
+ /**
1078
+ * @license React
1079
+ * react-jsx-runtime.development.js
1080
+ *
1081
+ * Copyright (c) Facebook, Inc. and its affiliates.
1082
+ *
1083
+ * This source code is licensed under the MIT license found in the
1084
+ * LICENSE file in the root directory of this source tree.
1085
+ */
1086
+
1087
+ var hasRequiredReactJsxRuntime_development;
1088
+
1089
+ function requireReactJsxRuntime_development () {
1090
+ if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
1091
+ hasRequiredReactJsxRuntime_development = 1;
1092
+
1093
+ if (process.env.NODE_ENV !== "production") {
1094
+ (function() {
1095
+
1096
+ var React$1 = React;
1097
+
1098
+ // ATTENTION
1099
+ // When adding new symbols to this file,
1100
+ // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
1101
+ // The Symbol used to tag the ReactElement-like types.
1102
+ var REACT_ELEMENT_TYPE = Symbol.for('react.element');
1103
+ var REACT_PORTAL_TYPE = Symbol.for('react.portal');
1104
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
1105
+ var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
1106
+ var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
1107
+ var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
1108
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
1109
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
1110
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
1111
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
1112
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
1113
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
1114
+ var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
1115
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
1116
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
1117
+ function getIteratorFn(maybeIterable) {
1118
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
1119
+ return null;
1120
+ }
1121
+
1122
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
1123
+
1124
+ if (typeof maybeIterator === 'function') {
1125
+ return maybeIterator;
1126
+ }
1127
+
1128
+ return null;
1129
+ }
1130
+
1131
+ var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1132
+
1133
+ function error(format) {
1134
+ {
1135
+ {
1136
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1137
+ args[_key2 - 1] = arguments[_key2];
1138
+ }
1139
+
1140
+ printWarning('error', format, args);
1141
+ }
1142
+ }
1143
+ }
1144
+
1145
+ function printWarning(level, format, args) {
1146
+ // When changing this logic, you might want to also
1147
+ // update consoleWithStackDev.www.js as well.
1148
+ {
1149
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1150
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
1151
+
1152
+ if (stack !== '') {
1153
+ format += '%s';
1154
+ args = args.concat([stack]);
1155
+ } // eslint-disable-next-line react-internal/safe-string-coercion
1156
+
1157
+
1158
+ var argsWithFormat = args.map(function (item) {
1159
+ return String(item);
1160
+ }); // Careful: RN currently depends on this prefix
1161
+
1162
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
1163
+ // breaks IE9: https://github.com/facebook/react/issues/13610
1164
+ // eslint-disable-next-line react-internal/no-production-logging
1165
+
1166
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
1167
+ }
1168
+ }
1169
+
1170
+ // -----------------------------------------------------------------------------
1171
+
1172
+ var enableScopeAPI = false; // Experimental Create Event Handle API.
1173
+ var enableCacheElement = false;
1174
+ var enableTransitionTracing = false; // No known bugs, but needs performance testing
1175
+
1176
+ var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
1177
+ // stuff. Intended to enable React core members to more easily debug scheduling
1178
+ // issues in DEV builds.
1179
+
1180
+ var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
1181
+
1182
+ var REACT_MODULE_REFERENCE;
1183
+
1184
+ {
1185
+ REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
1186
+ }
1187
+
1188
+ function isValidElementType(type) {
1189
+ if (typeof type === 'string' || typeof type === 'function') {
1190
+ return true;
1191
+ } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
1192
+
1193
+
1194
+ if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
1195
+ return true;
1196
+ }
1197
+
1198
+ if (typeof type === 'object' && type !== null) {
1199
+ if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
1200
+ // types supported by any Flight configuration anywhere since
1201
+ // we don't know which Flight build this will end up being used
1202
+ // with.
1203
+ type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
1204
+ return true;
1205
+ }
1206
+ }
1207
+
1208
+ return false;
1209
+ }
1210
+
1211
+ function getWrappedName(outerType, innerType, wrapperName) {
1212
+ var displayName = outerType.displayName;
1213
+
1214
+ if (displayName) {
1215
+ return displayName;
1216
+ }
1217
+
1218
+ var functionName = innerType.displayName || innerType.name || '';
1219
+ return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
1220
+ } // Keep in sync with react-reconciler/getComponentNameFromFiber
1221
+
1222
+
1223
+ function getContextName(type) {
1224
+ return type.displayName || 'Context';
1225
+ } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
1226
+
1227
+
1228
+ function getComponentNameFromType(type) {
1229
+ if (type == null) {
1230
+ // Host root, text node or just invalid type.
1231
+ return null;
1232
+ }
1233
+
1234
+ {
1235
+ if (typeof type.tag === 'number') {
1236
+ error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
1237
+ }
1238
+ }
1239
+
1240
+ if (typeof type === 'function') {
1241
+ return type.displayName || type.name || null;
1242
+ }
1243
+
1244
+ if (typeof type === 'string') {
1245
+ return type;
1246
+ }
1247
+
1248
+ switch (type) {
1249
+ case REACT_FRAGMENT_TYPE:
1250
+ return 'Fragment';
1251
+
1252
+ case REACT_PORTAL_TYPE:
1253
+ return 'Portal';
1254
+
1255
+ case REACT_PROFILER_TYPE:
1256
+ return 'Profiler';
1257
+
1258
+ case REACT_STRICT_MODE_TYPE:
1259
+ return 'StrictMode';
1260
+
1261
+ case REACT_SUSPENSE_TYPE:
1262
+ return 'Suspense';
1263
+
1264
+ case REACT_SUSPENSE_LIST_TYPE:
1265
+ return 'SuspenseList';
1266
+
1267
+ }
1268
+
1269
+ if (typeof type === 'object') {
1270
+ switch (type.$$typeof) {
1271
+ case REACT_CONTEXT_TYPE:
1272
+ var context = type;
1273
+ return getContextName(context) + '.Consumer';
1274
+
1275
+ case REACT_PROVIDER_TYPE:
1276
+ var provider = type;
1277
+ return getContextName(provider._context) + '.Provider';
1278
+
1279
+ case REACT_FORWARD_REF_TYPE:
1280
+ return getWrappedName(type, type.render, 'ForwardRef');
1281
+
1282
+ case REACT_MEMO_TYPE:
1283
+ var outerName = type.displayName || null;
1284
+
1285
+ if (outerName !== null) {
1286
+ return outerName;
1287
+ }
1288
+
1289
+ return getComponentNameFromType(type.type) || 'Memo';
1290
+
1291
+ case REACT_LAZY_TYPE:
1292
+ {
1293
+ var lazyComponent = type;
1294
+ var payload = lazyComponent._payload;
1295
+ var init = lazyComponent._init;
1296
+
1297
+ try {
1298
+ return getComponentNameFromType(init(payload));
1299
+ } catch (x) {
1300
+ return null;
1301
+ }
1302
+ }
1303
+
1304
+ // eslint-disable-next-line no-fallthrough
1305
+ }
1306
+ }
1307
+
1308
+ return null;
1309
+ }
1310
+
1311
+ var assign = Object.assign;
1312
+
1313
+ // Helpers to patch console.logs to avoid logging during side-effect free
1314
+ // replaying on render function. This currently only patches the object
1315
+ // lazily which won't cover if the log function was extracted eagerly.
1316
+ // We could also eagerly patch the method.
1317
+ var disabledDepth = 0;
1318
+ var prevLog;
1319
+ var prevInfo;
1320
+ var prevWarn;
1321
+ var prevError;
1322
+ var prevGroup;
1323
+ var prevGroupCollapsed;
1324
+ var prevGroupEnd;
1325
+
1326
+ function disabledLog() {}
1327
+
1328
+ disabledLog.__reactDisabledLog = true;
1329
+ function disableLogs() {
1330
+ {
1331
+ if (disabledDepth === 0) {
1332
+ /* eslint-disable react-internal/no-production-logging */
1333
+ prevLog = console.log;
1334
+ prevInfo = console.info;
1335
+ prevWarn = console.warn;
1336
+ prevError = console.error;
1337
+ prevGroup = console.group;
1338
+ prevGroupCollapsed = console.groupCollapsed;
1339
+ prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
1340
+
1341
+ var props = {
1342
+ configurable: true,
1343
+ enumerable: true,
1344
+ value: disabledLog,
1345
+ writable: true
1346
+ }; // $FlowFixMe Flow thinks console is immutable.
1347
+
1348
+ Object.defineProperties(console, {
1349
+ info: props,
1350
+ log: props,
1351
+ warn: props,
1352
+ error: props,
1353
+ group: props,
1354
+ groupCollapsed: props,
1355
+ groupEnd: props
1356
+ });
1357
+ /* eslint-enable react-internal/no-production-logging */
1358
+ }
1359
+
1360
+ disabledDepth++;
1361
+ }
1362
+ }
1363
+ function reenableLogs() {
1364
+ {
1365
+ disabledDepth--;
1366
+
1367
+ if (disabledDepth === 0) {
1368
+ /* eslint-disable react-internal/no-production-logging */
1369
+ var props = {
1370
+ configurable: true,
1371
+ enumerable: true,
1372
+ writable: true
1373
+ }; // $FlowFixMe Flow thinks console is immutable.
1374
+
1375
+ Object.defineProperties(console, {
1376
+ log: assign({}, props, {
1377
+ value: prevLog
1378
+ }),
1379
+ info: assign({}, props, {
1380
+ value: prevInfo
1381
+ }),
1382
+ warn: assign({}, props, {
1383
+ value: prevWarn
1384
+ }),
1385
+ error: assign({}, props, {
1386
+ value: prevError
1387
+ }),
1388
+ group: assign({}, props, {
1389
+ value: prevGroup
1390
+ }),
1391
+ groupCollapsed: assign({}, props, {
1392
+ value: prevGroupCollapsed
1393
+ }),
1394
+ groupEnd: assign({}, props, {
1395
+ value: prevGroupEnd
1396
+ })
1397
+ });
1398
+ /* eslint-enable react-internal/no-production-logging */
1399
+ }
1400
+
1401
+ if (disabledDepth < 0) {
1402
+ error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
1403
+ }
1404
+ }
1405
+ }
1406
+
1407
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
1408
+ var prefix;
1409
+ function describeBuiltInComponentFrame(name, source, ownerFn) {
1410
+ {
1411
+ if (prefix === undefined) {
1412
+ // Extract the VM specific prefix used by each line.
1413
+ try {
1414
+ throw Error();
1415
+ } catch (x) {
1416
+ var match = x.stack.trim().match(/\n( *(at )?)/);
1417
+ prefix = match && match[1] || '';
1418
+ }
1419
+ } // We use the prefix to ensure our stacks line up with native stack frames.
1420
+
1421
+
1422
+ return '\n' + prefix + name;
1423
+ }
1424
+ }
1425
+ var reentry = false;
1426
+ var componentFrameCache;
1427
+
1428
+ {
1429
+ var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
1430
+ componentFrameCache = new PossiblyWeakMap();
1431
+ }
1432
+
1433
+ function describeNativeComponentFrame(fn, construct) {
1434
+ // If something asked for a stack inside a fake render, it should get ignored.
1435
+ if ( !fn || reentry) {
1436
+ return '';
1437
+ }
1438
+
1439
+ {
1440
+ var frame = componentFrameCache.get(fn);
1441
+
1442
+ if (frame !== undefined) {
1443
+ return frame;
1444
+ }
1445
+ }
1446
+
1447
+ var control;
1448
+ reentry = true;
1449
+ var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
1450
+
1451
+ Error.prepareStackTrace = undefined;
1452
+ var previousDispatcher;
1453
+
1454
+ {
1455
+ previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
1456
+ // for warnings.
1457
+
1458
+ ReactCurrentDispatcher.current = null;
1459
+ disableLogs();
1460
+ }
1461
+
1462
+ try {
1463
+ // This should throw.
1464
+ if (construct) {
1465
+ // Something should be setting the props in the constructor.
1466
+ var Fake = function () {
1467
+ throw Error();
1468
+ }; // $FlowFixMe
1469
+
1470
+
1471
+ Object.defineProperty(Fake.prototype, 'props', {
1472
+ set: function () {
1473
+ // We use a throwing setter instead of frozen or non-writable props
1474
+ // because that won't throw in a non-strict mode function.
1475
+ throw Error();
1476
+ }
1477
+ });
1478
+
1479
+ if (typeof Reflect === 'object' && Reflect.construct) {
1480
+ // We construct a different control for this case to include any extra
1481
+ // frames added by the construct call.
1482
+ try {
1483
+ Reflect.construct(Fake, []);
1484
+ } catch (x) {
1485
+ control = x;
1486
+ }
1487
+
1488
+ Reflect.construct(fn, [], Fake);
1489
+ } else {
1490
+ try {
1491
+ Fake.call();
1492
+ } catch (x) {
1493
+ control = x;
1494
+ }
1495
+
1496
+ fn.call(Fake.prototype);
1497
+ }
1498
+ } else {
1499
+ try {
1500
+ throw Error();
1501
+ } catch (x) {
1502
+ control = x;
1503
+ }
1504
+
1505
+ fn();
1506
+ }
1507
+ } catch (sample) {
1508
+ // This is inlined manually because closure doesn't do it for us.
1509
+ if (sample && control && typeof sample.stack === 'string') {
1510
+ // This extracts the first frame from the sample that isn't also in the control.
1511
+ // Skipping one frame that we assume is the frame that calls the two.
1512
+ var sampleLines = sample.stack.split('\n');
1513
+ var controlLines = control.stack.split('\n');
1514
+ var s = sampleLines.length - 1;
1515
+ var c = controlLines.length - 1;
1516
+
1517
+ while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
1518
+ // We expect at least one stack frame to be shared.
1519
+ // Typically this will be the root most one. However, stack frames may be
1520
+ // cut off due to maximum stack limits. In this case, one maybe cut off
1521
+ // earlier than the other. We assume that the sample is longer or the same
1522
+ // and there for cut off earlier. So we should find the root most frame in
1523
+ // the sample somewhere in the control.
1524
+ c--;
1525
+ }
1526
+
1527
+ for (; s >= 1 && c >= 0; s--, c--) {
1528
+ // Next we find the first one that isn't the same which should be the
1529
+ // frame that called our sample function and the control.
1530
+ if (sampleLines[s] !== controlLines[c]) {
1531
+ // In V8, the first line is describing the message but other VMs don't.
1532
+ // If we're about to return the first line, and the control is also on the same
1533
+ // line, that's a pretty good indicator that our sample threw at same line as
1534
+ // the control. I.e. before we entered the sample frame. So we ignore this result.
1535
+ // This can happen if you passed a class to function component, or non-function.
1536
+ if (s !== 1 || c !== 1) {
1537
+ do {
1538
+ s--;
1539
+ c--; // We may still have similar intermediate frames from the construct call.
1540
+ // The next one that isn't the same should be our match though.
1541
+
1542
+ if (c < 0 || sampleLines[s] !== controlLines[c]) {
1543
+ // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
1544
+ var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
1545
+ // but we have a user-provided "displayName"
1546
+ // splice it in to make the stack more readable.
1547
+
1548
+
1549
+ if (fn.displayName && _frame.includes('<anonymous>')) {
1550
+ _frame = _frame.replace('<anonymous>', fn.displayName);
1551
+ }
1552
+
1553
+ {
1554
+ if (typeof fn === 'function') {
1555
+ componentFrameCache.set(fn, _frame);
1556
+ }
1557
+ } // Return the line we found.
1558
+
1559
+
1560
+ return _frame;
1561
+ }
1562
+ } while (s >= 1 && c >= 0);
1563
+ }
1564
+
1565
+ break;
1566
+ }
1567
+ }
1568
+ }
1569
+ } finally {
1570
+ reentry = false;
1571
+
1572
+ {
1573
+ ReactCurrentDispatcher.current = previousDispatcher;
1574
+ reenableLogs();
1575
+ }
1576
+
1577
+ Error.prepareStackTrace = previousPrepareStackTrace;
1578
+ } // Fallback to just using the name if we couldn't make it throw.
1579
+
1580
+
1581
+ var name = fn ? fn.displayName || fn.name : '';
1582
+ var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
1583
+
1584
+ {
1585
+ if (typeof fn === 'function') {
1586
+ componentFrameCache.set(fn, syntheticFrame);
1587
+ }
1588
+ }
1589
+
1590
+ return syntheticFrame;
1591
+ }
1592
+ function describeFunctionComponentFrame(fn, source, ownerFn) {
1593
+ {
1594
+ return describeNativeComponentFrame(fn, false);
1595
+ }
1596
+ }
1597
+
1598
+ function shouldConstruct(Component) {
1599
+ var prototype = Component.prototype;
1600
+ return !!(prototype && prototype.isReactComponent);
1601
+ }
1602
+
1603
+ function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
1604
+
1605
+ if (type == null) {
1606
+ return '';
1607
+ }
1608
+
1609
+ if (typeof type === 'function') {
1610
+ {
1611
+ return describeNativeComponentFrame(type, shouldConstruct(type));
1612
+ }
1613
+ }
1614
+
1615
+ if (typeof type === 'string') {
1616
+ return describeBuiltInComponentFrame(type);
1617
+ }
1618
+
1619
+ switch (type) {
1620
+ case REACT_SUSPENSE_TYPE:
1621
+ return describeBuiltInComponentFrame('Suspense');
1622
+
1623
+ case REACT_SUSPENSE_LIST_TYPE:
1624
+ return describeBuiltInComponentFrame('SuspenseList');
1625
+ }
1626
+
1627
+ if (typeof type === 'object') {
1628
+ switch (type.$$typeof) {
1629
+ case REACT_FORWARD_REF_TYPE:
1630
+ return describeFunctionComponentFrame(type.render);
1631
+
1632
+ case REACT_MEMO_TYPE:
1633
+ // Memo may contain any component type so we recursively resolve it.
1634
+ return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
1635
+
1636
+ case REACT_LAZY_TYPE:
1637
+ {
1638
+ var lazyComponent = type;
1639
+ var payload = lazyComponent._payload;
1640
+ var init = lazyComponent._init;
1641
+
1642
+ try {
1643
+ // Lazy may contain any component type so we recursively resolve it.
1644
+ return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
1645
+ } catch (x) {}
1646
+ }
1647
+ }
1648
+ }
1649
+
1650
+ return '';
1651
+ }
1652
+
1653
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
1654
+
1655
+ var loggedTypeFailures = {};
1656
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1657
+
1658
+ function setCurrentlyValidatingElement(element) {
1659
+ {
1660
+ if (element) {
1661
+ var owner = element._owner;
1662
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1663
+ ReactDebugCurrentFrame.setExtraStackFrame(stack);
1664
+ } else {
1665
+ ReactDebugCurrentFrame.setExtraStackFrame(null);
1666
+ }
1667
+ }
1668
+ }
1669
+
1670
+ function checkPropTypes(typeSpecs, values, location, componentName, element) {
1671
+ {
1672
+ // $FlowFixMe This is okay but Flow doesn't know it.
1673
+ var has = Function.call.bind(hasOwnProperty);
1674
+
1675
+ for (var typeSpecName in typeSpecs) {
1676
+ if (has(typeSpecs, typeSpecName)) {
1677
+ var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
1678
+ // fail the render phase where it didn't fail before. So we log it.
1679
+ // After these have been cleaned up, we'll let them throw.
1680
+
1681
+ try {
1682
+ // This is intentionally an invariant that gets caught. It's the same
1683
+ // behavior as without this statement except with a better message.
1684
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
1685
+ // eslint-disable-next-line react-internal/prod-error-codes
1686
+ var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
1687
+ err.name = 'Invariant Violation';
1688
+ throw err;
1689
+ }
1690
+
1691
+ error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
1692
+ } catch (ex) {
1693
+ error$1 = ex;
1694
+ }
1695
+
1696
+ if (error$1 && !(error$1 instanceof Error)) {
1697
+ setCurrentlyValidatingElement(element);
1698
+
1699
+ error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
1700
+
1701
+ setCurrentlyValidatingElement(null);
1702
+ }
1703
+
1704
+ if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
1705
+ // Only monitor this failure once because there tends to be a lot of the
1706
+ // same error.
1707
+ loggedTypeFailures[error$1.message] = true;
1708
+ setCurrentlyValidatingElement(element);
1709
+
1710
+ error('Failed %s type: %s', location, error$1.message);
1711
+
1712
+ setCurrentlyValidatingElement(null);
1713
+ }
1714
+ }
1715
+ }
1716
+ }
1717
+ }
1718
+
1719
+ var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
1720
+
1721
+ function isArray(a) {
1722
+ return isArrayImpl(a);
1723
+ }
1724
+
1725
+ /*
1726
+ * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
1727
+ * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
1728
+ *
1729
+ * The functions in this module will throw an easier-to-understand,
1730
+ * easier-to-debug exception with a clear errors message message explaining the
1731
+ * problem. (Instead of a confusing exception thrown inside the implementation
1732
+ * of the `value` object).
1733
+ */
1734
+ // $FlowFixMe only called in DEV, so void return is not possible.
1735
+ function typeName(value) {
1736
+ {
1737
+ // toStringTag is needed for namespaced types like Temporal.Instant
1738
+ var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
1739
+ var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
1740
+ return type;
1741
+ }
1742
+ } // $FlowFixMe only called in DEV, so void return is not possible.
1743
+
1744
+
1745
+ function willCoercionThrow(value) {
1746
+ {
1747
+ try {
1748
+ testStringCoercion(value);
1749
+ return false;
1750
+ } catch (e) {
1751
+ return true;
1752
+ }
1753
+ }
1754
+ }
1755
+
1756
+ function testStringCoercion(value) {
1757
+ // If you ended up here by following an exception call stack, here's what's
1758
+ // happened: you supplied an object or symbol value to React (as a prop, key,
1759
+ // DOM attribute, CSS property, string ref, etc.) and when React tried to
1760
+ // coerce it to a string using `'' + value`, an exception was thrown.
1761
+ //
1762
+ // The most common types that will cause this exception are `Symbol` instances
1763
+ // and Temporal objects like `Temporal.Instant`. But any object that has a
1764
+ // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
1765
+ // exception. (Library authors do this to prevent users from using built-in
1766
+ // numeric operators like `+` or comparison operators like `>=` because custom
1767
+ // methods are needed to perform accurate arithmetic or comparison.)
1768
+ //
1769
+ // To fix the problem, coerce this object or symbol value to a string before
1770
+ // passing it to React. The most reliable way is usually `String(value)`.
1771
+ //
1772
+ // To find which value is throwing, check the browser or debugger console.
1773
+ // Before this exception was thrown, there should be `console.error` output
1774
+ // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
1775
+ // problem and how that type was used: key, atrribute, input value prop, etc.
1776
+ // In most cases, this console output also shows the component and its
1777
+ // ancestor components where the exception happened.
1778
+ //
1779
+ // eslint-disable-next-line react-internal/safe-string-coercion
1780
+ return '' + value;
1781
+ }
1782
+ function checkKeyStringCoercion(value) {
1783
+ {
1784
+ if (willCoercionThrow(value)) {
1785
+ error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
1786
+
1787
+ return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
1788
+ }
1789
+ }
1790
+ }
1791
+
1792
+ var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
1793
+ var RESERVED_PROPS = {
1794
+ key: true,
1795
+ ref: true,
1796
+ __self: true,
1797
+ __source: true
1798
+ };
1799
+ var specialPropKeyWarningShown;
1800
+ var specialPropRefWarningShown;
1801
+
1802
+ function hasValidRef(config) {
1803
+ {
1804
+ if (hasOwnProperty.call(config, 'ref')) {
1805
+ var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
1806
+
1807
+ if (getter && getter.isReactWarning) {
1808
+ return false;
1809
+ }
1810
+ }
1811
+ }
1812
+
1813
+ return config.ref !== undefined;
1814
+ }
1815
+
1816
+ function hasValidKey(config) {
1817
+ {
1818
+ if (hasOwnProperty.call(config, 'key')) {
1819
+ var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
1820
+
1821
+ if (getter && getter.isReactWarning) {
1822
+ return false;
1823
+ }
1824
+ }
1825
+ }
1826
+
1827
+ return config.key !== undefined;
1828
+ }
1829
+
1830
+ function warnIfStringRefCannotBeAutoConverted(config, self) {
1831
+ {
1832
+ if (typeof config.ref === 'string' && ReactCurrentOwner.current && self) ;
1833
+ }
1834
+ }
1835
+
1836
+ function defineKeyPropWarningGetter(props, displayName) {
1837
+ {
1838
+ var warnAboutAccessingKey = function () {
1839
+ if (!specialPropKeyWarningShown) {
1840
+ specialPropKeyWarningShown = true;
1841
+
1842
+ error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1843
+ }
1844
+ };
1845
+
1846
+ warnAboutAccessingKey.isReactWarning = true;
1847
+ Object.defineProperty(props, 'key', {
1848
+ get: warnAboutAccessingKey,
1849
+ configurable: true
1850
+ });
1851
+ }
1852
+ }
1853
+
1854
+ function defineRefPropWarningGetter(props, displayName) {
1855
+ {
1856
+ var warnAboutAccessingRef = function () {
1857
+ if (!specialPropRefWarningShown) {
1858
+ specialPropRefWarningShown = true;
1859
+
1860
+ error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1861
+ }
1862
+ };
1863
+
1864
+ warnAboutAccessingRef.isReactWarning = true;
1865
+ Object.defineProperty(props, 'ref', {
1866
+ get: warnAboutAccessingRef,
1867
+ configurable: true
1868
+ });
1869
+ }
1870
+ }
1871
+ /**
1872
+ * Factory method to create a new React element. This no longer adheres to
1873
+ * the class pattern, so do not use new to call it. Also, instanceof check
1874
+ * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
1875
+ * if something is a React Element.
1876
+ *
1877
+ * @param {*} type
1878
+ * @param {*} props
1879
+ * @param {*} key
1880
+ * @param {string|object} ref
1881
+ * @param {*} owner
1882
+ * @param {*} self A *temporary* helper to detect places where `this` is
1883
+ * different from the `owner` when React.createElement is called, so that we
1884
+ * can warn. We want to get rid of owner and replace string `ref`s with arrow
1885
+ * functions, and as long as `this` and owner are the same, there will be no
1886
+ * change in behavior.
1887
+ * @param {*} source An annotation object (added by a transpiler or otherwise)
1888
+ * indicating filename, line number, and/or other information.
1889
+ * @internal
1890
+ */
1891
+
1892
+
1893
+ var ReactElement = function (type, key, ref, self, source, owner, props) {
1894
+ var element = {
1895
+ // This tag allows us to uniquely identify this as a React Element
1896
+ $$typeof: REACT_ELEMENT_TYPE,
1897
+ // Built-in properties that belong on the element
1898
+ type: type,
1899
+ key: key,
1900
+ ref: ref,
1901
+ props: props,
1902
+ // Record the component responsible for creating this element.
1903
+ _owner: owner
1904
+ };
1905
+
1906
+ {
1907
+ // The validation flag is currently mutative. We put it on
1908
+ // an external backing store so that we can freeze the whole object.
1909
+ // This can be replaced with a WeakMap once they are implemented in
1910
+ // commonly used development environments.
1911
+ element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
1912
+ // the validation flag non-enumerable (where possible, which should
1913
+ // include every environment we run tests in), so the test framework
1914
+ // ignores it.
1915
+
1916
+ Object.defineProperty(element._store, 'validated', {
1917
+ configurable: false,
1918
+ enumerable: false,
1919
+ writable: true,
1920
+ value: false
1921
+ }); // self and source are DEV only properties.
1922
+
1923
+ Object.defineProperty(element, '_self', {
1924
+ configurable: false,
1925
+ enumerable: false,
1926
+ writable: false,
1927
+ value: self
1928
+ }); // Two elements created in two different places should be considered
1929
+ // equal for testing purposes and therefore we hide it from enumeration.
1930
+
1931
+ Object.defineProperty(element, '_source', {
1932
+ configurable: false,
1933
+ enumerable: false,
1934
+ writable: false,
1935
+ value: source
1936
+ });
1937
+
1938
+ if (Object.freeze) {
1939
+ Object.freeze(element.props);
1940
+ Object.freeze(element);
1941
+ }
1942
+ }
1943
+
1944
+ return element;
1945
+ };
1946
+ /**
1947
+ * https://github.com/reactjs/rfcs/pull/107
1948
+ * @param {*} type
1949
+ * @param {object} props
1950
+ * @param {string} key
1951
+ */
1952
+
1953
+ function jsxDEV(type, config, maybeKey, source, self) {
1954
+ {
1955
+ var propName; // Reserved names are extracted
1956
+
1957
+ var props = {};
1958
+ var key = null;
1959
+ var ref = null; // Currently, key can be spread in as a prop. This causes a potential
1960
+ // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
1961
+ // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
1962
+ // but as an intermediary step, we will use jsxDEV for everything except
1963
+ // <div {...props} key="Hi" />, because we aren't currently able to tell if
1964
+ // key is explicitly declared to be undefined or not.
1965
+
1966
+ if (maybeKey !== undefined) {
1967
+ {
1968
+ checkKeyStringCoercion(maybeKey);
1969
+ }
1970
+
1971
+ key = '' + maybeKey;
1972
+ }
1973
+
1974
+ if (hasValidKey(config)) {
1975
+ {
1976
+ checkKeyStringCoercion(config.key);
1977
+ }
1978
+
1979
+ key = '' + config.key;
1980
+ }
1981
+
1982
+ if (hasValidRef(config)) {
1983
+ ref = config.ref;
1984
+ warnIfStringRefCannotBeAutoConverted(config, self);
1985
+ } // Remaining properties are added to a new props object
1986
+
1987
+
1988
+ for (propName in config) {
1989
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1990
+ props[propName] = config[propName];
1991
+ }
1992
+ } // Resolve default props
1993
+
1994
+
1995
+ if (type && type.defaultProps) {
1996
+ var defaultProps = type.defaultProps;
1997
+
1998
+ for (propName in defaultProps) {
1999
+ if (props[propName] === undefined) {
2000
+ props[propName] = defaultProps[propName];
2001
+ }
2002
+ }
2003
+ }
2004
+
2005
+ if (key || ref) {
2006
+ var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
2007
+
2008
+ if (key) {
2009
+ defineKeyPropWarningGetter(props, displayName);
2010
+ }
2011
+
2012
+ if (ref) {
2013
+ defineRefPropWarningGetter(props, displayName);
2014
+ }
2015
+ }
2016
+
2017
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
2018
+ }
2019
+ }
2020
+
2021
+ var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
2022
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2023
+
2024
+ function setCurrentlyValidatingElement$1(element) {
2025
+ {
2026
+ if (element) {
2027
+ var owner = element._owner;
2028
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
2029
+ ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
2030
+ } else {
2031
+ ReactDebugCurrentFrame$1.setExtraStackFrame(null);
2032
+ }
2033
+ }
2034
+ }
2035
+
2036
+ var propTypesMisspellWarningShown;
2037
+
2038
+ {
2039
+ propTypesMisspellWarningShown = false;
2040
+ }
2041
+ /**
2042
+ * Verifies the object is a ReactElement.
2043
+ * See https://reactjs.org/docs/react-api.html#isvalidelement
2044
+ * @param {?object} object
2045
+ * @return {boolean} True if `object` is a ReactElement.
2046
+ * @final
2047
+ */
2048
+
2049
+
2050
+ function isValidElement(object) {
2051
+ {
2052
+ return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
2053
+ }
2054
+ }
2055
+
2056
+ function getDeclarationErrorAddendum() {
2057
+ {
2058
+ if (ReactCurrentOwner$1.current) {
2059
+ var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
2060
+
2061
+ if (name) {
2062
+ return '\n\nCheck the render method of `' + name + '`.';
2063
+ }
2064
+ }
2065
+
2066
+ return '';
2067
+ }
2068
+ }
2069
+
2070
+ function getSourceInfoErrorAddendum(source) {
2071
+ {
2072
+
2073
+ return '';
2074
+ }
2075
+ }
2076
+ /**
2077
+ * Warn if there's no key explicitly set on dynamic arrays of children or
2078
+ * object keys are not valid. This allows us to keep track of children between
2079
+ * updates.
2080
+ */
2081
+
2082
+
2083
+ var ownerHasKeyUseWarning = {};
2084
+
2085
+ function getCurrentComponentErrorInfo(parentType) {
2086
+ {
2087
+ var info = getDeclarationErrorAddendum();
2088
+
2089
+ if (!info) {
2090
+ var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
2091
+
2092
+ if (parentName) {
2093
+ info = "\n\nCheck the top-level render call using <" + parentName + ">.";
2094
+ }
2095
+ }
2096
+
2097
+ return info;
2098
+ }
2099
+ }
2100
+ /**
2101
+ * Warn if the element doesn't have an explicit key assigned to it.
2102
+ * This element is in an array. The array could grow and shrink or be
2103
+ * reordered. All children that haven't already been validated are required to
2104
+ * have a "key" property assigned to it. Error statuses are cached so a warning
2105
+ * will only be shown once.
2106
+ *
2107
+ * @internal
2108
+ * @param {ReactElement} element Element that requires a key.
2109
+ * @param {*} parentType element's parent's type.
2110
+ */
2111
+
2112
+
2113
+ function validateExplicitKey(element, parentType) {
2114
+ {
2115
+ if (!element._store || element._store.validated || element.key != null) {
2116
+ return;
2117
+ }
2118
+
2119
+ element._store.validated = true;
2120
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
2121
+
2122
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
2123
+ return;
2124
+ }
2125
+
2126
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
2127
+ // property, it may be the creator of the child that's responsible for
2128
+ // assigning it a key.
2129
+
2130
+ var childOwner = '';
2131
+
2132
+ if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
2133
+ // Give the component that originally created this child.
2134
+ childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
2135
+ }
2136
+
2137
+ setCurrentlyValidatingElement$1(element);
2138
+
2139
+ error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
2140
+
2141
+ setCurrentlyValidatingElement$1(null);
2142
+ }
2143
+ }
2144
+ /**
2145
+ * Ensure that every element either is passed in a static location, in an
2146
+ * array with an explicit keys property defined, or in an object literal
2147
+ * with valid key property.
2148
+ *
2149
+ * @internal
2150
+ * @param {ReactNode} node Statically passed child of any type.
2151
+ * @param {*} parentType node's parent's type.
2152
+ */
2153
+
2154
+
2155
+ function validateChildKeys(node, parentType) {
2156
+ {
2157
+ if (typeof node !== 'object') {
2158
+ return;
2159
+ }
2160
+
2161
+ if (isArray(node)) {
2162
+ for (var i = 0; i < node.length; i++) {
2163
+ var child = node[i];
2164
+
2165
+ if (isValidElement(child)) {
2166
+ validateExplicitKey(child, parentType);
2167
+ }
2168
+ }
2169
+ } else if (isValidElement(node)) {
2170
+ // This element was passed in a valid location.
2171
+ if (node._store) {
2172
+ node._store.validated = true;
2173
+ }
2174
+ } else if (node) {
2175
+ var iteratorFn = getIteratorFn(node);
2176
+
2177
+ if (typeof iteratorFn === 'function') {
2178
+ // Entry iterators used to provide implicit keys,
2179
+ // but now we print a separate warning for them later.
2180
+ if (iteratorFn !== node.entries) {
2181
+ var iterator = iteratorFn.call(node);
2182
+ var step;
2183
+
2184
+ while (!(step = iterator.next()).done) {
2185
+ if (isValidElement(step.value)) {
2186
+ validateExplicitKey(step.value, parentType);
2187
+ }
2188
+ }
2189
+ }
2190
+ }
2191
+ }
2192
+ }
2193
+ }
2194
+ /**
2195
+ * Given an element, validate that its props follow the propTypes definition,
2196
+ * provided by the type.
2197
+ *
2198
+ * @param {ReactElement} element
2199
+ */
2200
+
2201
+
2202
+ function validatePropTypes(element) {
2203
+ {
2204
+ var type = element.type;
2205
+
2206
+ if (type === null || type === undefined || typeof type === 'string') {
2207
+ return;
2208
+ }
2209
+
2210
+ var propTypes;
2211
+
2212
+ if (typeof type === 'function') {
2213
+ propTypes = type.propTypes;
2214
+ } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
2215
+ // Inner props are checked in the reconciler.
2216
+ type.$$typeof === REACT_MEMO_TYPE)) {
2217
+ propTypes = type.propTypes;
2218
+ } else {
2219
+ return;
2220
+ }
2221
+
2222
+ if (propTypes) {
2223
+ // Intentionally inside to avoid triggering lazy initializers:
2224
+ var name = getComponentNameFromType(type);
2225
+ checkPropTypes(propTypes, element.props, 'prop', name, element);
2226
+ } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
2227
+ propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
2228
+
2229
+ var _name = getComponentNameFromType(type);
2230
+
2231
+ error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
2232
+ }
2233
+
2234
+ if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
2235
+ error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
2236
+ }
2237
+ }
2238
+ }
2239
+ /**
2240
+ * Given a fragment, validate that it can only be provided with fragment props
2241
+ * @param {ReactElement} fragment
2242
+ */
2243
+
2244
+
2245
+ function validateFragmentProps(fragment) {
2246
+ {
2247
+ var keys = Object.keys(fragment.props);
2248
+
2249
+ for (var i = 0; i < keys.length; i++) {
2250
+ var key = keys[i];
2251
+
2252
+ if (key !== 'children' && key !== 'key') {
2253
+ setCurrentlyValidatingElement$1(fragment);
2254
+
2255
+ error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
2256
+
2257
+ setCurrentlyValidatingElement$1(null);
2258
+ break;
2259
+ }
2260
+ }
2261
+
2262
+ if (fragment.ref !== null) {
2263
+ setCurrentlyValidatingElement$1(fragment);
2264
+
2265
+ error('Invalid attribute `ref` supplied to `React.Fragment`.');
2266
+
2267
+ setCurrentlyValidatingElement$1(null);
2268
+ }
2269
+ }
2270
+ }
2271
+
2272
+ var didWarnAboutKeySpread = {};
2273
+ function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
2274
+ {
2275
+ var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
2276
+ // succeed and there will likely be errors in render.
2277
+
2278
+ if (!validType) {
2279
+ var info = '';
2280
+
2281
+ if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
2282
+ info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
2283
+ }
2284
+
2285
+ var sourceInfo = getSourceInfoErrorAddendum();
2286
+
2287
+ if (sourceInfo) {
2288
+ info += sourceInfo;
2289
+ } else {
2290
+ info += getDeclarationErrorAddendum();
2291
+ }
2292
+
2293
+ var typeString;
2294
+
2295
+ if (type === null) {
2296
+ typeString = 'null';
2297
+ } else if (isArray(type)) {
2298
+ typeString = 'array';
2299
+ } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
2300
+ typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
2301
+ info = ' Did you accidentally export a JSX literal instead of a component?';
2302
+ } else {
2303
+ typeString = typeof type;
2304
+ }
2305
+
2306
+ error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
2307
+ }
2308
+
2309
+ var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
2310
+ // TODO: Drop this when these are no longer allowed as the type argument.
2311
+
2312
+ if (element == null) {
2313
+ return element;
2314
+ } // Skip key warning if the type isn't valid since our key validation logic
2315
+ // doesn't expect a non-string/function type and can throw confusing errors.
2316
+ // We don't want exception behavior to differ between dev and prod.
2317
+ // (Rendering will throw with a helpful message and as soon as the type is
2318
+ // fixed, the key warnings will appear.)
2319
+
2320
+
2321
+ if (validType) {
2322
+ var children = props.children;
2323
+
2324
+ if (children !== undefined) {
2325
+ if (isStaticChildren) {
2326
+ if (isArray(children)) {
2327
+ for (var i = 0; i < children.length; i++) {
2328
+ validateChildKeys(children[i], type);
2329
+ }
2330
+
2331
+ if (Object.freeze) {
2332
+ Object.freeze(children);
2333
+ }
2334
+ } else {
2335
+ error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
2336
+ }
2337
+ } else {
2338
+ validateChildKeys(children, type);
2339
+ }
2340
+ }
2341
+ }
2342
+
2343
+ {
2344
+ if (hasOwnProperty.call(props, 'key')) {
2345
+ var componentName = getComponentNameFromType(type);
2346
+ var keys = Object.keys(props).filter(function (k) {
2347
+ return k !== 'key';
2348
+ });
2349
+ var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
2350
+
2351
+ if (!didWarnAboutKeySpread[componentName + beforeExample]) {
2352
+ var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
2353
+
2354
+ error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
2355
+
2356
+ didWarnAboutKeySpread[componentName + beforeExample] = true;
2357
+ }
2358
+ }
2359
+ }
2360
+
2361
+ if (type === REACT_FRAGMENT_TYPE) {
2362
+ validateFragmentProps(element);
2363
+ } else {
2364
+ validatePropTypes(element);
2365
+ }
2366
+
2367
+ return element;
2368
+ }
2369
+ } // These two functions exist to still get child warnings in dev
2370
+ // even with the prod transform. This means that jsxDEV is purely
2371
+ // opt-in behavior for better messages but that we won't stop
2372
+ // giving you warnings if you use production apis.
2373
+
2374
+ function jsxWithValidationStatic(type, props, key) {
2375
+ {
2376
+ return jsxWithValidation(type, props, key, true);
2377
+ }
2378
+ }
2379
+ function jsxWithValidationDynamic(type, props, key) {
2380
+ {
2381
+ return jsxWithValidation(type, props, key, false);
2382
+ }
2383
+ }
2384
+
2385
+ var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
2386
+ // for now we can ship identical prod functions
2387
+
2388
+ var jsxs = jsxWithValidationStatic ;
2389
+
2390
+ reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
2391
+ reactJsxRuntime_development.jsx = jsx;
2392
+ reactJsxRuntime_development.jsxs = jsxs;
2393
+ })();
2394
+ }
2395
+ return reactJsxRuntime_development;
2396
+ }
2397
+
2398
+ if (process.env.NODE_ENV === 'production') {
2399
+ jsxRuntime.exports = requireReactJsxRuntime_production_min();
2400
+ } else {
2401
+ jsxRuntime.exports = requireReactJsxRuntime_development();
2402
+ }
2403
+
2404
+ var jsxRuntimeExports = jsxRuntime.exports;
2405
+
2406
+ const MauticForm = ({ formId, title, description, className = '', form, onSubmit, onSuccess, onError, }) => {
2407
+ const [formData, setFormData] = React.useState({});
2408
+ const [errors, setErrors] = React.useState({});
2409
+ const [isSubmitting, setIsSubmitting] = React.useState(false);
2410
+ const [isSubmitted, setIsSubmitted] = React.useState(false);
2411
+ const [showSuccessMessage, setShowSuccessMessage] = React.useState(false);
2412
+ const submitMutation = useMauticFormSubmission();
2413
+ React.useEffect(() => {
2414
+ if (!form) {
2415
+ console.warn(`Form ${formId} not found`);
2416
+ return;
2417
+ }
2418
+ // Initialize form data with default values
2419
+ const initialData = {};
2420
+ form.fields.forEach(field => {
2421
+ // Skip button/submit fields from initial state, they are rendered separately
2422
+ if (field.type === 'button' || field.alias === 'submit') {
2423
+ return;
2424
+ }
2425
+ if (field.defaultValue) {
2426
+ initialData[field.alias] = field.defaultValue;
2427
+ }
2428
+ else if (field.type === 'checkbox') {
2429
+ initialData[field.alias] = false;
2430
+ }
2431
+ else if (field.type === 'radio') {
2432
+ initialData[field.alias] = '';
2433
+ }
2434
+ else {
2435
+ initialData[field.alias] = '';
2436
+ }
2437
+ });
2438
+ setFormData(initialData);
2439
+ }, [formId, form]);
2440
+ const validateField = (field, value) => {
2441
+ if (field.isRequired && (!value || value === '')) {
2442
+ return field.validationMessage || `${field.label} is required`;
2443
+ }
2444
+ if (field.type === 'email' && value && !/\S+@\S+\.\S+/.test(value)) {
2445
+ return 'Please enter a valid email address';
2446
+ }
2447
+ return null;
2448
+ };
2449
+ const validateForm = () => {
2450
+ if (!form)
2451
+ return false;
2452
+ const newErrors = {};
2453
+ let isValid = true;
2454
+ form.fields.forEach(field => {
2455
+ const error = validateField(field, formData[field.alias]);
2456
+ if (error) {
2457
+ newErrors[field.alias] = error;
2458
+ isValid = false;
2459
+ }
2460
+ });
2461
+ setErrors(newErrors);
2462
+ return isValid;
2463
+ };
2464
+ const handleSubmit = async (e) => {
2465
+ e.preventDefault();
2466
+ if (!form)
2467
+ return;
2468
+ if (!validateForm()) {
2469
+ return;
2470
+ }
2471
+ setIsSubmitting(true);
2472
+ setErrors({});
2473
+ try {
2474
+ // Derive the exact Mautic formName (alias) from cachedHtml if available
2475
+ let derivedFormName = undefined;
2476
+ const cachedHtml = form?.cachedHtml;
2477
+ if (cachedHtml) {
2478
+ const byDataAttr = cachedHtml.match(/data-mautic-form=\"([a-zA-Z0-9_-]+)\"/);
2479
+ const byId = cachedHtml.match(/id=\"mauticform_([a-zA-Z0-9_-]+)\"/);
2480
+ derivedFormName = (byDataAttr?.[1] || byId?.[1])?.trim();
2481
+ }
2482
+ const submissionData = {
2483
+ formId: parseInt(formId),
2484
+ fields: formData,
2485
+ returnUrl: window.location.href,
2486
+ ...(derivedFormName ? { formName: derivedFormName } : {})
2487
+ };
2488
+ // Call custom onSubmit if provided
2489
+ if (onSubmit) {
2490
+ onSubmit(submissionData);
2491
+ }
2492
+ // Submit to Mautic
2493
+ const result = await submitMutation.mutateAsync(submissionData);
2494
+ // Handle post-action behavior: if form specifies redirect, do it client-side
2495
+ const postAction = form.postAction || 'message';
2496
+ const postActionProperty = form.postActionProperty || '';
2497
+ if (postAction === 'redirect' && postActionProperty) {
2498
+ // Perform a client-side redirect instead of relying on Mautic
2499
+ window.location.assign(postActionProperty);
2500
+ return;
2501
+ }
2502
+ setIsSubmitted(true);
2503
+ setShowSuccessMessage(true);
2504
+ // Call custom onSuccess if provided
2505
+ if (onSuccess) {
2506
+ onSuccess(result);
2507
+ }
2508
+ // Hide success message after 5 seconds
2509
+ setTimeout(() => {
2510
+ setShowSuccessMessage(false);
2511
+ }, 5000);
2512
+ }
2513
+ catch (error) {
2514
+ console.error('Form submission error:', error);
2515
+ // Call custom onError if provided
2516
+ if (onError) {
2517
+ onError(error);
2518
+ }
2519
+ }
2520
+ finally {
2521
+ setIsSubmitting(false);
2522
+ }
2523
+ };
2524
+ const handleInputChange = (field, value) => {
2525
+ setFormData(prev => ({
2526
+ ...prev,
2527
+ [field.alias]: value,
2528
+ }));
2529
+ // Clear error when user starts typing
2530
+ if (errors[field.alias]) {
2531
+ setErrors(prev => ({
2532
+ ...prev,
2533
+ [field.alias]: '',
2534
+ }));
2535
+ }
2536
+ };
2537
+ const renderField = (field) => {
2538
+ const value = formData[field.alias] || '';
2539
+ const error = errors[field.alias];
2540
+ const baseProps = {
2541
+ id: field.alias,
2542
+ name: field.alias,
2543
+ placeholder: field.properties?.placeholder,
2544
+ className: `form-control ${field.properties?.cssClass || ''} ${error ? 'error' : ''}`,
2545
+ required: field.isRequired,
2546
+ };
2547
+ switch (field.type) {
2548
+ case 'text':
2549
+ case 'email':
2550
+ case 'tel':
2551
+ case 'url':
2552
+ return (jsxRuntimeExports.jsx("input", { ...baseProps, type: field.type, value: value, onChange: (e) => handleInputChange(field, e.target.value) }));
2553
+ case 'textarea':
2554
+ return (jsxRuntimeExports.jsx("textarea", { ...baseProps, value: value, onChange: (e) => handleInputChange(field, e.target.value), rows: 4 }));
2555
+ case 'select':
2556
+ return (jsxRuntimeExports.jsxs("select", { ...baseProps, value: value, onChange: (e) => handleInputChange(field, e.target.value), children: [jsxRuntimeExports.jsx("option", { value: "", children: "Select an option" }), field.properties?.options?.map((option, index) => (jsxRuntimeExports.jsx("option", { value: option, children: option }, index)))] }));
2557
+ case 'checkbox':
2558
+ return (jsxRuntimeExports.jsx("input", { ...baseProps, type: "checkbox", checked: value, onChange: (e) => handleInputChange(field, e.target.checked) }));
2559
+ case 'radio':
2560
+ return (jsxRuntimeExports.jsx("div", { className: "radio-group", children: field.properties?.options?.map((option, index) => (jsxRuntimeExports.jsxs("label", { className: "radio-option", children: [jsxRuntimeExports.jsx("input", { type: "radio", name: field.alias, value: option, checked: value === option, onChange: (e) => handleInputChange(field, e.target.value) }), jsxRuntimeExports.jsx("span", { children: option })] }, index))) }));
2561
+ default:
2562
+ return (jsxRuntimeExports.jsx("input", { ...baseProps, type: "text", value: value, onChange: (e) => handleInputChange(field, e.target.value) }));
2563
+ }
2564
+ };
2565
+ if (!form) {
2566
+ return (jsxRuntimeExports.jsx("div", { className: `mautic-form-error ${className}`, children: jsxRuntimeExports.jsxs("p", { children: ["Form ", formId, " not found. Please check your configuration."] }) }));
2567
+ }
2568
+ if (isSubmitted && showSuccessMessage) {
2569
+ const successMessage = form.postActionProperty || 'Thank you for your submission!';
2570
+ return (jsxRuntimeExports.jsx("div", { className: `mautic-form-success ${className}`, children: jsxRuntimeExports.jsxs("div", { className: "success-message", children: [jsxRuntimeExports.jsx("h3", { children: "Success!" }), jsxRuntimeExports.jsx("p", { children: successMessage })] }) }));
2571
+ }
2572
+ return (jsxRuntimeExports.jsxs("form", { className: `mautic-form ${className}`, onSubmit: handleSubmit, children: [(title || form.name) && (jsxRuntimeExports.jsxs("div", { className: "form-header", children: [jsxRuntimeExports.jsx("h3", { children: title || form.name }), (description || form.description) && (jsxRuntimeExports.jsx("p", { className: "form-description", children: description || form.description }))] })), jsxRuntimeExports.jsx("div", { className: "form-fields", children: form.fields
2573
+ // Filter out button/submit from field group; render them in actions
2574
+ .filter((field) => field.type !== 'button' && field.alias !== 'submit')
2575
+ .map((field) => (jsxRuntimeExports.jsxs("div", { className: `form-field form-field-${field.type}`, children: [field.showLabel !== false && (jsxRuntimeExports.jsxs("label", { htmlFor: field.alias, className: "field-label", children: [field.label, field.isRequired && jsxRuntimeExports.jsx("span", { className: "required", children: "*" })] })), renderField(field), field.properties?.helpText && (jsxRuntimeExports.jsx("p", { className: "field-help", children: field.properties.helpText })), errors[field.alias] && (jsxRuntimeExports.jsx("p", { className: "field-error", children: errors[field.alias] }))] }, field.id))) }), jsxRuntimeExports.jsx("div", { className: "form-actions", children: jsxRuntimeExports.jsx("button", { type: "submit", disabled: isSubmitting, className: "submit-button", children: isSubmitting ? 'Submitting...' : 'Submit' }) }), submitMutation.error && (jsxRuntimeExports.jsx("div", { className: "form-error", children: jsxRuntimeExports.jsx("p", { children: "There was an error submitting the form. Please try again." }) }))] }));
2576
+ };
2577
+
2578
+ const MauticTracking = ({ enabled, mauticUrl, proxyUrl, appId, workerSecret, children }) => {
2579
+ React.useEffect(() => {
2580
+ // Determine if tracking is enabled
2581
+ const isEnabled = enabled ?? (!!proxyUrl && !!appId && !!workerSecret);
2582
+ const trackingProxyUrl = proxyUrl;
2583
+ // Debug logging to understand configuration
2584
+ if (undefined?.DEV) {
2585
+ console.log('🔍 Mautic Tracking Debug:', {
2586
+ isEnabled,
2587
+ mauticUrl,
2588
+ trackingProxyUrl,
2589
+ hasAppId: !!appId,
2590
+ hasWorkerSecret: !!workerSecret,
2591
+ isDev: undefined?.DEV,
2592
+ isProd: undefined?.PROD
2593
+ });
2594
+ }
2595
+ // Check if tracking is enabled
2596
+ if (!isEnabled) {
2597
+ console.log('Mautic tracking disabled - not enabled in configuration');
2598
+ return;
2599
+ }
2600
+ // Check if we're in development mode - skip tracking in dev
2601
+ if (undefined?.DEV) {
2602
+ console.log('Mautic tracking disabled in development mode');
2603
+ return;
2604
+ }
2605
+ // Require proxy URL in proxy mode
2606
+ if (!trackingProxyUrl) {
2607
+ console.warn('Mautic tracking disabled - proxy URL not configured');
2608
+ return;
2609
+ }
2610
+ console.log('✅ Mautic tracking enabled for production');
2611
+ // Initialize Mautic tracking with error handling
2612
+ try {
2613
+ // Pre-initialize tracking object and queue (standard Mautic snippet behavior)
2614
+ window.MauticTrackingObject = 'mt';
2615
+ window.mt = window.mt || function () {
2616
+ (window.mt.q = window.mt.q || []).push(arguments);
2617
+ };
2618
+ // Intercept Mautic tracking API calls to use our proxy (generic /mtc/ matcher)
2619
+ const originalFetch = window.fetch.bind(window);
2620
+ const interceptFetch = function (url, options) {
2621
+ if (typeof url === 'string' && /\/mtc\//.test(url)) {
2622
+ try {
2623
+ const proxyUrl = url.replace(/https?:\/\/[^/]+\/mtc\//, `${trackingProxyUrl}?endpoint=/mtc/`);
2624
+ const proxyOptions = {
2625
+ ...options,
2626
+ headers: {
2627
+ ...options?.headers,
2628
+ 'Content-Type': 'application/json',
2629
+ 'x-app-id': appId || '',
2630
+ ...(workerSecret ? { 'x-app-secret': workerSecret } : {})
2631
+ }
2632
+ };
2633
+ return originalFetch(proxyUrl, proxyOptions);
2634
+ }
2635
+ catch (e) {
2636
+ console.warn('Failed to rewrite Mautic tracking call to proxy', e);
2637
+ }
2638
+ }
2639
+ return originalFetch(url, options);
2640
+ };
2641
+ window.fetch = interceptFetch;
2642
+ // Fetch the tracking script through the proxy with required headers
2643
+ const trackingScriptUrl = `${trackingProxyUrl}?endpoint=/mtc.js`;
2644
+ fetch(trackingScriptUrl, {
2645
+ method: 'GET',
2646
+ headers: {
2647
+ 'Content-Type': 'application/javascript',
2648
+ 'x-app-id': appId || '',
2649
+ ...(workerSecret ? { 'x-app-secret': workerSecret } : {})
2650
+ }
2651
+ })
2652
+ .then(response => {
2653
+ if (!response.ok) {
2654
+ throw new Error(`Failed to load Mautic tracking script: ${response.status}`);
2655
+ }
2656
+ return response.text();
2657
+ })
2658
+ .then(scriptContent => {
2659
+ // Execute the tracking script
2660
+ const script = document.createElement('script');
2661
+ script.textContent = scriptContent;
2662
+ script.async = true;
2663
+ document.head.appendChild(script);
2664
+ console.log('✅ Mautic tracking script loaded successfully');
2665
+ // Send initial pageview
2666
+ if (window.mt) {
2667
+ window.mt('send', 'pageview');
2668
+ }
2669
+ })
2670
+ .catch(error => {
2671
+ console.error('❌ Failed to load Mautic tracking script:', error);
2672
+ });
2673
+ }
2674
+ catch (error) {
2675
+ console.error('❌ Error initializing Mautic tracking:', error);
2676
+ }
2677
+ // Cleanup function
2678
+ return () => {
2679
+ // Restore original fetch if needed
2680
+ if (window.fetch !== originalFetch) {
2681
+ window.fetch = originalFetch;
2682
+ }
2683
+ };
2684
+ }, [enabled, mauticUrl, proxyUrl, appId, workerSecret]);
2685
+ // Render children if provided, otherwise render nothing
2686
+ return children ? jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children }) : null;
2687
+ };
2688
+ /**
2689
+ * Hook to check if Mautic tracking is available
2690
+ */
2691
+ const useMauticTracking = () => {
2692
+ const [isAvailable, setIsAvailable] = React.useState(false);
2693
+ React.useEffect(() => {
2694
+ const checkAvailability = () => {
2695
+ setIsAvailable(!!(window.mt && typeof window.mt === 'function'));
2696
+ };
2697
+ // Check immediately
2698
+ checkAvailability();
2699
+ // Check periodically in case script loads later
2700
+ const interval = setInterval(checkAvailability, 1000);
2701
+ // Cleanup
2702
+ return () => clearInterval(interval);
2703
+ }, []);
2704
+ return isAvailable;
2705
+ };
2706
+ /**
2707
+ * Hook to track Mautic events
2708
+ */
2709
+ const useMauticEvent = () => {
2710
+ const isAvailable = useMauticTracking();
2711
+ const trackEvent = React.useCallback((eventName, eventData) => {
2712
+ if (isAvailable && window.mt) {
2713
+ window.mt('send', 'event', eventName, eventData);
2714
+ }
2715
+ else {
2716
+ console.warn('Mautic tracking not available');
2717
+ }
2718
+ }, [isAvailable]);
2719
+ const trackPageview = React.useCallback(() => {
2720
+ if (isAvailable && window.mt) {
2721
+ window.mt('send', 'pageview');
2722
+ }
2723
+ else {
2724
+ console.warn('Mautic tracking not available');
2725
+ }
2726
+ }, [isAvailable]);
2727
+ return {
2728
+ isAvailable,
2729
+ trackEvent,
2730
+ trackPageview,
2731
+ };
2732
+ };
2733
+
2734
+ const MauticContext = React.createContext(null);
2735
+ const MauticProvider = ({ config, children }) => {
2736
+ const client = React.useMemo(() => {
2737
+ const mauticClient = new MauticClient(config);
2738
+ setMauticClient(mauticClient);
2739
+ return mauticClient;
2740
+ }, [config]);
2741
+ const value = React.useMemo(() => ({
2742
+ client,
2743
+ config,
2744
+ }), [client, config]);
2745
+ return (jsxRuntimeExports.jsx(MauticContext.Provider, { value: value, children: children }));
2746
+ };
2747
+ /**
2748
+ * Hook to use Mautic context
2749
+ */
2750
+ const useMauticContext = () => {
2751
+ const context = React.useContext(MauticContext);
2752
+ if (!context) {
2753
+ throw new Error('useMauticContext must be used within a MauticProvider');
2754
+ }
2755
+ return context;
2756
+ };
2757
+ /**
2758
+ * Hook to get Mautic client from context
2759
+ */
2760
+ const useMauticClient = () => {
2761
+ const { client } = useMauticContext();
2762
+ return client;
2763
+ };
2764
+ /**
2765
+ * Hook to get Mautic config from context
2766
+ */
2767
+ const useMauticConfig = () => {
2768
+ const { config } = useMauticContext();
2769
+ return config;
2770
+ };
2771
+
2772
+ /**
2773
+ * @license GPL-3.0-or-later
2774
+ *
2775
+ * This file is part of the MarVAlt Open SDK.
2776
+ * Copyright (c) 2025 Vibune Pty Ltd.
2777
+ *
2778
+ * This program is free software: you can redistribute it and/or modify
2779
+ * it under the terms of the GNU General Public License as published by
2780
+ * the Free Software Foundation, either version 3 of the License, or
2781
+ * (at your option) any later version.
2782
+ *
2783
+ * This program is distributed in the hope that it will be useful,
2784
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
2785
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2786
+ * See the GNU General Public License for more details.
2787
+ */
2788
+ // Default empty data store
2789
+ const defaultDataStore = {
2790
+ generated_at: new Date().toISOString(),
2791
+ forms: [],
2792
+ };
2793
+ // Global data store instance
2794
+ let mauticDataStore = defaultDataStore;
2795
+ /**
2796
+ * Load Mautic data from JSON file
2797
+ */
2798
+ const loadMauticData = async () => {
2799
+ try {
2800
+ const response = await fetch('/mautic-data.json');
2801
+ if (!response.ok) {
2802
+ console.warn('Failed to load mautic-data.json:', response.status, response.statusText);
2803
+ return defaultDataStore;
2804
+ }
2805
+ const jsonData = await response.json().catch(() => ({}));
2806
+ // Transform the JSON data to match our interface
2807
+ const transformedForms = (Array.isArray(jsonData.forms) ? jsonData.forms : []).map((formData) => ({
2808
+ id: formData.id,
2809
+ name: formData.name,
2810
+ alias: formData.alias || formData.name?.toLowerCase().replace(/\s+/g, '-'),
2811
+ description: formData.description,
2812
+ isPublished: formData.isPublished,
2813
+ fields: (formData.fields || []).map((field) => ({
2814
+ id: field.id,
2815
+ label: field.label,
2816
+ alias: field.alias,
2817
+ type: field.type,
2818
+ isRequired: field.isRequired,
2819
+ validationMessage: field.validationMessage,
2820
+ defaultValue: field.defaultValue,
2821
+ properties: field.properties || {}
2822
+ })),
2823
+ actions: formData.actions || [],
2824
+ cssClass: formData.cssClass,
2825
+ submitAction: formData.submitAction,
2826
+ postAction: formData.postAction || 'message',
2827
+ postActionProperty: formData.postActionProperty || 'Thank you for your submission!',
2828
+ formType: formData.formType || 'standalone'
2829
+ }));
2830
+ mauticDataStore = {
2831
+ generated_at: jsonData.generated_at || new Date().toISOString(),
2832
+ forms: transformedForms
2833
+ };
2834
+ console.log('✅ Mautic data loaded successfully:', {
2835
+ totalForms: mauticDataStore.forms.length,
2836
+ publishedForms: mauticDataStore.forms.filter(f => f.isPublished).length
2837
+ });
2838
+ return mauticDataStore;
2839
+ }
2840
+ catch (error) {
2841
+ console.error('❌ Error loading Mautic data:', error);
2842
+ return defaultDataStore;
2843
+ }
2844
+ };
2845
+ /**
2846
+ * Get the current Mautic data store
2847
+ */
2848
+ const getMauticData = () => {
2849
+ return mauticDataStore;
2850
+ };
2851
+ /**
2852
+ * Get all published forms
2853
+ */
2854
+ const getPublishedForms = () => {
2855
+ return mauticDataStore.forms.filter(form => form.isPublished);
2856
+ };
2857
+ /**
2858
+ * Get form by ID
2859
+ */
2860
+ const getFormById = (id) => {
2861
+ return mauticDataStore.forms.find(form => form.id === id);
2862
+ };
2863
+ /**
2864
+ * Get form by alias
2865
+ */
2866
+ const getFormByAlias = (alias) => {
2867
+ return mauticDataStore.forms.find(form => form.alias === alias);
2868
+ };
2869
+ /**
2870
+ * Get forms by type
2871
+ */
2872
+ const getFormsByType = (type) => {
2873
+ return mauticDataStore.forms.filter(form => form.formType === type);
2874
+ };
2875
+ /**
2876
+ * Get forms by field type
2877
+ */
2878
+ const getFormsByFieldType = (fieldType) => {
2879
+ return mauticDataStore.forms.filter(form => form.fields.some(field => field.type === fieldType));
2880
+ };
2881
+ /**
2882
+ * Search forms by name or description
2883
+ */
2884
+ const searchForms = (query) => {
2885
+ const lowercaseQuery = query.toLowerCase();
2886
+ return mauticDataStore.forms.filter(form => form.name.toLowerCase().includes(lowercaseQuery) ||
2887
+ (form.description && form.description.toLowerCase().includes(lowercaseQuery)));
2888
+ };
2889
+ /**
2890
+ * Get form field by alias
2891
+ */
2892
+ const getFormFieldByAlias = (formId, fieldAlias) => {
2893
+ const form = getFormById(formId);
2894
+ return form?.fields.find(field => field.alias === fieldAlias);
2895
+ };
2896
+ /**
2897
+ * Get all unique field types across all forms
2898
+ */
2899
+ const getAllFieldTypes = () => {
2900
+ const fieldTypes = new Set();
2901
+ mauticDataStore.forms.forEach(form => {
2902
+ form.fields.forEach(field => {
2903
+ fieldTypes.add(field.type);
2904
+ });
2905
+ });
2906
+ return Array.from(fieldTypes);
2907
+ };
2908
+ /**
2909
+ * Get forms count by status
2910
+ */
2911
+ const getFormsCountByStatus = () => {
2912
+ const total = mauticDataStore.forms.length;
2913
+ const published = mauticDataStore.forms.filter(f => f.isPublished).length;
2914
+ const unpublished = total - published;
2915
+ return {
2916
+ total,
2917
+ published,
2918
+ unpublished
2919
+ };
2920
+ };
2921
+ /**
2922
+ * Check if data store is loaded
2923
+ */
2924
+ const isDataLoaded = () => {
2925
+ return mauticDataStore.forms.length > 0;
2926
+ };
2927
+ /**
2928
+ * Get data store metadata
2929
+ */
2930
+ const getDataMetadata = () => {
2931
+ return {
2932
+ generated_at: mauticDataStore.generated_at,
2933
+ total_forms: mauticDataStore.forms.length,
2934
+ published_forms: mauticDataStore.forms.filter(f => f.isPublished).length,
2935
+ field_types: getAllFieldTypes(),
2936
+ form_types: [...new Set(mauticDataStore.forms.map(f => f.formType).filter(Boolean))]
2937
+ };
2938
+ };
2939
+
2940
+ /**
2941
+ * @license GPL-3.0-or-later
2942
+ *
2943
+ * This file is part of the MarVAlt Open SDK.
2944
+ * Copyright (c) 2025 Vibune Pty Ltd.
2945
+ *
2946
+ * This program is free software: you can redistribute it and/or modify
2947
+ * it under the terms of the GNU General Public License as published by
2948
+ * the Free Software Foundation, either version 3 of the License, or
2949
+ * (at your option) any later version.
2950
+ *
2951
+ * This program is distributed in the hope that it will be useful,
2952
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
2953
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2954
+ * See the GNU General Public License for more details.
2955
+ */
2956
+ /**
2957
+ * Validate email address
2958
+ */
2959
+ const isValidEmail = (email) => {
2960
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2961
+ return emailRegex.test(email);
2962
+ };
2963
+ /**
2964
+ * Validate phone number (basic validation)
2965
+ */
2966
+ const isValidPhone = (phone) => {
2967
+ const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
2968
+ return phoneRegex.test(phone.replace(/[\s\-\(\)]/g, ''));
2969
+ };
2970
+ /**
2971
+ * Validate URL
2972
+ */
2973
+ const isValidUrl = (url) => {
2974
+ try {
2975
+ new URL(url);
2976
+ return true;
2977
+ }
2978
+ catch {
2979
+ return false;
2980
+ }
2981
+ };
2982
+ /**
2983
+ * Validate required field
2984
+ */
2985
+ const isRequiredFieldValid = (value) => {
2986
+ if (value === null || value === undefined)
2987
+ return false;
2988
+ if (typeof value === 'string')
2989
+ return value.trim().length > 0;
2990
+ if (typeof value === 'boolean')
2991
+ return true;
2992
+ if (Array.isArray(value))
2993
+ return value.length > 0;
2994
+ return true;
2995
+ };
2996
+ /**
2997
+ * Validate field based on its type and configuration
2998
+ */
2999
+ const validateField = (field, value) => {
3000
+ // Check required validation
3001
+ if (field.isRequired && !isRequiredFieldValid(value)) {
3002
+ return field.validationMessage || `${field.label} is required`;
3003
+ }
3004
+ // Skip further validation if value is empty and not required
3005
+ if (!isRequiredFieldValid(value)) {
3006
+ return null;
3007
+ }
3008
+ // Type-specific validation
3009
+ switch (field.type) {
3010
+ case 'email':
3011
+ if (!isValidEmail(value)) {
3012
+ return 'Please enter a valid email address';
3013
+ }
3014
+ break;
3015
+ case 'tel':
3016
+ if (!isValidPhone(value)) {
3017
+ return 'Please enter a valid phone number';
3018
+ }
3019
+ break;
3020
+ case 'url':
3021
+ if (!isValidUrl(value)) {
3022
+ return 'Please enter a valid URL';
3023
+ }
3024
+ break;
3025
+ case 'text':
3026
+ case 'textarea':
3027
+ if (typeof value !== 'string') {
3028
+ return 'Invalid text value';
3029
+ }
3030
+ break;
3031
+ case 'checkbox':
3032
+ if (typeof value !== 'boolean') {
3033
+ return 'Invalid checkbox value';
3034
+ }
3035
+ break;
3036
+ case 'select':
3037
+ case 'radio':
3038
+ if (field.properties?.options && !field.properties.options.includes(value)) {
3039
+ return 'Please select a valid option';
3040
+ }
3041
+ break;
3042
+ }
3043
+ // Custom validation rules
3044
+ if (field.properties?.validation) {
3045
+ for (const rule of field.properties.validation) {
3046
+ const error = validateCustomRule(rule, value, field);
3047
+ if (error)
3048
+ return error;
3049
+ }
3050
+ }
3051
+ return null;
3052
+ };
3053
+ /**
3054
+ * Validate custom validation rule
3055
+ */
3056
+ const validateCustomRule = (rule, value, field) => {
3057
+ switch (rule) {
3058
+ case 'min_length':
3059
+ if (typeof value === 'string' && value.length < (field.properties?.minLength || 0)) {
3060
+ return `Minimum length is ${field.properties?.minLength} characters`;
3061
+ }
3062
+ break;
3063
+ case 'max_length':
3064
+ if (typeof value === 'string' && value.length > (field.properties?.maxLength || 1000)) {
3065
+ return `Maximum length is ${field.properties?.maxLength} characters`;
3066
+ }
3067
+ break;
3068
+ case 'min_value':
3069
+ if (typeof value === 'number' && value < (field.properties?.minValue || 0)) {
3070
+ return `Minimum value is ${field.properties?.minValue}`;
3071
+ }
3072
+ break;
3073
+ case 'max_value':
3074
+ if (typeof value === 'number' && value > (field.properties?.maxValue || 1000000)) {
3075
+ return `Maximum value is ${field.properties?.maxValue}`;
3076
+ }
3077
+ break;
3078
+ case 'pattern':
3079
+ if (field.properties?.pattern) {
3080
+ const regex = new RegExp(field.properties.pattern);
3081
+ if (!regex.test(value)) {
3082
+ return 'Invalid format';
3083
+ }
3084
+ }
3085
+ break;
3086
+ }
3087
+ return null;
3088
+ };
3089
+ /**
3090
+ * Validate form data against form fields
3091
+ */
3092
+ const validateFormData = (fields, formData) => {
3093
+ const errors = {};
3094
+ fields.forEach(field => {
3095
+ const error = validateField(field, formData[field.alias]);
3096
+ if (error) {
3097
+ errors[field.alias] = error;
3098
+ }
3099
+ });
3100
+ return errors;
3101
+ };
3102
+ /**
3103
+ * Check if form data is valid
3104
+ */
3105
+ const isFormDataValid = (fields, formData) => {
3106
+ const errors = validateFormData(fields, formData);
3107
+ return Object.keys(errors).length === 0;
3108
+ };
3109
+ /**
3110
+ * Sanitize form data
3111
+ */
3112
+ const sanitizeFormData = (formData) => {
3113
+ const sanitized = {};
3114
+ Object.entries(formData).forEach(([key, value]) => {
3115
+ if (typeof value === 'string') {
3116
+ // Basic HTML sanitization
3117
+ sanitized[key] = value
3118
+ .replace(/</g, '&lt;')
3119
+ .replace(/>/g, '&gt;')
3120
+ .replace(/"/g, '&quot;')
3121
+ .replace(/'/g, '&#x27;')
3122
+ .trim();
3123
+ }
3124
+ else {
3125
+ sanitized[key] = value;
3126
+ }
3127
+ });
3128
+ return sanitized;
3129
+ };
3130
+ /**
3131
+ * Format form data for submission
3132
+ */
3133
+ const formatFormDataForSubmission = (formData) => {
3134
+ const formatted = {};
3135
+ Object.entries(formData).forEach(([key, value]) => {
3136
+ if (value !== null && value !== undefined && value !== '') {
3137
+ formatted[key] = value;
3138
+ }
3139
+ });
3140
+ return formatted;
3141
+ };
3142
+
3143
+ exports.MauticClient = MauticClient;
3144
+ exports.MauticForm = MauticForm;
3145
+ exports.MauticGenerator = MauticGenerator;
3146
+ exports.MauticProvider = MauticProvider;
3147
+ exports.MauticService = MauticService;
3148
+ exports.MauticTracking = MauticTracking;
3149
+ exports.createMauticConfig = createMauticConfig;
3150
+ exports.formatFormDataForSubmission = formatFormDataForSubmission;
3151
+ exports.generateMauticData = generateMauticData;
3152
+ exports.getAllFieldTypes = getAllFieldTypes;
3153
+ exports.getDataMetadata = getDataMetadata;
3154
+ exports.getDefaultMauticConfig = getDefaultMauticConfig;
3155
+ exports.getFormByAlias = getFormByAlias;
3156
+ exports.getFormById = getFormById;
3157
+ exports.getFormFieldByAlias = getFormFieldByAlias;
3158
+ exports.getFormsByFieldType = getFormsByFieldType;
3159
+ exports.getFormsByType = getFormsByType;
3160
+ exports.getFormsCountByStatus = getFormsCountByStatus;
3161
+ exports.getMauticConfigSummary = getMauticConfigSummary;
3162
+ exports.getMauticData = getMauticData;
3163
+ exports.getPublishedForms = getPublishedForms;
3164
+ exports.isDataLoaded = isDataLoaded;
3165
+ exports.isFormDataValid = isFormDataValid;
3166
+ exports.isMauticEnabled = isMauticEnabled;
3167
+ exports.isRequiredFieldValid = isRequiredFieldValid;
3168
+ exports.isValidEmail = isValidEmail;
3169
+ exports.isValidPhone = isValidPhone;
3170
+ exports.isValidUrl = isValidUrl;
3171
+ exports.loadMauticData = loadMauticData;
3172
+ exports.mauticService = mauticService;
3173
+ exports.mergeMauticConfig = mergeMauticConfig;
3174
+ exports.sanitizeFormData = sanitizeFormData;
3175
+ exports.searchForms = searchForms;
3176
+ exports.setMauticClient = setMauticClient;
3177
+ exports.useMauticAddTags = useMauticAddTags;
3178
+ exports.useMauticAddToSegment = useMauticAddToSegment;
3179
+ exports.useMauticClient = useMauticClient;
3180
+ exports.useMauticConfig = useMauticConfig;
3181
+ exports.useMauticContactByEmail = useMauticContactByEmail;
3182
+ exports.useMauticContactTags = useMauticContactTags;
3183
+ exports.useMauticContext = useMauticContext;
3184
+ exports.useMauticCreateContact = useMauticCreateContact;
3185
+ exports.useMauticEvent = useMauticEvent;
3186
+ exports.useMauticEventTracking = useMauticEventTracking;
3187
+ exports.useMauticForm = useMauticForm;
3188
+ exports.useMauticFormSubmission = useMauticFormSubmission;
3189
+ exports.useMauticForms = useMauticForms;
3190
+ exports.useMauticRemoveFromSegment = useMauticRemoveFromSegment;
3191
+ exports.useMauticRemoveTags = useMauticRemoveTags;
3192
+ exports.useMauticSegments = useMauticSegments;
3193
+ exports.useMauticTags = useMauticTags;
3194
+ exports.useMauticTracking = useMauticTracking;
3195
+ exports.useMauticUpdateContact = useMauticUpdateContact;
3196
+ exports.validateField = validateField;
3197
+ exports.validateFormData = validateFormData;
3198
+ exports.validateMauticConfig = validateMauticConfig;
3199
+ //# sourceMappingURL=index.cjs.map