@marvalt/wadapter 2.3.6 → 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.
package/dist/index.js CHANGED
@@ -1,8 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  var require$$0 = require('react');
4
- var fs = require('fs');
5
- var path = require('path');
6
4
 
7
5
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
8
6
  /**
@@ -268,18 +266,47 @@ function transformWordPressMediaItems(media) {
268
266
  class GravityFormsClient {
269
267
  constructor(config) {
270
268
  this.config = config;
269
+ // Determine mode: direct for generators (Node.js), proxy for browser
270
+ const hasCredentials = !!(config.username && config.password && config.username.length > 0 && config.password.length > 0);
271
+ this.useDirectMode = config.authMode === 'direct' && hasCredentials;
272
+ // Debug logging for Node.js environments (generators)
273
+ if (typeof process !== 'undefined' && process.env) {
274
+ console.log('🔍 GravityFormsClient Configuration:', {
275
+ authMode: config.authMode,
276
+ hasUsername: !!config.username,
277
+ hasPassword: !!config.password,
278
+ hasApiUrl: !!config.apiUrl,
279
+ useDirectMode: this.useDirectMode,
280
+ });
281
+ }
271
282
  // Convention-based: Always use /api/gravity-forms-submit unless explicitly overridden
272
- // This matches the Mautic pattern for consistency
273
283
  this.proxyEndpoint = config.proxyEndpoint || '/api/gravity-forms-submit';
274
284
  }
275
285
  async makeRequest(endpoint, options = {}) {
276
- // Always use proxy endpoint (convention-based, like Mautic)
277
- const proxyEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
278
- const url = `${this.proxyEndpoint}?endpoint=${encodeURIComponent(proxyEndpoint)}`;
286
+ let url;
279
287
  const headers = {
280
288
  'Content-Type': 'application/json',
281
289
  ...options.headers,
282
290
  };
291
+ if (this.useDirectMode) {
292
+ // Direct mode: Call WordPress API directly (for generators/Node.js)
293
+ url = `${this.config.apiUrl}${endpoint}`;
294
+ // Add Basic Auth
295
+ if (this.config.username && this.config.password) {
296
+ const credentials = btoa(`${this.config.username}:${this.config.password}`);
297
+ headers['Authorization'] = `Basic ${credentials}`;
298
+ }
299
+ // Add CF Access headers if provided
300
+ if (this.config.cfAccessClientId && this.config.cfAccessClientSecret) {
301
+ headers['CF-Access-Client-Id'] = this.config.cfAccessClientId;
302
+ headers['CF-Access-Client-Secret'] = this.config.cfAccessClientSecret;
303
+ }
304
+ }
305
+ else {
306
+ // Proxy mode: Use Pages Function (for browser)
307
+ const proxyEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
308
+ url = `${this.proxyEndpoint}?endpoint=${encodeURIComponent(proxyEndpoint)}`;
309
+ }
283
310
  const response = await fetch(url, {
284
311
  ...options,
285
312
  headers,
@@ -2164,507 +2191,6 @@ function getFormById(id) {
2164
2191
  return (gravityFormsStaticData?.forms ?? []).find(f => String(f.id) === key);
2165
2192
  }
2166
2193
 
2167
- let document$1;
2168
- let offset;
2169
- let output;
2170
- let stack;
2171
- const tokenizer = /<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;
2172
- function Block(blockName, attrs, innerBlocks, innerHTML, innerContent) {
2173
- return {
2174
- blockName,
2175
- attrs,
2176
- innerBlocks,
2177
- innerHTML,
2178
- innerContent
2179
- };
2180
- }
2181
- function Freeform(innerHTML) {
2182
- return Block(null, {}, [], innerHTML, [innerHTML]);
2183
- }
2184
- function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
2185
- return {
2186
- block,
2187
- tokenStart,
2188
- tokenLength,
2189
- prevOffset: prevOffset || tokenStart + tokenLength,
2190
- leadingHtmlStart
2191
- };
2192
- }
2193
- const parse = (doc) => {
2194
- document$1 = doc;
2195
- offset = 0;
2196
- output = [];
2197
- stack = [];
2198
- tokenizer.lastIndex = 0;
2199
- do {
2200
- } while (proceed());
2201
- return output;
2202
- };
2203
- function proceed() {
2204
- const stackDepth = stack.length;
2205
- const next = nextToken();
2206
- const [tokenType, blockName, attrs, startOffset, tokenLength] = next;
2207
- const leadingHtmlStart = startOffset > offset ? offset : null;
2208
- switch (tokenType) {
2209
- case "no-more-tokens":
2210
- if (0 === stackDepth) {
2211
- addFreeform();
2212
- return false;
2213
- }
2214
- if (1 === stackDepth) {
2215
- addBlockFromStack();
2216
- return false;
2217
- }
2218
- while (0 < stack.length) {
2219
- addBlockFromStack();
2220
- }
2221
- return false;
2222
- case "void-block":
2223
- if (0 === stackDepth) {
2224
- if (null !== leadingHtmlStart) {
2225
- output.push(
2226
- Freeform(
2227
- document$1.substr(
2228
- leadingHtmlStart,
2229
- startOffset - leadingHtmlStart
2230
- )
2231
- )
2232
- );
2233
- }
2234
- output.push(Block(blockName, attrs, [], "", []));
2235
- offset = startOffset + tokenLength;
2236
- return true;
2237
- }
2238
- addInnerBlock(
2239
- Block(blockName, attrs, [], "", []),
2240
- startOffset,
2241
- tokenLength
2242
- );
2243
- offset = startOffset + tokenLength;
2244
- return true;
2245
- case "block-opener":
2246
- stack.push(
2247
- Frame(
2248
- Block(blockName, attrs, [], "", []),
2249
- startOffset,
2250
- tokenLength,
2251
- startOffset + tokenLength,
2252
- leadingHtmlStart
2253
- )
2254
- );
2255
- offset = startOffset + tokenLength;
2256
- return true;
2257
- case "block-closer":
2258
- if (0 === stackDepth) {
2259
- addFreeform();
2260
- return false;
2261
- }
2262
- if (1 === stackDepth) {
2263
- addBlockFromStack(startOffset);
2264
- offset = startOffset + tokenLength;
2265
- return true;
2266
- }
2267
- const stackTop = stack.pop();
2268
- const html = document$1.substr(
2269
- stackTop.prevOffset,
2270
- startOffset - stackTop.prevOffset
2271
- );
2272
- stackTop.block.innerHTML += html;
2273
- stackTop.block.innerContent.push(html);
2274
- stackTop.prevOffset = startOffset + tokenLength;
2275
- addInnerBlock(
2276
- stackTop.block,
2277
- stackTop.tokenStart,
2278
- stackTop.tokenLength,
2279
- startOffset + tokenLength
2280
- );
2281
- offset = startOffset + tokenLength;
2282
- return true;
2283
- default:
2284
- addFreeform();
2285
- return false;
2286
- }
2287
- }
2288
- function parseJSON(input) {
2289
- try {
2290
- return JSON.parse(input);
2291
- } catch (e) {
2292
- return null;
2293
- }
2294
- }
2295
- function nextToken() {
2296
- const matches = tokenizer.exec(document$1);
2297
- if (null === matches) {
2298
- return ["no-more-tokens", "", null, 0, 0];
2299
- }
2300
- const startedAt = matches.index;
2301
- const [
2302
- match,
2303
- closerMatch,
2304
- namespaceMatch,
2305
- nameMatch,
2306
- attrsMatch,
2307
- ,
2308
- voidMatch
2309
- ] = matches;
2310
- const length = match.length;
2311
- const isCloser = !!closerMatch;
2312
- const isVoid = !!voidMatch;
2313
- const namespace = namespaceMatch || "core/";
2314
- const name = namespace + nameMatch;
2315
- const hasAttrs = !!attrsMatch;
2316
- const attrs = hasAttrs ? parseJSON(attrsMatch) : {};
2317
- if (isVoid) {
2318
- return ["void-block", name, attrs, startedAt, length];
2319
- }
2320
- if (isCloser) {
2321
- return ["block-closer", name, null, startedAt, length];
2322
- }
2323
- return ["block-opener", name, attrs, startedAt, length];
2324
- }
2325
- function addFreeform(rawLength) {
2326
- const length = document$1.length - offset;
2327
- if (0 === length) {
2328
- return;
2329
- }
2330
- output.push(Freeform(document$1.substr(offset, length)));
2331
- }
2332
- function addInnerBlock(block, tokenStart, tokenLength, lastOffset) {
2333
- const parent = stack[stack.length - 1];
2334
- parent.block.innerBlocks.push(block);
2335
- const html = document$1.substr(
2336
- parent.prevOffset,
2337
- tokenStart - parent.prevOffset
2338
- );
2339
- if (html) {
2340
- parent.block.innerHTML += html;
2341
- parent.block.innerContent.push(html);
2342
- }
2343
- parent.block.innerContent.push(null);
2344
- parent.prevOffset = lastOffset ? lastOffset : tokenStart + tokenLength;
2345
- }
2346
- function addBlockFromStack(endOffset) {
2347
- const { block, leadingHtmlStart, prevOffset, tokenStart } = stack.pop();
2348
- const html = endOffset ? document$1.substr(prevOffset, endOffset - prevOffset) : document$1.substr(prevOffset);
2349
- if (html) {
2350
- block.innerHTML += html;
2351
- block.innerContent.push(html);
2352
- }
2353
- if (null !== leadingHtmlStart) {
2354
- output.push(
2355
- Freeform(
2356
- document$1.substr(
2357
- leadingHtmlStart,
2358
- tokenStart - leadingHtmlStart
2359
- )
2360
- )
2361
- );
2362
- }
2363
- output.push(block);
2364
- }
2365
-
2366
- /**
2367
- * @license GPL-3.0-or-later
2368
- *
2369
- * This file is part of the MarVAlt Open SDK.
2370
- * Copyright (c) 2025 Vibune Pty Ltd.
2371
- *
2372
- * This program is free software: you can redistribute it and/or modify
2373
- * it under the terms of the GNU General Public License as published by
2374
- * the Free Software Foundation, either version 3 of the License, or
2375
- * (at your option) any later version.
2376
- *
2377
- * This program is distributed in the hope that it will be useful,
2378
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
2379
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2380
- * See the GNU General Public License for more details.
2381
- */
2382
- // WordPress Static Data Generator
2383
- class WordPressGenerator {
2384
- constructor(config) {
2385
- this.config = config;
2386
- }
2387
- async generateStaticData() {
2388
- const client = new WordPressClient(this.config);
2389
- console.log('🚀 Starting WordPress static data generation...');
2390
- const frontendId = this.config.frontendId || 'default-frontend';
2391
- const frontendName = this.config.frontendName || 'Default Frontend';
2392
- const postTypes = this.config.postTypes || ['posts', 'pages', 'case_studies', 'projects', 'members', 'testimonial', 'faqs', 'products', 'services', 'events'];
2393
- // Use 'edit' context only when credentials are provided; otherwise fall back to 'view'
2394
- const hasBasicAuth = !!(this.config.username && this.config.password);
2395
- const data = await client.getAllData({
2396
- per_page: this.config.maxItems || 100,
2397
- _embed: this.config.includeEmbedded || false,
2398
- context: hasBasicAuth ? 'edit' : 'view',
2399
- });
2400
- // Create the static data structure matching the existing format
2401
- const staticData = {
2402
- generated_at: new Date().toISOString(),
2403
- frontend_id: frontendId,
2404
- frontend_name: frontendName,
2405
- config: {
2406
- frontend_id: frontendId,
2407
- frontend_name: frontendName,
2408
- post_types: postTypes.reduce((acc, postType) => {
2409
- acc[postType] = {
2410
- max_items: this.config.maxItems || 100,
2411
- include_embedded: this.config.includeEmbedded || true,
2412
- orderby: 'date',
2413
- order: 'desc',
2414
- };
2415
- return acc;
2416
- }, {}),
2417
- },
2418
- // Map the data to the expected structure
2419
- posts: data.posts,
2420
- pages: (data.pages || []).map((p) => {
2421
- let blocks = [];
2422
- try {
2423
- const raw = p?.content?.raw || '';
2424
- blocks = raw ? parse(raw) : [];
2425
- }
2426
- catch (e) {
2427
- console.warn('⚠️ Failed to parse Gutenberg blocks for page', p?.id, e);
2428
- }
2429
- return { ...p, blocks };
2430
- }),
2431
- media: data.media,
2432
- categories: data.categories,
2433
- tags: data.tags,
2434
- };
2435
- // Write to file
2436
- this.writeStaticData(staticData);
2437
- console.log('✅ WordPress static data generation completed');
2438
- console.log(`📊 Generated data: ${data.posts.length} posts, ${data.pages.length} pages, ${data.media.length} media items`);
2439
- return staticData;
2440
- }
2441
- writeStaticData(data) {
2442
- try {
2443
- const outputPath = path.join(process.cwd(), this.config.outputPath);
2444
- fs.writeFileSync(outputPath, JSON.stringify(data, null, 2));
2445
- console.log(`📁 Static data written to: ${outputPath}`);
2446
- }
2447
- catch (error) {
2448
- console.error('❌ Error writing static data:', error);
2449
- throw error;
2450
- }
2451
- }
2452
- async generatePostsOnly() {
2453
- const client = new WordPressClient(this.config);
2454
- return client.getPosts({ per_page: 100 });
2455
- }
2456
- async generatePagesOnly() {
2457
- const client = new WordPressClient(this.config);
2458
- return client.getPages({ per_page: 100 });
2459
- }
2460
- async generateMediaOnly() {
2461
- const client = new WordPressClient(this.config);
2462
- return client.getMedia({ per_page: 100 });
2463
- }
2464
- }
2465
- // Convenience function for easy usage
2466
- async function generateWordPressData(config) {
2467
- const generator = new WordPressGenerator(config);
2468
- return generator.generateStaticData();
2469
- }
2470
-
2471
- /**
2472
- * @license GPL-3.0-or-later
2473
- *
2474
- * This file is part of the MarVAlt Open SDK.
2475
- * Copyright (c) 2025 Vibune Pty Ltd.
2476
- *
2477
- * This program is free software: you can redistribute it and/or modify
2478
- * it under the terms of the GNU General Public License as published by
2479
- * the Free Software Foundation, either version 3 of the License, or
2480
- * (at your option) any later version.
2481
- *
2482
- * This program is distributed in the hope that it will be useful,
2483
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
2484
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2485
- * See the GNU General Public License for more details.
2486
- */
2487
- // Gravity Forms Static Data Generator
2488
- class GravityFormsGenerator {
2489
- constructor(config) {
2490
- this.config = config;
2491
- }
2492
- async generateStaticData() {
2493
- const client = new GravityFormsClient(this.config);
2494
- console.log('🚀 Starting Gravity Forms static data generation...');
2495
- let forms = [];
2496
- if (this.config.formIds && this.config.formIds.length > 0) {
2497
- // Generate specific forms
2498
- for (const formId of this.config.formIds) {
2499
- try {
2500
- const form = await client.getFormConfig(formId);
2501
- if (this.config.includeInactive || form.is_active) {
2502
- forms.push(form);
2503
- }
2504
- }
2505
- catch (error) {
2506
- console.warn(`⚠️ Could not fetch form ${formId}:`, error);
2507
- }
2508
- }
2509
- }
2510
- else {
2511
- // Generate all forms
2512
- const formsList = await client.getForms();
2513
- console.log('🔍 Gravity Forms Response:', {
2514
- formsType: typeof formsList,
2515
- isArray: Array.isArray(formsList),
2516
- formsLength: formsList?.length,
2517
- formsPreview: formsList ? JSON.stringify(formsList).substring(0, 200) : 'null',
2518
- });
2519
- let formsMetadata = [];
2520
- if (Array.isArray(formsList)) {
2521
- formsMetadata = formsList;
2522
- }
2523
- else if (formsList && typeof formsList === 'object' && Array.isArray(formsList.forms)) {
2524
- formsMetadata = formsList.forms;
2525
- }
2526
- else if (formsList) {
2527
- formsMetadata = [formsList];
2528
- }
2529
- if (!this.config.includeInactive) {
2530
- formsMetadata = formsMetadata.filter(form => form.is_active === '1' || form.is_active === true);
2531
- }
2532
- // Fetch full form configuration for each form (schema lives under /config)
2533
- console.log(`🔄 Fetching full data for ${formsMetadata.length} forms...`);
2534
- forms = [];
2535
- for (const formMetadata of formsMetadata) {
2536
- try {
2537
- const formId = Number(formMetadata.id);
2538
- const fullForm = await client.getFormConfig(formId);
2539
- forms.push(fullForm);
2540
- console.log(`✅ Fetched form: ${fullForm.title} (${fullForm.fields?.length || 0} fields)`);
2541
- }
2542
- catch (error) {
2543
- console.error(`❌ Failed to fetch form ${formMetadata.id} config:`, error);
2544
- throw error;
2545
- }
2546
- }
2547
- }
2548
- const staticData = {
2549
- generated_at: new Date().toISOString(),
2550
- total_forms: forms.length,
2551
- forms,
2552
- };
2553
- // Write to file
2554
- this.writeStaticData(staticData);
2555
- console.log('✅ Gravity Forms static data generation completed');
2556
- console.log(`📊 Generated data: ${forms.length} forms`);
2557
- return staticData;
2558
- }
2559
- writeStaticData(data) {
2560
- try {
2561
- const outputPath = path.join(process.cwd(), this.config.outputPath);
2562
- fs.writeFileSync(outputPath, JSON.stringify(data, null, 2));
2563
- console.log(`📁 Static data written to: ${outputPath}`);
2564
- }
2565
- catch (error) {
2566
- console.error('❌ Error writing static data:', error);
2567
- throw error;
2568
- }
2569
- }
2570
- async generateFormConfig(formId) {
2571
- const client = new GravityFormsClient(this.config);
2572
- return client.getFormConfig(formId);
2573
- }
2574
- }
2575
- // Convenience function for easy usage
2576
- async function generateGravityFormsData(config) {
2577
- const generator = new GravityFormsGenerator(config);
2578
- return generator.generateStaticData();
2579
- }
2580
-
2581
- /**
2582
- * @license GPL-3.0-or-later
2583
- *
2584
- * This file is part of the MarVAlt Open SDK.
2585
- * Copyright (c) 2025 Vibune Pty Ltd.
2586
- *
2587
- * This program is free software: you can redistribute it and/or modify
2588
- * it under the terms of the GNU General Public License as published by
2589
- * the Free Software Foundation, either version 3 of the License, or
2590
- * (at your option) any later version.
2591
- *
2592
- * This program is distributed in the hope that it will be useful,
2593
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
2594
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2595
- * See the GNU General Public License for more details.
2596
- */
2597
- class FormProtectionGenerator {
2598
- constructor(config) {
2599
- this.config = config;
2600
- }
2601
- async generateStaticData() {
2602
- console.log('🚀 Starting Form Protection static data generation...');
2603
- const forms = this.config.forms.map(form => ({
2604
- id: form.id,
2605
- name: form.name,
2606
- protectionLevel: form.protectionLevel,
2607
- emailVerification: this.config.emailVerification,
2608
- spamProtection: this.config.spamProtection,
2609
- rateLimiting: this.config.rateLimiting,
2610
- }));
2611
- const staticData = {
2612
- config: {
2613
- enabled: this.config.enabled,
2614
- secret: this.config.secret,
2615
- emailVerification: this.config.emailVerification,
2616
- spamProtection: this.config.spamProtection,
2617
- rateLimiting: this.config.rateLimiting,
2618
- maxSubmissionsPerHour: this.config.maxSubmissionsPerHour,
2619
- maxSubmissionsPerDay: this.config.maxSubmissionsPerDay,
2620
- },
2621
- forms,
2622
- generatedAt: new Date().toISOString(),
2623
- };
2624
- // Write to file
2625
- this.writeStaticData(staticData);
2626
- console.log('✅ Form Protection static data generation completed');
2627
- console.log(`📊 Generated data: ${forms.length} protected forms`);
2628
- return staticData;
2629
- }
2630
- writeStaticData(data) {
2631
- try {
2632
- const outputPath = path.join(process.cwd(), this.config.outputPath);
2633
- fs.writeFileSync(outputPath, JSON.stringify(data, null, 2));
2634
- console.log(`📁 Static data written to: ${outputPath}`);
2635
- }
2636
- catch (error) {
2637
- console.error('❌ Error writing static data:', error);
2638
- throw error;
2639
- }
2640
- }
2641
- validateFormProtection(formData) {
2642
- // Basic validation logic for form protection
2643
- const errors = [];
2644
- if (this.config.emailVerification && !formData.email) {
2645
- errors.push('Email verification is required');
2646
- }
2647
- if (this.config.spamProtection) {
2648
- // Basic spam detection logic
2649
- if (formData.message && formData.message.length < 10) {
2650
- errors.push('Message too short');
2651
- }
2652
- }
2653
- return {
2654
- success: errors.length === 0,
2655
- protected: this.config.enabled,
2656
- message: errors.length > 0 ? errors.join(', ') : 'Form is protected',
2657
- verificationRequired: this.config.emailVerification,
2658
- spamDetected: errors.length > 0,
2659
- };
2660
- }
2661
- }
2662
- // Convenience function for easy usage
2663
- async function generateFormProtectionData(config) {
2664
- const generator = new FormProtectionGenerator(config);
2665
- return generator.generateStaticData();
2666
- }
2667
-
2668
2194
  /**
2669
2195
  * @license GPL-3.0-or-later
2670
2196
  *
@@ -2838,21 +2364,15 @@ function validateFormData(formData, rules) {
2838
2364
  return { isValid, errors };
2839
2365
  }
2840
2366
 
2841
- exports.FormProtectionGenerator = FormProtectionGenerator;
2842
2367
  exports.GravityForm = GravityForm;
2843
2368
  exports.GravityFormsClient = GravityFormsClient;
2844
- exports.GravityFormsGenerator = GravityFormsGenerator;
2845
2369
  exports.GravityFormsProvider = GravityFormsProvider;
2846
2370
  exports.WordPressClient = WordPressClient;
2847
2371
  exports.WordPressContent = WordPressContent;
2848
- exports.WordPressGenerator = WordPressGenerator;
2849
2372
  exports.WordPressProvider = WordPressProvider;
2850
2373
  exports.createFormProtectionConfig = createFormProtectionConfig;
2851
2374
  exports.createGravityFormsConfig = createGravityFormsConfig;
2852
2375
  exports.createWordPressConfig = createWordPressConfig;
2853
- exports.generateFormProtectionData = generateFormProtectionData;
2854
- exports.generateGravityFormsData = generateGravityFormsData;
2855
- exports.generateWordPressData = generateWordPressData;
2856
2376
  exports.getActiveForms = getActiveForms;
2857
2377
  exports.getFormById = getFormById;
2858
2378
  exports.getPublishedForms = getPublishedForms;