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