@marvalt/wadapter 2.3.7 → 2.3.9

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.
@@ -0,0 +1,785 @@
1
+ import { writeFileSync } from 'fs';
2
+ import { join } from 'path';
3
+
4
+ /**
5
+ * @license GPL-3.0-or-later
6
+ *
7
+ * This file is part of the MarVAlt Open SDK.
8
+ * Copyright (c) 2025 Vibune Pty Ltd.
9
+ *
10
+ * This program is free software: you can redistribute it and/or modify
11
+ * it under the terms of the GNU General Public License as published by
12
+ * the Free Software Foundation, either version 3 of the License, or
13
+ * (at your option) any later version.
14
+ *
15
+ * This program is distributed in the hope that it will be useful,
16
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18
+ * See the GNU General Public License for more details.
19
+ */
20
+ class WordPressClient {
21
+ constructor(config) {
22
+ this.config = config;
23
+ }
24
+ async makeRequest(endpoint, params = {}, options = {}) {
25
+ const baseUrl = this.getBaseUrl();
26
+ const queryString = new URLSearchParams();
27
+ Object.entries(params).forEach(([key, value]) => {
28
+ if (value !== undefined && value !== null) {
29
+ if (Array.isArray(value)) {
30
+ value.forEach(v => queryString.append(key, v.toString()));
31
+ }
32
+ else {
33
+ queryString.append(key, value.toString());
34
+ }
35
+ }
36
+ });
37
+ // Construct URL based on auth mode
38
+ let url;
39
+ if (this.config.authMode === 'cloudflare_proxy') {
40
+ // For proxy modes, pass the full REST path including /wp-json as query parameter
41
+ const fullEndpoint = `/wp-json${endpoint}?${queryString.toString()}`;
42
+ url = `${baseUrl}?endpoint=${encodeURIComponent(fullEndpoint)}`;
43
+ }
44
+ else {
45
+ // For direct mode, construct the full WordPress API URL
46
+ url = `${baseUrl}/wp-json${endpoint}?${queryString.toString()}`;
47
+ }
48
+ const headers = {
49
+ 'Content-Type': 'application/json',
50
+ };
51
+ // Add authentication based on mode
52
+ if (this.config.authMode === 'cloudflare_proxy') ;
53
+ else {
54
+ // Direct mode - use basic auth
55
+ if (this.config.username && this.config.password) {
56
+ const credentials = btoa(`${this.config.username}:${this.config.password}`);
57
+ headers.Authorization = `Basic ${credentials}`;
58
+ }
59
+ }
60
+ console.log('🔍 WordPress API Request Debug:', {
61
+ url,
62
+ method: options.method || 'GET',
63
+ authMode: this.config.authMode,
64
+ headers: Object.keys(headers),
65
+ });
66
+ const response = await fetch(url, {
67
+ method: options.method || 'GET',
68
+ headers,
69
+ body: options.body,
70
+ signal: AbortSignal.timeout(this.config.timeout || 30000),
71
+ ...options,
72
+ });
73
+ if (!response.ok) {
74
+ console.error('❌ WordPress API Error:', {
75
+ status: response.status,
76
+ statusText: response.statusText,
77
+ url,
78
+ headers: Object.fromEntries(response.headers.entries()),
79
+ });
80
+ throw new Error(`WordPress API request failed: ${response.status} ${response.statusText}`);
81
+ }
82
+ const responseText = await response.text();
83
+ console.log('🔍 WordPress API Response:', {
84
+ status: response.status,
85
+ responseLength: responseText.length,
86
+ responsePreview: responseText.substring(0, 200),
87
+ });
88
+ if (!responseText) {
89
+ // Return empty array for empty responses (common for endpoints with no data)
90
+ return [];
91
+ }
92
+ try {
93
+ return JSON.parse(responseText);
94
+ }
95
+ catch (error) {
96
+ const message = error instanceof Error ? error.message : String(error);
97
+ console.error('❌ JSON Parse Error:', {
98
+ error: message,
99
+ responseText: responseText.substring(0, 500),
100
+ });
101
+ throw new Error(`Failed to parse JSON response: ${message}`);
102
+ }
103
+ }
104
+ getBaseUrl() {
105
+ switch (this.config.authMode) {
106
+ case 'cloudflare_proxy':
107
+ return this.config.cloudflareWorkerUrl || '';
108
+ default:
109
+ return this.config.apiUrl || '';
110
+ }
111
+ }
112
+ async getPosts(params = {}) {
113
+ return this.makeRequest('/wp/v2/posts', params);
114
+ }
115
+ async getPost(id) {
116
+ return this.makeRequest(`/wp/v2/posts/${id}`);
117
+ }
118
+ async getPages(params = {}) {
119
+ return this.makeRequest('/wp/v2/pages', params);
120
+ }
121
+ async getPage(id) {
122
+ return this.makeRequest(`/wp/v2/pages/${id}`);
123
+ }
124
+ async getMedia(params = {}) {
125
+ return this.makeRequest('/wp/v2/media', params);
126
+ }
127
+ async getMediaItem(id) {
128
+ return this.makeRequest(`/wp/v2/media/${id}`);
129
+ }
130
+ async getCategories(params = {}) {
131
+ return this.makeRequest('/wp/v2/categories', params);
132
+ }
133
+ async getTags(params = {}) {
134
+ return this.makeRequest('/wp/v2/tags', params);
135
+ }
136
+ // Gravity Forms endpoints
137
+ async getGravityForms() {
138
+ return this.makeRequest('/gf-api/v1/forms');
139
+ }
140
+ async getGravityForm(formId) {
141
+ return this.makeRequest(`/gf-api/v1/forms/${formId}/config`);
142
+ }
143
+ async submitGravityForm(formId, entry) {
144
+ return this.makeRequest(`/gf-api/v1/forms/${formId}/submit`, {}, {
145
+ method: 'POST',
146
+ body: JSON.stringify(entry),
147
+ });
148
+ }
149
+ // Static data endpoints
150
+ async getStaticDataNonce() {
151
+ return this.makeRequest('/static-data/v1/nonce');
152
+ }
153
+ async getAllData(params = {}) {
154
+ const [posts, pages, media, categories, tags] = await Promise.all([
155
+ this.getPosts(params),
156
+ this.getPages(params),
157
+ this.getMedia(params),
158
+ this.getCategories(params),
159
+ this.getTags(params),
160
+ ]);
161
+ return { posts, pages, media, categories, tags };
162
+ }
163
+ }
164
+
165
+ let document;
166
+ let offset;
167
+ let output;
168
+ let stack;
169
+ const tokenizer = /<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;
170
+ function Block(blockName, attrs, innerBlocks, innerHTML, innerContent) {
171
+ return {
172
+ blockName,
173
+ attrs,
174
+ innerBlocks,
175
+ innerHTML,
176
+ innerContent
177
+ };
178
+ }
179
+ function Freeform(innerHTML) {
180
+ return Block(null, {}, [], innerHTML, [innerHTML]);
181
+ }
182
+ function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
183
+ return {
184
+ block,
185
+ tokenStart,
186
+ tokenLength,
187
+ prevOffset: prevOffset || tokenStart + tokenLength,
188
+ leadingHtmlStart
189
+ };
190
+ }
191
+ const parse = (doc) => {
192
+ document = doc;
193
+ offset = 0;
194
+ output = [];
195
+ stack = [];
196
+ tokenizer.lastIndex = 0;
197
+ do {
198
+ } while (proceed());
199
+ return output;
200
+ };
201
+ function proceed() {
202
+ const stackDepth = stack.length;
203
+ const next = nextToken();
204
+ const [tokenType, blockName, attrs, startOffset, tokenLength] = next;
205
+ const leadingHtmlStart = startOffset > offset ? offset : null;
206
+ switch (tokenType) {
207
+ case "no-more-tokens":
208
+ if (0 === stackDepth) {
209
+ addFreeform();
210
+ return false;
211
+ }
212
+ if (1 === stackDepth) {
213
+ addBlockFromStack();
214
+ return false;
215
+ }
216
+ while (0 < stack.length) {
217
+ addBlockFromStack();
218
+ }
219
+ return false;
220
+ case "void-block":
221
+ if (0 === stackDepth) {
222
+ if (null !== leadingHtmlStart) {
223
+ output.push(
224
+ Freeform(
225
+ document.substr(
226
+ leadingHtmlStart,
227
+ startOffset - leadingHtmlStart
228
+ )
229
+ )
230
+ );
231
+ }
232
+ output.push(Block(blockName, attrs, [], "", []));
233
+ offset = startOffset + tokenLength;
234
+ return true;
235
+ }
236
+ addInnerBlock(
237
+ Block(blockName, attrs, [], "", []),
238
+ startOffset,
239
+ tokenLength
240
+ );
241
+ offset = startOffset + tokenLength;
242
+ return true;
243
+ case "block-opener":
244
+ stack.push(
245
+ Frame(
246
+ Block(blockName, attrs, [], "", []),
247
+ startOffset,
248
+ tokenLength,
249
+ startOffset + tokenLength,
250
+ leadingHtmlStart
251
+ )
252
+ );
253
+ offset = startOffset + tokenLength;
254
+ return true;
255
+ case "block-closer":
256
+ if (0 === stackDepth) {
257
+ addFreeform();
258
+ return false;
259
+ }
260
+ if (1 === stackDepth) {
261
+ addBlockFromStack(startOffset);
262
+ offset = startOffset + tokenLength;
263
+ return true;
264
+ }
265
+ const stackTop = stack.pop();
266
+ const html = document.substr(
267
+ stackTop.prevOffset,
268
+ startOffset - stackTop.prevOffset
269
+ );
270
+ stackTop.block.innerHTML += html;
271
+ stackTop.block.innerContent.push(html);
272
+ stackTop.prevOffset = startOffset + tokenLength;
273
+ addInnerBlock(
274
+ stackTop.block,
275
+ stackTop.tokenStart,
276
+ stackTop.tokenLength,
277
+ startOffset + tokenLength
278
+ );
279
+ offset = startOffset + tokenLength;
280
+ return true;
281
+ default:
282
+ addFreeform();
283
+ return false;
284
+ }
285
+ }
286
+ function parseJSON(input) {
287
+ try {
288
+ return JSON.parse(input);
289
+ } catch (e) {
290
+ return null;
291
+ }
292
+ }
293
+ function nextToken() {
294
+ const matches = tokenizer.exec(document);
295
+ if (null === matches) {
296
+ return ["no-more-tokens", "", null, 0, 0];
297
+ }
298
+ const startedAt = matches.index;
299
+ const [
300
+ match,
301
+ closerMatch,
302
+ namespaceMatch,
303
+ nameMatch,
304
+ attrsMatch,
305
+ ,
306
+ voidMatch
307
+ ] = matches;
308
+ const length = match.length;
309
+ const isCloser = !!closerMatch;
310
+ const isVoid = !!voidMatch;
311
+ const namespace = namespaceMatch || "core/";
312
+ const name = namespace + nameMatch;
313
+ const hasAttrs = !!attrsMatch;
314
+ const attrs = hasAttrs ? parseJSON(attrsMatch) : {};
315
+ if (isVoid) {
316
+ return ["void-block", name, attrs, startedAt, length];
317
+ }
318
+ if (isCloser) {
319
+ return ["block-closer", name, null, startedAt, length];
320
+ }
321
+ return ["block-opener", name, attrs, startedAt, length];
322
+ }
323
+ function addFreeform(rawLength) {
324
+ const length = document.length - offset;
325
+ if (0 === length) {
326
+ return;
327
+ }
328
+ output.push(Freeform(document.substr(offset, length)));
329
+ }
330
+ function addInnerBlock(block, tokenStart, tokenLength, lastOffset) {
331
+ const parent = stack[stack.length - 1];
332
+ parent.block.innerBlocks.push(block);
333
+ const html = document.substr(
334
+ parent.prevOffset,
335
+ tokenStart - parent.prevOffset
336
+ );
337
+ if (html) {
338
+ parent.block.innerHTML += html;
339
+ parent.block.innerContent.push(html);
340
+ }
341
+ parent.block.innerContent.push(null);
342
+ parent.prevOffset = lastOffset ? lastOffset : tokenStart + tokenLength;
343
+ }
344
+ function addBlockFromStack(endOffset) {
345
+ const { block, leadingHtmlStart, prevOffset, tokenStart } = stack.pop();
346
+ const html = endOffset ? document.substr(prevOffset, endOffset - prevOffset) : document.substr(prevOffset);
347
+ if (html) {
348
+ block.innerHTML += html;
349
+ block.innerContent.push(html);
350
+ }
351
+ if (null !== leadingHtmlStart) {
352
+ output.push(
353
+ Freeform(
354
+ document.substr(
355
+ leadingHtmlStart,
356
+ tokenStart - leadingHtmlStart
357
+ )
358
+ )
359
+ );
360
+ }
361
+ output.push(block);
362
+ }
363
+
364
+ /**
365
+ * @license GPL-3.0-or-later
366
+ *
367
+ * This file is part of the MarVAlt Open SDK.
368
+ * Copyright (c) 2025 Vibune Pty Ltd.
369
+ *
370
+ * This program is free software: you can redistribute it and/or modify
371
+ * it under the terms of the GNU General Public License as published by
372
+ * the Free Software Foundation, either version 3 of the License, or
373
+ * (at your option) any later version.
374
+ *
375
+ * This program is distributed in the hope that it will be useful,
376
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
377
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
378
+ * See the GNU General Public License for more details.
379
+ */
380
+ // WordPress Static Data Generator
381
+ class WordPressGenerator {
382
+ constructor(config) {
383
+ this.config = config;
384
+ }
385
+ async generateStaticData() {
386
+ const client = new WordPressClient(this.config);
387
+ console.log('🚀 Starting WordPress static data generation...');
388
+ const frontendId = this.config.frontendId || 'default-frontend';
389
+ const frontendName = this.config.frontendName || 'Default Frontend';
390
+ const postTypes = this.config.postTypes || ['posts', 'pages', 'case_studies', 'projects', 'members', 'testimonial', 'faqs', 'products', 'services', 'events'];
391
+ // Use 'edit' context only when credentials are provided; otherwise fall back to 'view'
392
+ const hasBasicAuth = !!(this.config.username && this.config.password);
393
+ const data = await client.getAllData({
394
+ per_page: this.config.maxItems || 100,
395
+ _embed: this.config.includeEmbedded || false,
396
+ context: hasBasicAuth ? 'edit' : 'view',
397
+ });
398
+ // Create the static data structure matching the existing format
399
+ const staticData = {
400
+ generated_at: new Date().toISOString(),
401
+ frontend_id: frontendId,
402
+ frontend_name: frontendName,
403
+ config: {
404
+ frontend_id: frontendId,
405
+ frontend_name: frontendName,
406
+ post_types: postTypes.reduce((acc, postType) => {
407
+ acc[postType] = {
408
+ max_items: this.config.maxItems || 100,
409
+ include_embedded: this.config.includeEmbedded || true,
410
+ orderby: 'date',
411
+ order: 'desc',
412
+ };
413
+ return acc;
414
+ }, {}),
415
+ },
416
+ // Map the data to the expected structure
417
+ posts: data.posts,
418
+ pages: (data.pages || []).map((p) => {
419
+ let blocks = [];
420
+ try {
421
+ const raw = p?.content?.raw || '';
422
+ blocks = raw ? parse(raw) : [];
423
+ }
424
+ catch (e) {
425
+ console.warn('⚠️ Failed to parse Gutenberg blocks for page', p?.id, e);
426
+ }
427
+ return { ...p, blocks };
428
+ }),
429
+ media: data.media,
430
+ categories: data.categories,
431
+ tags: data.tags,
432
+ };
433
+ // Write to file
434
+ this.writeStaticData(staticData);
435
+ console.log('✅ WordPress static data generation completed');
436
+ console.log(`📊 Generated data: ${data.posts.length} posts, ${data.pages.length} pages, ${data.media.length} media items`);
437
+ return staticData;
438
+ }
439
+ writeStaticData(data) {
440
+ try {
441
+ const outputPath = join(process.cwd(), this.config.outputPath);
442
+ writeFileSync(outputPath, JSON.stringify(data, null, 2));
443
+ console.log(`📁 Static data written to: ${outputPath}`);
444
+ }
445
+ catch (error) {
446
+ console.error('❌ Error writing static data:', error);
447
+ throw error;
448
+ }
449
+ }
450
+ async generatePostsOnly() {
451
+ const client = new WordPressClient(this.config);
452
+ return client.getPosts({ per_page: 100 });
453
+ }
454
+ async generatePagesOnly() {
455
+ const client = new WordPressClient(this.config);
456
+ return client.getPages({ per_page: 100 });
457
+ }
458
+ async generateMediaOnly() {
459
+ const client = new WordPressClient(this.config);
460
+ return client.getMedia({ per_page: 100 });
461
+ }
462
+ }
463
+ // Convenience function for easy usage
464
+ async function generateWordPressData(config) {
465
+ const generator = new WordPressGenerator(config);
466
+ return generator.generateStaticData();
467
+ }
468
+
469
+ /**
470
+ * @license GPL-3.0-or-later
471
+ *
472
+ * This file is part of the MarVAlt Open SDK.
473
+ * Copyright (c) 2025 Vibune Pty Ltd.
474
+ *
475
+ * This program is free software: you can redistribute it and/or modify
476
+ * it under the terms of the GNU General Public License as published by
477
+ * the Free Software Foundation, either version 3 of the License, or
478
+ * (at your option) any later version.
479
+ *
480
+ * This program is distributed in the hope that it will be useful,
481
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
482
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
483
+ * See the GNU General Public License for more details.
484
+ */
485
+ class GravityFormsClient {
486
+ constructor(config) {
487
+ this.config = config;
488
+ // Determine mode: direct for generators (Node.js), proxy for browser
489
+ const hasCredentials = !!(config.username && config.password && config.username.length > 0 && config.password.length > 0);
490
+ this.useDirectMode = config.authMode === 'direct' && hasCredentials;
491
+ // Debug logging for Node.js environments (generators)
492
+ if (typeof process !== 'undefined' && process.env) {
493
+ console.log('🔍 GravityFormsClient Configuration:', {
494
+ authMode: config.authMode,
495
+ hasUsername: !!config.username,
496
+ hasPassword: !!config.password,
497
+ hasApiUrl: !!config.apiUrl,
498
+ useDirectMode: this.useDirectMode,
499
+ });
500
+ }
501
+ // Convention-based: Always use /api/gravity-forms-submit unless explicitly overridden
502
+ this.proxyEndpoint = config.proxyEndpoint || '/api/gravity-forms-submit';
503
+ }
504
+ async makeRequest(endpoint, options = {}) {
505
+ let url;
506
+ const headers = {
507
+ 'Content-Type': 'application/json',
508
+ ...options.headers,
509
+ };
510
+ if (this.useDirectMode) {
511
+ // Direct mode: Call WordPress API directly (for generators/Node.js)
512
+ url = `${this.config.apiUrl}${endpoint}`;
513
+ // Add Basic Auth
514
+ if (this.config.username && this.config.password) {
515
+ const credentials = btoa(`${this.config.username}:${this.config.password}`);
516
+ headers['Authorization'] = `Basic ${credentials}`;
517
+ }
518
+ // Add CF Access headers if provided
519
+ if (this.config.cfAccessClientId && this.config.cfAccessClientSecret) {
520
+ headers['CF-Access-Client-Id'] = this.config.cfAccessClientId;
521
+ headers['CF-Access-Client-Secret'] = this.config.cfAccessClientSecret;
522
+ }
523
+ }
524
+ else {
525
+ // Proxy mode: Use Pages Function (for browser)
526
+ const proxyEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
527
+ url = `${this.proxyEndpoint}?endpoint=${encodeURIComponent(proxyEndpoint)}`;
528
+ }
529
+ const response = await fetch(url, {
530
+ ...options,
531
+ headers,
532
+ signal: AbortSignal.timeout(this.config.timeout || 30000),
533
+ });
534
+ if (!response.ok) {
535
+ throw new Error(`Gravity Forms API request failed: ${response.status} ${response.statusText}`);
536
+ }
537
+ const responseText = await response.text();
538
+ if (!responseText) {
539
+ return [];
540
+ }
541
+ try {
542
+ return JSON.parse(responseText);
543
+ }
544
+ catch (error) {
545
+ console.error('❌ Gravity Forms JSON Parse Error:', {
546
+ error: error.message,
547
+ responseText: responseText.substring(0, 500),
548
+ });
549
+ throw new Error(`Failed to parse JSON response: ${error.message}`);
550
+ }
551
+ }
552
+ async getForm(id) {
553
+ // Always use custom gf-api/v1 endpoint (from custom plugin)
554
+ const endpoint = `/forms/${id}`;
555
+ return this.makeRequest(endpoint);
556
+ }
557
+ async getForms() {
558
+ // Always use custom gf-api/v1 endpoint (from custom plugin)
559
+ const endpoint = '/forms';
560
+ return this.makeRequest(endpoint);
561
+ }
562
+ async getFormConfig(id) {
563
+ // Always use custom gf-api/v1 endpoint (from custom plugin)
564
+ const endpoint = `/forms/${id}/config`;
565
+ return this.makeRequest(endpoint);
566
+ }
567
+ async submitForm(formId, submission) {
568
+ // Always use custom gf-api/v1 submit endpoint (from custom plugin)
569
+ const endpoint = `/forms/${formId}/submit`;
570
+ // Merge custom headers (e.g., Turnstile token) with default headers
571
+ const headers = {
572
+ 'Content-Type': 'application/json',
573
+ ...(submission.headers || {}),
574
+ };
575
+ return this.makeRequest(endpoint, {
576
+ method: 'POST',
577
+ headers,
578
+ body: JSON.stringify(submission.field_values),
579
+ });
580
+ }
581
+ async getHealth() {
582
+ const endpoint = '/health';
583
+ return this.makeRequest(endpoint);
584
+ }
585
+ }
586
+
587
+ /**
588
+ * @license GPL-3.0-or-later
589
+ *
590
+ * This file is part of the MarVAlt Open SDK.
591
+ * Copyright (c) 2025 Vibune Pty Ltd.
592
+ *
593
+ * This program is free software: you can redistribute it and/or modify
594
+ * it under the terms of the GNU General Public License as published by
595
+ * the Free Software Foundation, either version 3 of the License, or
596
+ * (at your option) any later version.
597
+ *
598
+ * This program is distributed in the hope that it will be useful,
599
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
600
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
601
+ * See the GNU General Public License for more details.
602
+ */
603
+ // Gravity Forms Static Data Generator
604
+ class GravityFormsGenerator {
605
+ constructor(config) {
606
+ this.config = config;
607
+ }
608
+ async generateStaticData() {
609
+ const client = new GravityFormsClient(this.config);
610
+ console.log('🚀 Starting Gravity Forms static data generation...');
611
+ let forms = [];
612
+ if (this.config.formIds && this.config.formIds.length > 0) {
613
+ // Generate specific forms
614
+ for (const formId of this.config.formIds) {
615
+ try {
616
+ const form = await client.getFormConfig(formId);
617
+ if (this.config.includeInactive || form.is_active) {
618
+ forms.push(form);
619
+ }
620
+ }
621
+ catch (error) {
622
+ console.warn(`⚠️ Could not fetch form ${formId}:`, error);
623
+ }
624
+ }
625
+ }
626
+ else {
627
+ // Generate all forms
628
+ const formsList = await client.getForms();
629
+ console.log('🔍 Gravity Forms Response:', {
630
+ formsType: typeof formsList,
631
+ isArray: Array.isArray(formsList),
632
+ formsLength: formsList?.length,
633
+ formsPreview: formsList ? JSON.stringify(formsList).substring(0, 200) : 'null',
634
+ });
635
+ let formsMetadata = [];
636
+ if (Array.isArray(formsList)) {
637
+ formsMetadata = formsList;
638
+ }
639
+ else if (formsList && typeof formsList === 'object' && Array.isArray(formsList.forms)) {
640
+ formsMetadata = formsList.forms;
641
+ }
642
+ else if (formsList) {
643
+ formsMetadata = [formsList];
644
+ }
645
+ if (!this.config.includeInactive) {
646
+ formsMetadata = formsMetadata.filter(form => form.is_active === '1' || form.is_active === true);
647
+ }
648
+ // Fetch full form configuration for each form (schema lives under /config)
649
+ console.log(`🔄 Fetching full data for ${formsMetadata.length} forms...`);
650
+ forms = [];
651
+ for (const formMetadata of formsMetadata) {
652
+ try {
653
+ const formId = Number(formMetadata.id);
654
+ const fullForm = await client.getFormConfig(formId);
655
+ forms.push(fullForm);
656
+ console.log(`✅ Fetched form: ${fullForm.title} (${fullForm.fields?.length || 0} fields)`);
657
+ }
658
+ catch (error) {
659
+ console.error(`❌ Failed to fetch form ${formMetadata.id} config:`, error);
660
+ throw error;
661
+ }
662
+ }
663
+ }
664
+ const staticData = {
665
+ generated_at: new Date().toISOString(),
666
+ total_forms: forms.length,
667
+ forms,
668
+ };
669
+ // Write to file
670
+ this.writeStaticData(staticData);
671
+ console.log('✅ Gravity Forms static data generation completed');
672
+ console.log(`📊 Generated data: ${forms.length} forms`);
673
+ return staticData;
674
+ }
675
+ writeStaticData(data) {
676
+ try {
677
+ const outputPath = join(process.cwd(), this.config.outputPath);
678
+ writeFileSync(outputPath, JSON.stringify(data, null, 2));
679
+ console.log(`📁 Static data written to: ${outputPath}`);
680
+ }
681
+ catch (error) {
682
+ console.error('❌ Error writing static data:', error);
683
+ throw error;
684
+ }
685
+ }
686
+ async generateFormConfig(formId) {
687
+ const client = new GravityFormsClient(this.config);
688
+ return client.getFormConfig(formId);
689
+ }
690
+ }
691
+ // Convenience function for easy usage
692
+ async function generateGravityFormsData(config) {
693
+ const generator = new GravityFormsGenerator(config);
694
+ return generator.generateStaticData();
695
+ }
696
+
697
+ /**
698
+ * @license GPL-3.0-or-later
699
+ *
700
+ * This file is part of the MarVAlt Open SDK.
701
+ * Copyright (c) 2025 Vibune Pty Ltd.
702
+ *
703
+ * This program is free software: you can redistribute it and/or modify
704
+ * it under the terms of the GNU General Public License as published by
705
+ * the Free Software Foundation, either version 3 of the License, or
706
+ * (at your option) any later version.
707
+ *
708
+ * This program is distributed in the hope that it will be useful,
709
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
710
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
711
+ * See the GNU General Public License for more details.
712
+ */
713
+ class FormProtectionGenerator {
714
+ constructor(config) {
715
+ this.config = config;
716
+ }
717
+ async generateStaticData() {
718
+ console.log('🚀 Starting Form Protection static data generation...');
719
+ const forms = this.config.forms.map(form => ({
720
+ id: form.id,
721
+ name: form.name,
722
+ protectionLevel: form.protectionLevel,
723
+ emailVerification: this.config.emailVerification,
724
+ spamProtection: this.config.spamProtection,
725
+ rateLimiting: this.config.rateLimiting,
726
+ }));
727
+ const staticData = {
728
+ config: {
729
+ enabled: this.config.enabled,
730
+ secret: this.config.secret,
731
+ emailVerification: this.config.emailVerification,
732
+ spamProtection: this.config.spamProtection,
733
+ rateLimiting: this.config.rateLimiting,
734
+ maxSubmissionsPerHour: this.config.maxSubmissionsPerHour,
735
+ maxSubmissionsPerDay: this.config.maxSubmissionsPerDay,
736
+ },
737
+ forms,
738
+ generatedAt: new Date().toISOString(),
739
+ };
740
+ // Write to file
741
+ this.writeStaticData(staticData);
742
+ console.log('✅ Form Protection static data generation completed');
743
+ console.log(`📊 Generated data: ${forms.length} protected forms`);
744
+ return staticData;
745
+ }
746
+ writeStaticData(data) {
747
+ try {
748
+ const outputPath = join(process.cwd(), this.config.outputPath);
749
+ writeFileSync(outputPath, JSON.stringify(data, null, 2));
750
+ console.log(`📁 Static data written to: ${outputPath}`);
751
+ }
752
+ catch (error) {
753
+ console.error('❌ Error writing static data:', error);
754
+ throw error;
755
+ }
756
+ }
757
+ validateFormProtection(formData) {
758
+ // Basic validation logic for form protection
759
+ const errors = [];
760
+ if (this.config.emailVerification && !formData.email) {
761
+ errors.push('Email verification is required');
762
+ }
763
+ if (this.config.spamProtection) {
764
+ // Basic spam detection logic
765
+ if (formData.message && formData.message.length < 10) {
766
+ errors.push('Message too short');
767
+ }
768
+ }
769
+ return {
770
+ success: errors.length === 0,
771
+ protected: this.config.enabled,
772
+ message: errors.length > 0 ? errors.join(', ') : 'Form is protected',
773
+ verificationRequired: this.config.emailVerification,
774
+ spamDetected: errors.length > 0,
775
+ };
776
+ }
777
+ }
778
+ // Convenience function for easy usage
779
+ async function generateFormProtectionData(config) {
780
+ const generator = new FormProtectionGenerator(config);
781
+ return generator.generateStaticData();
782
+ }
783
+
784
+ export { FormProtectionGenerator, GravityFormsGenerator, WordPressGenerator, generateFormProtectionData, generateGravityFormsData, generateWordPressData };
785
+ //# sourceMappingURL=generators.esm.js.map