Changeset 3673252
- Timestamp:
- 08/31/2026 12:27:41 AM (3 months ago)
- Location:
- blaze-ai-discovery-for-woocommerce
- Files:
-
- 14 added
- 94 edited
- 1 copied
-
tags/1.1.3 (copied) (copied from blaze-ai-discovery-for-woocommerce/trunk )
-
tags/1.1.3/assets/js/admin/components/polling.js (added)
-
tags/1.1.3/assets/js/admin/components/restErrors.js (added)
-
tags/1.1.3/assets/js/admin/pages/Audit.js (modified) (6 diffs)
-
tags/1.1.3/assets/js/admin/pages/Dashboard.js (modified) (11 diffs)
-
tags/1.1.3/assets/js/admin/pages/Feed.js (modified) (7 diffs)
-
tags/1.1.3/assets/js/admin/pages/Products.js (modified) (4 diffs)
-
tags/1.1.3/assets/js/admin/pages/Visibility.js (modified) (7 diffs)
-
tags/1.1.3/blaze-ai-discovery-for-woocommerce.php (modified) (7 diffs)
-
tags/1.1.3/build/index.asset.php (modified) (1 diff)
-
tags/1.1.3/build/index.js (modified) (2 diffs)
-
tags/1.1.3/readme.txt (modified) (6 diffs)
-
tags/1.1.3/src/Attribution/CookieBridge.php (modified) (3 diffs)
-
tags/1.1.3/src/Attribution/InlineTracker.php (modified) (3 diffs)
-
tags/1.1.3/src/Attribution/OrderAttributor.php (modified) (3 diffs)
-
tags/1.1.3/src/Attribution/PayloadSignature.php (modified) (3 diffs)
-
tags/1.1.3/src/Attribution/Platforms.php (modified) (2 diffs)
-
tags/1.1.3/src/Attribution/TrackingEndpoint.php (modified) (6 diffs)
-
tags/1.1.3/src/Audit/AuditRunner.php (modified) (7 diffs)
-
tags/1.1.3/src/Audit/Checks/CoreWebVitals.php (modified) (6 diffs)
-
tags/1.1.3/src/Audit/Checks/ExistingFeedPlugins.php (modified) (1 diff)
-
tags/1.1.3/src/Audit/Checks/ExistingSchema.php (modified) (3 diffs)
-
tags/1.1.3/src/Audit/Checks/LlmsTxtExists.php (modified) (2 diffs)
-
tags/1.1.3/src/Audit/Checks/RestApiAccessible.php (modified) (2 diffs)
-
tags/1.1.3/src/Audit/Checks/RobotsTxt.php (modified) (1 diff)
-
tags/1.1.3/src/Audit/Checks/StoreVisibility.php (added)
-
tags/1.1.3/src/Audit/CrawlerAccess/SelfFetch.php (modified) (2 diffs)
-
tags/1.1.3/src/Cloud/CloudClient.php (modified) (5 diffs)
-
tags/1.1.3/src/Cloud/PayloadCache.php (modified) (1 diff)
-
tags/1.1.3/src/Cloud/VisibilityClient.php (modified) (5 diffs)
-
tags/1.1.3/src/Database/DatabaseModule.php (modified) (4 diffs)
-
tags/1.1.3/src/Database/Installer.php (added)
-
tags/1.1.3/src/Database/Migrator.php (modified) (3 diffs)
-
tags/1.1.3/src/Database/RetentionCleanup.php (modified) (4 diffs)
-
tags/1.1.3/src/Feed/ChatGptFeedGenerator.php (modified) (7 diffs)
-
tags/1.1.3/src/Feed/FeedFormatter.php (modified) (1 diff)
-
tags/1.1.3/src/Feed/FeedScheduler.php (modified) (5 diffs)
-
tags/1.1.3/src/Feed/FeedStorage.php (added)
-
tags/1.1.3/src/Feed/FeedValidator.php (modified) (3 diffs)
-
tags/1.1.3/src/Feed/FeedWriter.php (added)
-
tags/1.1.3/src/LlmsTxt/LlmsTxtRewriter.php (modified) (1 diff)
-
tags/1.1.3/src/Rest/AuditController.php (modified) (2 diffs)
-
tags/1.1.3/src/Rest/FeedController.php (modified) (3 diffs)
-
tags/1.1.3/src/Schema/CompatibilityDetector.php (modified) (3 diffs)
-
tags/1.1.3/src/Schema/SchemaModule.php (modified) (1 diff)
-
tags/1.1.3/src/Schema/SchemaOrchestrator.php (modified) (1 diff)
-
tags/1.1.3/src/Schema/Strategies/RankMathStrategy.php (modified) (3 diffs)
-
tags/1.1.3/src/Schema/Strategies/StandaloneStrategy.php (modified) (1 diff)
-
tags/1.1.3/src/Scoring/BatchScorer.php (modified) (8 diffs)
-
tags/1.1.3/src/Scoring/Criteria/IdentifierPresence.php (modified) (1 diff)
-
tags/1.1.3/uninstall.php (modified) (2 diffs)
-
tags/1.1.3/vendor/bin (added)
-
tags/1.1.3/vendor/composer/autoload_classmap.php (modified) (3 diffs)
-
tags/1.1.3/vendor/composer/autoload_static.php (modified) (3 diffs)
-
tags/1.1.3/vendor/composer/installed.php (modified) (2 diffs)
-
trunk/assets/js/admin/components/polling.js (added)
-
trunk/assets/js/admin/components/restErrors.js (added)
-
trunk/assets/js/admin/pages/Audit.js (modified) (6 diffs)
-
trunk/assets/js/admin/pages/Dashboard.js (modified) (11 diffs)
-
trunk/assets/js/admin/pages/Feed.js (modified) (7 diffs)
-
trunk/assets/js/admin/pages/Products.js (modified) (4 diffs)
-
trunk/assets/js/admin/pages/Visibility.js (modified) (7 diffs)
-
trunk/blaze-ai-discovery-for-woocommerce.php (modified) (7 diffs)
-
trunk/build/index.asset.php (modified) (1 diff)
-
trunk/build/index.js (modified) (2 diffs)
-
trunk/readme.txt (modified) (6 diffs)
-
trunk/src/Attribution/CookieBridge.php (modified) (3 diffs)
-
trunk/src/Attribution/InlineTracker.php (modified) (3 diffs)
-
trunk/src/Attribution/OrderAttributor.php (modified) (3 diffs)
-
trunk/src/Attribution/PayloadSignature.php (modified) (3 diffs)
-
trunk/src/Attribution/Platforms.php (modified) (2 diffs)
-
trunk/src/Attribution/TrackingEndpoint.php (modified) (6 diffs)
-
trunk/src/Audit/AuditRunner.php (modified) (7 diffs)
-
trunk/src/Audit/Checks/CoreWebVitals.php (modified) (6 diffs)
-
trunk/src/Audit/Checks/ExistingFeedPlugins.php (modified) (1 diff)
-
trunk/src/Audit/Checks/ExistingSchema.php (modified) (3 diffs)
-
trunk/src/Audit/Checks/LlmsTxtExists.php (modified) (2 diffs)
-
trunk/src/Audit/Checks/RestApiAccessible.php (modified) (2 diffs)
-
trunk/src/Audit/Checks/RobotsTxt.php (modified) (1 diff)
-
trunk/src/Audit/Checks/StoreVisibility.php (added)
-
trunk/src/Audit/CrawlerAccess/SelfFetch.php (modified) (2 diffs)
-
trunk/src/Cloud/CloudClient.php (modified) (5 diffs)
-
trunk/src/Cloud/PayloadCache.php (modified) (1 diff)
-
trunk/src/Cloud/VisibilityClient.php (modified) (5 diffs)
-
trunk/src/Database/DatabaseModule.php (modified) (4 diffs)
-
trunk/src/Database/Installer.php (added)
-
trunk/src/Database/Migrator.php (modified) (3 diffs)
-
trunk/src/Database/RetentionCleanup.php (modified) (4 diffs)
-
trunk/src/Feed/ChatGptFeedGenerator.php (modified) (7 diffs)
-
trunk/src/Feed/FeedFormatter.php (modified) (1 diff)
-
trunk/src/Feed/FeedScheduler.php (modified) (5 diffs)
-
trunk/src/Feed/FeedStorage.php (added)
-
trunk/src/Feed/FeedValidator.php (modified) (3 diffs)
-
trunk/src/Feed/FeedWriter.php (added)
-
trunk/src/LlmsTxt/LlmsTxtRewriter.php (modified) (1 diff)
-
trunk/src/Rest/AuditController.php (modified) (2 diffs)
-
trunk/src/Rest/FeedController.php (modified) (3 diffs)
-
trunk/src/Schema/CompatibilityDetector.php (modified) (3 diffs)
-
trunk/src/Schema/SchemaModule.php (modified) (1 diff)
-
trunk/src/Schema/SchemaOrchestrator.php (modified) (1 diff)
-
trunk/src/Schema/Strategies/RankMathStrategy.php (modified) (3 diffs)
-
trunk/src/Schema/Strategies/StandaloneStrategy.php (modified) (1 diff)
-
trunk/src/Scoring/BatchScorer.php (modified) (8 diffs)
-
trunk/src/Scoring/Criteria/IdentifierPresence.php (modified) (1 diff)
-
trunk/uninstall.php (modified) (2 diffs)
-
trunk/vendor/bin (added)
-
trunk/vendor/composer/autoload_classmap.php (modified) (3 diffs)
-
trunk/vendor/composer/autoload_static.php (modified) (3 diffs)
-
trunk/vendor/composer/installed.php (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
blaze-ai-discovery-for-woocommerce/tags/1.1.3/assets/js/admin/pages/Audit.js
r3671993 r3673252 1 import { useState, useEffect } from '@wordpress/element';1 import { useState, useEffect, useRef } from '@wordpress/element'; 2 2 import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components'; 3 3 import { __, sprintf } from '@wordpress/i18n'; 4 4 import apiFetch from '@wordpress/api-fetch'; 5 5 import CloudConsentCard from '../components/CloudConsentCard'; 6 import RestErrorNotice, { classifyRestError, restErrorMessage } from '../components/restErrors'; 7 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 6 8 7 9 const statusIcon = ( status ) => { … … 10 12 case 'warning': return { icon: '\u26A0', color: '#856404', bg: '#fff3cd' }; 11 13 case 'fail': return { icon: '\u2717', color: '#721c24', bg: '#f8d7da' }; 14 case 'pending': return { icon: '\u2026', color: '#2271b1', bg: '#e7f0fa' }; 12 15 default: return { icon: '\u2139', color: '#004085', bg: '#cce5ff' }; 13 16 } 14 17 }; 18 19 // Rows the forced inline run could not finish within its cloud budget; the 20 // queued background audit replaces them. 21 const hasPending = ( audit ) => ( audit?.results || [] ).some( ( r ) => r && r.status === 'pending' ); 15 22 16 23 const verdictColors = ( verdict ) => { … … 225 232 const [ runNotice, setRunNotice ] = useState( null ); 226 233 const [ consent, setConsent ] = useState( null ); 234 // 401/403, non-JSON or no response from the REST API: shown as such 235 // rather than as "no audit yet". 236 const [ restError, setRestError ] = useState( null ); 237 const pollStop = useRef( null ); 238 239 const noteRestError = ( errOrKind ) => { 240 const kind = typeof errOrKind === 'string' ? errOrKind : classifyRestError( errOrKind ); 241 if ( restErrorMessage( kind ) ) { 242 setRestError( kind ); 243 } 244 return kind; 245 }; 246 247 const stopPolling = () => { 248 if ( pollStop.current ) { 249 pollStop.current(); 250 pollStop.current = null; 251 } 252 }; 227 253 228 254 const loadConsent = () => { … … 237 263 setLoading( false ); 238 264 } ) 239 .catch( () => setLoading( false ) ); 240 }; 241 242 useEffect( () => { loadAudit(); loadConsent(); }, [] ); 265 .catch( ( err ) => { 266 // 404 = no audit has run yet; anything else is worth a notice. 267 noteRestError( err ); 268 setLoading( false ); 269 } ); 270 }; 271 272 useEffect( () => { 273 loadAudit(); 274 loadConsent(); 275 return stopPolling; 276 }, [] ); // eslint-disable-line react-hooks/exhaustive-deps 243 277 244 278 // POST /audit/run answers 202 { queued: true } when the run is handed to 245 // Action Scheduler; poll GET /audit every 3 s (up to 90 s) until run_at 246 // moves past the previous audit. A 200 (no scheduler) carries the results. 279 // Action Scheduler; poll GET /audit every 3 s for 90 s, then every 30 s 280 // (20 min cap) until run_at moves past the previous audit and no row is 281 // still pending. A 200 (no scheduler, or a forced run) carries the results. 247 282 const POLL_INTERVAL_MS = 3000; 248 const POLL_TIMEOUT_MS = 90000; 249 250 const pollForNewAudit = ( previousRunAt, startedAt ) => { 251 apiFetch( { path: '/blazeaid/v1/audit' } ) 252 .then( ( data ) => { 283 const POLL_SLOW_AFTER_MS = 90000; 284 const POLL_SLOW_INTERVAL_MS = 30000; 285 286 const pollForNewAudit = ( previousRunAt ) => { 287 stopPolling(); 288 pollStop.current = startPoll( { 289 request: () => apiFetch( { path: '/blazeaid/v1/audit' } ), 290 onData: ( data ) => { 253 291 if ( data && data.run_at && data.run_at !== previousRunAt ) { 254 292 setAudit( data ); 255 setRunning( false );256 return;257 293 } 258 scheduleNextPoll( previousRunAt, startedAt ); 259 } ) 260 .catch( () => scheduleNextPoll( previousRunAt, startedAt ) ); 261 }; 262 263 const scheduleNextPoll = ( previousRunAt, startedAt ) => { 264 if ( Date.now() - startedAt >= POLL_TIMEOUT_MS ) { 265 setRunning( false ); 266 setRunNotice( __( 'Still running — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 267 return; 268 } 269 setTimeout( () => pollForNewAudit( previousRunAt, startedAt ), POLL_INTERVAL_MS ); 294 }, 295 isDone: ( data ) => !! ( data && data.run_at && data.run_at !== previousRunAt && ! hasPending( data ) ), 296 intervalMs: POLL_INTERVAL_MS, 297 slowAfterMs: POLL_SLOW_AFTER_MS, 298 slowIntervalMs: POLL_SLOW_INTERVAL_MS, 299 onSlow: () => setRunNotice( __( 'Still running — this page keeps checking for up to 20 minutes.', 'blaze-ai-discovery-for-woocommerce' ) ), 300 onStop: ( reason ) => { 301 pollStop.current = null; 302 setRunning( false ); 303 const kind = stopReasonToErrorKind( reason ); 304 if ( kind ) { 305 noteRestError( kind ); 306 setRunNotice( null ); 307 } else if ( reason === 'timeout' ) { 308 setRunNotice( __( 'Still running — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 309 } else { 310 setRunNotice( null ); 311 } 312 }, 313 } ); 270 314 }; 271 315 … … 277 321 .then( ( data ) => { 278 322 if ( data && data.queued ) { 279 scheduleNextPoll( previousRunAt, Date.now());323 pollForNewAudit( previousRunAt ); 280 324 return; 281 325 } 282 326 setAudit( data ); 283 327 setRunning( false ); 328 if ( hasPending( data ) ) { 329 // Cloud rows did not fit the request budget; the queued 330 // background audit fills them in. 331 setRunNotice( __( 'Cloud checks are still running in the background — the rows marked pending will update.', 'blaze-ai-discovery-for-woocommerce' ) ); 332 pollForNewAudit( data.run_at || previousRunAt ); 333 } 284 334 } ) 285 .catch( () => setRunning( false ) ); 335 .catch( ( err ) => { 336 setRunning( false ); 337 const kind = noteRestError( err ); 338 if ( ! restErrorMessage( kind ) ) { 339 setRunNotice( __( 'Could not start the audit. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 340 } 341 } ); 286 342 }; 287 343 … … 312 368 </Button> 313 369 </div> 370 371 { restError && <RestErrorNotice kind={ restError } /> } 314 372 315 373 { audit?.run_at && ( -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/assets/js/admin/pages/Dashboard.js
r3672021 r3673252 6 6 import CloudConsentCard from '../components/CloudConsentCard'; 7 7 import JobsHealthNotice, { fetchJobsHealth } from '../components/JobsHealthNotice'; 8 import RestErrorNotice, { classifyRestError, restErrorMessage } from '../components/restErrors'; 9 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 8 10 9 11 // First-run polling: GET /audit every 5 s for 3 min, then every 30 s up to … … 29 31 30 32 const probeRan = ( audit ) => crawlerAccessResult( audit )?.probe?.ran === true; 33 34 // Rows the forced inline run could not finish within its cloud budget; the 35 // queued background audit replaces them (F-011). 36 const pendingRows = ( audit ) => ( audit?.results || [] ).filter( ( r ) => r && r.status === 'pending' ); 37 const auditHasPending = ( audit ) => pendingRows( audit ).length > 0; 31 38 32 39 const blockedRetrievalCrawlers = ( result ) => … … 241 248 const warnings = results.filter( ( c ) => c && c.status === 'warning' ).length; 242 249 const issues = fails + warnings; 250 const pending = results.filter( ( c ) => c && c.status === 'pending' ).length; 243 251 const bg = fails > 0 ? '#f8d7da' : warnings > 0 ? '#fff3cd' : '#d4edda'; 244 252 const color = fails > 0 ? '#721c24' : warnings > 0 ? '#856404' : '#155724'; … … 256 264 results.length 257 265 ); 266 if ( pending > 0 ) { 267 body += ' · ' + sprintf( 268 /* translators: %d: number of audit rows whose cloud check is still running */ 269 _n( '%d cloud check still running', '%d cloud checks still running', pending, 'blaze-ai-discovery-for-woocommerce' ), 270 pending 271 ); 272 } 258 273 } else { 259 274 icon = <Bubble bg="#f0f0f0" color="#757575" fontSize={ 24 }>?</Bubble>; … … 369 384 const [ probeState, setProbeState ] = useState( null ); // null | 'waiting' | 'done' 370 385 const [ reminderOpen, setReminderOpen ] = useState( false ); 371 372 // One live poll at a time; bumping the token cancels the previous one (and all on unmount). 373 const pollToken = useRef( 0 ); 386 // A REST failure that is not "nothing yet": 401/403 (session expired or a 387 // security plugin), non-JSON, or no response. Shown instead of the 388 // "background jobs haven't run" copy, which used to swallow all of them. 389 const [ restError, setRestError ] = useState( null ); 390 391 // One live audit poll at a time; stop() cancels the previous one (and all on unmount). 392 const pollStop = useRef( null ); 374 393 const firstRunStarted = useRef( false ); 375 394 const modalOffered = useRef( false ); 376 395 const reminderRecorded = useRef( false ); 377 396 const dismissedWithAudit = useRef( false ); 378 useEffect( () => () => { pollToken.current += 1; }, [] ); 397 const stopAuditPoll = () => { 398 if ( pollStop.current ) { 399 pollStop.current(); 400 pollStop.current = null; 401 } 402 }; 403 useEffect( () => stopAuditPoll, [] ); 404 405 const noteRestError = ( errOrKind ) => { 406 const kind = typeof errOrKind === 'string' ? errOrKind : classifyRestError( errOrKind ); 407 if ( restErrorMessage( kind ) ) { 408 setRestError( kind ); 409 } 410 return kind; 411 }; 379 412 380 413 // Polls GET /audit until done(data) is true: every 5 s for 3 min, then 381 // (after calling onSlow once) every 30 s until 20 min have passed. 414 // (after calling onSlow once) every 30 s until 20 min have passed. Stops 415 // early on a 401/403 or three unexpected responses and says so. 382 416 const pollAudit = ( done, onSlow ) => { 383 const token = ++pollToken.current; 384 const startedAt = Date.now(); 385 let slowNotified = false; 386 const tick = () => { 387 if ( token !== pollToken.current ) { 388 return; 389 } 390 apiFetch( { path: '/blazeaid/v1/audit' } ) 391 .catch( () => null ) 392 .then( ( data ) => { 393 if ( token !== pollToken.current ) { 394 return; 395 } 396 if ( data && data.run_at ) { 397 setAudit( data ); 398 if ( done( data ) ) { 399 return; 400 } 401 } 402 const elapsed = Date.now() - startedAt; 403 if ( elapsed >= AUDIT_POLL_MAX_MS ) { 404 return; 405 } 406 if ( elapsed >= AUDIT_POLL_LIMIT_MS ) { 407 if ( ! slowNotified ) { 408 slowNotified = true; 409 if ( onSlow ) { 410 onSlow(); 411 } 412 } 413 setTimeout( tick, AUDIT_SLOW_POLL_MS ); 414 return; 415 } 416 setTimeout( tick, AUDIT_POLL_MS ); 417 } ); 418 }; 419 setTimeout( tick, AUDIT_POLL_MS ); 417 stopAuditPoll(); 418 pollStop.current = startPoll( { 419 request: () => apiFetch( { path: '/blazeaid/v1/audit' } ), 420 onData: ( data ) => { 421 if ( data && data.run_at ) { 422 setAudit( data ); 423 } 424 }, 425 isDone: ( data ) => !! ( data && data.run_at && done( data ) ), 426 intervalMs: AUDIT_POLL_MS, 427 slowAfterMs: AUDIT_POLL_LIMIT_MS, 428 slowIntervalMs: AUDIT_SLOW_POLL_MS, 429 onSlow, 430 maxMs: AUDIT_POLL_MAX_MS, 431 onStop: ( reason ) => { 432 pollStop.current = null; 433 const kind = stopReasonToErrorKind( reason ); 434 if ( kind ) { 435 noteRestError( kind ); 436 } 437 }, 438 } ); 420 439 }; 421 440 … … 448 467 } 449 468 setLoading( false ); 450 } ).catch( () => setLoading( false ) ); 451 }, [ days ] ); 469 } ).catch( ( err ) => { 470 noteRestError( err ); 471 setLoading( false ); 472 } ); 473 }, [ days ] ); // eslint-disable-line react-hooks/exhaustive-deps 452 474 453 475 // Cloud results arrive in the background: while the visibility report is 454 // pending, or consent is on but the crawler probe has not run yet, poll 455 // until they land (5 s, up to 3 min) instead of waiting for a reload. 456 const cloudPollToken = useRef( 0 ); 457 useEffect( () => () => { cloudPollToken.current += 1; }, [] ); 476 // pending, consent is on but the crawler probe has not run yet, or the 477 // forced inline audit left rows pending, poll until they land (5 s for 478 // 3 min, then 30 s, 20 min cap) instead of waiting for a reload. The 479 // effect depends on the pending *booleans*, not the audit object, so a 480 // poll that stores a fresh audit does not restart the clock (adm-F12). 481 const consentOn = consent ? !! consent.granted : false; 482 const crawlerRow = crawlerAccessResult( audit ); 483 const probePending = !! ( consentOn && crawlerRow && crawlerRow.probe && crawlerRow.probe.ran === false && crawlerRow.probe.notice === 'consent_off' ); 484 const rowsPending = auditHasPending( audit ); 485 const visibilityPending = visibility?.state === 'pending' || ( consentOn && visibility?.state === 'consent_off' ); 458 486 useEffect( () => { 459 const consentOn = consent ? !! consent.granted : false; 460 const crawlerRow = Array.isArray( audit?.results ) ? audit.results.find( ( c ) => c && c.crawlers ) : null; 461 const probePending = consentOn && crawlerRow && crawlerRow.probe && crawlerRow.probe.ran === false && crawlerRow.probe.notice === 'consent_off'; 462 const visibilityPending = visibility?.state === 'pending' || ( consentOn && visibility?.state === 'consent_off' ); 463 if ( loading || ( ! probePending && ! visibilityPending ) ) { 464 return; 465 } 466 const token = ++cloudPollToken.current; 467 const startedAt = Date.now(); 468 const tick = () => { 469 if ( token !== cloudPollToken.current || Date.now() - startedAt > AUDIT_POLL_LIMIT_MS ) { 470 return; 471 } 472 Promise.all( [ 473 visibilityPending ? apiFetch( { path: '/blazeaid/v1/visibility' } ).catch( () => null ) : Promise.resolve( undefined ), 474 probePending ? apiFetch( { path: '/blazeaid/v1/audit' } ).catch( () => null ) : Promise.resolve( undefined ), 475 ] ).then( ( [ v, a ] ) => { 476 if ( token !== cloudPollToken.current ) { 477 return; 478 } 479 if ( v !== undefined && v ) { 487 if ( loading || ( ! probePending && ! visibilityPending && ! rowsPending ) ) { 488 return undefined; 489 } 490 const wantVisibility = visibilityPending; 491 const wantAudit = probePending || rowsPending; 492 const stillPending = ( [ v, a ] ) => { 493 const stillVisibility = wantVisibility ? !! ( v && v.state === 'pending' ) : false; 494 const row = wantAudit ? crawlerAccessResult( a ) : null; 495 const stillProbe = wantAudit ? !! ( row && row.probe && row.probe.ran === false ) : false; 496 const stillRows = wantAudit ? auditHasPending( a ) : false; 497 return stillVisibility || stillProbe || stillRows; 498 }; 499 return startPoll( { 500 request: () => Promise.all( [ 501 wantVisibility ? apiFetch( { path: '/blazeaid/v1/visibility' } ) : Promise.resolve( undefined ), 502 wantAudit ? apiFetch( { path: '/blazeaid/v1/audit' } ) : Promise.resolve( undefined ), 503 ] ), 504 onData: ( [ v, a ] ) => { 505 if ( v ) { 480 506 setVisibility( v ); 481 507 } 482 if ( a !== undefined && a) {508 if ( a && a.run_at ) { 483 509 setAudit( a ); 484 510 } 485 const stillVisibility = v !== undefined ? ( v && v.state === 'pending' ) : false; 486 const row = a && Array.isArray( a.results ) ? a.results.find( ( c ) => c && c.crawlers ) : null; 487 const stillProbe = a !== undefined ? !! ( row && row.probe && row.probe.ran === false ) : false; 488 if ( stillVisibility || stillProbe ) { 489 setTimeout( tick, AUDIT_POLL_MS ); 511 }, 512 isDone: ( pair ) => ! stillPending( pair ), 513 intervalMs: AUDIT_POLL_MS, 514 slowAfterMs: AUDIT_POLL_LIMIT_MS, 515 slowIntervalMs: AUDIT_SLOW_POLL_MS, 516 maxMs: AUDIT_POLL_MAX_MS, 517 onStop: ( reason ) => { 518 const kind = stopReasonToErrorKind( reason ); 519 if ( kind ) { 520 noteRestError( kind ); 490 521 } 491 } ); 492 }; 493 setTimeout( tick, AUDIT_POLL_MS ); 494 }, [ loading, visibility?.state, consent?.granted, audit ] ); // eslint-disable-line react-hooks/exhaustive-deps 522 }, 523 } ); 524 }, [ loading, visibilityPending, probePending, rowsPending ] ); // eslint-disable-line react-hooks/exhaustive-deps 495 525 496 526 // First run: no audit yet, so the activation audit is still queued. Poll … … 498 528 // on the request thread (polling continues, slower, up to 20 min). 499 529 useEffect( () => { 500 if ( loading || audit || firstRunStarted.current ) {530 if ( loading || audit || restError || firstRunStarted.current ) { 501 531 return; 502 532 } … … 506 536 refreshJobsHealth(); 507 537 } ); 508 }, [ loading, audit ] ); // eslint-disable-line react-hooks/exhaustive-deps538 }, [ loading, audit, restError ] ); // eslint-disable-line react-hooks/exhaustive-deps 509 539 510 540 // While the first-run card is up, ask once (at 60 s) whether the queue is 511 541 // moving, so the background-jobs notice appears without a reload. 512 542 useEffect( () => { 513 if ( loading || audit ) {543 if ( loading || audit || restError ) { 514 544 return undefined; 515 545 } 516 546 const timer = setTimeout( refreshJobsHealth, JOBS_HEALTH_CHECK_MS ); 517 547 return () => clearTimeout( timer ); 518 }, [ loading, audit ] ); // eslint-disable-line react-hooks/exhaustive-deps548 }, [ loading, audit, restError ] ); // eslint-disable-line react-hooks/exhaustive-deps 519 549 520 550 // The cloud-checks offer: once per plugin version while consent is off. … … 547 577 // Run the audit on this request (force) and show the result at once. 548 578 // A run that fails (timeout, 5xx) restarts the first-run poll: the 549 // queued copy may still land, or the owner can click again. 579 // queued copy may still land, or the owner can click again. A 401/403 580 // or a non-JSON answer is reported as such instead. 550 581 const runAuditNow = () => { 551 582 setRunningNow( true ); 552 583 setRunNowError( false ); 553 pollToken.current += 1; // stop the first-run poll;the result arrives here.554 const failed = ( ) => {584 stopAuditPoll(); // the result arrives here. 585 const failed = ( err ) => { 555 586 setRunNowError( true ); 587 const kind = err ? noteRestError( err ) : null; 588 if ( kind === 'auth' || kind === 'html' ) { 589 return false; 590 } 556 591 setFirstRunSlow( true ); 557 592 if ( ! audit ) { … … 567 602 return true; 568 603 } 569 return failed( );604 return failed( null ); 570 605 } ) 571 606 .catch( failed ) … … 721 756 ) } 722 757 758 { restError && <RestErrorNotice kind={ restError } /> } 759 723 760 <JobsHealthNotice health={ jobsHealth } audit={ audit } onRunNow={ afterJobsRan } onRunAudit={ runAuditNow } /> 724 761 725 { ! audit && (762 { ! audit && ! restError && ( 726 763 <FirstRunCard slow={ firstRunSlow } running={ runningNow } error={ runNowError } onRunNow={ runAuditNow } /> 727 764 ) } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/assets/js/admin/pages/Feed.js
r3668873 r3673252 1 import { useState, useEffect } from '@wordpress/element';2 import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components';3 import { __ } from '@wordpress/i18n';1 import { useState, useEffect, useRef } from '@wordpress/element'; 2 import { Card, CardHeader, CardBody, Button, Spinner, Notice } from '@wordpress/components'; 3 import { __, sprintf } from '@wordpress/i18n'; 4 4 import apiFetch from '@wordpress/api-fetch'; 5 import { classifyRestError, restErrorMessage } from '../components/restErrors'; 6 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 7 8 // A queued run is polled every POLL_MS until it finishes. startPoll() ends 9 // the poll at its 20-minute cap, on a 401/403 and after three unexpected 10 // responses, and stop() clears the timer when the page is left. 11 const POLL_MS = 3000; 12 13 const isActive = ( progress ) => !! progress && ( progress.state === 'queued' || progress.state === 'running' ); 5 14 6 15 export default function Feed() { … … 9 18 const [ loading, setLoading ] = useState( true ); 10 19 const [ generating, setGenerating ] = useState( false ); 20 const [ error, setError ] = useState( null ); 21 // The live poll's stop(); one at a time, cleared on unmount. 22 const pollStop = useRef( null ); 23 24 const stopPolling = () => { 25 if ( pollStop.current ) { 26 pollStop.current(); 27 pollStop.current = null; 28 } 29 }; 30 31 const loadValidation = () => 32 apiFetch( { path: '/blazeaid/v1/feed/validate' } ) 33 .then( setValidation ) 34 .catch( () => {} ); 35 36 const watchProgress = () => { 37 stopPolling(); 38 setGenerating( true ); 39 let last = null; 40 pollStop.current = startPoll( { 41 request: () => apiFetch( { path: '/blazeaid/v1/feed/status' } ), 42 onData: ( s ) => { 43 last = s; 44 setStatus( s ); 45 }, 46 isDone: ( s ) => ! isActive( s && s.progress ), 47 intervalMs: POLL_MS, 48 onStop: ( reason ) => { 49 pollStop.current = null; 50 setGenerating( false ); 51 if ( reason === 'done' ) { 52 if ( last && last.progress && last.progress.state === 'error' ) { 53 setError( last.progress.error || __( 'Feed generation failed.', 'blaze-ai-discovery-for-woocommerce' ) ); 54 } 55 loadValidation(); 56 return; 57 } 58 if ( reason === 'timeout' ) { 59 setError( __( 'The feed is still queued. Background jobs may not be running on this site — check the Jobs page, then try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 60 return; 61 } 62 const kind = stopReasonToErrorKind( reason ); 63 setError( restErrorMessage( kind ) || __( 'Feed generation failed.', 'blaze-ai-discovery-for-woocommerce' ) ); 64 }, 65 } ); 66 }; 11 67 12 68 useEffect( () => { … … 19 75 setValidation( v ); 20 76 setLoading( false ); 21 } ).catch( () => setLoading( false ) ); 22 }, [] ); 77 if ( isActive( s.progress ) ) { 78 watchProgress(); 79 } 80 } ).catch( ( err ) => { 81 setLoading( false ); 82 const message = restErrorMessage( classifyRestError( err ) ); 83 if ( message ) { 84 setError( message ); 85 } 86 } ); 87 return stopPolling; 88 }, [] ); // eslint-disable-line react-hooks/exhaustive-deps 23 89 24 90 const generateFeed = () => { 25 91 setGenerating( true ); 26 apiFetch( { path: '/blazeaid/v1/feed/generate', method: 'POST' } ) 92 setError( null ); 93 // Small catalogues run on the request and come back finished; larger ones are queued and polled. 94 const inline = !! status && status.total_products <= status.inline_limit; 95 apiFetch( { path: '/blazeaid/v1/feed/generate', method: 'POST', data: { force: inline } } ) 27 96 .then( ( data ) => { 28 97 setStatus( data ); 98 if ( data.queued ) { 99 watchProgress(); 100 return; 101 } 29 102 setGenerating( false ); 103 loadValidation(); 30 104 } ) 31 .catch( () => setGenerating( false ) ); 105 .catch( ( err ) => { 106 setGenerating( false ); 107 // A blocked REST API, an HTML page or no response get the shared 108 // sentence; a JSON error (503 no scheduler, 500 write failure, 109 // 409 already running) carries its own message. 110 const kind = classifyRestError( err ); 111 const shared = kind === 'other' ? null : restErrorMessage( kind ); 112 setError( shared || ( err && ( err.error || err.message ) ) || __( 'Feed generation failed.', 'blaze-ai-discovery-for-woocommerce' ) ); 113 } ); 32 114 }; 33 115 … … 40 122 } 41 123 124 const progress = status?.progress; 125 let buttonLabel = __( 'Generate Feed', 'blaze-ai-discovery-for-woocommerce' ); 126 if ( generating ) { 127 if ( progress?.state === 'running' && progress.total > 0 ) { 128 buttonLabel = sprintf( 129 /* translators: 1: products processed, 2: products total */ 130 __( 'Generating… %1$s of %2$s', 'blaze-ai-discovery-for-woocommerce' ), 131 progress.done, 132 progress.total 133 ); 134 } else if ( progress?.state === 'queued' ) { 135 buttonLabel = __( 'Queued…', 'blaze-ai-discovery-for-woocommerce' ); 136 } else { 137 buttonLabel = __( 'Generating…', 'blaze-ai-discovery-for-woocommerce' ); 138 } 139 } 140 42 141 return ( 43 142 <div style={ { maxWidth: 900, margin: '20px auto' } }> 44 143 <h1>{ __( 'ChatGPT Merchant Feed', 'blaze-ai-discovery-for-woocommerce' ) }</h1> 144 145 { error && ( 146 <Notice status="error" isDismissible onRemove={ () => setError( null ) }> 147 { error } 148 </Notice> 149 ) } 45 150 46 151 { /* Feed status */ } … … 60 165 </p> 61 166 ) } 167 { generating && progress?.state === 'queued' && ( 168 <p style={ { margin: '8px 0 0', color: '#757575', fontSize: 13 } }> 169 { __( 'Queued as a background job — this page updates when it finishes.', 'blaze-ai-discovery-for-woocommerce' ) } 170 </p> 171 ) } 62 172 </div> 63 173 <div style={ { display: 'flex', gap: 8 } }> 64 174 <Button variant="primary" onClick={ generateFeed } disabled={ generating }> 65 { generating ? __( 'Generating…', 'blaze-ai-discovery-for-woocommerce' ) : __( 'Generate Feed', 'blaze-ai-discovery-for-woocommerce' )}175 { buttonLabel } 66 176 </Button> 67 177 { status?.download_url && ( … … 86 196 </CardHeader> 87 197 <CardBody> 88 { validation ? (198 { validation && validation.available !== false ? ( 89 199 <div> 90 200 <p> … … 93 203 <span style={ { color: '#d63638', fontWeight: 600, marginLeft: 16 } }>{ validation.invalid } { __( 'invalid', 'blaze-ai-discovery-for-woocommerce' ) }</span> 94 204 ) } 205 { validation.ineligible > 0 && ( 206 <span style={ { color: '#996800', fontWeight: 600, marginLeft: 16 } }>{ validation.ineligible } { __( 'not searchable yet', 'blaze-ai-discovery-for-woocommerce' ) }</span> 207 ) } 95 208 </p> 209 { validation.truncated && ( 210 <p style={ { color: '#757575', fontSize: 13 } }> 211 { sprintf( 212 /* translators: %s: number of rows checked */ 213 __( 'Checked the first %s rows of the feed.', 'blaze-ai-discovery-for-woocommerce' ), 214 validation.checked 215 ) } 216 </p> 217 ) } 96 218 { validation.issues?.length > 0 && ( 97 219 <div style={ { marginTop: 12 } }> -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/assets/js/admin/pages/Products.js
r3672021 r3673252 1 1 import { useState, useEffect } from '@wordpress/element'; 2 import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components';2 import { Card, CardHeader, CardBody, Button, Spinner, Notice } from '@wordpress/components'; 3 3 import { __, sprintf } from '@wordpress/i18n'; 4 4 import apiFetch from '@wordpress/api-fetch'; 5 5 import JobsHealthNotice, { fetchJobsHealth } from '../components/JobsHealthNotice'; 6 import RestErrorNotice, { classifyRestError, restErrorMessage } from '../components/restErrors'; 7 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 8 9 // GET /scores/progress every 3 s while a run is in flight; 20 min cap. 10 const PROGRESS_POLL_MS = 3000; 6 11 7 12 const severityStyle = ( severity ) => { … … 125 130 const [ scoring, setScoring ] = useState( false ); 126 131 const [ jobsHealth, setJobsHealth ] = useState( null ); 132 // 401/403, non-JSON or no response from the REST API. 133 const [ restError, setRestError ] = useState( null ); 134 const [ scoringNotice, setScoringNotice ] = useState( null ); 135 136 const noteRestError = ( errOrKind ) => { 137 const kind = typeof errOrKind === 'string' ? errOrKind : classifyRestError( errOrKind ); 138 if ( restErrorMessage( kind ) ) { 139 setRestError( kind ); 140 } 141 return kind; 142 }; 127 143 128 144 // Refetch everything; `initial` shows the page spinner (which would … … 149 165 } 150 166 setLoading( false ); 151 } ).catch( () => setLoading( false ) ); 167 } ).catch( ( err ) => { 168 noteRestError( err ); 169 setLoading( false ); 170 } ); 152 171 }; 153 172 154 useEffect( () => loadData( true ), [] ); 155 173 useEffect( () => loadData( true ), [] ); // eslint-disable-line react-hooks/exhaustive-deps 174 175 // While a run is in flight: poll progress until it completes or fails. 176 // Bounded (20 min), stops on a 401/403 or three unexpected responses, 177 // and the timer is cleared when the page unmounts. 156 178 useEffect( () => { 157 if ( ! scoring ) return; 158 const interval = setInterval( () => { 159 apiFetch( { path: '/blazeaid/v1/scores/progress' } ).then( ( pr ) => { 179 if ( ! scoring ) { 180 return undefined; 181 } 182 let last = null; 183 const isOver = ( pr ) => !! pr && ( pr.status === 'complete' || pr.status === 'idle' || pr.status === 'failed' ); 184 return startPoll( { 185 request: () => apiFetch( { path: '/blazeaid/v1/scores/progress' } ), 186 onData: ( pr ) => { 187 last = pr; 160 188 setProgress( pr ); 161 if ( pr.status === 'complete' || pr.status === 'idle' ) { 162 setScoring( false ); 163 loadData(); 189 }, 190 isDone: isOver, 191 intervalMs: PROGRESS_POLL_MS, 192 onStop: ( reason ) => { 193 setScoring( false ); 194 if ( reason === 'done' ) { 195 if ( last && last.status !== 'failed' ) { 196 loadData( false ); 197 } 198 return; 199 } 200 if ( reason === 'timeout' ) { 201 setScoringNotice( __( 'Scoring is still running in the background — reload the page later to see the result.', 'blaze-ai-discovery-for-woocommerce' ) ); 202 return; 203 } 204 const kind = stopReasonToErrorKind( reason ); 205 if ( kind ) { 206 noteRestError( kind ); 207 } 208 }, 209 } ); 210 }, [ scoring ] ); // eslint-disable-line react-hooks/exhaustive-deps 211 212 const startScoring = () => { 213 setScoringNotice( null ); 214 setScoring( true ); 215 apiFetch( { path: '/blazeaid/v1/scores/recalculate', method: 'POST' } ) 216 .then( ( r ) => { 217 if ( r && r.progress ) { 218 setProgress( r.progress ); 219 } 220 } ) 221 .catch( ( err ) => { 222 setScoring( false ); 223 const kind = noteRestError( err ); 224 if ( ! restErrorMessage( kind ) ) { 225 setScoringNotice( __( 'Could not start scoring. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 164 226 } 165 227 } ); 166 }, 3000 );167 return () => clearInterval( interval );168 }, [ scoring ] );169 170 const startScoring = () => {171 setScoring( true );172 apiFetch( { path: '/blazeaid/v1/scores/recalculate', method: 'POST' } );173 228 }; 174 229 … … 194 249 </div> 195 250 251 { restError && <RestErrorNotice kind={ restError } /> } 252 196 253 <JobsHealthNotice health={ jobsHealth } onRunNow={ () => loadData( false ) } /> 254 255 { progress?.status === 'failed' && ( 256 <div style={ { display: 'grid', gap: 12, marginBottom: 16 } }> 257 <Notice status="error" isDismissible={ false }> 258 { progress.reason || __( 'The last scoring run stopped before it finished. Click Recalculate All to start again.', 'blaze-ai-discovery-for-woocommerce' ) } 259 </Notice> 260 </div> 261 ) } 262 263 { scoringNotice && ( 264 <div style={ { display: 'grid', gap: 12, marginBottom: 16 } }> 265 <Notice status="warning" onRemove={ () => setScoringNotice( null ) }>{ scoringNotice }</Notice> 266 </div> 267 ) } 197 268 198 269 { scoring && progress?.status === 'running' && ( -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/assets/js/admin/pages/Visibility.js
r3671993 r3673252 5 5 import CloudConsentCard from '../components/CloudConsentCard'; 6 6 import PayloadRenderer, { PayloadNotices } from '../components/PayloadRenderer'; 7 import { classifyRestError, restErrorMessage } from '../components/restErrors'; 8 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 7 9 8 10 // GET /blazeaid/v1/visibility → { consent, payload, state } … … 29 31 const [ timedOut, setTimedOut ] = useState( false ); 30 32 const [ loadFailed, setLoadFailed ] = useState( false ); 31 const poll Timer= useRef( null );33 const pollStop = useRef( null ); 32 34 const unmounted = useRef( false ); 33 35 34 36 const stopPolling = () => { 35 if ( poll Timer.current ) {36 clearTimeout( pollTimer.current);37 poll Timer.current = null;37 if ( pollStop.current ) { 38 pollStop.current(); 39 pollStop.current = null; 38 40 } 39 41 }; … … 58 60 setLoading( false ); 59 61 if ( data?.state === 'pending' ) { 60 s cheduleNextPoll( Date.now());62 startPolling(); 61 63 } 62 64 } ) 63 .catch( ( ) => {65 .catch( ( err ) => { 64 66 if ( unmounted.current ) { 65 67 return; … … 69 71 setLoadFailed( true ); 70 72 setLoading( false ); 71 setNotice( __( 'Could not load AI visibility data. Reload the page to try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 73 // 401/403 or a non-JSON answer is named as such; anything else gets the generic line. 74 setNotice( restErrorMessage( classifyRestError( err ) ) || __( 'Could not load AI visibility data. Reload the page to try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 72 75 } ); 73 76 }; 74 77 75 78 // Poll GET /visibility every 5 s (up to 2 min) until the background 76 // refresh has cached a payload and the state moves off `pending`. 77 const poll = ( startedAt ) => {78 apiFetch( { path: '/blazeaid/v1/visibility' } )79 .then( ( data ) => {80 if ( unmounted.current ){81 return;82 }79 // refresh has cached a payload and the state moves off `pending`. Stops 80 // early on a 401/403 or three unexpected responses. 81 const startPolling = () => { 82 stopPolling(); 83 pollStop.current = startPoll( { 84 request: () => apiFetch( { path: '/blazeaid/v1/visibility' } ), 85 onData: ( data ) => { 83 86 if ( data && data.state !== 'pending' ) { 84 87 applyResponse( data ); 85 setRefreshing( false ); 86 return; 87 } 88 scheduleNextPoll( startedAt ); 89 } ) 90 .catch( () => scheduleNextPoll( startedAt ) ); 91 }; 92 93 const scheduleNextPoll = ( startedAt ) => { 94 if ( unmounted.current ) { 95 return; 96 } 97 if ( Date.now() - startedAt >= POLL_TIMEOUT_MS ) { 98 // The background job is still running; stop polling, keep the 99 // state as pending (so nothing claims there is no data) and let 100 // the user try Refresh again. 101 setRefreshing( false ); 102 setTimedOut( true ); 103 setNotice( __( 'Still fetching — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 104 return; 105 } 106 stopPolling(); 107 pollTimer.current = setTimeout( () => poll( startedAt ), POLL_INTERVAL_MS ); 88 } 89 }, 90 isDone: ( data ) => !! ( data && data.state !== 'pending' ), 91 intervalMs: POLL_INTERVAL_MS, 92 maxMs: POLL_TIMEOUT_MS, 93 onStop: ( reason ) => { 94 pollStop.current = null; 95 if ( unmounted.current ) { 96 return; 97 } 98 setRefreshing( false ); 99 if ( reason === 'timeout' ) { 100 // The background job is still running; keep the state as 101 // pending (so nothing claims there is no data) and let the 102 // user try Refresh again. 103 setTimedOut( true ); 104 setNotice( __( 'Still fetching — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 105 return; 106 } 107 const kind = stopReasonToErrorKind( reason ); 108 if ( kind ) { 109 setLoadFailed( true ); 110 setNotice( restErrorMessage( kind ) ); 111 } 112 }, 113 } ); 108 114 }; 109 115 … … 130 136 setPayload( null ); 131 137 setState( 'pending' ); 132 s cheduleNextPoll( Date.now());138 startPolling(); 133 139 return; 134 140 } … … 149 155 // apiFetch rejects with the parsed JSON body of a non-2xx response, so the 150 156 // controller's 403 arrives as { queued: false, state: 'consent_off' }. 151 if ( err && ( err.state === 'consent_off' || ( err.data && err.data.status === 403 ) )) {157 if ( err && err.state === 'consent_off' ) { 152 158 setConsent( false ); 153 159 setPayload( null ); … … 155 161 return; 156 162 } 157 setNotice( __( 'Could not start a refresh. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) );163 setNotice( restErrorMessage( classifyRestError( err ) ) || __( 'Could not start a refresh. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 158 164 } ); 159 165 }; -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/blaze-ai-discovery-for-woocommerce.php
r3672021 r3673252 4 4 * Plugin URI: https://blazecommerce.io/blaze-ai-discovery/ 5 5 * Description: Make your WooCommerce store visible to AI shopping agents. Tracks AI-referred traffic, scores product AI-readiness, enhances Schema.org markup, and generates ChatGPT merchant feeds. 6 * Version: 1.1. 26 * Version: 1.1.3 7 7 * Author: Blaze Commerce 8 8 * Author URI: https://blazecommerce.io … … 22 22 defined( 'ABSPATH' ) || exit; 23 23 24 define( 'BLAZEAID_VERSION', '1.1. 2' );24 define( 'BLAZEAID_VERSION', '1.1.3' ); 25 25 define( 'BLAZEAID_FILE', __FILE__ ); 26 26 define( 'BLAZEAID_PATH', plugin_dir_path( __FILE__ ) ); … … 57 57 printf( 58 58 '<div class="notice notice-error"><p>%s</p></div>', 59 esc_html__( ' WooCommerce AI Discovery requires WooCommerce to be installed and active.', 'blaze-ai-discovery-for-woocommerce' )59 esc_html__( 'Blaze AI Discovery needs WooCommerce. Install and activate WooCommerce and the setup completes automatically.', 'blaze-ai-discovery-for-woocommerce' ) 60 60 ); 61 61 } ); … … 73 73 } 74 74 75 // One autoloaded option compare per request. Out of sync when the plugin 76 // was activated before WooCommerce (WP 6.4 has no Requires Plugins gate; 77 // WP-CLI and bulk activation run the hooks alphabetically) or updated in 78 // place without an activation hook (zip upload, WP.org auto-update): 79 // finish the install or run the upgrade on init, once WooCommerce has 80 // registered its post types and before our rewrite flush at init:99. 81 if ( \BlazeAiDiscovery\Database\Installer::needs_sync() ) { 82 add_action( 'init', [ \BlazeAiDiscovery\Database\Installer::class, 'sync' ], 20 ); 83 } 84 75 85 $plugin = \BlazeAiDiscovery\Plugin::get_instance(); 76 86 $plugin->init(); … … 79 89 80 90 /** 91 * Whether the Composer autoloader shipped (a GitHub "Download ZIP" install 92 * has none); the lifecycle hooks must not fatal without it. 93 */ 94 function blazeaid_autoload(): bool { 95 if ( ! file_exists( BLAZEAID_PATH . 'vendor/autoload.php' ) ) { 96 return false; 97 } 98 require_once BLAZEAID_PATH . 'vendor/autoload.php'; 99 return true; 100 } 101 102 /** 81 103 * Activation hook. 104 * 105 * @param bool $network_wide Activated from the network admin. 82 106 */ 83 function blazeaid_activate( ): void {84 if ( ! class_exists( 'WooCommerce') ) {107 function blazeaid_activate( $network_wide = false ): void { 108 if ( ! blazeaid_autoload() ) { 85 109 return; 86 110 } 87 111 88 require_once BLAZEAID_PATH . 'vendor/autoload.php'; 89 90 $migrator = new \BlazeAiDiscovery\Database\Migrator(); 91 $migrator->run(); 92 93 // Generate payload signature salt. 94 if ( ! get_option( 'blazeaid_payload_salt' ) ) { 95 update_option( 'blazeaid_payload_salt', wp_generate_password( 64, true, true ) ); 112 if ( ! class_exists( 'WooCommerce' ) ) { 113 // Nothing can be installed yet; blazeaid_boot() finishes it when WooCommerce appears. 114 \BlazeAiDiscovery\Database\Installer::mark_pending( (bool) $network_wide ); 115 return; 96 116 } 97 117 98 // Generate visitor identification salt. 99 if ( ! get_option( 'blazeaid_visitor_salt' ) ) { 100 update_option( 'blazeaid_visitor_salt', wp_generate_password( 64, true, true ) ); 101 } 102 103 // Record when tracking started (kept across re-activations; removed on uninstall). 104 \BlazeAiDiscovery\Onboarding\Onboarding::ensure_installed_at(); 105 106 // Queue the first audit now (falls back to the admin_init flag without Action Scheduler). 107 \BlazeAiDiscovery\Onboarding\Onboarding::schedule_first_audit(); 108 109 // Score the catalog in the background so the Products page has numbers without a click. 110 \BlazeAiDiscovery\Onboarding\Onboarding::schedule_first_scoring(); 118 // Schema, salts, install date, first audit + scoring, llms.txt rewrite 119 // rule then flush - on every site of the network for a network activation. 120 \BlazeAiDiscovery\Database\Installer::activate( (bool) $network_wide ); 111 121 112 122 // Open the dashboard on the next admin load: single activation only, … … 116 126 $blazeaid_request['activate-multi'] = true; 117 127 } 118 if ( isset( $_REQUEST['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only guard, no state change.128 if ( isset( $_REQUEST['action'] ) && is_string( $_REQUEST['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only guard, no state change. 119 129 $blazeaid_request['action'] = sanitize_key( wp_unslash( $_REQUEST['action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended 120 130 } … … 122 132 \BlazeAiDiscovery\Onboarding\Onboarding::arm_redirect(); 123 133 } 124 125 flush_rewrite_rules();126 134 } 127 135 register_activation_hook( __FILE__, 'blazeaid_activate' ); 128 136 129 137 /** 130 * Deactivation hook. 138 * Deactivation hook: cancel every queued job (all seven hooks plus a group 139 * sweep), drop progress transients, flush the rewrite rules without ours. 140 * 141 * @param bool $network_wide Deactivated from the network admin. 131 142 */ 132 function blazeaid_deactivate(): void { 133 // Unschedule Action Scheduler jobs. 134 if ( function_exists( 'as_unschedule_all_actions' ) ) { 135 as_unschedule_all_actions( 'blazeaid_retention_cleanup' ); 136 as_unschedule_all_actions( 'blazeaid_batch_score' ); 137 as_unschedule_all_actions( 'blazeaid_feed_refresh' ); 138 as_unschedule_all_actions( 'blazeaid_run_audit' ); 139 as_unschedule_all_actions( 'blazeaid_visibility_monthly' ); 140 as_unschedule_all_actions( 'blazeaid_visibility_refresh' ); 143 function blazeaid_deactivate( $network_wide = false ): void { 144 if ( ! blazeaid_autoload() ) { 145 return; 141 146 } 142 delete_transient( 'blazeaid_visibility_sched' ); 143 144 flush_rewrite_rules(); 147 \BlazeAiDiscovery\Database\Installer::deactivate( (bool) $network_wide ); 145 148 } 146 149 register_deactivation_hook( __FILE__, 'blazeaid_deactivate' ); 150 151 /** 152 * New subsite on a network where the plugin is network-active: install for 153 * it (priority 20 - after core and WooCommerce created the site's tables). 154 */ 155 add_action( 'wp_initialize_site', static function ( $new_site ) { 156 if ( class_exists( \BlazeAiDiscovery\Database\Installer::class ) ) { 157 \BlazeAiDiscovery\Database\Installer::on_new_site( $new_site ); 158 } 159 }, 20 ); 147 160 148 161 /** -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/build/index.asset.php
r3672021 r3673252 1 <?php return array('dependencies' => array('react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => ' d252e97fd979af6f6e74');1 <?php return array('dependencies' => array('react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => 'c23c16312ac595e8533f'); -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/build/index.js
r3672021 r3673252 1 (()=>{"use strict";var e={n:r=>{var o=r&&r.__esModule?()=>r.default:()=>r;return e.d(o,{a:o}),o},d:(r,o)=>{for(var t in o)e.o(o,t)&&!e.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:o[t]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)};const r=window.wp.element,o=window.wp.components,t=window.wp.i18n,i=window.wp.apiFetch;var a=e.n(i);const s=window.ReactJSXRuntime,n=()=>(0,t.__)("Free, no account, no API key. Runs on our infrastructure. Sends your store URL, one product URL and a few category names (publicly available information) to api.blazecommerce.io — never customer or order data. One toggle to turn off.","blaze-ai-discovery-for-woocommerce");function l({style:e}){return(0,s.jsxs)("p",{style:{margin:"8px 0 0",fontSize:13,...e||{}},children:[(0,s.jsx)("a",{href:window.blazeaid?.privacyUrl||"https://blazecommerce.io/privacy-policy/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Privacy policy","blaze-ai-discovery-for-woocommerce")})," · ",(0,s.jsx)("a",{href:window.blazeaid?.disclosureUrl||"https://wordpress.org/plugins/blaze-ai-discovery-for-woocommerce/#faq",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Full disclosure","blaze-ai-discovery-for-woocommerce")})]})}function c({onEnable:e,onDismiss:i,busy:a}){const[c,d]=(0,r.useState)(!1);return(0,s.jsxs)(o.Modal,{title:(0,t.__)("See what AI assistants actually see","blaze-ai-discovery-for-woocommerce"),onRequestClose:()=>!a&&i(),shouldCloseOnClickOutside:!1,style:{maxWidth:560},className:"blazeaid-cloud-checks-modal",children:[(0,s.jsx)("p",{style:{marginTop:0},children:(0,t.__)("Your store audit is already running. Turn on cloud checks and you also get:","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("ul",{style:{margin:"0 0 16px",paddingLeft:0,listStyle:"none"},children:[{title:(0,t.__)("Crawler access from the open internet","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("We fetch your pages as GPTBot, OAI-SearchBot, ClaudeBot and PerplexityBot from outside your network — the only way to catch a Cloudflare or firewall block your own server can't see.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Core Web Vitals from real shoppers","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("Google's field data for your store on mobile — LCP, INP, CLS — not a lab test.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Your AI Visibility report","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("How often ChatGPT and Google AI mention your store, which pages they cite, and who gets named instead. Refreshed monthly.","blaze-ai-discovery-for-woocommerce")}].map(e=>(0,s.jsxs)("li",{style:{margin:"0 0 12px"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("p",{style:{margin:"2px 0 0",color:"#50575e",fontSize:13},children:e.body})]},e.title))}),(0,s.jsxs)("p",{style:{color:"#50575e",fontSize:12,margin:"0 0 4px"},children:[n()," ",(0,s.jsx)(o.Button,{variant:"link",onClick:()=>d(!c),"aria-expanded":c,style:{fontSize:12,textDecoration:"underline"},children:(0,t.__)("Details","blaze-ai-discovery-for-woocommerce")})]}),c&&(0,s.jsxs)("div",{style:{background:"#f6f7f7",borderRadius:4,padding:"10px 12px",margin:"8px 0 12px",fontSize:12,color:"#3c434a"},children:[(0,s.jsx)("ul",{style:{margin:0,paddingLeft:18},children:[(0,t.__)("Crawler access: your store URL, one public product URL, and the plugin, WordPress, WooCommerce and PHP version numbers. Returns what each AI crawler saw.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("Core Web Vitals: your store URL. Returns Google's Chrome UX Report figures for your origin.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("AI Visibility: your domain, store country, site locale and up to five product category names. Returns the monthly mentions report.","blaze-ai-discovery-for-woocommerce")].map(e=>(0,s.jsx)("li",{style:{margin:"0 0 6px"},children:e},e))}),(0,s.jsx)("p",{style:{margin:"8px 0 0"},children:(0,t.__)("All of it is publicly available information; nothing about customers, orders or users ever leaves your site.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(l,{style:{fontSize:12}})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:16},children:[(0,s.jsx)(o.Button,{variant:"tertiary",onClick:i,disabled:a,children:(0,t.__)("Not now","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:e,isBusy:a,disabled:a,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})]})}function d({consent:e,onToggle:r,busy:i,style:a}){if(!e)return null;const c=!!e.granted;return(0,s.jsx)(o.Card,{style:{marginBottom:16,...a||{}},id:"blazeaid-cloud-consent",children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:c?(0,t.__)("Cloud checks: on","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Cloud checks: off","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[c?(0,t.__)("Your store is checked from outside your network: AI crawler access, Core Web Vitals and your AI Visibility report.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Test your store from outside your network and see your AI Visibility report.","blaze-ai-discovery-for-woocommerce")," ",n()]}),(0,s.jsx)(l,{style:{margin:"4px 0 0"}})]}),(0,s.jsx)(o.Button,{variant:c?"secondary":"primary",onClick:()=>r(!c),disabled:i,isBusy:i,children:c?(0,t.__)("Turn off","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}const u=()=>a()({path:"/blazeaid/v1/jobs/health"}).catch(()=>null);function m({health:e,audit:i,onRunNow:n,onRunAudit:l}){const[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[h,f]=(0,r.useState)(null);if(!e||c)return null;const y=l?((e,r)=>{const o=(e?.failed||[]).find(e=>e&&"blazeaid_run_audit"===e.hook);return o&&(o.at||0)>(e=>{if(!e||!e.run_at)return 0;const r=Date.parse(String(e.run_at).replace(" ","T")+"Z");return Number.isFinite(r)?r/1e3:0})(r)?o:null})(e,i):null;if(!y&&!e.stuck)return null;let p;if(y)p=y.message?(0,t.sprintf)(/* translators: %s: the Action Scheduler log line for the failed action */ /* translators: %s: the Action Scheduler log line for the failed action */2 (0,t.__)("The last background audit failed: %s","blaze-ai-discovery-for-woocommerce"), y.message):(0,t.__)("The last background audit failed.","blaze-ai-discovery-for-woocommerce");else{const r=(e=>{const r=e?.past_due;return"number"==typeof r?Math.max(0,r-(e.pending_due||0)):r||0})(e),o=(e=>{const r=Math.max(0,Number(e)||0);if(r<3600){const e=Math.max(1,Math.round(r/60));1 (()=>{"use strict";var e={n:r=>{var o=r&&r.__esModule?()=>r.default:()=>r;return e.d(o,{a:o}),o},d:(r,o)=>{for(var t in o)e.o(o,t)&&!e.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:o[t]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)};const r=window.wp.element,o=window.wp.components,t=window.wp.i18n,i=window.wp.apiFetch;var n=e.n(i);const s=window.ReactJSXRuntime,a=()=>(0,t.__)("Free, no account, no API key. Runs on our infrastructure. Sends your store URL, one product URL and a few category names (publicly available information) to api.blazecommerce.io — never customer or order data. One toggle to turn off.","blaze-ai-discovery-for-woocommerce");function l({style:e}){return(0,s.jsxs)("p",{style:{margin:"8px 0 0",fontSize:13,...e||{}},children:[(0,s.jsx)("a",{href:window.blazeaid?.privacyUrl||"https://blazecommerce.io/privacy-policy/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Privacy policy","blaze-ai-discovery-for-woocommerce")})," · ",(0,s.jsx)("a",{href:window.blazeaid?.disclosureUrl||"https://wordpress.org/plugins/blaze-ai-discovery-for-woocommerce/#faq",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Full disclosure","blaze-ai-discovery-for-woocommerce")})]})}function c({onEnable:e,onDismiss:i,busy:n}){const[c,d]=(0,r.useState)(!1);return(0,s.jsxs)(o.Modal,{title:(0,t.__)("See what AI assistants actually see","blaze-ai-discovery-for-woocommerce"),onRequestClose:()=>!n&&i(),shouldCloseOnClickOutside:!1,style:{maxWidth:560},className:"blazeaid-cloud-checks-modal",children:[(0,s.jsx)("p",{style:{marginTop:0},children:(0,t.__)("Your store audit is already running. Turn on cloud checks and you also get:","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("ul",{style:{margin:"0 0 16px",paddingLeft:0,listStyle:"none"},children:[{title:(0,t.__)("Crawler access from the open internet","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("We fetch your pages as GPTBot, OAI-SearchBot, ClaudeBot and PerplexityBot from outside your network — the only way to catch a Cloudflare or firewall block your own server can't see.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Core Web Vitals from real shoppers","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("Google's field data for your store on mobile — LCP, INP, CLS — not a lab test.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Your AI Visibility report","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("How often ChatGPT and Google AI mention your store, which pages they cite, and who gets named instead. Refreshed monthly.","blaze-ai-discovery-for-woocommerce")}].map(e=>(0,s.jsxs)("li",{style:{margin:"0 0 12px"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("p",{style:{margin:"2px 0 0",color:"#50575e",fontSize:13},children:e.body})]},e.title))}),(0,s.jsxs)("p",{style:{color:"#50575e",fontSize:12,margin:"0 0 4px"},children:[a()," ",(0,s.jsx)(o.Button,{variant:"link",onClick:()=>d(!c),"aria-expanded":c,style:{fontSize:12,textDecoration:"underline"},children:(0,t.__)("Details","blaze-ai-discovery-for-woocommerce")})]}),c&&(0,s.jsxs)("div",{style:{background:"#f6f7f7",borderRadius:4,padding:"10px 12px",margin:"8px 0 12px",fontSize:12,color:"#3c434a"},children:[(0,s.jsx)("ul",{style:{margin:0,paddingLeft:18},children:[(0,t.__)("Crawler access: your store URL, one public product URL, and the plugin, WordPress, WooCommerce and PHP version numbers. Returns what each AI crawler saw.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("Core Web Vitals: your store URL. Returns Google's Chrome UX Report figures for your origin.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("AI Visibility: your domain, store country, site locale and up to five product category names. Returns the monthly mentions report.","blaze-ai-discovery-for-woocommerce")].map(e=>(0,s.jsx)("li",{style:{margin:"0 0 6px"},children:e},e))}),(0,s.jsx)("p",{style:{margin:"8px 0 0"},children:(0,t.__)("All of it is publicly available information; nothing about customers, orders or users ever leaves your site.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(l,{style:{fontSize:12}})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:16},children:[(0,s.jsx)(o.Button,{variant:"tertiary",onClick:i,disabled:n,children:(0,t.__)("Not now","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:e,isBusy:n,disabled:n,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})]})}function d({consent:e,onToggle:r,busy:i,style:n}){if(!e)return null;const c=!!e.granted;return(0,s.jsx)(o.Card,{style:{marginBottom:16,...n||{}},id:"blazeaid-cloud-consent",children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:c?(0,t.__)("Cloud checks: on","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Cloud checks: off","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[c?(0,t.__)("Your store is checked from outside your network: AI crawler access, Core Web Vitals and your AI Visibility report.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Test your store from outside your network and see your AI Visibility report.","blaze-ai-discovery-for-woocommerce")," ",a()]}),(0,s.jsx)(l,{style:{margin:"4px 0 0"}})]}),(0,s.jsx)(o.Button,{variant:c?"secondary":"primary",onClick:()=>r(!c),disabled:i,isBusy:i,children:c?(0,t.__)("Turn off","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}const u=()=>n()({path:"/blazeaid/v1/jobs/health"}).catch(()=>null);function m({health:e,audit:i,onRunNow:a,onRunAudit:l}){const[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[h,f]=(0,r.useState)(null);if(!e||c)return null;const p=l?((e,r)=>{const o=(e?.failed||[]).find(e=>e&&"blazeaid_run_audit"===e.hook);return o&&(o.at||0)>(e=>{if(!e||!e.run_at)return 0;const r=Date.parse(String(e.run_at).replace(" ","T")+"Z");return Number.isFinite(r)?r/1e3:0})(r)?o:null})(e,i):null;if(!p&&!e.stuck)return null;let y;if(p)y=p.message?(0,t.sprintf)(/* translators: %s: the Action Scheduler log line for the failed action */ /* translators: %s: the Action Scheduler log line for the failed action */ 2 (0,t.__)("The last background audit failed: %s","blaze-ai-discovery-for-woocommerce"),p.message):(0,t.__)("The last background audit failed.","blaze-ai-discovery-for-woocommerce");else{const r=(e=>{const r=e?.past_due;return"number"==typeof r?Math.max(0,r-(e.pending_due||0)):r||0})(e),o=(e=>{const r=Math.max(0,Number(e)||0);if(r<3600){const e=Math.max(1,Math.round(r/60)); 3 3 /* translators: %d: number of minutes */return(0,t.sprintf)((0,t._n)("%d minute","%d minutes",e,"blaze-ai-discovery-for-woocommerce"),e)}if(r<86400){const e=Math.round(r/3600); 4 4 /* translators: %d: number of hours */return(0,t.sprintf)((0,t._n)("%d hour","%d hours",e,"blaze-ai-discovery-for-woocommerce"),e)}const o=Math.round(r/86400); … … 6 6 (0,t.__)("queued %1$s ago; %2$s other tasks are waiting","blaze-ai-discovery-for-woocommerce"),o,r):r>0?(0,t.sprintf)(/* translators: 1: how long ago, e.g. "13 minutes"; 2: number of other past-due tasks */ /* translators: 1: how long ago, e.g. "13 minutes"; 2: number of other past-due tasks */ 7 7 (0,t._n)("queued %1$s ago; %2$d other task is waiting","queued %1$s ago; %2$d other tasks are waiting",r,"blaze-ai-discovery-for-woocommerce"),o,r):(0,t.sprintf)(/* translators: %s: how long ago, e.g. "13 minutes" */ /* translators: %s: how long ago, e.g. "13 minutes" */ 8 (0,t.__)("queued %s ago","blaze-ai-discovery-for-woocommerce"),o);const a=e.wp_cron_disabled?(0,t.__)("WP-Cron is disabled on this site (DISABLE_WP_CRON); jobs run only from a server cron.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("WP-Cron runs only when the site gets visits, so on quiet or shared hosts this can take a while.","blaze-ai-discovery-for-woocommerce");p=(0,t.sprintf)(/* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */ /* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */9 (0,t.__)("Your site's background job queue hasn't run Blaze AI Discovery's tasks yet (%1$s). %2$s","blaze-ai-discovery-for-woocommerce"),i, a)}let b=null;if(h&&h.error)b=(0,t.__)("Could not run the queue — try again or use the link.","blaze-ai-discovery-for-woocommerce");else if(h){const e=h.processed||0,r=h.remaining_due||0;b=(0,t.sprintf)(/* translators: %d: number of tasks processed */ /* translators: %d: number of tasks processed */8 (0,t.__)("queued %s ago","blaze-ai-discovery-for-woocommerce"),o);const n=e.wp_cron_disabled?(0,t.__)("WP-Cron is disabled on this site (DISABLE_WP_CRON); jobs run only from a server cron.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("WP-Cron runs only when the site gets visits, so on quiet or shared hosts this can take a while.","blaze-ai-discovery-for-woocommerce");y=(0,t.sprintf)(/* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */ /* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */ 9 (0,t.__)("Your site's background job queue hasn't run Blaze AI Discovery's tasks yet (%1$s). %2$s","blaze-ai-discovery-for-woocommerce"),i,n)}let g=null;if(h&&h.error)g=(0,t.__)("Could not run the queue — try again or use the link.","blaze-ai-discovery-for-woocommerce");else if(h){const e=h.processed||0,r=h.remaining_due||0;g=(0,t.sprintf)(/* translators: %d: number of tasks processed */ /* translators: %d: number of tasks processed */ 10 10 (0,t._n)("Ran %d task","Ran %d tasks",e,"blaze-ai-discovery-for-woocommerce"),e)+"; "+(0,t.sprintf)(/* translators: %d: number of tasks still due */ /* translators: %d: number of tasks still due */ 11 (0,t._n)("%d task still due.","%d tasks still due.",r,"blaze-ai-discovery-for-woocommerce"),r)}return(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"warning",onRemove:()=>d(!0),className:"blazeaid-jobs-health",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsxs)("span",{style:{flex:1,minWidth:0},children:[p,b&&(0,s.jsx)("span",{style:{display:"block",marginTop:4,color:"#555"},children:b})]}),(0,s.jsx)(o.Button,{variant:"primary",onClick:y?()=>{m(!0),Promise.resolve(l()).finally(()=>m(!1))}:()=>{m(!0),f(null),a()({path:"/blazeaid/v1/jobs/run-now",method:"POST"}).then(e=>{f(e||{}),n&&n(e)}).catch(()=>f({error:!0})).finally(()=>m(!1))},isBusy:u,disabled:u,children:(0,t.__)("Run now","blaze-ai-discovery-for-woocommerce")}),e.faq_url&&(0,s.jsx)("a",{href:e.faq_url,target:"_blank",rel:"noreferrer",children:(0,t.__)("How to fix","blaze-ai-discovery-for-woocommerce")})]})})})}const h=5e3,f=18e4,y=e=>(e?.results||[]).filter(e=>"fail"===e.status||"warning"===e.status).length,p=e=>a()({path:"/blazeaid/v1/onboarding",method:"POST",data:{event:e}}),b=e=>(e?.results||[]).find(e=>Array.isArray(e.crawlers))||null,g={blocked_edge:3,blocked_robots:2,challenged:1};function x({result:e}){const r=(e=>(e?.crawlers||[]).filter(e=>"retrieval"===e.class&&"string"==typeof e.verdict&&e.verdict.startsWith("blocked_")))(e);if(!r.length)return null;const i=((e,r)=>{const o=e?.fix_links||[],t=r.reduce((e,r)=>!e||(g[r.verdict]||0)>(g[e.verdict]||0)?r:e,null);return(t&&t.layer?o.find(e=>e.layer===t.layer):null)||o[0]||null})(e,r),a=r.map(e=>e.name).join(", "),n=1===r.length?(0,t.sprintf)(/* translators: %s: crawler name */ /* translators: %s: crawler name */ 12 (0,t.__)("%s is blocked, so the AI assistant behind it cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),a):(0,t.sprintf)(/* translators: %s: comma-separated list of crawler names */ /* translators: %s: comma-separated list of crawler names */ 13 (0,t.__)("%s are blocked, so the AI assistants behind them cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),a);return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:"4px solid #d63638"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:(0,t.__)("AI shopping assistants can't reach your store","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:n})]}),(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexShrink:0},children:[i&&(0,s.jsx)(o.Button,{variant:"primary",href:i.url,target:"_blank",rel:"noopener noreferrer",children:i.label}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("View audit","blaze-ai-discovery-for-woocommerce")})]})]})})}function _({slow:e,running:r,error:i,onRunNow:a}){return(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(!e||r)&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Still queued — your site's background jobs haven't run it yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Your first store audit is running — results in about a minute.","blaze-ai-discovery-for-woocommerce")}),e&&(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:i?(0,t.__)("The audit could not run on this request. Try again, or check the notice above.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("You can run it on this page load instead — it takes up to a minute.","blaze-ai-discovery-for-woocommerce")})]}),e&&(0,s.jsx)(o.Button,{variant:"primary",onClick:a,isBusy:r,disabled:r,children:(0,t.__)("Run audit now","blaze-ai-discovery-for-woocommerce")})]})})}function v({done:e}){return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:e?"4px solid #00a32a":"4px solid #2271b1"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[!e&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsx)("div",{style:{minWidth:0,flex:1},children:(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Cloud checks are on — your store was checked from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Checking your store from outside your network…","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("See crawler results","blaze-ai-discovery-for-woocommerce")})]})})}const j={chatgpt:"ChatGPT",openai:"ChatGPT",perplexity:"Perplexity",copilot:"Microsoft Copilot",bing:"Microsoft Copilot",gemini:"Google Gemini",google_ai:"Google AI Mode",claude:"Claude",grok:"Grok",mistral:"Mistral",meta:"Meta AI"},w=/^no ai mentions/i,z=(e,r)=>new Intl.DateTimeFormat(void 0,{day:"numeric",month:"short",...r?{year:"numeric"}:{}}).format(e);function k({bg:e,color:r,fontSize:o,children:t}){return(0,s.jsx)("div",{style:{fontSize:o,fontWeight:"bold",width:56,height:56,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:e,color:r,flexShrink:0},children:t})}function S({icon:e,title:r,body:t,href:i,linkLabel:a}){return(0,s.jsx)(o.Card,{children:(0,s.jsxs)(o.CardBody,{style:{padding:20,display:"flex",alignItems:"center",gap:16},children:[e,(0,s.jsxs)("div",{style:{minWidth:0},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600},children:r}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13},children:t}),(0,s.jsx)("p",{style:{margin:"4px 0 0",fontSize:13},children:(0,s.jsx)("a",{href:i,children:a})})]})]})})}function C({audit:e}){const r=Array.isArray(e?.results)?e.results:null;let o,i;if(r){const e=r.filter(e=>e&&"fail"===e.status).length,a=r.filter(e=>e&&"warning"===e.status).length,n=e+a,l=e>0?"#f8d7da":a>0?"#fff3cd":"#d4edda",c=e>0?"#721c24":a>0?"#856404":"#155724";o=(0,s.jsx)(k,{bg:l,color:c,fontSize:24,children:e>0?"✗":a>0?"⚠":"✓"}),i=n>0?(0,t.sprintf)(/* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ /* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ 14 (0,t._n)("%1$d issue across %2$d checks","%1$d issues across %2$d checks",n,"blaze-ai-discovery-for-woocommerce"),n,r.length):(0,t.sprintf)(/* translators: %d: total number of audit rows */ /* translators: %d: total number of audit rows */ 15 (0,t.__)("All %d checks passed","blaze-ai-discovery-for-woocommerce"),r.length)}else o=(0,s.jsx)(k,{bg:"#f0f0f0",color:"#757575",fontSize:24,children:"?"}),i=(0,t.__)("No audit result yet","blaze-ai-discovery-for-woocommerce");return(0,s.jsx)(S,{icon:o,title:(0,t.__)("Store audit","blaze-ai-discovery-for-woocommerce"),body:i,href:"admin.php?page=blazeaid-audit",linkLabel:(0,t.__)("Open Store Audit","blaze-ai-discovery-for-woocommerce")})}function A({storeScore:e}){const r="number"==typeof e?.average&&Number.isFinite(e.average),o=r?e.average:0;let i="#f0f0f0",a="#757575";return r&&(i=o>=70?"#d4edda":o>=40?"#fff3cd":"#f8d7da",a=o>=70?"#155724":o>=40?"#856404":"#721c24"),(0,s.jsx)(S,{icon:(0,s.jsx)(k,{bg:i,color:a,fontSize:32,children:r?Math.round(o):"—"}),title:(0,t.__)("Product AI readiness","blaze-ai-discovery-for-woocommerce"),body:e?(0,t.sprintf)(/* translators: 1: number of scored products, 2: total number of products */ /* translators: 1: number of scored products, 2: total number of products */ 16 (0,t.__)("%1$s / %2$s products scored","blaze-ai-discovery-for-woocommerce"),e.scored_products??0,e.total_products??0):(0,t.__)("Not yet scored","blaze-ai-discovery-for-woocommerce"),href:"admin.php?page=blazeaid-products",linkLabel:(0,t.__)("See products","blaze-ai-discovery-for-woocommerce")})}function B({visibility:e,consentGranted:r}){const o=(e=>{const r=(e=>{if(!e||"ready"!==e.state)return null;const r=(e.payload?.sections||[]).find(e=>e&&"mentions"===e.id);return(r?.blocks||[]).find(e=>e&&"stat"===e.type)||null})(e);return r&&"number"==typeof r.value&&Number.isFinite(r.value)&&!(e=>(e?.payload?.notices||[]).some(e=>e&&(e.code||w.test("string"==typeof e.text?e.text:""))))(e)?r.value:null})(e),i=null!==o,a=e?.payload?.period?.label;let n;return n=i?a?(0,t.sprintf)(/* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ /* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ 17 (0,t.__)("mentions, %s","blaze-ai-discovery-for-woocommerce"),a):(0,t.__)("mentions","blaze-ai-discovery-for-woocommerce"):r?"pending"===e?.state?(0,t.__)("fetching your first report…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("no data yet","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(S,{icon:(0,s.jsx)(k,{bg:i?"#e7f0fa":"#f0f0f0",color:i?"#2271b1":"#757575",fontSize:22,children:i?(new Intl.NumberFormat).format(o):"—"}),title:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce"),body:n,href:"admin.php?page=blazeaid-visibility",linkLabel:(0,t.__)("Open AI Visibility","blaze-ai-discovery-for-woocommerce")})}function I({value:e,label:r}){return(0,s.jsxs)("div",{children:[(0,s.jsx)("h2",{style:{fontSize:36,margin:"0 0 4px"},children:e}),(0,s.jsx)("p",{style:{color:"#757575",margin:0,fontSize:14},children:r})]})}function T(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)([]),[g,w]=(0,r.useState)([]),[k,S]=(0,r.useState)(null),[T,R]=(0,r.useState)(null),[P,W]=(0,r.useState)(null),[N,$]=(0,r.useState)("30"),[L,F]=(0,r.useState)(!0),[O,D]=(0,r.useState)(window.blazeaid?.consent||null),[G,M]=(0,r.useState)(window.blazeaid?.onboarding||{}),[E,H]=(0,r.useState)(!1),[V,q]=(0,r.useState)(!1),[U,Y]=(0,r.useState)(!1),[X,J]=(0,r.useState)(!1),[Z,K]=(0,r.useState)(!1),[Q,ee]=(0,r.useState)(!1),[re,oe]=(0,r.useState)(null),[te,ie]=(0,r.useState)(null),[ae,se]=(0,r.useState)(!1),ne=(0,r.useRef)(0),le=(0,r.useRef)(!1),ce=(0,r.useRef)(!1),de=(0,r.useRef)(!1),ue=(0,r.useRef)(!1);(0,r.useEffect)(()=>()=>{ne.current+=1},[]);const me=(e,r)=>{const o=++ne.current,t=Date.now();let i=!1;const s=()=>{o===ne.current&&a()({path:"/blazeaid/v1/audit"}).catch(()=>null).then(a=>{if(o!==ne.current)return;if(a&&a.run_at&&(S(a),e(a)))return;const n=Date.now()-t;return n>=12e5?void 0:n>=f?(i||(i=!0,r&&r()),void setTimeout(s,3e4)):void setTimeout(s,h)})};setTimeout(s,h)},he=()=>u().then(e=>(e&&oe(e),e));(0,r.useEffect)(()=>{F(!0),Promise.all([a()({path:`/blazeaid/v1/attribution/summary?days=${N}`}),a()({path:`/blazeaid/v1/attribution/products?days=${N}`}),a()({path:`/blazeaid/v1/attribution/trend?days=${N}`}),a()({path:"/blazeaid/v1/audit"}).catch(()=>null),a()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),a()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t,a,s,n])=>{i(e),l(r),w(o),S(t),R(a),W(s),n&&oe(n),F(!1)}).catch(()=>F(!1))},[N]);const fe=(0,r.useRef)(0);(0,r.useEffect)(()=>()=>{fe.current+=1},[]),(0,r.useEffect)(()=>{const e=!!O&&!!O.granted,r=Array.isArray(k?.results)?k.results.find(e=>e&&e.crawlers):null,o=e&&r&&r.probe&&!1===r.probe.ran&&"consent_off"===r.probe.notice,t="pending"===P?.state||e&&"consent_off"===P?.state;if(L||!o&&!t)return;const i=++fe.current,s=Date.now(),n=()=>{i!==fe.current||Date.now()-s>f||Promise.all([t?a()({path:"/blazeaid/v1/visibility"}).catch(()=>null):Promise.resolve(void 0),o?a()({path:"/blazeaid/v1/audit"}).catch(()=>null):Promise.resolve(void 0)]).then(([e,r])=>{if(i!==fe.current)return;void 0!==e&&e&&W(e),void 0!==r&&r&&S(r);const o=void 0!==e&&e&&"pending"===e.state,t=r&&Array.isArray(r.results)?r.results.find(e=>e&&e.crawlers):null,a=void 0!==r&&!(!t||!t.probe||!1!==t.probe.ran);(o||a)&&setTimeout(n,h)})};setTimeout(n,h)},[L,P?.state,O?.granted,k]),(0,r.useEffect)(()=>{L||k||le.current||(le.current=!0,me(e=>!!e.run_at,()=>{J(!0),he()}))},[L,k]),(0,r.useEffect)(()=>{if(L||k)return;const e=setTimeout(he,6e4);return()=>clearTimeout(e)},[L,k]),(0,r.useEffect)(()=>{L||!O||O.granted||ce.current||G.modal_shown_version===(window.blazeaid?.version||"")||(ce.current=!0,H(!0))},[L]),(0,r.useEffect)(()=>{L||E||!k||!O||O.granted||!G.dismissed_at||G.reminder_shown||de.current||ue.current||(de.current=!0,se(!0),p("reminder_shown").then(M).catch(()=>{}))},[L,E,k,O,G]);const ye=()=>{K(!0),ee(!1),ne.current+=1;const e=()=>(ee(!0),J(!0),k||me(e=>!!e.run_at,()=>J(!0)),!1);return a()({path:"/blazeaid/v1/audit/run",method:"POST",data:{force:!0}}).then(r=>r&&r.results?(S(r),he(),!0):e()).catch(e).finally(()=>K(!1))},pe=()=>(Y(!0),a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!0}}).then(e=>(D(e),se(!1),ie("waiting"),a()({path:"/blazeaid/v1/audit/run",method:"POST"}).catch(()=>null))).then(e=>{if(e&&e.results)return S(e),void ie("done");me(e=>!!(e=>!0===b(e)?.probe?.ran)(e)&&(ie("done"),!0),()=>ie("done"))}).finally(()=>Y(!1)));if(L)return(0,s.jsxs)("div",{style:{padding:"40px",textAlign:"center"},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{children:(0,t.__)("Loading AI traffic data…","blaze-ai-discovery-for-woocommerce")})]});const be=(()=>{const e=window.blazeaid?.installedAt;if("string"!=typeof e||!e)return null;const r=new Date(e.replace(" ","T")+"Z");return Number.isNaN(r.getTime())?null:r})(),ge=parseInt(N,10)||30,xe=be?(_e=be,Math.max(0,Math.floor((Date.now()-_e.getTime())/864e5))):null;var _e;const ve=be&&ge>xe?(0,t.sprintf)(/* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ /* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ 18 (0,t.__)("Last %1$d days (tracking since %2$s)","blaze-ai-discovery-for-woocommerce"),ge,z(be,!1)):(0,t.sprintf)(/* translators: %d: number of days in the selected period */ /* translators: %d: number of days in the selected period */ 19 (0,t.__)("Last %d days","blaze-ai-discovery-for-woocommerce"),ge),je=be?(0,t.sprintf)(/* translators: %s: date tracking started, e.g. "30 Aug 2026" */ /* translators: %s: date tracking started, e.g. "30 Aug 2026" */ 20 (0,t.__)("Tracking since %s — the plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),z(be,!0)):(0,t.__)("The plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),we="number"==typeof e?.total_visits?e.total_visits:0,ze=Array.isArray(e?.platforms)?e.platforms.filter(e=>e&&e.platform):[],ke=Array.isArray(n)?n.filter(e=>e&&e.product_id):[],Se=(ze.length?1:0)+(ke.length?1:0);return(0,s.jsxs)("div",{className:"blazeaid-dashboard",style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsx)("h1",{style:{marginBottom:20},children:(0,t.__)("AI Discovery Dashboard","blaze-ai-discovery-for-woocommerce")}),E&&(0,s.jsx)(c,{onEnable:()=>{q(!0),pe().then(()=>p("modal_shown")).then(M).catch(()=>{}).finally(()=>{q(!1),H(!1)})},onDismiss:()=>{ue.current=!!k,H(!1),p("dismissed").then(M).catch(()=>{})},busy:V}),ae&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"info",onRemove:()=>se(!1),className:"blazeaid-onboarding-reminder",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsx)("span",{style:{flex:1,minWidth:0},children:(0,t.sprintf)(/* translators: %d: number of failed or warning audit rows */ /* translators: %d: number of failed or warning audit rows */ 21 (0,t._n)("Your local audit found %d issue. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.","Your local audit found %d issues. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.",y(k),"blaze-ai-discovery-for-woocommerce"),y(k))}),(0,s.jsx)(o.Button,{variant:"primary",onClick:pe,isBusy:U,disabled:U,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}),(0,s.jsx)(m,{health:re,audit:k,onRunNow:()=>{Promise.all([a()({path:"/blazeaid/v1/audit"}).catch(()=>null),a()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),a()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t])=>{e&&e.run_at&&S(e),r&&R(r),o&&W(o),t&&oe(t)})},onRunAudit:ye}),!k&&(0,s.jsx)(_,{slow:X,running:Z,error:Q,onRunNow:ye}),te&&(0,s.jsx)(v,{done:"done"===te}),(0,s.jsx)(x,{result:b(k)}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,marginBottom:16},children:[(0,s.jsx)(C,{audit:k}),(0,s.jsx)(A,{storeScore:T}),(0,s.jsx)(B,{visibility:P,consentGranted:O?!!O.granted:"consent_off"!==P?.state})]}),O&&!O.granted&&!E&&(0,s.jsx)(d,{consent:O,onToggle:e=>e?pe():(Y(!0),a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!1}}).then(e=>{D(e),ie(null)}).catch(()=>{}).finally(()=>Y(!1))),busy:U}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsxs)(o.CardHeader,{style:{flexWrap:"wrap",gap:12},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("AI traffic","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13,fontWeight:"normal"},children:je})]}),(0,s.jsx)(o.SelectControl,{value:N,options:[{label:(0,t.__)("Last 7 days","blaze-ai-discovery-for-woocommerce"),value:"7"},{label:(0,t.__)("Last 30 days","blaze-ai-discovery-for-woocommerce"),value:"30"},{label:(0,t.__)("Last 90 days","blaze-ai-discovery-for-woocommerce"),value:"90"}],onChange:$,__nextHasNoMarginBottom:!0})]}),(0,s.jsxs)(o.CardBody,{children:[0===we?(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No AI-referred visits recorded yet. Visits from ChatGPT, Perplexity, Copilot, Gemini and Claude will appear here.","blaze-ai-discovery-for-woocommerce")}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("p",{style:{color:"#757575",margin:"0 0 12px",fontSize:13},children:ve}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16},children:[(0,s.jsx)(I,{value:(new Intl.NumberFormat).format(we),label:(0,t.__)("AI-referred visitors","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(I,{value:(new Intl.NumberFormat).format(e?.orders?.count??0),label:(0,t.__)("AI-attributed orders","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(I,{value:new Intl.NumberFormat(void 0,{style:"currency",currency:window.blazeaid?.currency||"USD"}).format(e?.orders?.revenue??0),label:(0,t.__)("AI-attributed revenue","blaze-ai-discovery-for-woocommerce")})]})]}),(0,s.jsx)("p",{style:{color:"#757575",fontSize:13,margin:"16px 0 0"},children:(0,t.__)("Industry benchmarks show ~70% of AI traffic arrives without identifiable headers. Your actual AI traffic is likely higher than what we can detect. We track referrer headers, UTM parameters, and URL text fragments to capture as much as possible.","blaze-ai-discovery-for-woocommerce")})]})]}),Se>0&&(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:2===Se?"1fr 1fr":"1fr",gap:16},children:[ze.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Visits by platform","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Platform","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:ze.map(e=>{return(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0",textTransform:"capitalize"},children:(r=e.platform,j[String(r).toLowerCase()]||String(r).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.count})]},e.platform);var r})})]})})]}),ke.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Top products","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("AI visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:ke.map(e=>(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0"},children:e.url?(0,s.jsx)("a",{href:e.url,children:e.name}):e.name}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.visit_count})]},e.product_id))})]})})]})]})]})}function R({product:e}){const[o,i]=(0,r.useState)(!1),a=e.issues||[],n=a.filter(e=>"error"===e.severity||"warning"===e.severity).length;return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("tr",{onClick:()=>a.length>0&&i(!o),style:{cursor:a.length>0?"pointer":"default"},children:[(0,s.jsx)("td",{style:{padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[a.length>0&&(0,s.jsx)("span",{style:{fontSize:11,color:"#757575",transition:"transform 0.2s",transform:o?"rotate(90deg)":"none"},children:"▶"}),(0,s.jsx)("span",{children:e.product_name}),n>0&&(0,s.jsxs)("span",{style:{fontSize:11,color:"#757575",background:"#f0f0f0",padding:"1px 6px",borderRadius:8},children:[n," ",1===n?"issue":"issues"]})]})}),(0,s.jsx)("td",{style:{textAlign:"center",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsx)("span",{style:{display:"inline-block",padding:"2px 12px",borderRadius:12,fontSize:13,fontWeight:600,background:e.total_score>=70?"#d4edda":e.total_score>=40?"#fff3cd":"#f8d7da",color:e.total_score>=70?"#155724":e.total_score>=40?"#856404":"#721c24"},children:e.total_score})}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:e.edit_url&&(0,s.jsx)("a",{href:e.edit_url,onClick:e=>e.stopPropagation(),style:{fontSize:13},children:(0,t.__)("Edit","blaze-ai-discovery-for-woocommerce")})})]}),o&&(0,s.jsx)("tr",{children:(0,s.jsx)("td",{colSpan:"3",style:{padding:"0 0 12px 28px",borderBottom:"1px solid #eee"},children:(0,s.jsxs)("div",{style:{background:"#f9f9f9",borderRadius:6,padding:16},children:[(0,s.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[["title_score","Title",15],["description_score","Description",15],["image_score","Images",10],["brand_score","Brand",10],["category_score","Category",10],["attributes_score","Attributes",15],["price_score","Price",5],["identifier_score","Identifiers",10],["rating_score","Reviews",5],["policy_score","Policies",5]].map(([r,o,t])=>{const i=parseInt(e[r])||0,a=Math.round(i/t*100);return(0,s.jsxs)("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:4,background:a>=80?"#d4edda":a>=40?"#fff3cd":"#f8d7da",color:a>=80?"#155724":a>=40?"#856404":"#721c24"},children:[o," ",i,"/",t]},r)})}),a.length>0&&(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontWeight:600,fontSize:13,margin:"0 0 8px"},children:(0,t.__)("How to improve this product:","blaze-ai-discovery-for-woocommerce")}),a.map((e,r)=>{const o=(e=>{switch(e){case"error":return{color:"#721c24",icon:"✗"};case"warning":return{color:"#856404",icon:"⚠"};default:return{color:"#004085",icon:"ℹ"}}})(e.severity);return(0,s.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",marginBottom:6},children:[(0,s.jsx)("span",{style:{color:o.color,fontSize:12,flexShrink:0,marginTop:1},children:o.icon}),(0,s.jsxs)("span",{style:{fontSize:13,color:"#333"},children:[(0,s.jsxs)("strong",{style:{color:o.color},children:[e.name,":"]})," ",e.message]})]},r)})]})]})})})]})}const P=e=>{switch(e){case"pass":return{icon:"✓",color:"#00a32a",bg:"#d4edda"};case"warning":return{icon:"⚠",color:"#856404",bg:"#fff3cd"};case"fail":return{icon:"✗",color:"#721c24",bg:"#f8d7da"};default:return{icon:"ℹ",color:"#004085",bg:"#cce5ff"}}},W=e=>{switch(e){case"allowed":return(0,t.__)("allowed","blaze-ai-discovery-for-woocommerce");case"blocked_robots":return(0,t.__)("blocked by robots.txt","blaze-ai-discovery-for-woocommerce");case"blocked_edge":return(0,t.__)("blocked at the edge","blaze-ai-discovery-for-woocommerce");case"challenged":return(0,t.__)("challenged","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("unknown","blaze-ai-discovery-for-woocommerce")}},N=e=>{switch(e){case"high":return(0,t.__)("high confidence","blaze-ai-discovery-for-woocommerce");case"medium":return(0,t.__)("medium confidence","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("low confidence","blaze-ai-discovery-for-woocommerce")}},$=(e,r)=>{const o={display:"inline-block",width:8,height:8,borderRadius:"50%",border:`1.5px solid ${r}`,boxSizing:"border-box",flexShrink:0};return"high"===e?{...o,background:r}:"medium"===e?{...o,background:`linear-gradient(90deg, ${r} 50%, transparent 50%)`}:{...o,background:"transparent"}};function L({check:e,consentGranted:r}){const o=e.crawlers||[],i=e.fix_links||[],a=e.probe||{};let n=null;return!1===a.ran&&(n="consent_off"===a.notice?r?(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce")}):(0,t.sprintf)(/* translators: %s: reason code, e.g. rate_limited */ /* translators: %s: reason code, e.g. rate_limited */ 22 (0,t.__)("Outside-in probe unavailable (%s); results are based on robots.txt and your server log only.","blaze-ai-discovery-for-woocommerce"),a.notice||"unavailable")),(0,s.jsxs)("div",{style:{marginTop:8},children:[(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:o.map(e=>{const r="allowed"===(o=e.verdict)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:o&&o.startsWith("blocked_")?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:"challenged"===o?{color:"#856404",bg:"#fff3cd",border:"#ffe08a"}:{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"};var o;const t=[`${e.name}: ${W(e.verdict)} (${N(e.confidence)})`,e.evidence&&e.evidence.length?e.evidence[0]:null].filter(Boolean).join(" — ");return(0,s.jsxs)("span",{title:t,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("span",{style:$(e.confidence,r.color),"aria-hidden":"true"}),e.name]},e.name)})}),n&&(0,s.jsx)("p",{style:{margin:"8px 0 0",color:"#555",fontSize:13},children:n}),i.length>0&&(0,s.jsx)("ul",{style:{margin:"8px 0 0",paddingLeft:18,fontSize:13},children:i.map(e=>(0,s.jsx)("li",{children:(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.label})},e.layer))}),o.length>0&&(0,s.jsxs)("details",{style:{marginTop:8,fontSize:13},children:[(0,s.jsx)("summary",{style:{cursor:"pointer",color:"#2271b1"},children:(0,t.__)("Evidence","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("dl",{style:{margin:"8px 0 0"},children:o.map(e=>(0,s.jsxs)("div",{style:{marginBottom:6},children:[(0,s.jsxs)("dt",{style:{fontWeight:600},children:[e.name," — ",W(e.verdict),", ",N(e.confidence)]}),(e.evidence||[]).map((e,r)=>(0,s.jsx)("dd",{style:{margin:"2px 0 0 12px",color:"#555"},children:e},r))]},e.name))})]})]})}const F=e=>{switch(e){case"good":return(0,t.__)("good","blaze-ai-discovery-for-woocommerce");case"poor":return(0,t.__)("poor","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("needs improvement","blaze-ai-discovery-for-woocommerce")}};function O({cwv:e}){const r=Object.values(e?.metrics||{}).filter(e=>e&&e.label);return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:r.map(e=>{const r="good"===(o=e.rating)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:"poor"===o?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};var o;return(0,s.jsxs)("span",{title:`${e.label}: ${F(e.rating)}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("strong",{children:e.label}),e.display]},e.label)})}):null}const D=e=>"number"==typeof e&&Number.isFinite(e)?(new Intl.NumberFormat).format(e):String(e??"");function G({delta:e,deltaLabel:r}){const o="number"==typeof e&&Number.isFinite(e);if(!o&&!r)return null;let t="",i="#757575";return o&&e>0?(t="▲ ",i="#00a32a"):o&&e<0&&(t="▼ ",i="#d63638"),(0,s.jsxs)("p",{style:{margin:"4px 0 0",fontSize:13,color:i},children:[o&&(0,s.jsxs)("span",{children:[t,D(Math.abs(e))]}),o&&r?" ":"",r&&(0,s.jsx)("span",{style:{color:"#757575"},children:r})]})}function M({block:e}){return(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontSize:32,fontWeight:"bold",lineHeight:1.2},children:D(e.value)}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:14},children:e.label}),(0,s.jsx)(G,{delta:e.delta,deltaLabel:e.delta_label})]})}function E({block:e}){const r=Array.isArray(e.columns)?e.columns:[],o=Array.isArray(e.rows)?e.rows:[];if(!r.length&&!o.length)return null;const t=(e,r)=>({textAlign:"number"==typeof e?"right":"left",padding:"8px 12px 8px 0",borderBottom:r?"1px solid #ddd":"1px solid #f0f0f1",whiteSpace:"nowrap"}),i=o[0]||[];return(0,s.jsx)("div",{style:{overflowX:"auto"},children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[r.length>0&&(0,s.jsx)("thead",{children:(0,s.jsx)("tr",{children:r.map((e,r)=>(0,s.jsx)("th",{style:t(i[r],!0),children:e},r))})}),(0,s.jsx)("tbody",{children:o.map((e,r)=>(0,s.jsx)("tr",{children:(Array.isArray(e)?e:[]).map((e,r)=>(0,s.jsx)("td",{style:t(e,!1),children:"number"==typeof e?D(e):e},r))},r))})]})})}function H({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("ul",{style:{margin:"4px 0",paddingLeft:18},children:r.map((e,r)=>(0,s.jsx)("li",{style:{marginBottom:4},children:e.url?(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.text}):e.text},r))}):null}function V({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:r.map((e,r)=>{const o=(e=>["pass","warning","fail"].includes(e)?e:"unknown")(e.status),t=(e=>{switch(e){case"pass":return{color:"#155724",bg:"#d4edda",border:"#8fd19e"};case"warning":return{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};case"fail":return{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"};default:return{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"}}})(o);return(0,s.jsx)("span",{className:`blazeaid-chip blazeaid-chip--${o}`,style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:t.color,background:t.bg,border:`1px solid ${t.border}`},children:e.label},r)})}):null}function q({block:e}){return e.html?(0,s.jsx)("div",{className:"blazeaid-payload-text",style:{fontSize:13,color:"#50575e"},dangerouslySetInnerHTML:{__html:e.html}}):null}function U(e){const r=[];return(Array.isArray(e)?e:[]).forEach(e=>{const o=r[r.length-1];e&&"stat"===e.type?o&&"stats"===o.kind?o.items.push(e):r.push({kind:"stats",items:[e]}):r.push({kind:"block",block:e})}),r}function Y({block:e}){if(!e||"object"!=typeof e)return null;switch(e.type){case"stat":return(0,s.jsx)(M,{block:e});case"table":return(0,s.jsx)(E,{block:e});case"list":return(0,s.jsx)(H,{block:e});case"chips":return(0,s.jsx)(V,{block:e});case"text":return(0,s.jsx)(q,{block:e});default:return null}}function X({notices:e}){const r=Array.isArray(e)?e:[];return r.length?(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:r.map((e,r)=>{return(0,s.jsxs)(o.Notice,{status:(t=e.level,["info","warning","error"].includes(t)?t:"info"),isDismissible:!1,children:[e.text,e.link&&e.link.url&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:"_blank",rel:"noopener noreferrer",children:e.link.label||e.link.url})]})]},r);var t})}):null}function J({payload:e}){if(!e||"object"!=typeof e)return null;const r=Array.isArray(e.sections)?e.sections:[];return(0,s.jsxs)("div",{className:"blazeaid-payload",children:[(0,s.jsx)(X,{notices:e.notices}),r.map((e,r)=>{const i=Array.isArray(e.blocks)?e.blocks:[];return(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:e.title||(0,t.__)("Untitled section","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:i.length?U(i).map((e,r,o)=>(0,s.jsx)("div",{style:{marginBottom:r<o.length-1?16:0},children:"stats"===e.kind?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"16px 48px"},children:e.items.map((e,r)=>(0,s.jsx)("div",{style:{minWidth:160},children:(0,s.jsx)(Y,{block:e})},r))}):(0,s.jsx)(Y,{block:e.block})},r)):(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No data for this period.","blaze-ai-discovery-for-woocommerce")})})]},e.id||r)})]})}const Z={blazeaid:T,"blazeaid-products":function(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)([]),[c,d]=(0,r.useState)(null),[h,f]=(0,r.useState)(!0),[y,p]=(0,r.useState)(!1),[b,g]=(0,r.useState)(null),x=(e=!0)=>{e&&f(!0),Promise.all([a()({path:"/blazeaid/v1/scores/summary"}),a()({path:"/blazeaid/v1/scores/products?per_page=100&order=ASC"}),a()({path:"/blazeaid/v1/scores/progress"}),u()]).then(([e,r,o,t])=>{i(e),l(r),d(o),t&&g(t),"running"===o?.status&&p(!0),f(!1)}).catch(()=>f(!1))};if((0,r.useEffect)(()=>x(!0),[]),(0,r.useEffect)(()=>{if(!y)return;const e=setInterval(()=>{a()({path:"/blazeaid/v1/scores/progress"}).then(e=>{d(e),"complete"!==e.status&&"idle"!==e.status||(p(!1),x())})},3e3);return()=>clearInterval(e)},[y]),h)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const _=c?.total>0?Math.round(c.scored/c.total*100):0;return(0,s.jsxs)("div",{style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Product AI Readiness","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{p(!0),a()({path:"/blazeaid/v1/scores/recalculate",method:"POST"})},disabled:y,children:y?(0,t.__)("Scoring...","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Recalculate All","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsx)(m,{health:b,onRunNow:()=>x(!1)}),y&&"running"===c?.status&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{padding:20},children:[(0,s.jsxs)("p",{children:[(0,t.__)("Scoring products...","blaze-ai-discovery-for-woocommerce")," ",c.scored," / ",c.total," (",_,"%)"]}),(0,s.jsx)("div",{style:{background:"#e0e0e0",borderRadius:4,height:8},children:(0,s.jsx)("div",{style:{background:"#007cba",borderRadius:4,height:8,width:`${_}%`,transition:"width 0.3s"}})})]})}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{style:{padding:24},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:24},children:[(0,s.jsx)("div",{style:{fontSize:48,fontWeight:"bold",color:e?.average>=70?"#00a32a":e?.average>=40?"#dba617":"#d63638"},children:e?.average??0}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontSize:18,margin:0},children:(0,t.__)("Product AI Readiness Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:"running"===c?.status?(0,t.sprintf)(/* translators: 1: products scored so far, 2: total products */ /* translators: 1: products scored so far, 2: total products */ 23 (0,t.__)("Scoring your products… %1$d / %2$d","blaze-ai-discovery-for-woocommerce"),c.scored??0,c.total??0):`${e?.scored_products??0} / ${e?.total_products??0} ${(0,t.__)("products scored","blaze-ai-discovery-for-woocommerce")}`})]})]})})}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Products by AI Readiness (lowest first)","blaze-ai-discovery-for-woocommerce"),(0,s.jsx)("span",{style:{fontWeight:"normal",fontSize:13,color:"#757575",marginLeft:8},children:(0,t.__)("Click a row to see recommendations","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)(o.CardBody,{children:n.length>0?(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"2px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"center",padding:"8px 0",borderBottom:"2px solid #ddd",width:100},children:(0,t.__)("Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"2px solid #ddd",width:80},children:(0,t.__)("Action","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:n.map(e=>(0,s.jsx)(R,{product:e},e.product_id))})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No products scored yet. Click "Recalculate All" to scan your catalog.',"blaze-ai-discovery-for-woocommerce")})})]})]})},"blazeaid-audit":function(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)(!0),[c,u]=(0,r.useState)(!1),[m,h]=(0,r.useState)(null),[f,y]=(0,r.useState)(null);(0,r.useEffect)(()=>{l(!0),a()({path:"/blazeaid/v1/audit"}).then(e=>{i(e),l(!1)}).catch(()=>l(!1)),a()({path:"/blazeaid/v1/cloud/consent"}).then(y).catch(()=>y(null))},[]);const p=(e,r)=>{if(Date.now()-r>=9e4)return u(!1),void h((0,t.__)("Still running — check back shortly.","blaze-ai-discovery-for-woocommerce"));setTimeout(()=>((e,r)=>{a()({path:"/blazeaid/v1/audit"}).then(o=>{if(o&&o.run_at&&o.run_at!==e)return i(o),void u(!1);p(e,r)}).catch(()=>p(e,r))})(e,r),3e3)},b=()=>{u(!0),h(null);const r=e?.run_at||null;a()({path:"/blazeaid/v1/audit/run",method:"POST"}).then(e=>{e&&e.queued?p(r,Date.now()):(i(e),u(!1))}).catch(()=>u(!1))};if(n)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const g=e?.results||[],x=e?.overall_status||"unknown",_=(0,s.jsx)(d,{consent:f,onToggle:e=>{a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(e=>{y(e),b()})},busy:c,style:{marginTop:16}});return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Store Readiness Audit","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:b,disabled:c,children:c?(0,t.__)("Running…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Re-run Audit","blaze-ai-discovery-for-woocommerce")})]}),e?.run_at&&(0,s.jsxs)("p",{style:{color:"#757575",marginBottom:16},children:[(0,t.__)("Last run:","blaze-ai-discovery-for-woocommerce")," ",e.run_at]}),(c||m)&&(0,s.jsxs)("div",{style:{display:"grid",gap:12,marginBottom:16},children:[c&&(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("Running… this can take up to a minute while the store is checked from outside your network.","blaze-ai-discovery-for-woocommerce")}),m&&(0,s.jsx)("p",{style:{color:"#856404",margin:0},children:m})]}),!f?.granted&&_,(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Readiness Checklist","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:12,...P(x)},children:x.toUpperCase()})]})}),(0,s.jsx)(o.CardBody,{children:g.length>0?(0,s.jsx)("div",{children:g.map((e,r)=>{const o=P(e.status);return(0,s.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:"12px 0",borderBottom:r<g.length-1?"1px solid #eee":"none"},children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",background:o.bg,color:o.color,fontWeight:"bold",fontSize:14,flexShrink:0},children:o.icon}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:e.check}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[e.message,e.link&&!Array.isArray(e.crawlers)&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:e.link.url.startsWith("http")&&!e.link.url.includes("/wp-admin/")?"_blank":"_self",rel:"noopener noreferrer",children:e.link.label})]})]}),Array.isArray(e.crawlers)&&(0,s.jsx)(L,{check:e,consentGranted:!!f?.granted}),e.cwv&&(0,s.jsx)(O,{cwv:e.cwv})]})]},r)})}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No audit has been run yet. Click "Re-run Audit" to check your store.',"blaze-ai-discovery-for-woocommerce")})})]}),f?.granted&&_]})},"blazeaid-feed":function(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)(null),[c,d]=(0,r.useState)(!0),[u,m]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{d(!0),Promise.all([a()({path:"/blazeaid/v1/feed/status"}),a()({path:"/blazeaid/v1/feed/validate"})]).then(([e,r])=>{i(e),l(r),d(!1)}).catch(()=>d(!1))},[]),c?(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})}):(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsx)("h1",{children:(0,t.__)("ChatGPT Merchant Feed","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Status","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{style:{margin:"0 0 8px"},children:[(0,s.jsx)("strong",{children:(0,t.__)("Products in feed:","blaze-ai-discovery-for-woocommerce")})," ",e?.product_count??0]}),e?.generated_at&&(0,s.jsxs)("p",{style:{margin:0,color:"#757575",fontSize:13},children:[(0,t.__)("Last generated:","blaze-ai-discovery-for-woocommerce")," ",e.generated_at]})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{m(!0),a()({path:"/blazeaid/v1/feed/generate",method:"POST"}).then(e=>{i(e),m(!1)}).catch(()=>m(!1))},disabled:u,children:u?(0,t.__)("Generating…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Generate Feed","blaze-ai-discovery-for-woocommerce")}),e?.download_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.download_url,target:"_blank",children:(0,t.__)("Download CSV","blaze-ai-discovery-for-woocommerce")}),e?.json_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.json_url,target:"_blank",children:(0,t.__)("View JSON","blaze-ai-discovery-for-woocommerce")})]})]})})]}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Validation","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:n?(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{children:[(0,s.jsxs)("span",{style:{color:"#00a32a",fontWeight:600},children:[n.valid," ",(0,t.__)("valid","blaze-ai-discovery-for-woocommerce")]}),n.invalid>0&&(0,s.jsxs)("span",{style:{color:"#d63638",fontWeight:600,marginLeft:16},children:[n.invalid," ",(0,t.__)("invalid","blaze-ai-discovery-for-woocommerce")]})]}),n.issues?.length>0&&(0,s.jsxs)("div",{style:{marginTop:12},children:[(0,s.jsx)("h4",{children:(0,t.__)("Issues to fix:","blaze-ai-discovery-for-woocommerce")}),n.issues.map((e,r)=>(0,s.jsxs)("div",{style:{padding:"8px 0",borderBottom:"1px solid #eee"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("ul",{style:{margin:"4px 0 0",paddingLeft:20},children:e.issues.map((e,r)=>(0,s.jsx)("li",{style:{fontSize:13,color:"#555"},children:e},r))})]},r))]})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)("Generate a feed to see validation results.","blaze-ai-discovery-for-woocommerce")})})]}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("How to Submit to ChatGPT","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("ol",{style:{lineHeight:1.8},children:[(0,s.jsx)("li",{children:(0,t.__)('Click "Generate Feed", then "Download CSV" — CSV is the format OpenAI ingests.',"blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Apply to the merchant programme at","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://chatgpt.com/merchants",target:"_blank",rel:"noopener noreferrer",children:"chatgpt.com/merchants"}),"."]}),(0,s.jsx)("li",{children:(0,t.__)("Once approved, OpenAI gives you an SFTP endpoint. Upload the CSV there and re-upload whenever your catalogue changes.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Want automatic SFTP delivery or help with merchant-programme onboarding? Ask on the","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://wordpress.org/support/plugin/blaze-ai-discovery-for-woocommerce/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("support forum","blaze-ai-discovery-for-woocommerce")})," ",(0,t.__)("and we will work with you.","blaze-ai-discovery-for-woocommerce")]})]})})]})]})},"blazeaid-visibility":function(){const[e,i]=(0,r.useState)(!0),[n,l]=(0,r.useState)(null),[c,u]=(0,r.useState)(null),[m,h]=(0,r.useState)(!1),[f,y]=(0,r.useState)(!1),[p,b]=(0,r.useState)(null),[g,x]=(0,r.useState)(!1),[_,v]=(0,r.useState)(!1),j=(0,r.useRef)(null),w=(0,r.useRef)(!1),z=()=>{j.current&&(clearTimeout(j.current),j.current=null)},k=e=>{h(!!e?.consent),u(e?.payload||null),l(e?.state||"empty")},S=()=>{i(!0),b(null),x(!1),v(!1),a()({path:"/blazeaid/v1/visibility"}).then(e=>{w.current||(k(e),i(!1),"pending"===e?.state&&C(Date.now()))}).catch(()=>{w.current||(l(null),v(!0),i(!1),b((0,t.__)("Could not load AI visibility data. Reload the page to try again.","blaze-ai-discovery-for-woocommerce")))})},C=e=>{if(!w.current){if(Date.now()-e>=12e4)return y(!1),x(!0),void b((0,t.__)("Still fetching — check back shortly.","blaze-ai-discovery-for-woocommerce"));z(),j.current=setTimeout(()=>(e=>{a()({path:"/blazeaid/v1/visibility"}).then(r=>{if(!w.current)return r&&"pending"!==r.state?(k(r),void y(!1)):void C(e)}).catch(()=>C(e))})(e),5e3)}};(0,r.useEffect)(()=>(w.current=!1,S(),()=>{w.current=!0,z()}),[]);const A=e=>{y(!0),a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(()=>{w.current||(y(!1),z(),S())}).catch(()=>y(!1))};if(e)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const B=c?.period?.label||(0,t.__)("last 30 days","blaze-ai-discovery-for-woocommerce"),I=(Array.isArray(c?.sections)?c.sections:[]).length>0,T="empty"===n||"ready"===n&&!I,R="pending"===n&&!g,P=m&&"consent_off"!==n&&!R&&!f;return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20,gap:16,flexWrap:"wrap"},children:[(0,s.jsx)("h1",{style:{margin:0},children:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==n&&(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{y(!0),b(null),x(!1),v(!1),a()({path:"/blazeaid/v1/visibility/refresh",method:"POST"}).then(e=>{if(!w.current){if(e&&e.queued)return u(null),l("pending"),void C(Date.now());e&&e.payload?(u(e.payload),l("ready")):l("empty"),y(!1)}}).catch(e=>{if(!w.current){if(y(!1),e&&("consent_off"===e.state||e.data&&403===e.data.status))return h(!1),u(null),void l("consent_off");b((0,t.__)("Could not start a refresh. Please try again.","blaze-ai-discovery-for-woocommerce"))}})},disabled:!P,children:R||f?(0,t.__)("Refreshing…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Refresh","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsx)("p",{style:{color:"#757575",marginBottom:16},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ /* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ 24 (0,t.__)("How often AI assistants (ChatGPT, Google AI) mentioned your store over the %s, and who gets named instead.","blaze-ai-discovery-for-woocommerce"),B)}),p&&(0,s.jsx)("p",{style:{color:_?"#d63638":"#856404",marginBottom:16},role:_?"alert":"status",children:p}),"consent_off"===n&&(0,s.jsx)(d,{consent:{granted:!1,decided:!0},onToggle:A,busy:f,style:{marginTop:16}}),R&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:12},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{style:{margin:0,color:"#555"},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "last 30 days" */ /* translators: %s: reporting window, e.g. "last 30 days" */ 25 (0,t.__)("Fetching AI visibility data for the %s — this runs in the background and usually takes under a minute.","blaze-ai-discovery-for-woocommerce"),B)})]})}),"ready"===n&&I&&(0,s.jsx)(J,{payload:c}),T&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(X,{notices:c?.notices}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("p",{style:{margin:0,color:"#555"},children:["ready"===n?(0,t.__)("No AI visibility data is available for this period yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("AI visibility data has not been fetched yet. Background scheduling is unavailable on this site, so use Refresh to fetch it now.","blaze-ai-discovery-for-woocommerce")," ",(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")]})})})]}),"ready"===n&&I&&(0,s.jsx)("p",{style:{color:"#757575",fontSize:13},children:(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==n&&(0,s.jsx)(d,{consent:{granted:!0,decided:!0},onToggle:A,busy:f,style:{marginTop:16}})]})}},K=document.getElementById("blazeaid-root");if(K){const e=Z[window.blazeaid?.currentPage||"blazeaid"]||T;(0,r.render)((0,s.jsx)(e,{}),K)}})(); 11 (0,t._n)("%d task still due.","%d tasks still due.",r,"blaze-ai-discovery-for-woocommerce"),r)}return(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"warning",onRemove:()=>d(!0),className:"blazeaid-jobs-health",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsxs)("span",{style:{flex:1,minWidth:0},children:[y,g&&(0,s.jsx)("span",{style:{display:"block",marginTop:4,color:"#555"},children:g})]}),(0,s.jsx)(o.Button,{variant:"primary",onClick:p?()=>{m(!0),Promise.resolve(l()).finally(()=>m(!1))}:()=>{m(!0),f(null),n()({path:"/blazeaid/v1/jobs/run-now",method:"POST"}).then(e=>{f(e||{}),a&&a(e)}).catch(()=>f({error:!0})).finally(()=>m(!1))},isBusy:u,disabled:u,children:(0,t.__)("Run now","blaze-ai-discovery-for-woocommerce")}),e.faq_url&&(0,s.jsx)("a",{href:e.faq_url,target:"_blank",rel:"noreferrer",children:(0,t.__)("How to fix","blaze-ai-discovery-for-woocommerce")})]})})})}const h=["rest_forbidden","rest_cookie_invalid_nonce","rest_not_logged_in","rest_forbidden_context"],f=e=>{if(!e||"object"!=typeof e)return"other";const r=Number(e.data&&e.data.status),o="string"==typeof e.code?e.code:"";return 401===r||403===r||h.includes(o)?"auth":"invalid_json"===o?"html":"fetch_error"===o?"network":404===r?"not_found":"other"},p=(0,t.__)("Your session expired or a security plugin is blocking the WordPress REST API for logged-in requests — reload the page.","blaze-ai-discovery-for-woocommerce"),y=(0,t.__)("Unexpected response from your site's REST API (not JSON — a firewall page, a maintenance page or a PHP error printed before the data). Reload the page; if it keeps happening, check the site's error log.","blaze-ai-discovery-for-woocommerce"),g=(0,t.__)("Could not reach your site. Check your connection and reload the page.","blaze-ai-discovery-for-woocommerce"),b=e=>{switch(e){case"auth":return p;case"html":case"other":return y;case"network":return g;default:return null}};function x({kind:e}){const r=b(e);return r?(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"error",isDismissible:!1,className:"blazeaid-rest-error",children:r})}):null}const _=12e5;function v({request:e,onData:r,isDone:o,intervalMs:t,firstDelayMs:i,slowAfterMs:n,slowIntervalMs:s,onSlow:a,maxMs:l,onStop:c}){const d=Math.min(_,"number"==typeof l&&l>0?l:_),u=Date.now();let m=null,h=!1,p=!1,y=0,g=null;const b=()=>{h=!0,m&&(clearTimeout(m),m=null)},x=e=>{b(),c&&c(e)},v=()=>{if(h)return;const e=Date.now()-u;if(e>=d)return void x("timeout");let r=t;"number"==typeof n&&e>=n&&(p||(p=!0,a&&a()),r=s||t),m=setTimeout(w,r)},w=()=>{m=null,h||Promise.resolve().then(e).then(e=>{h||(y=0,g=null,r&&r(e),o&&o(e)?x("done"):v())}).catch(e=>{if(h)return;const r=f(e);if("auth"!==r){if("not_found"===r)return y=0,void v();y+=1,g=r,y>=3?x("network"===g?"network":"unexpected"):v()}else x("auth")})};return m=setTimeout(w,"number"==typeof i?i:t),b}const w=e=>{switch(e){case"auth":return"auth";case"unexpected":return"html";case"network":return"network";default:return null}},j=18e4,z=12e5,k=e=>(e?.results||[]).filter(e=>"fail"===e.status||"warning"===e.status).length,S=e=>n()({path:"/blazeaid/v1/onboarding",method:"POST",data:{event:e}}),C=e=>(e?.results||[]).find(e=>Array.isArray(e.crawlers))||null,A=e=>(e=>(e?.results||[]).filter(e=>e&&"pending"===e.status))(e).length>0,B={blocked_edge:3,blocked_robots:2,challenged:1};function I({result:e}){const r=(e=>(e?.crawlers||[]).filter(e=>"retrieval"===e.class&&"string"==typeof e.verdict&&e.verdict.startsWith("blocked_")))(e);if(!r.length)return null;const i=((e,r)=>{const o=e?.fix_links||[],t=r.reduce((e,r)=>!e||(B[r.verdict]||0)>(B[e.verdict]||0)?r:e,null);return(t&&t.layer?o.find(e=>e.layer===t.layer):null)||o[0]||null})(e,r),n=r.map(e=>e.name).join(", "),a=1===r.length?(0,t.sprintf)(/* translators: %s: crawler name */ /* translators: %s: crawler name */ 12 (0,t.__)("%s is blocked, so the AI assistant behind it cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),n):(0,t.sprintf)(/* translators: %s: comma-separated list of crawler names */ /* translators: %s: comma-separated list of crawler names */ 13 (0,t.__)("%s are blocked, so the AI assistants behind them cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),n);return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:"4px solid #d63638"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:(0,t.__)("AI shopping assistants can't reach your store","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:a})]}),(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexShrink:0},children:[i&&(0,s.jsx)(o.Button,{variant:"primary",href:i.url,target:"_blank",rel:"noopener noreferrer",children:i.label}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("View audit","blaze-ai-discovery-for-woocommerce")})]})]})})}function T({slow:e,running:r,error:i,onRunNow:n}){return(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(!e||r)&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Still queued — your site's background jobs haven't run it yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Your first store audit is running — results in about a minute.","blaze-ai-discovery-for-woocommerce")}),e&&(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:i?(0,t.__)("The audit could not run on this request. Try again, or check the notice above.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("You can run it on this page load instead — it takes up to a minute.","blaze-ai-discovery-for-woocommerce")})]}),e&&(0,s.jsx)(o.Button,{variant:"primary",onClick:n,isBusy:r,disabled:r,children:(0,t.__)("Run audit now","blaze-ai-discovery-for-woocommerce")})]})})}function R({done:e}){return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:e?"4px solid #00a32a":"4px solid #2271b1"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[!e&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsx)("div",{style:{minWidth:0,flex:1},children:(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Cloud checks are on — your store was checked from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Checking your store from outside your network…","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("See crawler results","blaze-ai-discovery-for-woocommerce")})]})})}const P={chatgpt:"ChatGPT",openai:"ChatGPT",perplexity:"Perplexity",copilot:"Microsoft Copilot",bing:"Microsoft Copilot",gemini:"Google Gemini",google_ai:"Google AI Mode",claude:"Claude",grok:"Grok",mistral:"Mistral",meta:"Meta AI"},W=/^no ai mentions/i,N=(e,r)=>new Intl.DateTimeFormat(void 0,{day:"numeric",month:"short",...r?{year:"numeric"}:{}}).format(e);function M({bg:e,color:r,fontSize:o,children:t}){return(0,s.jsx)("div",{style:{fontSize:o,fontWeight:"bold",width:56,height:56,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:e,color:r,flexShrink:0},children:t})}function $({icon:e,title:r,body:t,href:i,linkLabel:n}){return(0,s.jsx)(o.Card,{children:(0,s.jsxs)(o.CardBody,{style:{padding:20,display:"flex",alignItems:"center",gap:16},children:[e,(0,s.jsxs)("div",{style:{minWidth:0},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600},children:r}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13},children:t}),(0,s.jsx)("p",{style:{margin:"4px 0 0",fontSize:13},children:(0,s.jsx)("a",{href:i,children:n})})]})]})})}function D({audit:e}){const r=Array.isArray(e?.results)?e.results:null;let o,i;if(r){const e=r.filter(e=>e&&"fail"===e.status).length,n=r.filter(e=>e&&"warning"===e.status).length,a=e+n,l=r.filter(e=>e&&"pending"===e.status).length,c=e>0?"#f8d7da":n>0?"#fff3cd":"#d4edda",d=e>0?"#721c24":n>0?"#856404":"#155724";o=(0,s.jsx)(M,{bg:c,color:d,fontSize:24,children:e>0?"✗":n>0?"⚠":"✓"}),i=a>0?(0,t.sprintf)(/* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ /* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ 14 (0,t._n)("%1$d issue across %2$d checks","%1$d issues across %2$d checks",a,"blaze-ai-discovery-for-woocommerce"),a,r.length):(0,t.sprintf)(/* translators: %d: total number of audit rows */ /* translators: %d: total number of audit rows */ 15 (0,t.__)("All %d checks passed","blaze-ai-discovery-for-woocommerce"),r.length),l>0&&(i+=" · "+(0,t.sprintf)(/* translators: %d: number of audit rows whose cloud check is still running */ /* translators: %d: number of audit rows whose cloud check is still running */ 16 (0,t._n)("%d cloud check still running","%d cloud checks still running",l,"blaze-ai-discovery-for-woocommerce"),l))}else o=(0,s.jsx)(M,{bg:"#f0f0f0",color:"#757575",fontSize:24,children:"?"}),i=(0,t.__)("No audit result yet","blaze-ai-discovery-for-woocommerce");return(0,s.jsx)($,{icon:o,title:(0,t.__)("Store audit","blaze-ai-discovery-for-woocommerce"),body:i,href:"admin.php?page=blazeaid-audit",linkLabel:(0,t.__)("Open Store Audit","blaze-ai-discovery-for-woocommerce")})}function L({storeScore:e}){const r="number"==typeof e?.average&&Number.isFinite(e.average),o=r?e.average:0;let i="#f0f0f0",n="#757575";return r&&(i=o>=70?"#d4edda":o>=40?"#fff3cd":"#f8d7da",n=o>=70?"#155724":o>=40?"#856404":"#721c24"),(0,s.jsx)($,{icon:(0,s.jsx)(M,{bg:i,color:n,fontSize:32,children:r?Math.round(o):"—"}),title:(0,t.__)("Product AI readiness","blaze-ai-discovery-for-woocommerce"),body:e?(0,t.sprintf)(/* translators: 1: number of scored products, 2: total number of products */ /* translators: 1: number of scored products, 2: total number of products */ 17 (0,t.__)("%1$s / %2$s products scored","blaze-ai-discovery-for-woocommerce"),e.scored_products??0,e.total_products??0):(0,t.__)("Not yet scored","blaze-ai-discovery-for-woocommerce"),href:"admin.php?page=blazeaid-products",linkLabel:(0,t.__)("See products","blaze-ai-discovery-for-woocommerce")})}function F({visibility:e,consentGranted:r}){const o=(e=>{const r=(e=>{if(!e||"ready"!==e.state)return null;const r=(e.payload?.sections||[]).find(e=>e&&"mentions"===e.id);return(r?.blocks||[]).find(e=>e&&"stat"===e.type)||null})(e);return r&&"number"==typeof r.value&&Number.isFinite(r.value)&&!(e=>(e?.payload?.notices||[]).some(e=>e&&(e.code||W.test("string"==typeof e.text?e.text:""))))(e)?r.value:null})(e),i=null!==o,n=e?.payload?.period?.label;let a;return a=i?n?(0,t.sprintf)(/* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ /* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ 18 (0,t.__)("mentions, %s","blaze-ai-discovery-for-woocommerce"),n):(0,t.__)("mentions","blaze-ai-discovery-for-woocommerce"):r?"pending"===e?.state?(0,t.__)("fetching your first report…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("no data yet","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)($,{icon:(0,s.jsx)(M,{bg:i?"#e7f0fa":"#f0f0f0",color:i?"#2271b1":"#757575",fontSize:22,children:i?(new Intl.NumberFormat).format(o):"—"}),title:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce"),body:a,href:"admin.php?page=blazeaid-visibility",linkLabel:(0,t.__)("Open AI Visibility","blaze-ai-discovery-for-woocommerce")})}function O({value:e,label:r}){return(0,s.jsxs)("div",{children:[(0,s.jsx)("h2",{style:{fontSize:36,margin:"0 0 4px"},children:e}),(0,s.jsx)("p",{style:{color:"#757575",margin:0,fontSize:14},children:r})]})}function q(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)([]),[h,p]=(0,r.useState)([]),[y,g]=(0,r.useState)(null),[_,B]=(0,r.useState)(null),[W,M]=(0,r.useState)(null),[$,q]=(0,r.useState)("30"),[G,E]=(0,r.useState)(!0),[H,V]=(0,r.useState)(window.blazeaid?.consent||null),[U,Y]=(0,r.useState)(window.blazeaid?.onboarding||{}),[J,X]=(0,r.useState)(!1),[Q,Z]=(0,r.useState)(!1),[K,ee]=(0,r.useState)(!1),[re,oe]=(0,r.useState)(!1),[te,ie]=(0,r.useState)(!1),[ne,se]=(0,r.useState)(!1),[ae,le]=(0,r.useState)(null),[ce,de]=(0,r.useState)(null),[ue,me]=(0,r.useState)(!1),[he,fe]=(0,r.useState)(null),pe=(0,r.useRef)(null),ye=(0,r.useRef)(!1),ge=(0,r.useRef)(!1),be=(0,r.useRef)(!1),xe=(0,r.useRef)(!1),_e=()=>{pe.current&&(pe.current(),pe.current=null)};(0,r.useEffect)(()=>_e,[]);const ve=e=>{const r="string"==typeof e?e:f(e);return b(r)&&fe(r),r},we=(e,r)=>{_e(),pe.current=v({request:()=>n()({path:"/blazeaid/v1/audit"}),onData:e=>{e&&e.run_at&&g(e)},isDone:r=>!!(r&&r.run_at&&e(r)),intervalMs:5e3,slowAfterMs:j,slowIntervalMs:3e4,onSlow:r,maxMs:z,onStop:e=>{pe.current=null;const r=w(e);r&&ve(r)}})},je=()=>u().then(e=>(e&&le(e),e));(0,r.useEffect)(()=>{E(!0),Promise.all([n()({path:`/blazeaid/v1/attribution/summary?days=${$}`}),n()({path:`/blazeaid/v1/attribution/products?days=${$}`}),n()({path:`/blazeaid/v1/attribution/trend?days=${$}`}),n()({path:"/blazeaid/v1/audit"}).catch(()=>null),n()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),n()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t,n,s,a])=>{i(e),l(r),p(o),g(t),B(n),M(s),a&&le(a),E(!1)}).catch(e=>{ve(e),E(!1)})},[$]);const ze=!!H&&!!H.granted,ke=C(y),Se=!!(ze&&ke&&ke.probe&&!1===ke.probe.ran&&"consent_off"===ke.probe.notice),Ce=A(y),Ae="pending"===W?.state||ze&&"consent_off"===W?.state;(0,r.useEffect)(()=>{if(G||!Se&&!Ae&&!Ce)return;const e=Ae,r=Se||Ce;return v({request:()=>Promise.all([e?n()({path:"/blazeaid/v1/visibility"}):Promise.resolve(void 0),r?n()({path:"/blazeaid/v1/audit"}):Promise.resolve(void 0)]),onData:([e,r])=>{e&&M(e),r&&r.run_at&&g(r)},isDone:o=>!(([o,t])=>{const i=!!e&&!(!o||"pending"!==o.state),n=r?C(t):null,s=!!r&&!(!n||!n.probe||!1!==n.probe.ran),a=!!r&&A(t);return i||s||a})(o),intervalMs:5e3,slowAfterMs:j,slowIntervalMs:3e4,maxMs:z,onStop:e=>{const r=w(e);r&&ve(r)}})},[G,Ae,Se,Ce]),(0,r.useEffect)(()=>{G||y||he||ye.current||(ye.current=!0,we(e=>!!e.run_at,()=>{oe(!0),je()}))},[G,y,he]),(0,r.useEffect)(()=>{if(G||y||he)return;const e=setTimeout(je,6e4);return()=>clearTimeout(e)},[G,y,he]),(0,r.useEffect)(()=>{G||!H||H.granted||ge.current||U.modal_shown_version===(window.blazeaid?.version||"")||(ge.current=!0,X(!0))},[G]),(0,r.useEffect)(()=>{G||J||!y||!H||H.granted||!U.dismissed_at||U.reminder_shown||be.current||xe.current||(be.current=!0,me(!0),S("reminder_shown").then(Y).catch(()=>{}))},[G,J,y,H,U]);const Be=()=>{ie(!0),se(!1),_e();const e=e=>{se(!0);const r=e?ve(e):null;return"auth"===r||"html"===r||(oe(!0),y||we(e=>!!e.run_at,()=>oe(!0))),!1};return n()({path:"/blazeaid/v1/audit/run",method:"POST",data:{force:!0}}).then(r=>r&&r.results?(g(r),je(),!0):e(null)).catch(e).finally(()=>ie(!1))},Ie=()=>(ee(!0),n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!0}}).then(e=>(V(e),me(!1),de("waiting"),n()({path:"/blazeaid/v1/audit/run",method:"POST"}).catch(()=>null))).then(e=>{if(e&&e.results)return g(e),void de("done");we(e=>!!(e=>!0===C(e)?.probe?.ran)(e)&&(de("done"),!0),()=>de("done"))}).finally(()=>ee(!1)));if(G)return(0,s.jsxs)("div",{style:{padding:"40px",textAlign:"center"},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{children:(0,t.__)("Loading AI traffic data…","blaze-ai-discovery-for-woocommerce")})]});const Te=(()=>{const e=window.blazeaid?.installedAt;if("string"!=typeof e||!e)return null;const r=new Date(e.replace(" ","T")+"Z");return Number.isNaN(r.getTime())?null:r})(),Re=parseInt($,10)||30,Pe=Te?(We=Te,Math.max(0,Math.floor((Date.now()-We.getTime())/864e5))):null;var We;const Ne=Te&&Re>Pe?(0,t.sprintf)(/* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ /* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ 19 (0,t.__)("Last %1$d days (tracking since %2$s)","blaze-ai-discovery-for-woocommerce"),Re,N(Te,!1)):(0,t.sprintf)(/* translators: %d: number of days in the selected period */ /* translators: %d: number of days in the selected period */ 20 (0,t.__)("Last %d days","blaze-ai-discovery-for-woocommerce"),Re),Me=Te?(0,t.sprintf)(/* translators: %s: date tracking started, e.g. "30 Aug 2026" */ /* translators: %s: date tracking started, e.g. "30 Aug 2026" */ 21 (0,t.__)("Tracking since %s — the plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),N(Te,!0)):(0,t.__)("The plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),$e="number"==typeof e?.total_visits?e.total_visits:0,De=Array.isArray(e?.platforms)?e.platforms.filter(e=>e&&e.platform):[],Le=Array.isArray(a)?a.filter(e=>e&&e.product_id):[],Fe=(De.length?1:0)+(Le.length?1:0);return(0,s.jsxs)("div",{className:"blazeaid-dashboard",style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsx)("h1",{style:{marginBottom:20},children:(0,t.__)("AI Discovery Dashboard","blaze-ai-discovery-for-woocommerce")}),J&&(0,s.jsx)(c,{onEnable:()=>{Z(!0),Ie().then(()=>S("modal_shown")).then(Y).catch(()=>{}).finally(()=>{Z(!1),X(!1)})},onDismiss:()=>{xe.current=!!y,X(!1),S("dismissed").then(Y).catch(()=>{})},busy:Q}),ue&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"info",onRemove:()=>me(!1),className:"blazeaid-onboarding-reminder",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsx)("span",{style:{flex:1,minWidth:0},children:(0,t.sprintf)(/* translators: %d: number of failed or warning audit rows */ /* translators: %d: number of failed or warning audit rows */ 22 (0,t._n)("Your local audit found %d issue. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.","Your local audit found %d issues. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.",k(y),"blaze-ai-discovery-for-woocommerce"),k(y))}),(0,s.jsx)(o.Button,{variant:"primary",onClick:Ie,isBusy:K,disabled:K,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}),he&&(0,s.jsx)(x,{kind:he}),(0,s.jsx)(m,{health:ae,audit:y,onRunNow:()=>{Promise.all([n()({path:"/blazeaid/v1/audit"}).catch(()=>null),n()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),n()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t])=>{e&&e.run_at&&g(e),r&&B(r),o&&M(o),t&&le(t)})},onRunAudit:Be}),!y&&!he&&(0,s.jsx)(T,{slow:re,running:te,error:ne,onRunNow:Be}),ce&&(0,s.jsx)(R,{done:"done"===ce}),(0,s.jsx)(I,{result:C(y)}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,marginBottom:16},children:[(0,s.jsx)(D,{audit:y}),(0,s.jsx)(L,{storeScore:_}),(0,s.jsx)(F,{visibility:W,consentGranted:H?!!H.granted:"consent_off"!==W?.state})]}),H&&!H.granted&&!J&&(0,s.jsx)(d,{consent:H,onToggle:e=>e?Ie():(ee(!0),n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!1}}).then(e=>{V(e),de(null)}).catch(()=>{}).finally(()=>ee(!1))),busy:K}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsxs)(o.CardHeader,{style:{flexWrap:"wrap",gap:12},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("AI traffic","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13,fontWeight:"normal"},children:Me})]}),(0,s.jsx)(o.SelectControl,{value:$,options:[{label:(0,t.__)("Last 7 days","blaze-ai-discovery-for-woocommerce"),value:"7"},{label:(0,t.__)("Last 30 days","blaze-ai-discovery-for-woocommerce"),value:"30"},{label:(0,t.__)("Last 90 days","blaze-ai-discovery-for-woocommerce"),value:"90"}],onChange:q,__nextHasNoMarginBottom:!0})]}),(0,s.jsxs)(o.CardBody,{children:[0===$e?(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No AI-referred visits recorded yet. Visits from ChatGPT, Perplexity, Copilot, Gemini and Claude will appear here.","blaze-ai-discovery-for-woocommerce")}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("p",{style:{color:"#757575",margin:"0 0 12px",fontSize:13},children:Ne}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16},children:[(0,s.jsx)(O,{value:(new Intl.NumberFormat).format($e),label:(0,t.__)("AI-referred visitors","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(O,{value:(new Intl.NumberFormat).format(e?.orders?.count??0),label:(0,t.__)("AI-attributed orders","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(O,{value:new Intl.NumberFormat(void 0,{style:"currency",currency:window.blazeaid?.currency||"USD"}).format(e?.orders?.revenue??0),label:(0,t.__)("AI-attributed revenue","blaze-ai-discovery-for-woocommerce")})]})]}),(0,s.jsx)("p",{style:{color:"#757575",fontSize:13,margin:"16px 0 0"},children:(0,t.__)("Industry benchmarks show ~70% of AI traffic arrives without identifiable headers. Your actual AI traffic is likely higher than what we can detect. We track referrer headers, UTM parameters, and URL text fragments to capture as much as possible.","blaze-ai-discovery-for-woocommerce")})]})]}),Fe>0&&(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:2===Fe?"1fr 1fr":"1fr",gap:16},children:[De.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Visits by platform","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Platform","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:De.map(e=>{return(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0",textTransform:"capitalize"},children:(r=e.platform,P[String(r).toLowerCase()]||String(r).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.count})]},e.platform);var r})})]})})]}),Le.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Top products","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("AI visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:Le.map(e=>(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0"},children:e.url?(0,s.jsx)("a",{href:e.url,children:e.name}):e.name}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.visit_count})]},e.product_id))})]})})]})]})]})}function G({product:e}){const[o,i]=(0,r.useState)(!1),n=e.issues||[],a=n.filter(e=>"error"===e.severity||"warning"===e.severity).length;return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("tr",{onClick:()=>n.length>0&&i(!o),style:{cursor:n.length>0?"pointer":"default"},children:[(0,s.jsx)("td",{style:{padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.length>0&&(0,s.jsx)("span",{style:{fontSize:11,color:"#757575",transition:"transform 0.2s",transform:o?"rotate(90deg)":"none"},children:"▶"}),(0,s.jsx)("span",{children:e.product_name}),a>0&&(0,s.jsxs)("span",{style:{fontSize:11,color:"#757575",background:"#f0f0f0",padding:"1px 6px",borderRadius:8},children:[a," ",1===a?"issue":"issues"]})]})}),(0,s.jsx)("td",{style:{textAlign:"center",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsx)("span",{style:{display:"inline-block",padding:"2px 12px",borderRadius:12,fontSize:13,fontWeight:600,background:e.total_score>=70?"#d4edda":e.total_score>=40?"#fff3cd":"#f8d7da",color:e.total_score>=70?"#155724":e.total_score>=40?"#856404":"#721c24"},children:e.total_score})}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:e.edit_url&&(0,s.jsx)("a",{href:e.edit_url,onClick:e=>e.stopPropagation(),style:{fontSize:13},children:(0,t.__)("Edit","blaze-ai-discovery-for-woocommerce")})})]}),o&&(0,s.jsx)("tr",{children:(0,s.jsx)("td",{colSpan:"3",style:{padding:"0 0 12px 28px",borderBottom:"1px solid #eee"},children:(0,s.jsxs)("div",{style:{background:"#f9f9f9",borderRadius:6,padding:16},children:[(0,s.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[["title_score","Title",15],["description_score","Description",15],["image_score","Images",10],["brand_score","Brand",10],["category_score","Category",10],["attributes_score","Attributes",15],["price_score","Price",5],["identifier_score","Identifiers",10],["rating_score","Reviews",5],["policy_score","Policies",5]].map(([r,o,t])=>{const i=parseInt(e[r])||0,n=Math.round(i/t*100);return(0,s.jsxs)("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:4,background:n>=80?"#d4edda":n>=40?"#fff3cd":"#f8d7da",color:n>=80?"#155724":n>=40?"#856404":"#721c24"},children:[o," ",i,"/",t]},r)})}),n.length>0&&(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontWeight:600,fontSize:13,margin:"0 0 8px"},children:(0,t.__)("How to improve this product:","blaze-ai-discovery-for-woocommerce")}),n.map((e,r)=>{const o=(e=>{switch(e){case"error":return{color:"#721c24",icon:"✗"};case"warning":return{color:"#856404",icon:"⚠"};default:return{color:"#004085",icon:"ℹ"}}})(e.severity);return(0,s.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",marginBottom:6},children:[(0,s.jsx)("span",{style:{color:o.color,fontSize:12,flexShrink:0,marginTop:1},children:o.icon}),(0,s.jsxs)("span",{style:{fontSize:13,color:"#333"},children:[(0,s.jsxs)("strong",{style:{color:o.color},children:[e.name,":"]})," ",e.message]})]},r)})]})]})})})]})}const E=e=>{switch(e){case"pass":return{icon:"✓",color:"#00a32a",bg:"#d4edda"};case"warning":return{icon:"⚠",color:"#856404",bg:"#fff3cd"};case"fail":return{icon:"✗",color:"#721c24",bg:"#f8d7da"};case"pending":return{icon:"…",color:"#2271b1",bg:"#e7f0fa"};default:return{icon:"ℹ",color:"#004085",bg:"#cce5ff"}}},H=e=>(e?.results||[]).some(e=>e&&"pending"===e.status),V=e=>{switch(e){case"allowed":return(0,t.__)("allowed","blaze-ai-discovery-for-woocommerce");case"blocked_robots":return(0,t.__)("blocked by robots.txt","blaze-ai-discovery-for-woocommerce");case"blocked_edge":return(0,t.__)("blocked at the edge","blaze-ai-discovery-for-woocommerce");case"challenged":return(0,t.__)("challenged","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("unknown","blaze-ai-discovery-for-woocommerce")}},U=e=>{switch(e){case"high":return(0,t.__)("high confidence","blaze-ai-discovery-for-woocommerce");case"medium":return(0,t.__)("medium confidence","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("low confidence","blaze-ai-discovery-for-woocommerce")}},Y=(e,r)=>{const o={display:"inline-block",width:8,height:8,borderRadius:"50%",border:`1.5px solid ${r}`,boxSizing:"border-box",flexShrink:0};return"high"===e?{...o,background:r}:"medium"===e?{...o,background:`linear-gradient(90deg, ${r} 50%, transparent 50%)`}:{...o,background:"transparent"}};function J({check:e,consentGranted:r}){const o=e.crawlers||[],i=e.fix_links||[],n=e.probe||{};let a=null;return!1===n.ran&&(a="consent_off"===n.notice?r?(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce")}):(0,t.sprintf)(/* translators: %s: reason code, e.g. rate_limited */ /* translators: %s: reason code, e.g. rate_limited */ 23 (0,t.__)("Outside-in probe unavailable (%s); results are based on robots.txt and your server log only.","blaze-ai-discovery-for-woocommerce"),n.notice||"unavailable")),(0,s.jsxs)("div",{style:{marginTop:8},children:[(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:o.map(e=>{const r="allowed"===(o=e.verdict)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:o&&o.startsWith("blocked_")?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:"challenged"===o?{color:"#856404",bg:"#fff3cd",border:"#ffe08a"}:{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"};var o;const t=[`${e.name}: ${V(e.verdict)} (${U(e.confidence)})`,e.evidence&&e.evidence.length?e.evidence[0]:null].filter(Boolean).join(" — ");return(0,s.jsxs)("span",{title:t,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("span",{style:Y(e.confidence,r.color),"aria-hidden":"true"}),e.name]},e.name)})}),a&&(0,s.jsx)("p",{style:{margin:"8px 0 0",color:"#555",fontSize:13},children:a}),i.length>0&&(0,s.jsx)("ul",{style:{margin:"8px 0 0",paddingLeft:18,fontSize:13},children:i.map(e=>(0,s.jsx)("li",{children:(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.label})},e.layer))}),o.length>0&&(0,s.jsxs)("details",{style:{marginTop:8,fontSize:13},children:[(0,s.jsx)("summary",{style:{cursor:"pointer",color:"#2271b1"},children:(0,t.__)("Evidence","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("dl",{style:{margin:"8px 0 0"},children:o.map(e=>(0,s.jsxs)("div",{style:{marginBottom:6},children:[(0,s.jsxs)("dt",{style:{fontWeight:600},children:[e.name," — ",V(e.verdict),", ",U(e.confidence)]}),(e.evidence||[]).map((e,r)=>(0,s.jsx)("dd",{style:{margin:"2px 0 0 12px",color:"#555"},children:e},r))]},e.name))})]})]})}const X=e=>{switch(e){case"good":return(0,t.__)("good","blaze-ai-discovery-for-woocommerce");case"poor":return(0,t.__)("poor","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("needs improvement","blaze-ai-discovery-for-woocommerce")}};function Q({cwv:e}){const r=Object.values(e?.metrics||{}).filter(e=>e&&e.label);return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:r.map(e=>{const r="good"===(o=e.rating)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:"poor"===o?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};var o;return(0,s.jsxs)("span",{title:`${e.label}: ${X(e.rating)}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("strong",{children:e.label}),e.display]},e.label)})}):null}const Z=e=>!!e&&("queued"===e.state||"running"===e.state),K=e=>"number"==typeof e&&Number.isFinite(e)?(new Intl.NumberFormat).format(e):String(e??"");function ee({delta:e,deltaLabel:r}){const o="number"==typeof e&&Number.isFinite(e);if(!o&&!r)return null;let t="",i="#757575";return o&&e>0?(t="▲ ",i="#00a32a"):o&&e<0&&(t="▼ ",i="#d63638"),(0,s.jsxs)("p",{style:{margin:"4px 0 0",fontSize:13,color:i},children:[o&&(0,s.jsxs)("span",{children:[t,K(Math.abs(e))]}),o&&r?" ":"",r&&(0,s.jsx)("span",{style:{color:"#757575"},children:r})]})}function re({block:e}){return(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontSize:32,fontWeight:"bold",lineHeight:1.2},children:K(e.value)}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:14},children:e.label}),(0,s.jsx)(ee,{delta:e.delta,deltaLabel:e.delta_label})]})}function oe({block:e}){const r=Array.isArray(e.columns)?e.columns:[],o=Array.isArray(e.rows)?e.rows:[];if(!r.length&&!o.length)return null;const t=(e,r)=>({textAlign:"number"==typeof e?"right":"left",padding:"8px 12px 8px 0",borderBottom:r?"1px solid #ddd":"1px solid #f0f0f1",whiteSpace:"nowrap"}),i=o[0]||[];return(0,s.jsx)("div",{style:{overflowX:"auto"},children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[r.length>0&&(0,s.jsx)("thead",{children:(0,s.jsx)("tr",{children:r.map((e,r)=>(0,s.jsx)("th",{style:t(i[r],!0),children:e},r))})}),(0,s.jsx)("tbody",{children:o.map((e,r)=>(0,s.jsx)("tr",{children:(Array.isArray(e)?e:[]).map((e,r)=>(0,s.jsx)("td",{style:t(e,!1),children:"number"==typeof e?K(e):e},r))},r))})]})})}function te({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("ul",{style:{margin:"4px 0",paddingLeft:18},children:r.map((e,r)=>(0,s.jsx)("li",{style:{marginBottom:4},children:e.url?(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.text}):e.text},r))}):null}function ie({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:r.map((e,r)=>{const o=(e=>["pass","warning","fail"].includes(e)?e:"unknown")(e.status),t=(e=>{switch(e){case"pass":return{color:"#155724",bg:"#d4edda",border:"#8fd19e"};case"warning":return{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};case"fail":return{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"};default:return{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"}}})(o);return(0,s.jsx)("span",{className:`blazeaid-chip blazeaid-chip--${o}`,style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:t.color,background:t.bg,border:`1px solid ${t.border}`},children:e.label},r)})}):null}function ne({block:e}){return e.html?(0,s.jsx)("div",{className:"blazeaid-payload-text",style:{fontSize:13,color:"#50575e"},dangerouslySetInnerHTML:{__html:e.html}}):null}function se(e){const r=[];return(Array.isArray(e)?e:[]).forEach(e=>{const o=r[r.length-1];e&&"stat"===e.type?o&&"stats"===o.kind?o.items.push(e):r.push({kind:"stats",items:[e]}):r.push({kind:"block",block:e})}),r}function ae({block:e}){if(!e||"object"!=typeof e)return null;switch(e.type){case"stat":return(0,s.jsx)(re,{block:e});case"table":return(0,s.jsx)(oe,{block:e});case"list":return(0,s.jsx)(te,{block:e});case"chips":return(0,s.jsx)(ie,{block:e});case"text":return(0,s.jsx)(ne,{block:e});default:return null}}function le({notices:e}){const r=Array.isArray(e)?e:[];return r.length?(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:r.map((e,r)=>{return(0,s.jsxs)(o.Notice,{status:(t=e.level,["info","warning","error"].includes(t)?t:"info"),isDismissible:!1,children:[e.text,e.link&&e.link.url&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:"_blank",rel:"noopener noreferrer",children:e.link.label||e.link.url})]})]},r);var t})}):null}function ce({payload:e}){if(!e||"object"!=typeof e)return null;const r=Array.isArray(e.sections)?e.sections:[];return(0,s.jsxs)("div",{className:"blazeaid-payload",children:[(0,s.jsx)(le,{notices:e.notices}),r.map((e,r)=>{const i=Array.isArray(e.blocks)?e.blocks:[];return(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:e.title||(0,t.__)("Untitled section","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:i.length?se(i).map((e,r,o)=>(0,s.jsx)("div",{style:{marginBottom:r<o.length-1?16:0},children:"stats"===e.kind?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"16px 48px"},children:e.items.map((e,r)=>(0,s.jsx)("div",{style:{minWidth:160},children:(0,s.jsx)(ae,{block:e})},r))}):(0,s.jsx)(ae,{block:e.block})},r)):(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No data for this period.","blaze-ai-discovery-for-woocommerce")})})]},e.id||r)})]})}const de={blazeaid:q,"blazeaid-products":function(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)([]),[c,d]=(0,r.useState)(null),[h,p]=(0,r.useState)(!0),[y,g]=(0,r.useState)(!1),[_,j]=(0,r.useState)(null),[z,k]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),A=e=>{const r="string"==typeof e?e:f(e);return b(r)&&k(r),r},B=(e=!0)=>{e&&p(!0),Promise.all([n()({path:"/blazeaid/v1/scores/summary"}),n()({path:"/blazeaid/v1/scores/products?per_page=100&order=ASC"}),n()({path:"/blazeaid/v1/scores/progress"}),u()]).then(([e,r,o,t])=>{i(e),l(r),d(o),t&&j(t),"running"===o?.status&&g(!0),p(!1)}).catch(e=>{A(e),p(!1)})};if((0,r.useEffect)(()=>B(!0),[]),(0,r.useEffect)(()=>{if(!y)return;let e=null;return v({request:()=>n()({path:"/blazeaid/v1/scores/progress"}),onData:r=>{e=r,d(r)},isDone:e=>!!e&&("complete"===e.status||"idle"===e.status||"failed"===e.status),intervalMs:3e3,onStop:r=>{if(g(!1),"done"===r)return void(e&&"failed"!==e.status&&B(!1));if("timeout"===r)return void C((0,t.__)("Scoring is still running in the background — reload the page later to see the result.","blaze-ai-discovery-for-woocommerce"));const o=w(r);o&&A(o)}})},[y]),h)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const I=c?.total>0?Math.round(c.scored/c.total*100):0;return(0,s.jsxs)("div",{style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Product AI Readiness","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{C(null),g(!0),n()({path:"/blazeaid/v1/scores/recalculate",method:"POST"}).then(e=>{e&&e.progress&&d(e.progress)}).catch(e=>{g(!1);const r=A(e);b(r)||C((0,t.__)("Could not start scoring. Please try again.","blaze-ai-discovery-for-woocommerce"))})},disabled:y,children:y?(0,t.__)("Scoring...","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Recalculate All","blaze-ai-discovery-for-woocommerce")})]}),z&&(0,s.jsx)(x,{kind:z}),(0,s.jsx)(m,{health:_,onRunNow:()=>B(!1)}),"failed"===c?.status&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"error",isDismissible:!1,children:c.reason||(0,t.__)("The last scoring run stopped before it finished. Click Recalculate All to start again.","blaze-ai-discovery-for-woocommerce")})}),S&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"warning",onRemove:()=>C(null),children:S})}),y&&"running"===c?.status&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{padding:20},children:[(0,s.jsxs)("p",{children:[(0,t.__)("Scoring products...","blaze-ai-discovery-for-woocommerce")," ",c.scored," / ",c.total," (",I,"%)"]}),(0,s.jsx)("div",{style:{background:"#e0e0e0",borderRadius:4,height:8},children:(0,s.jsx)("div",{style:{background:"#007cba",borderRadius:4,height:8,width:`${I}%`,transition:"width 0.3s"}})})]})}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{style:{padding:24},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:24},children:[(0,s.jsx)("div",{style:{fontSize:48,fontWeight:"bold",color:e?.average>=70?"#00a32a":e?.average>=40?"#dba617":"#d63638"},children:e?.average??0}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontSize:18,margin:0},children:(0,t.__)("Product AI Readiness Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:"running"===c?.status?(0,t.sprintf)(/* translators: 1: products scored so far, 2: total products */ /* translators: 1: products scored so far, 2: total products */ 24 (0,t.__)("Scoring your products… %1$d / %2$d","blaze-ai-discovery-for-woocommerce"),c.scored??0,c.total??0):`${e?.scored_products??0} / ${e?.total_products??0} ${(0,t.__)("products scored","blaze-ai-discovery-for-woocommerce")}`})]})]})})}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Products by AI Readiness (lowest first)","blaze-ai-discovery-for-woocommerce"),(0,s.jsx)("span",{style:{fontWeight:"normal",fontSize:13,color:"#757575",marginLeft:8},children:(0,t.__)("Click a row to see recommendations","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)(o.CardBody,{children:a.length>0?(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"2px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"center",padding:"8px 0",borderBottom:"2px solid #ddd",width:100},children:(0,t.__)("Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"2px solid #ddd",width:80},children:(0,t.__)("Action","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:a.map(e=>(0,s.jsx)(G,{product:e},e.product_id))})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No products scored yet. Click "Recalculate All" to scan your catalog.',"blaze-ai-discovery-for-woocommerce")})})]})]})},"blazeaid-audit":function(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(!0),[c,u]=(0,r.useState)(!1),[m,h]=(0,r.useState)(null),[p,y]=(0,r.useState)(null),[g,_]=(0,r.useState)(null),j=(0,r.useRef)(null),z=e=>{const r="string"==typeof e?e:f(e);return b(r)&&_(r),r},k=()=>{j.current&&(j.current(),j.current=null)};(0,r.useEffect)(()=>(l(!0),n()({path:"/blazeaid/v1/audit"}).then(e=>{i(e),l(!1)}).catch(e=>{z(e),l(!1)}),n()({path:"/blazeaid/v1/cloud/consent"}).then(y).catch(()=>y(null)),k),[]);const S=e=>{k(),j.current=v({request:()=>n()({path:"/blazeaid/v1/audit"}),onData:r=>{r&&r.run_at&&r.run_at!==e&&i(r)},isDone:r=>!(!r||!r.run_at||r.run_at===e||H(r)),intervalMs:3e3,slowAfterMs:9e4,slowIntervalMs:3e4,onSlow:()=>h((0,t.__)("Still running — this page keeps checking for up to 20 minutes.","blaze-ai-discovery-for-woocommerce")),onStop:e=>{j.current=null,u(!1);const r=w(e);r?(z(r),h(null)):h("timeout"===e?(0,t.__)("Still running — check back shortly.","blaze-ai-discovery-for-woocommerce"):null)}})},C=()=>{u(!0),h(null);const r=e?.run_at||null;n()({path:"/blazeaid/v1/audit/run",method:"POST"}).then(e=>{e&&e.queued?S(r):(i(e),u(!1),H(e)&&(h((0,t.__)("Cloud checks are still running in the background — the rows marked pending will update.","blaze-ai-discovery-for-woocommerce")),S(e.run_at||r)))}).catch(e=>{u(!1);const r=z(e);b(r)||h((0,t.__)("Could not start the audit. Please try again.","blaze-ai-discovery-for-woocommerce"))})};if(a)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const A=e?.results||[],B=e?.overall_status||"unknown",I=(0,s.jsx)(d,{consent:p,onToggle:e=>{n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(e=>{y(e),C()})},busy:c,style:{marginTop:16}});return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Store Readiness Audit","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:C,disabled:c,children:c?(0,t.__)("Running…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Re-run Audit","blaze-ai-discovery-for-woocommerce")})]}),g&&(0,s.jsx)(x,{kind:g}),e?.run_at&&(0,s.jsxs)("p",{style:{color:"#757575",marginBottom:16},children:[(0,t.__)("Last run:","blaze-ai-discovery-for-woocommerce")," ",e.run_at]}),(c||m)&&(0,s.jsxs)("div",{style:{display:"grid",gap:12,marginBottom:16},children:[c&&(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("Running… this can take up to a minute while the store is checked from outside your network.","blaze-ai-discovery-for-woocommerce")}),m&&(0,s.jsx)("p",{style:{color:"#856404",margin:0},children:m})]}),!p?.granted&&I,(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Readiness Checklist","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:12,...E(B)},children:B.toUpperCase()})]})}),(0,s.jsx)(o.CardBody,{children:A.length>0?(0,s.jsx)("div",{children:A.map((e,r)=>{const o=E(e.status);return(0,s.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:"12px 0",borderBottom:r<A.length-1?"1px solid #eee":"none"},children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",background:o.bg,color:o.color,fontWeight:"bold",fontSize:14,flexShrink:0},children:o.icon}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:e.check}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[e.message,e.link&&!Array.isArray(e.crawlers)&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:e.link.url.startsWith("http")&&!e.link.url.includes("/wp-admin/")?"_blank":"_self",rel:"noopener noreferrer",children:e.link.label})]})]}),Array.isArray(e.crawlers)&&(0,s.jsx)(J,{check:e,consentGranted:!!p?.granted}),e.cwv&&(0,s.jsx)(Q,{cwv:e.cwv})]})]},r)})}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No audit has been run yet. Click "Re-run Audit" to check your store.',"blaze-ai-discovery-for-woocommerce")})})]}),p?.granted&&I]})},"blazeaid-feed":function(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(null),[c,d]=(0,r.useState)(!0),[u,m]=(0,r.useState)(!1),[h,p]=(0,r.useState)(null),y=(0,r.useRef)(null),g=()=>{y.current&&(y.current(),y.current=null)},x=()=>n()({path:"/blazeaid/v1/feed/validate"}).then(l).catch(()=>{}),_=()=>{g(),m(!0);let e=null;y.current=v({request:()=>n()({path:"/blazeaid/v1/feed/status"}),onData:r=>{e=r,i(r)},isDone:e=>!Z(e&&e.progress),intervalMs:3e3,onStop:r=>{if(y.current=null,m(!1),"done"===r)return e&&e.progress&&"error"===e.progress.state&&p(e.progress.error||(0,t.__)("Feed generation failed.","blaze-ai-discovery-for-woocommerce")),void x();if("timeout"===r)return void p((0,t.__)("The feed is still queued. Background jobs may not be running on this site — check the Jobs page, then try again.","blaze-ai-discovery-for-woocommerce"));const o=w(r);p(b(o)||(0,t.__)("Feed generation failed.","blaze-ai-discovery-for-woocommerce"))}})};if((0,r.useEffect)(()=>(d(!0),Promise.all([n()({path:"/blazeaid/v1/feed/status"}),n()({path:"/blazeaid/v1/feed/validate"})]).then(([e,r])=>{i(e),l(r),d(!1),Z(e.progress)&&_()}).catch(e=>{d(!1);const r=b(f(e));r&&p(r)}),g),[]),c)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const j=e?.progress;let z=(0,t.__)("Generate Feed","blaze-ai-discovery-for-woocommerce");return u&&(z="running"===j?.state&&j.total>0?(0,t.sprintf)(/* translators: 1: products processed, 2: products total */ /* translators: 1: products processed, 2: products total */ 25 (0,t.__)("Generating… %1$s of %2$s","blaze-ai-discovery-for-woocommerce"),j.done,j.total):"queued"===j?.state?(0,t.__)("Queued…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Generating…","blaze-ai-discovery-for-woocommerce")),(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsx)("h1",{children:(0,t.__)("ChatGPT Merchant Feed","blaze-ai-discovery-for-woocommerce")}),h&&(0,s.jsx)(o.Notice,{status:"error",isDismissible:!0,onRemove:()=>p(null),children:h}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Status","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{style:{margin:"0 0 8px"},children:[(0,s.jsx)("strong",{children:(0,t.__)("Products in feed:","blaze-ai-discovery-for-woocommerce")})," ",e?.product_count??0]}),e?.generated_at&&(0,s.jsxs)("p",{style:{margin:0,color:"#757575",fontSize:13},children:[(0,t.__)("Last generated:","blaze-ai-discovery-for-woocommerce")," ",e.generated_at]}),u&&"queued"===j?.state&&(0,s.jsx)("p",{style:{margin:"8px 0 0",color:"#757575",fontSize:13},children:(0,t.__)("Queued as a background job — this page updates when it finishes.","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{m(!0),p(null);const r=!!e&&e.total_products<=e.inline_limit;n()({path:"/blazeaid/v1/feed/generate",method:"POST",data:{force:r}}).then(e=>{i(e),e.queued?_():(m(!1),x())}).catch(e=>{m(!1);const r=f(e),o="other"===r?null:b(r);p(o||e&&(e.error||e.message)||(0,t.__)("Feed generation failed.","blaze-ai-discovery-for-woocommerce"))})},disabled:u,children:z}),e?.download_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.download_url,target:"_blank",children:(0,t.__)("Download CSV","blaze-ai-discovery-for-woocommerce")}),e?.json_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.json_url,target:"_blank",children:(0,t.__)("View JSON","blaze-ai-discovery-for-woocommerce")})]})]})})]}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Validation","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:a&&!1!==a.available?(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{children:[(0,s.jsxs)("span",{style:{color:"#00a32a",fontWeight:600},children:[a.valid," ",(0,t.__)("valid","blaze-ai-discovery-for-woocommerce")]}),a.invalid>0&&(0,s.jsxs)("span",{style:{color:"#d63638",fontWeight:600,marginLeft:16},children:[a.invalid," ",(0,t.__)("invalid","blaze-ai-discovery-for-woocommerce")]}),a.ineligible>0&&(0,s.jsxs)("span",{style:{color:"#996800",fontWeight:600,marginLeft:16},children:[a.ineligible," ",(0,t.__)("not searchable yet","blaze-ai-discovery-for-woocommerce")]})]}),a.truncated&&(0,s.jsx)("p",{style:{color:"#757575",fontSize:13},children:(0,t.sprintf)(/* translators: %s: number of rows checked */ /* translators: %s: number of rows checked */ 26 (0,t.__)("Checked the first %s rows of the feed.","blaze-ai-discovery-for-woocommerce"),a.checked)}),a.issues?.length>0&&(0,s.jsxs)("div",{style:{marginTop:12},children:[(0,s.jsx)("h4",{children:(0,t.__)("Issues to fix:","blaze-ai-discovery-for-woocommerce")}),a.issues.map((e,r)=>(0,s.jsxs)("div",{style:{padding:"8px 0",borderBottom:"1px solid #eee"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("ul",{style:{margin:"4px 0 0",paddingLeft:20},children:e.issues.map((e,r)=>(0,s.jsx)("li",{style:{fontSize:13,color:"#555"},children:e},r))})]},r))]})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)("Generate a feed to see validation results.","blaze-ai-discovery-for-woocommerce")})})]}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("How to Submit to ChatGPT","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("ol",{style:{lineHeight:1.8},children:[(0,s.jsx)("li",{children:(0,t.__)('Click "Generate Feed", then "Download CSV" — CSV is the format OpenAI ingests.',"blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Apply to the merchant programme at","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://chatgpt.com/merchants",target:"_blank",rel:"noopener noreferrer",children:"chatgpt.com/merchants"}),"."]}),(0,s.jsx)("li",{children:(0,t.__)("Once approved, OpenAI gives you an SFTP endpoint. Upload the CSV there and re-upload whenever your catalogue changes.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Want automatic SFTP delivery or help with merchant-programme onboarding? Ask on the","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://wordpress.org/support/plugin/blaze-ai-discovery-for-woocommerce/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("support forum","blaze-ai-discovery-for-woocommerce")})," ",(0,t.__)("and we will work with you.","blaze-ai-discovery-for-woocommerce")]})]})})]})]})},"blazeaid-visibility":function(){const[e,i]=(0,r.useState)(!0),[a,l]=(0,r.useState)(null),[c,u]=(0,r.useState)(null),[m,h]=(0,r.useState)(!1),[p,y]=(0,r.useState)(!1),[g,x]=(0,r.useState)(null),[_,j]=(0,r.useState)(!1),[z,k]=(0,r.useState)(!1),S=(0,r.useRef)(null),C=(0,r.useRef)(!1),A=()=>{S.current&&(S.current(),S.current=null)},B=e=>{h(!!e?.consent),u(e?.payload||null),l(e?.state||"empty")},I=()=>{i(!0),x(null),j(!1),k(!1),n()({path:"/blazeaid/v1/visibility"}).then(e=>{C.current||(B(e),i(!1),"pending"===e?.state&&T())}).catch(e=>{C.current||(l(null),k(!0),i(!1),x(b(f(e))||(0,t.__)("Could not load AI visibility data. Reload the page to try again.","blaze-ai-discovery-for-woocommerce")))})},T=()=>{A(),S.current=v({request:()=>n()({path:"/blazeaid/v1/visibility"}),onData:e=>{e&&"pending"!==e.state&&B(e)},isDone:e=>!(!e||"pending"===e.state),intervalMs:5e3,maxMs:12e4,onStop:e=>{if(S.current=null,C.current)return;if(y(!1),"timeout"===e)return j(!0),void x((0,t.__)("Still fetching — check back shortly.","blaze-ai-discovery-for-woocommerce"));const r=w(e);r&&(k(!0),x(b(r)))}})};(0,r.useEffect)(()=>(C.current=!1,I(),()=>{C.current=!0,A()}),[]);const R=e=>{y(!0),n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(()=>{C.current||(y(!1),A(),I())}).catch(()=>y(!1))};if(e)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const P=c?.period?.label||(0,t.__)("last 30 days","blaze-ai-discovery-for-woocommerce"),W=(Array.isArray(c?.sections)?c.sections:[]).length>0,N="empty"===a||"ready"===a&&!W,M="pending"===a&&!_,$=m&&"consent_off"!==a&&!M&&!p;return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20,gap:16,flexWrap:"wrap"},children:[(0,s.jsx)("h1",{style:{margin:0},children:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==a&&(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{y(!0),x(null),j(!1),k(!1),n()({path:"/blazeaid/v1/visibility/refresh",method:"POST"}).then(e=>{if(!C.current){if(e&&e.queued)return u(null),l("pending"),void T();e&&e.payload?(u(e.payload),l("ready")):l("empty"),y(!1)}}).catch(e=>{if(!C.current){if(y(!1),e&&"consent_off"===e.state)return h(!1),u(null),void l("consent_off");x(b(f(e))||(0,t.__)("Could not start a refresh. Please try again.","blaze-ai-discovery-for-woocommerce"))}})},disabled:!$,children:M||p?(0,t.__)("Refreshing…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Refresh","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsx)("p",{style:{color:"#757575",marginBottom:16},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ /* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ 27 (0,t.__)("How often AI assistants (ChatGPT, Google AI) mentioned your store over the %s, and who gets named instead.","blaze-ai-discovery-for-woocommerce"),P)}),g&&(0,s.jsx)("p",{style:{color:z?"#d63638":"#856404",marginBottom:16},role:z?"alert":"status",children:g}),"consent_off"===a&&(0,s.jsx)(d,{consent:{granted:!1,decided:!0},onToggle:R,busy:p,style:{marginTop:16}}),M&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:12},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{style:{margin:0,color:"#555"},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "last 30 days" */ /* translators: %s: reporting window, e.g. "last 30 days" */ 28 (0,t.__)("Fetching AI visibility data for the %s — this runs in the background and usually takes under a minute.","blaze-ai-discovery-for-woocommerce"),P)})]})}),"ready"===a&&W&&(0,s.jsx)(ce,{payload:c}),N&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(le,{notices:c?.notices}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("p",{style:{margin:0,color:"#555"},children:["ready"===a?(0,t.__)("No AI visibility data is available for this period yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("AI visibility data has not been fetched yet. Background scheduling is unavailable on this site, so use Refresh to fetch it now.","blaze-ai-discovery-for-woocommerce")," ",(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")]})})})]}),"ready"===a&&W&&(0,s.jsx)("p",{style:{color:"#757575",fontSize:13},children:(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==a&&(0,s.jsx)(d,{consent:{granted:!0,decided:!0},onToggle:R,busy:p,style:{marginTop:16}})]})}},ue=document.getElementById("blazeaid-root");if(ue){const e=de[window.blazeaid?.currentPage||"blazeaid"]||q;(0,r.render)((0,s.jsx)(e,{}),ue)}})(); -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/readme.txt
r3672021 r3673252 5 5 Tested up to: 7.1 6 6 Requires PHP: 7.4 7 Stable tag: 1.1. 27 Stable tag: 1.1.3 8 8 License: GPLv2 or later 9 9 License URI: https://www.gnu.org/licenses/gpl-2.0.html … … 41 41 42 42 **Store audit, including Core Web Vitals** 43 Eleven diagnostic checks covering what affects AI discoverability: WooCommerce version, SSL, REST API, existing schema, product data quality, robots.txt rules for AI crawlers, crawler access, Google for WooCommerce status, existing feed plugins, llms.txt and — with cloud checks on — mobile Core Web Vitals measured from real Chrome users.43 Twelve diagnostic checks covering what affects AI discoverability: WooCommerce version, store visibility (WooCommerce "Coming soon" mode), SSL, REST API, existing schema, product data quality, robots.txt rules for AI crawlers, crawler access, Google for WooCommerce status, existing feed plugins, llms.txt and — with cloud checks on — mobile Core Web Vitals measured from real Chrome users. 44 44 45 45 = Key Features = … … 51 51 * AI traffic attribution dashboard with platform breakdown and revenue tracking 52 52 * Order attribution — traces AI-referred visits through to WooCommerce orders 53 * Enhanced Schema.org/JSON-LD that augments Yoast SEOor Rank Math (never duplicates)53 * Enhanced Schema.org/JSON-LD that augments your store's Product schema whether it is printed by WooCommerce, Yoast SEO (with its WooCommerce SEO add-on), or Rank Math (never duplicates) 54 54 * Google Merchant Center data quality audit 55 55 * Automatic llms.txt generation 56 * Store readiness audit with 1 1diagnostic checks56 * Store readiness audit with 12 diagnostic checks 57 57 * Core Web Vitals — mobile field data (LCP, INP, CLS, TTFB) from real Chrome users 58 58 * Zero-config — starts tracking the moment you activate … … 113 113 = Does it work with Yoast SEO or Rank Math? = 114 114 115 Yes. The plugin detects which SEO plugin you're using and augments its schema output using the plugin's ownfilter hooks. It never creates duplicate schema blocks. Tested with Yoast SEO, Yoast WooCommerce SEO, and Rank Math.115 Yes. The plugin detects which system prints your Product schema — WooCommerce itself, Yoast's WooCommerce SEO add-on, or Rank Math — and augments that output through its filter hooks. It never creates duplicate schema blocks. Tested with Yoast SEO, Yoast WooCommerce SEO, and Rank Math. 116 116 117 117 = What AI platforms can it detect? = … … 148 148 149 149 == Changelog == 150 151 = 1.1.3 = 152 * Fixed: product pages returned HTTP 500 and product saves failed on WooCommerce 8.0–9.1 (a WooCommerce 9.2+ method is now guarded) 153 * Fixed: orders placed through the Checkout block (Store API) are now attributed to AI referrals; previously only the classic shortcode checkout was 154 * Fixed: database tables are created on the first request with WooCommerce when the plugin was activated before WooCommerce, and repaired automatically if missing; the schema version is recorded only after every table exists, and a restricted database user sees a notice naming the missing tables 155 * Fixed: multisite — network activation installs every site, new subsites are installed automatically, network uninstall cleans every site 156 * Fixed: /llms.txt returned 404 after activation on some sites; the rewrite rule is registered before the rules are flushed and removed on deactivation 157 * Fixed: deactivation cancels the scoring healthcheck job along with every other background job 158 * Feed: generation runs as a background job with progress on the Feed page; products are processed in pages of 200 so large catalogues no longer exhaust memory (catalogues of 500 or fewer still generate instantly); works on hosts where WordPress cannot write files directly; write failures show an error instead of a blank 500 159 * Feed: is_eligible_search reflects stock, purchasability, status and visibility; validation reads the written file (first 2,000 rows) and lists not-yet-searchable products separately 160 * Attribution: the AI platform is derived on the server from the referrer host and utm_source, so visits from lookalike referrer domains are no longer credited to an AI platform; the tracker signature stays valid for 30 days and is refreshed automatically on long-cached pages (for up to 400 days from when the page was cached) 161 * Retention: cleanup deletes everything older than 90 days in batches (was capped at 1,000 rows a day) and now also covers attributed orders 162 * New "Store visibility" audit row: fails while WooCommerce "Coming soon" mode is on and links to Settings → Site visibility 163 * Audit: the REST API, robots.txt and llms.txt rows report "Could not verify" with the HTTP code when the site answers the plugin's own request with 401/403/407/429, a server error or a bot challenge, instead of a pass; the self-fetch also requests one published product page and never takes more than 20 s 164 * Audit: "Run audit now" finishes within a request — local checks run in full, cloud checks share a 12 s budget and rows that do not fit show as pending until the background audit fills them in 165 * Cloud: a response that is not the expected JSON is never cached as an empty result; transient failures (connection errors, 429, 5xx) are retried once; new filter blazeaid_cloud_retry_delay 166 * Scoring: batch scoring resumes from the last product actually scored, retries a stalled chunk three times and then marks the run failed with a reason; a second run cannot start while one is running 167 * Admin: pages say when the REST API is blocked (session expired or a security plugin) or answers with something other than JSON; every status poll stops after 20 minutes and when the page is left 168 * Schema: enhancement now works with Yoast SEO free and Rank Math — Yoast free stores augment WooCommerce's own Product block (only the Yoast WooCommerce SEO add-on replaces it), and the Rank Math integration now matches the payload Rank Math actually passes to its filter 169 * Schema: Schema Pro stores no longer get a second Product JSON-LD block from this plugin; the plugin augments WooCommerce's block instead 150 170 151 171 = 1.1.2 = … … 218 238 == Upgrade Notice == 219 239 240 = 1.1.3 = 241 Compatibility release: fixes product-page errors on WooCommerce 8.0–9.1, attribution for the Checkout block, feed generation on large catalogues, and installs where the plugin was activated before WooCommerce. Update recommended for every store. 242 220 243 = 1.1.2 = 221 244 The Dashboard keeps checking for the first audit and can run it immediately; background jobs can be run on demand when the site's queue is behind. Site verification works on sites whose security plugin rejects unauthenticated REST requests. Admin pages load on WordPress 6.4 and 6.5. -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Attribution/CookieBridge.php
r3670977 r3673252 5 5 * JS sets cookies on AI referral detection. This class reads them at 6 6 * add-to-cart (always uncached) and stores attribution in the WC session 7 * so it survives through to checkout. 7 * so it survives through to checkout; OrderAttributor also reads the 8 * cookies directly for Store API (Checkout block) orders. 8 9 * 9 10 * @package BlazeAiDiscovery … … 47 48 } 48 49 50 $attribution = self::read_cookies(); 51 if ( null === $attribution ) { 52 return; 53 } 54 55 WC()->session->set( self::SESSION_KEY, $attribution ); 56 } 57 58 /** 59 * Read and normalise the tracker cookies on the current request. 60 * 61 * @return array{source: string, referred_at: int, landing_page: string}|null Null when no recognised source cookie is present. 62 */ 63 public static function read_cookies(): ?array { 49 64 // phpcs:disable WordPress.Security.ValidatedSanitizedInput 50 65 $source = isset( $_COOKIE[ self::COOKIE_SRC ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE_SRC ] ) ) : ''; … … 54 69 55 70 if ( empty( $source ) ) { 56 return ;71 return null; 57 72 } 58 73 59 74 $source = self::normalise_source( $source ); 60 $lp = self::normalise_landing( $lp );61 62 75 if ( null === $source ) { 63 return ;76 return null; 64 77 } 65 78 66 WC()->session->set( 67 self::SESSION_KEY, 68 [ 69 'source' => $source, 70 'referred_at' => $ts, 71 'landing_page' => $lp, 72 ] 73 ); 79 return [ 80 'source' => $source, 81 'referred_at' => $ts, 82 'landing_page' => self::normalise_landing( $lp ), 83 ]; 74 84 } 75 85 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Attribution/InlineTracker.php
r3670977 r3673252 5 5 * Modeled on Independent Analytics: inline script survives page caching, 6 6 * uses requestIdleCallback for zero Core Web Vitals impact, and sends 7 * data to a local REST endpoint via fetch with keepalive. 7 * data to a local REST endpoint via fetch with keepalive. Referrer hosts 8 * are matched host-anchored (the server re-derives the platform anyway), 9 * and a stale signature from a long-cached page is retried once with the 10 * fresh one the endpoint hands back. 8 11 * 9 12 * @package BlazeAiDiscovery … … 85 88 'var hash=window.location.hash||\'\';' . 86 89 'var platform=null;var method=null;' . 87 'var refLower=ref.toLowerCase();var rm=c.referrerMap;' . 88 'for(var domain in rm){if(refLower.indexOf(domain)!==-1){platform=rm[domain];method=\'referrer\';break;}}' . 90 // Host-anchored referrer match: exact host or a subdomain of it, plus the path prefix when the pattern has one. 91 'var refHost=\'\',refPath=\'/\';' . 92 'if(ref){try{var u=new URL(ref);refHost=(u.hostname||\'\').toLowerCase();refPath=u.pathname||\'/\';}catch(e){}}' . 93 'if(refHost){var rm=c.referrerMap;for(var d in rm){var i=d.indexOf(\'/\');var dh=i===-1?d:d.slice(0,i);var dp=i===-1?\'\':d.slice(i);' . 94 'if((refHost===dh||refHost.slice(-(dh.length+1))===\'.\'+dh)&&(!dp||refPath.indexOf(dp)===0)){platform=rm[d];method=\'referrer\';break;}}}' . 89 95 'if(!platform){var src=(params.get(\'utm_source\')||\'\').toLowerCase();if(src){var um=c.utmMap;if(um[src]){platform=um[src];method=\'utm\';}}}' . 90 96 'if(!platform&&hash.indexOf(\':~:text=\')!==-1){platform=\'google_ai\';method=\'text_fragment\';}' . … … 94 100 'utm_campaign:params.get(\'utm_campaign\')||null,search_query:params.get(\'q\')||params.get(\'query\')||null,' . 95 101 'payload:c.payload,signature:c.signature};' . 96 'var json=JSON.stringify(body);' . 97 'if(navigator.sendBeacon){navigator.sendBeacon(c.endpoint,new Blob([json],{type:\'application/json\'}));}' . 98 'else if(window.fetch){fetch(c.endpoint,{method:\'POST\',body:json,headers:{\'Content-Type\':\'application/json\'},keepalive:true});}' . 99 'else{var xhr=new XMLHttpRequest();xhr.open(\'POST\',c.endpoint);xhr.setRequestHeader(\'Content-Type\',\'application/json\');xhr.send(json);}' . 102 // fetch first: it returns the response, so a stale signature (page cached past the window) can be re-signed and retried once. 103 'var send=function(sig,retry){body.signature=sig;var json=JSON.stringify(body);' . 104 'if(window.fetch){fetch(c.endpoint,{method:\'POST\',body:json,headers:{\'Content-Type\':\'application/json\'},keepalive:true})' . 105 '.then(function(r){return r.json();}).then(function(d){if(retry&&d&&typeof d.resign===\'string\'&&d.resign){send(d.resign,false);}}).catch(function(){});}' . 106 'else if(navigator.sendBeacon){navigator.sendBeacon(c.endpoint,new Blob([json],{type:\'application/json\'}));}' . 107 'else{var xhr=new XMLHttpRequest();xhr.open(\'POST\',c.endpoint);xhr.setRequestHeader(\'Content-Type\',\'application/json\');xhr.send(json);}};' . 108 'send(c.signature,true);' . 100 109 'var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);var ex=\'expires=\'+d.toUTCString();' . 101 110 'var sec=(location.protocol===\'https:\')?\';Secure\':\'\';' . -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Attribution/OrderAttributor.php
r3666933 r3673252 3 3 * Tags WooCommerce orders with AI attribution data. 4 4 * 5 * Reads from WC session (populated by CookieBridge) at checkout 6 * and writes HPOS-compatible order meta + blazeaid_orders table row. 5 * Reads the attribution captured by the tracker (WC session first, the 6 * tracker cookies as a fallback) when an order is created and writes 7 * HPOS-compatible order meta plus a blazeaid_orders table row. 7 8 * 8 9 * @package BlazeAiDiscovery … … 15 16 class OrderAttributor { 16 17 18 /** Order meta set once an order has been through attribution (dedupes the two checkout hooks). */ 19 public const ATTRIBUTED_META = '_blazeaid_attributed'; 20 17 21 public function register(): void { 18 // HPOS-compatible hook — fires for all order types.22 // Shortcode checkout: fired by WC_Checkout::create_order(). 19 23 add_action( 'woocommerce_checkout_order_created', [ $this, 'attribute_order' ], 10, 1 ); 24 25 // Checkout block / Store API: fired by the Store API checkout routes, 26 // which deliberately do not fire woocommerce_checkout_order_created. 27 add_action( 'woocommerce_store_api_checkout_order_processed', [ $this, 'attribute_order' ], 10, 1 ); 20 28 } 21 29 22 30 /** 23 * Attribute an order to an AI source if session has attribution data. 31 * Attribute an order to an AI source if the session or the tracker 32 * cookies carry attribution data. Idempotent per order. 24 33 * 25 34 * @param \WC_Order $order The newly created order. 26 35 */ 27 36 public function attribute_order( \WC_Order $order ): void { 28 $attribution = CookieBridge::get_from_session(); 37 if ( '' !== (string) $order->get_meta( self::ATTRIBUTED_META ) ) { 38 return; 39 } 40 41 // The Store API never renders the checkout form, so the session may 42 // be empty even though the tracker cookies are on the request. 43 $attribution = CookieBridge::get_from_session() ?? CookieBridge::read_cookies(); 29 44 30 45 if ( null === $attribution ) { … … 40 55 $order->update_meta_data( '_blazeaid_referred_at', $referred_at ); 41 56 $order->update_meta_data( '_blazeaid_landing_page', $landing ); 57 $order->update_meta_data( self::ATTRIBUTED_META, 1 ); 42 58 $order->save(); 43 59 44 // Write to attribution orders table .60 // Write to attribution orders table (order_id is unique there too). 45 61 global $wpdb; 46 62 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Attribution/PayloadSignature.php
r3670977 r3673252 3 3 * Cache-compatible payload signature (replaces WordPress nonces). 4 4 * 5 * HMAC-SHA256 over a UTC day bucket + canonical JSON. Standard WordPress 6 * nonces break with page caching because they expire and are embedded in 7 * cached HTML; a day-bucketed HMAC lets a page cached today still validate 8 * tomorrow while a scraped signature can't be replayed indefinitely. 5 * HMAC-SHA256 over a UTC day bucket + canonical JSON, prefixed with the 6 * bucket it was issued in: `<issued>.<hmac>`. Standard WordPress nonces 7 * break with page caching because they expire and are embedded in cached 8 * HTML; a day-bucketed HMAC lets a page cached today still validate for a 9 * month. A signature older than the window but still ours is re-issued 10 * once per request so the tracker on a long-cached page can retry; the 11 * renewed form `<issued>.<renewed>.<hmac>` keeps the original issue bucket, 12 * and nothing is renewed past STALE_DAYS after that original issue — so a 13 * scraped signature cannot be kept alive indefinitely by renewing it every 14 * month. 15 * 16 * Signatures without a prefix (pages cached before 1.1.3) are verified by 17 * trying each bucket of the window; they are gone from caches within 18 * WINDOW_DAYS of the upgrade. 9 19 * 10 20 * @package BlazeAiDiscovery … … 19 29 private const SALT_OPTION = 'blazeaid_payload_salt'; 20 30 21 /** 22 * HMAC-SHA256 over a UTC day bucket + canonical JSON. Cache-safe: a page cached 23 * today still validates for at least 48 hours (window = 3 buckets by default). 31 /** Buckets (UTC days) a signature stays valid for: covers pages cached for a month. */ 32 public const WINDOW_DAYS = 30; 33 34 /** 35 * Days after the ORIGINAL issue in which a signature is still recognised 36 * as ours and re-issued, though no longer accepted as-is. Renewal never 37 * moves this bound. 38 */ 39 public const STALE_DAYS = 400; 40 41 /** `<issued>.<hmac>` or `<issued>.<renewed>.<hmac>`; buckets are UTC Ymd. */ 42 private const PREFIXED = '/^(\d{8})(?:\.(\d{8}))?\.([0-9a-f]{64})$/'; 43 44 /** A signature from before 1.1.3: the bare HMAC. */ 45 private const PLAIN = '/^[0-9a-f]{64}$/'; 46 47 /** 48 * Sign a payload. 24 49 * 25 50 * @param array $payload Data to sign. 26 * @param string|null $bucket UTC Ymd; defaults to today. 27 * @return string HMAC-SHA256 hex signature. 28 */ 29 public static function generate( array $payload, ?string $bucket = null ): string { 51 * @param string|null $bucket UTC Ymd the signature is valid from; defaults to today. 52 * @param string|null $issued UTC Ymd of the original issue when renewing; defaults to $bucket. 53 * @return string `<issued>.<hmac>` (or `<issued>.<renewed>.<hmac>` when renewed). 54 */ 55 public static function generate( array $payload, ?string $bucket = null, ?string $issued = null ): string { 30 56 $bucket = $bucket ?? gmdate( 'Ymd' ); 31 return hash_hmac( 'sha256', $bucket . wp_json_encode( $payload ), self::get_salt() ); 32 } 33 34 /** 35 * Validate an incoming signature against a payload, accepting today's, yesterday's, 36 * and the day before's UTC day bucket — a guaranteed window of at least 48 hours even 37 * for a page cached right before a UTC day boundary (filterable via 38 * `blazeaid_signature_window_days`). 57 $issued = $issued ?? $bucket; 58 $prefix = $issued === $bucket ? $issued : $issued . '.' . $bucket; 59 60 return $prefix . '.' . self::hmac( $prefix, $payload ); 61 } 62 63 /** 64 * Validate an incoming signature against a payload: the bucket it is 65 * valid from must be today's or one of the previous WINDOW_DAYS - 1 UTC 66 * day buckets (filterable via `blazeaid_signature_window_days`). 67 * Full-page caches routinely keep a product page for a week (LiteSpeed 68 * default) or until purged (WP Rocket, Cloudflare), so the window has 69 * to outlive them. 39 70 * 40 71 * @param string $signature The signature to validate. … … 43 74 */ 44 75 public static function validate( string $signature, array $payload ): bool { 45 $window = max( 1, (int) apply_filters( 'blazeaid_signature_window_days', 3 ) ); 46 for ( $i = 0; $i < $window; $i++ ) { 47 $bucket = gmdate( 'Ymd', time() - $i * DAY_IN_SECONDS ); 48 if ( hash_equals( self::generate( $payload, $bucket ), $signature ) ) { 49 return true; 76 $parts = self::parse( $signature, $payload ); 77 if ( null !== $parts ) { 78 return $parts['age'] >= 0 && $parts['age'] < self::window(); 79 } 80 81 return null !== self::plain_bucket( $signature, $payload, 0, self::window() ); 82 } 83 84 /** 85 * Whether a signature is one we issued for this payload, but older than 86 * the accepted window (a page cached longer than WINDOW_DAYS) — and 87 * still within STALE_DAYS of its original issue, so it may be renewed. 88 */ 89 public static function is_stale( string $signature, array $payload ): bool { 90 return null !== self::stale_issue( $signature, $payload ); 91 } 92 93 /** 94 * A fresh signature for the payload when the presented one is stale, so a 95 * tracker running on a long-cached page can retry once and recover. The 96 * fresh signature carries the original issue bucket forward, so the 97 * renewal chain ends STALE_DAYS after the first issue. 98 * 99 * @return string|null Fresh signature, or null when the presented one is not ours or too old to renew. 100 */ 101 public static function resign_if_stale( string $signature, array $payload ): ?string { 102 $issued = self::stale_issue( $signature, $payload ); 103 104 return null === $issued ? null : self::generate( $payload, null, $issued ); 105 } 106 107 private static function window(): int { 108 return max( 1, (int) apply_filters( 'blazeaid_signature_window_days', self::WINDOW_DAYS ) ); 109 } 110 111 /** 112 * The original issue bucket of a stale signature, or null when it is 113 * not ours, still valid, or past STALE_DAYS. 114 */ 115 private static function stale_issue( string $signature, array $payload ): ?string { 116 $parts = self::parse( $signature, $payload ); 117 if ( null !== $parts ) { 118 if ( $parts['age'] < self::window() ) { 119 return null; // Valid (or from the future): nothing to renew. 50 120 } 51 } 52 return false; 121 $issued_age = self::age( $parts['issued'] ); 122 if ( null === $issued_age || $issued_age >= self::STALE_DAYS ) { 123 return null; 124 } 125 return $parts['issued']; 126 } 127 128 return self::plain_bucket( $signature, $payload, self::window(), self::STALE_DAYS ); 129 } 130 131 /** 132 * Verify a prefixed signature and read its buckets. 133 * 134 * @return array{issued: string, age: int}|null issued: original bucket; age: days since the bucket it is valid from. Null when malformed or not ours. 135 */ 136 private static function parse( string $signature, array $payload ): ?array { 137 if ( 1 !== preg_match( self::PREFIXED, $signature, $m ) ) { 138 return null; 139 } 140 $issued = $m[1]; 141 $renewed = '' === ( $m[2] ?? '' ) ? null : $m[2]; 142 $prefix = null === $renewed ? $issued : $issued . '.' . $renewed; 143 144 if ( ! hash_equals( self::hmac( $prefix, $payload ), $m[3] ) ) { 145 return null; 146 } 147 148 $age = self::age( $renewed ?? $issued ); 149 if ( null === $age || null === self::age( $issued ) ) { 150 return null; 151 } 152 153 return [ 154 'issued' => $issued, 155 'age' => $age, 156 ]; 157 } 158 159 /** 160 * Pre-1.1.3 form: constant-time comparison against every bucket from 161 * $from (inclusive) to $to (exclusive) days ago. 162 * 163 * @return string|null The matching bucket, or null. 164 */ 165 private static function plain_bucket( string $signature, array $payload, int $from, int $to ): ?string { 166 if ( 1 !== preg_match( self::PLAIN, $signature ) ) { 167 return null; 168 } 169 $now = time(); 170 for ( $i = $from; $i < $to; $i++ ) { 171 $bucket = gmdate( 'Ymd', $now - $i * DAY_IN_SECONDS ); 172 if ( hash_equals( self::hmac( $bucket, $payload ), $signature ) ) { 173 return $bucket; 174 } 175 } 176 return null; 177 } 178 179 /** 180 * Whole UTC days from a Ymd bucket to today (negative for a future 181 * bucket), or null when it is not a calendar date. 182 */ 183 private static function age( string $bucket ): ?int { 184 $year = (int) substr( $bucket, 0, 4 ); 185 $month = (int) substr( $bucket, 4, 2 ); 186 $day = (int) substr( $bucket, 6, 2 ); 187 if ( 8 !== strlen( $bucket ) || ! checkdate( $month, $day, $year ) ) { 188 return null; 189 } 190 191 $then = gmmktime( 0, 0, 0, $month, $day, $year ); 192 $today = gmmktime( 0, 0, 0, (int) gmdate( 'n' ), (int) gmdate( 'j' ), (int) gmdate( 'Y' ) ); 193 194 return (int) round( ( $today - $then ) / DAY_IN_SECONDS ); 195 } 196 197 private static function hmac( string $prefix, array $payload ): string { 198 return hash_hmac( 'sha256', $prefix . wp_json_encode( $payload ), self::get_salt() ); 53 199 } 54 200 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Attribution/Platforms.php
r3668873 r3673252 13 13 14 14 /** 15 * Layer 1: Referrer domain patterns for JS document.referrer matching. 16 * Key = platform slug, value = array of domain substrings. 15 * Layer 1: Referrer host patterns, matched host-anchored (exact host or 16 * subdomain) by the inline JS and again by the /track endpoint. An entry 17 * may carry a path prefix (x.com/i/grok). 18 * Key = platform slug, value = array of host[/path] patterns. 17 19 * 18 20 * @return array<string, string[]> … … 127 129 128 130 /** 131 * Resolve the platform a referrer URL belongs to. The host must be the 132 * pattern host or a subdomain of it (chat.openai.com matches 133 * "openai.com"-style patterns, "evilchatgpt.com" does not); patterns that 134 * carry a path (x.com/i/grok) also require that path prefix. 135 * 136 * @param string $referrer Full referrer URL. 137 * @return string|null Platform slug, or null when the host is not an AI platform. 138 */ 139 public static function platform_from_referrer( string $referrer ): ?string { 140 $host = strtolower( (string) wp_parse_url( $referrer, PHP_URL_HOST ) ); 141 if ( '' === $host ) { 142 return null; 143 } 144 $path = (string) wp_parse_url( $referrer, PHP_URL_PATH ); 145 146 foreach ( self::referrer_patterns() as $platform => $patterns ) { 147 foreach ( $patterns as $pattern ) { 148 $slash = strpos( $pattern, '/' ); 149 $pattern_host = false === $slash ? $pattern : substr( $pattern, 0, $slash ); 150 $pattern_path = false === $slash ? '' : substr( $pattern, $slash ); 151 152 if ( ! self::host_matches( $host, $pattern_host ) ) { 153 continue; 154 } 155 if ( '' !== $pattern_path && 0 !== strpos( $path, $pattern_path ) ) { 156 continue; 157 } 158 return $platform; 159 } 160 } 161 162 return null; 163 } 164 165 /** 166 * Whether $host is $domain or a subdomain of it. 167 */ 168 public static function host_matches( string $host, string $domain ): bool { 169 $host = strtolower( $host ); 170 $domain = strtolower( $domain ); 171 if ( '' === $host || '' === $domain ) { 172 return false; 173 } 174 if ( $host === $domain ) { 175 return true; 176 } 177 $suffix = '.' . $domain; 178 return substr( $host, -strlen( $suffix ) ) === $suffix; 179 } 180 181 /** 182 * Resolve the platform for a utm_source value (exact, case-insensitive). 183 * 184 * @return string|null Platform slug or null. 185 */ 186 public static function platform_from_utm_source( string $source ): ?string { 187 $source = strtolower( trim( $source ) ); 188 if ( '' === $source ) { 189 return null; 190 } 191 return self::js_utm_map()[ $source ] ?? null; 192 } 193 194 /** 129 195 * Build JS-compatible referrer pattern map for inline script. 130 196 * Returns a flat object: { "chatgpt.com": "chatgpt", "chat.openai.com": "chatgpt", ... } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Attribution/TrackingEndpoint.php
r3670977 r3673252 4 4 * 5 5 * Public endpoint (no auth) protected by payload signature validation. 6 * Receives AI referral data from the inline JS tracker and stores it. 6 * Receives AI referral data from the inline JS tracker and stores it; the 7 * platform is derived server-side from the referrer host and utm_source. 7 8 * 8 9 * @package BlazeAiDiscovery … … 34 35 * Handle an incoming tracking request. 35 36 * 37 * The platform is derived here from the referrer host and utm_source — 38 * never trusted from the body. A well-formed but expired signature (a 39 * page cached longer than the window) is answered with a fresh one so 40 * the tracker can retry once. 41 * 36 42 * @param \WP_REST_Request $request The request. 37 43 * @return \WP_REST_Response … … 39 45 public function handle_track( \WP_REST_Request $request ): \WP_REST_Response { 40 46 $body = $request->get_json_params(); 47 $body = is_array( $body ) ? $body : []; 41 48 42 49 // Validate required fields. … … 50 57 // Validate signature (silently reject — don't reveal failure reason). 51 58 if ( ! PayloadSignature::validate( $signature, $payload ) ) { 59 $fresh = PayloadSignature::resign_if_stale( $signature, $payload ); 60 if ( null !== $fresh ) { 61 return new \WP_REST_Response( [ 'success' => false, 'resign' => $fresh ], 200 ); 62 } 52 63 return new \WP_REST_Response( [ 'success' => false ], 200 ); 53 64 } 65 66 $detected = self::detect( $body ); 67 if ( null === $detected ) { 68 return new \WP_REST_Response( [ 'success' => false ], 200 ); 69 } 70 [ $platform, $detection_method ] = $detected; 54 71 55 72 $landing = is_string( $payload['url'] ?? null ) ? $payload['url'] : ''; … … 59 76 if ( ! WriteGuard::allow( 'visit:' . $hash . ':' . md5( $landing ), 10 * MINUTE_IN_SECONDS ) || ! WriteGuard::under_daily_cap( 'visits', (int) $caps['visits'] ) ) { 60 77 return new \WP_REST_Response( [ 'success' => true ], 200 ); // Accepted, deliberately not stored. 61 }62 63 $platform = sanitize_text_field( $body['platform'] ?? '' );64 $detection_method = sanitize_text_field( $body['detection_method'] ?? '' );65 66 if ( empty( $platform ) || empty( $detection_method ) ) {67 return new \WP_REST_Response( [ 'success' => false ], 200 );68 }69 70 $allowed_platforms = array_keys( Platforms::referrer_patterns() + [ 'google_ai' => [], 'other_ai' => [] ] );71 if ( ! in_array( $platform, $allowed_platforms, true ) ) {72 $platform = 'other_ai';73 }74 75 $allowed_methods = [ 'referrer', 'utm', 'text_fragment' ];76 if ( ! in_array( $detection_method, $allowed_methods, true ) ) {77 return new \WP_REST_Response( [ 'success' => false ], 200 );78 78 } 79 79 … … 108 108 109 109 /** 110 * Derive platform and detection method server-side, in the same order 111 * the tracker does: referrer host, then utm_source, then the text 112 * fragment (which never reaches the server, so the client's 113 * detection_method is accepted as a hint for that layer only and the 114 * platform is fixed to google_ai). The client's platform field is 115 * ignored. 116 * 117 * @param array $body Decoded request body. 118 * @return array{0: string, 1: string}|null [ platform, method ] or null when nothing is detected. 119 */ 120 public static function detect( array $body ): ?array { 121 $referrer = is_string( $body['referrer_url'] ?? null ) ? $body['referrer_url'] : ''; 122 if ( '' !== $referrer ) { 123 $platform = Platforms::platform_from_referrer( $referrer ); 124 if ( null !== $platform ) { 125 return [ $platform, 'referrer' ]; 126 } 127 } 128 129 $utm_source = is_string( $body['utm_source'] ?? null ) ? $body['utm_source'] : ''; 130 if ( '' !== $utm_source ) { 131 $platform = Platforms::platform_from_utm_source( $utm_source ); 132 if ( null !== $platform ) { 133 return [ $platform, 'utm' ]; 134 } 135 } 136 137 $hint = is_string( $body['detection_method'] ?? null ) ? $body['detection_method'] : ''; 138 if ( 'text_fragment' === $hint ) { 139 return [ 'google_ai', 'text_fragment' ]; 140 } 141 142 return null; 143 } 144 145 /** 110 146 * @param mixed $url Raw request value; must be typed-checked since callers 111 147 * send arbitrary JSON (arrays would otherwise crash esc_url_raw()). -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/AuditRunner.php
r3672021 r3673252 11 11 12 12 use BlazeAiDiscovery\Audit\Checks\CheckInterface; 13 use BlazeAiDiscovery\Cloud\CloudClient; 13 14 use BlazeAiDiscovery\Database\Tables; 14 15 … … 16 17 17 18 /** 19 * Seconds the cloud checks (Core Web Vitals, the outside-in crawler 20 * probe) may spend together when the audit runs on a request thread 21 * (POST /audit/run { force: true }). Two 25 s cloud timeouts in a row 22 * blew past 60 s proxies; local checks run in full, cloud rows that do 23 * not fit come back `pending` and the queued background audit fills 24 * them in. 25 */ 26 public const INLINE_CLOUD_BUDGET = 12; 27 28 /** Row status for a cloud check that did not finish within the budget. */ 29 public const STATUS_PENDING = 'pending'; 30 31 /** 18 32 * Run all audit checks and save results. 19 33 * 20 * @return array{results: array, overall_status: string} 21 */ 22 public function run(): array { 34 * @param array{cloud_budget?: float|int} $options `cloud_budget`: seconds the cloud calls may take in total (default: unbounded, 25 s per call). 35 * @return array{results: array, overall_status: string, pending: bool} 36 */ 37 public function run( array $options = [] ): array { 38 $budget = isset( $options['cloud_budget'] ) && is_numeric( $options['cloud_budget'] ) 39 ? (float) $options['cloud_budget'] 40 : null; 41 42 // The budget clock starts at the first cloud call, not now: the 43 // local checks (two loopback fetches, up to 10 s each on a slow 44 // host) run first and must not spend the cloud checks' seconds. 45 CloudClient::set_budget( $budget ); 46 47 try { 48 return $this->run_checks( null !== $budget ); 49 } finally { 50 CloudClient::set_budget( null ); 51 } 52 } 53 54 /** 55 * @param bool $budgeted Whether the cloud calls share a request budget. 56 * @return array{results: array, overall_status: string, pending: bool} 57 */ 58 private function run_checks( bool $budgeted ): array { 23 59 $checks = [ 24 60 new Checks\WooCommerceVersion(), 61 new Checks\StoreVisibility(), 25 62 new Checks\SslActive(), 26 63 new Checks\RestApiAccessible(), … … 44 81 $results = []; 45 82 $worst = 'pass'; 83 $pending = false; 46 84 47 85 foreach ( $checks as $check ) { 48 $result = $this->run_check( $check ); 49 $result['check'] = $check->name(); 50 $results[] = $result; 86 // The budget-exhausted flag is read per check. 87 CloudClient::clear_budget_exhausted(); 88 89 $result = $this->run_check( $check ); 90 91 if ( $budgeted && CloudClient::budget_exhausted() && self::STATUS_PENDING !== $result['status'] ) { 92 $result = self::as_pending( $result ); 93 } 94 95 $result['check'] = $check->name(); 96 if ( self::STATUS_PENDING === $result['status'] ) { 97 $result['pending'] = true; 98 $pending = true; 99 } 100 $results[] = $result; 51 101 52 102 if ( 'fail' === $result['status'] ) { … … 60 110 'results' => $results, 61 111 'overall_status' => $worst, 112 'pending' => $pending, 62 113 ]; 63 114 … … 65 116 66 117 return $audit; 118 } 119 120 /** 121 * A check whose cloud call was skipped or cut short by the request 122 * budget: keep whatever it gathered locally, but the row is `pending` 123 * — the background audit replaces it — rather than a warning that 124 * reads like a verdict. 125 * 126 * @param array{status: string, message: string} $result The check's own result. 127 * @return array{status: string, message: string} 128 */ 129 public static function as_pending( array $result ): array { 130 $result['status'] = self::STATUS_PENDING; 131 $result['message'] = __( 'Cloud check still running — this row will update when the background audit finishes.', 'blaze-ai-discovery-for-woocommerce' ); 132 133 return $result; 134 } 135 136 /** 137 * @param array $audit An audit as returned by run() or get_latest(). 138 */ 139 public static function has_pending( array $audit ): bool { 140 foreach ( $audit['results'] ?? [] as $row ) { 141 if ( is_array( $row ) && self::STATUS_PENDING === ( $row['status'] ?? '' ) ) { 142 return true; 143 } 144 } 145 146 return false; 67 147 } 68 148 … … 119 199 } 120 200 121 return[201 $audit = [ 122 202 'id' => (int) $row->id, 123 203 'run_at' => $row->run_at, … … 125 205 'overall_status' => $row->overall_status, 126 206 ]; 207 208 $audit['pending'] = self::has_pending( $audit ); 209 210 return $audit; 127 211 } 128 212 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/Checks/CoreWebVitals.php
r3671993 r3673252 46 46 private const RATINGS = [ 'good', 'needs_improvement', 'poor' ]; 47 47 48 /** Top-level keys the /v1/cwv payload must carry (on top of `version`). */ 49 private const REQUIRED_KEYS = [ 'has_data' ]; 50 48 51 private const STATUS_BY_RATING = [ 49 52 'good' => 'pass', … … 78 81 79 82 if ( null === $payload ) { 80 $response = CloudClient::post( self::ENDPOINT, [] );83 $response = CloudClient::post( self::ENDPOINT, [], self::REQUIRED_KEYS ); 81 84 82 85 if ( is_wp_error( $response ) ) { … … 320 323 case 'disabled': 321 324 return $code; 325 case CloudClient::ERROR_BUDGET_EXHAUSTED: 326 return 'pending'; 327 case CloudClient::ERROR_BAD_PAYLOAD: 328 return 'bad_payload'; 322 329 default: 323 330 return 'http_error'; … … 330 337 * message; for errors it follows the local explanation. 331 338 * 332 * @param string $code consent_off | no_data | site_verification_failed | rate_limited | disabled | http_error | internal_error. 339 * A `pending` row (the inline audit's cloud budget ran out) carries 340 * status `pending`: the queued background audit replaces it. 341 * 342 * @param string $code consent_off | no_data | site_verification_failed | rate_limited | disabled | bad_payload | pending | http_error | internal_error. 333 343 * @param array $notices Raw server notices. 334 344 */ … … 343 353 344 354 $result = [ 345 'status' => ' warning',355 'status' => 'pending' === $code ? 'pending' : 'warning', 346 356 'message' => $message, 347 357 'notice' => $code, … … 371 381 case 'disabled': 372 382 return __( 'The Core Web Vitals service is temporarily unavailable. Re-run the audit later.', 'blaze-ai-discovery-for-woocommerce' ); 383 case 'pending': 384 return __( 'Cloud check still running — Core Web Vitals will appear here when the background audit finishes.', 'blaze-ai-discovery-for-woocommerce' ); 385 case 'bad_payload': 386 return __( 'The Core Web Vitals service answered with something other than a result (a network or firewall page, most likely). Re-run the audit later.', 'blaze-ai-discovery-for-woocommerce' ); 373 387 case 'internal_error': 374 388 return __( 'The Core Web Vitals check hit an unexpected error. Re-run the audit; if it keeps happening, contact Blaze Commerce support.', 'blaze-ai-discovery-for-woocommerce' ); -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/Checks/ExistingFeedPlugins.php
r3670977 r3673252 19 19 'wp-product-feed-manager/wp-product-feed-manager.php' => 'WP Product Feed Manager', 20 20 'woo-product-feed-pro/woocommerce-sea.php' => 'Product Feed PRO (alt)', 21 ' ctx-feed/ctx-feed.php'=> 'CTX Feed',21 'webappick-product-feed-for-woocommerce/woo-feed.php' => 'CTX Feed', 22 22 'pinterest-for-woocommerce/pinterest-for-woocommerce.php' => 'Pinterest for WooCommerce', 23 23 ]; -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/Checks/ExistingSchema.php
r3666933 r3673252 18 18 19 19 if ( CompatibilityDetector::YOAST === $detected ) { 20 $has_woo_seo = defined( 'WPSEO_WOO_VERSION' ); 21 if ( $has_woo_seo ) { 22 return [ 23 'status' => 'pass', 24 'message' => sprintf( 25 /* translators: %s: plugin name */ 26 __( '%s with WooCommerce SEO add-on detected. We augment its Product schema with additional AI-relevant properties.', 'blaze-ai-discovery-for-woocommerce' ), 27 $name 28 ), 29 ]; 30 } 20 // detect() only routes here once the WooCommerce SEO add-on is 21 // present (adm-F6); Yoast free is WOOCOMMERCE_NATIVE below. 31 22 return [ 32 23 'status' => 'pass', 33 24 'message' => sprintf( 34 25 /* translators: %s: plugin name */ 35 __( '%s detected. We augment its schema output. Consider adding Yoast WooCommerce SEO for richer Product schema.', 'blaze-ai-discovery-for-woocommerce' ),26 __( '%s with WooCommerce SEO add-on detected. We augment its Product schema with additional AI-relevant properties.', 'blaze-ai-discovery-for-woocommerce' ), 36 27 $name 37 28 ), … … 42 33 return [ 43 34 'status' => 'pass', 44 'message' => __( 'Rank Math detected. We augment its schema output with additional AI-relevant properties. ', 'blaze-ai-discovery-for-woocommerce' ),35 'message' => __( 'Rank Math detected. We augment its schema output with additional AI-relevant properties. If Rank Math\'s product schema is turned off, enable it or WooCommerce\'s own markup so a Product block is printed.', 'blaze-ai-discovery-for-woocommerce' ), 45 36 ]; 46 37 } … … 50 41 'status' => 'warning', 51 42 'message' => __( 'No SEO plugin detected. We generate standalone Product schema. Consider installing Yoast SEO or Rank Math for comprehensive site-wide schema.', 'blaze-ai-discovery-for-woocommerce' ), 43 ]; 44 } 45 46 if ( CompatibilityDetector::WOOCOMMERCE_NATIVE === $detected && CompatibilityDetector::installed( 'yoast' ) ) { 47 return [ 48 'status' => 'pass', 49 'message' => __( 'Yoast SEO is active without its WooCommerce SEO add-on, so WooCommerce prints your Product schema — we augment WooCommerce\'s output with AI-relevant properties. The add-on would give richer Product schema.', 'blaze-ai-discovery-for-woocommerce' ), 50 ]; 51 } 52 53 if ( CompatibilityDetector::SCHEMA_PRO === $detected ) { 54 return [ 55 'status' => 'pass', 56 'message' => __( 'Schema Pro detected. WooCommerce prints your Product schema and we augment it; Schema Pro\'s own Product schema, if enabled, should be turned off to avoid duplicates.', 'blaze-ai-discovery-for-woocommerce' ), 52 57 ]; 53 58 } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/Checks/LlmsTxtExists.php
r3668873 r3673252 4 4 5 5 defined( 'ABSPATH' ) || exit; 6 7 use BlazeAiDiscovery\Audit\CrawlerAccess\SelfFetch; 6 8 7 9 class LlmsTxtExists implements CheckInterface { … … 24 26 } 25 27 28 // 401/403/407/429/5xx or a bot challenge: the file may well be served, 29 // the plugin's own request just could not get to it. 30 $unverifiable = SelfFetch::unverifiable( $response ); 31 if ( null !== $unverifiable ) { 32 return [ 33 'status' => 'warning', 34 'message' => SelfFetch::unverifiable_message( $unverifiable ), 35 ]; 36 } 37 26 38 $code = wp_remote_retrieve_response_code( $response ); 27 39 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/Checks/RestApiAccessible.php
r3666933 r3673252 4 4 5 5 defined( 'ABSPATH' ) || exit; 6 7 use BlazeAiDiscovery\Audit\CrawlerAccess\SelfFetch; 6 8 7 9 class RestApiAccessible implements CheckInterface { … … 28 30 } 29 31 32 // 401/403/407/429/5xx or a bot challenge: the edge answered, not 33 // WordPress, so nothing is known about the REST API itself. 34 $unverifiable = SelfFetch::unverifiable( $response ); 35 if ( null !== $unverifiable ) { 36 return [ 37 'status' => 'warning', 38 'message' => SelfFetch::unverifiable_message( $unverifiable ), 39 ]; 40 } 41 30 42 $code = wp_remote_retrieve_response_code( $response ); 31 43 if ( $code >= 200 && $code < 500 ) { -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/Checks/RobotsTxt.php
r3670977 r3673252 47 47 } 48 48 49 $code = (int) wp_remote_retrieve_response_code( $response ); 50 if ( $code >= 500 ) { 49 // 401/403/407/429/5xx or a bot challenge: the rules could not be read, 50 // which is not the same as "no rules". 51 $unverifiable = SelfFetch::unverifiable( $response ); 52 if ( null !== $unverifiable ) { 51 53 return [ 52 54 'status' => 'warning', 53 'message' => __( 'Could not read robots.txt. Ensure it is accessible.', 'blaze-ai-discovery-for-woocommerce'),55 'message' => SelfFetch::unverifiable_message( $unverifiable ), 54 56 ]; 55 57 } 58 59 $code = (int) wp_remote_retrieve_response_code( $response ); 56 60 57 61 // A missing robots.txt (404) disallows nobody. -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Audit/CrawlerAccess/SelfFetch.php
r3670977 r3673252 1 1 <?php 2 2 /** 3 * Self-request probe: fetch robots.txt and the home page as ourselves and4 * fingerprint the response headers for edge-security presence (Cloudflare,5 * Sucuri, Kinsta).3 * Self-request probe: fetch robots.txt, the home page and one product page 4 * as ourselves and fingerprint the response headers for edge-security 5 * presence (Cloudflare, Sucuri, Kinsta). 6 6 * 7 7 * @package BlazeAiDiscovery … … 15 15 16 16 /** 17 * Fetch robots.txt and the home page, and fingerprint the response headers. 18 * 19 * @return array{cf_present: bool, robots: ?string, robots_status: int, home_status: int, headers: array} 20 */ 21 public static function probe(): array { 22 $args = [ 23 'timeout' => 10, 17 * Upper bound on the wall-clock time probe() may spend across its 18 * fetches (robots.txt, home page, one product page): the per-request 19 * timeout is 10 s, so a host that drops loopback traffic on the floor 20 * cannot turn three fetches into thirty seconds. 21 */ 22 public const TOTAL_BUDGET = 20; 23 24 /** Per-request timeout, seconds. */ 25 private const REQUEST_TIMEOUT = 10; 26 27 /** 28 * Fetch robots.txt, the home page and one published product page as 29 * ourselves, and fingerprint the response headers. The product page is 30 * the one CrawlerAccessCheck::product_url() picks (the newest published, 31 * catalog-visible product) so the crawler-access signals cover the page 32 * a shopping assistant actually reads, not just `/`. 33 * 34 * Edge fingerprints (cf_present, host) are taken from the home and 35 * product responses together; a header seen on either counts. 36 * 37 * @param string|null $product_url Product page to fetch; null looks one up, '' skips it. 38 * @return array{cf_present: bool, robots: ?string, robots_status: int, home_status: int, product_status: int, product_url: ?string, headers: array} 39 */ 40 public static function probe( ?string $product_url = null ): array { 41 $started = microtime( true ); 42 43 if ( null === $product_url ) { 44 $product_url = self::product_url(); 45 } 46 if ( '' === $product_url ) { 47 $product_url = null; 48 } 49 50 $robots_response = self::fetch( self::robots_url(), $started ); 51 $home_response = self::fetch( home_url( '/' ), $started ); 52 $product_response = null === $product_url ? null : self::fetch( $product_url, $started ); 53 54 $robots_status = self::status_of( $robots_response ); 55 $robots_body = ( is_array( $robots_response ) ) ? wp_remote_retrieve_body( $robots_response ) : null; 56 57 $home_status = self::status_of( $home_response ); 58 $product_status = self::status_of( $product_response ); 59 60 // Home headers first; product headers fill in what home lacks. 61 $headers = self::response_headers( $home_response ); 62 $seen = array_change_key_case( $headers, CASE_LOWER ); 63 foreach ( self::response_headers( $product_response ) as $name => $value ) { 64 if ( ! isset( $seen[ strtolower( $name ) ] ) ) { 65 $headers[ $name ] = $value; 66 $seen[ strtolower( $name ) ] = $value; 67 } 68 } 69 70 $fingerprint = self::fingerprint_headers( $headers ); 71 72 return [ 73 'cf_present' => $fingerprint['cf_present'], 74 'robots' => $robots_body, 75 'robots_status' => $robots_status, 76 'home_status' => $home_status, 77 'product_status' => $product_status, 78 'product_url' => $product_url, 79 'headers' => $headers, 80 ]; 81 } 82 83 /** 84 * One self-fetch, its timeout cut to whatever is left of TOTAL_BUDGET 85 * (and of the cloud request deadline when an inline audit set one). 86 * Returns a WP_Error without a request once the budget is spent. 87 * 88 * @return array|\WP_Error 89 */ 90 private static function fetch( string $url, float $started ) { 91 $remaining = self::TOTAL_BUDGET - ( microtime( true ) - $started ); 92 $deadline = \BlazeAiDiscovery\Cloud\CloudClient::remaining(); 93 if ( null !== $deadline ) { 94 $remaining = min( $remaining, $deadline ); 95 } 96 97 if ( $remaining < 1 ) { 98 return new \WP_Error( 'blazeaid_self_fetch_budget', __( 'Self-fetch budget exhausted.', 'blaze-ai-discovery-for-woocommerce' ) ); 99 } 100 101 return wp_remote_get( $url, [ 102 'timeout' => (int) min( self::REQUEST_TIMEOUT, ceil( $remaining ) ), 24 103 'redirection' => 3, 25 104 'user-agent' => self::user_agent(), 105 ] ); 106 } 107 108 /** 109 * Permalink of one published product for the self-fetch, or null when 110 * WooCommerce (or a product) is missing. Never throws. 111 */ 112 public static function product_url(): ?string { 113 try { 114 return CrawlerAccessCheck::product_url(); 115 } catch ( \Throwable $e ) { 116 return null; 117 } 118 } 119 120 /** 121 * @param mixed $response wp_remote_get() result, or null when skipped. 122 */ 123 private static function status_of( $response ): int { 124 return is_array( $response ) ? (int) wp_remote_retrieve_response_code( $response ) : 0; 125 } 126 127 /** 128 * @param mixed $response wp_remote_get() result, or null when skipped. 129 * @return array<string, string> 130 */ 131 private static function response_headers( $response ): array { 132 return is_array( $response ) ? self::headers_to_array( wp_remote_retrieve_headers( $response ) ) : []; 133 } 134 135 /** 136 * HTTP statuses that mean something in front of WordPress (HTTP auth, 137 * a firewall, a bot challenge, an overloaded origin) answered the 138 * plugin's own request instead of the page. None of them says anything 139 * about what the page would serve, so a check must report "could not 140 * verify", never pass or fail. 141 */ 142 public const UNVERIFIABLE_STATUSES = [ 401, 403, 407, 429 ]; 143 144 /** 145 * Whether a self-fetch response cannot be read as the page's own answer: 146 * 401/403/407/429, any 5xx, or a Cloudflare challenge page (any status). 147 * 148 * @param mixed $response wp_remote_get() result. 149 * @return array{code: int, challenge: bool}|null Null when the response is the page's own answer (2xx, 404, ...). 150 */ 151 public static function unverifiable( $response ): ?array { 152 if ( ! is_array( $response ) ) { 153 return null; 154 } 155 156 $code = (int) wp_remote_retrieve_response_code( $response ); 157 $challenge = self::is_challenge( $response ); 158 159 if ( ! $challenge && ! in_array( $code, self::UNVERIFIABLE_STATUSES, true ) && $code < 500 ) { 160 return null; 161 } 162 163 return [ 164 'code' => $code, 165 'challenge' => $challenge, 26 166 ]; 27 28 $robots_response = wp_remote_get( self::robots_url(), $args ); 29 $home_response = wp_remote_get( home_url( '/' ), $args ); 30 31 $robots_status = is_wp_error( $robots_response ) ? 0 : (int) wp_remote_retrieve_response_code( $robots_response ); 32 $robots_body = is_wp_error( $robots_response ) ? null : wp_remote_retrieve_body( $robots_response ); 33 34 $home_status = is_wp_error( $home_response ) ? 0 : (int) wp_remote_retrieve_response_code( $home_response ); 35 $headers = is_wp_error( $home_response ) ? [] : self::headers_to_array( wp_remote_retrieve_headers( $home_response ) ); 36 37 $fingerprint = self::fingerprint_headers( $headers ); 38 39 return [ 40 'cf_present' => $fingerprint['cf_present'], 41 'robots' => $robots_body, 42 'robots_status' => $robots_status, 43 'home_status' => $home_status, 44 'headers' => $headers, 45 ]; 167 } 168 169 /** 170 * Cloudflare challenge fingerprint: the `cf-mitigated: challenge` header 171 * (managed / JS challenge, Bot Fight Mode), or the challenge page markup 172 * itself when the header was stripped. 173 * 174 * @param array $response wp_remote_get() result. 175 */ 176 public static function is_challenge( array $response ): bool { 177 $headers = array_change_key_case( self::headers_to_array( wp_remote_retrieve_headers( $response ) ), CASE_LOWER ); 178 if ( isset( $headers['cf-mitigated'] ) && false !== stripos( (string) $headers['cf-mitigated'], 'challenge' ) ) { 179 return true; 180 } 181 182 $body = (string) wp_remote_retrieve_body( $response ); 183 if ( '' === $body ) { 184 return false; 185 } 186 $head = substr( $body, 0, 8192 ); 187 188 return false !== strpos( $head, '/cdn-cgi/challenge-platform/' ) 189 || false !== strpos( $head, 'cf-chl' ) 190 || ( false !== stripos( $head, '<title>Just a moment...</title>' ) && false !== stripos( $head, 'cloudflare' ) ); 191 } 192 193 /** 194 * The one sentence every loopback check uses for an unverifiable answer. 195 * 196 * @param array{code: int, challenge: bool} $info unverifiable() result. 197 */ 198 public static function unverifiable_message( array $info ): string { 199 $message = sprintf( 200 /* translators: %d: HTTP status code the site answered with */ 201 __( 'Could not verify — your site answered HTTP %d to the plugin\'s own request (password protection, firewall or bot challenge).', 'blaze-ai-discovery-for-woocommerce' ), 202 $info['code'] 203 ); 204 205 if ( ! empty( $info['challenge'] ) ) { 206 $message .= ' ' . __( 'A Cloudflare challenge page was detected.', 'blaze-ai-discovery-for-woocommerce' ); 207 } 208 209 return $message; 46 210 } 47 211 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Cloud/CloudClient.php
r3670977 r3673252 14 14 public const BASE_URL = 'https://api.blazecommerce.io/v1/'; 15 15 16 /** Per-request timeout, seconds, when no deadline is set. */ 17 public const TIMEOUT = 25; 18 19 /** WP_Error code for a 2xx whose body is not the JSON object the service sends. */ 20 public const ERROR_BAD_PAYLOAD = 'blazeaid_bad_payload'; 21 22 /** WP_Error code for a call skipped or cut short by the request deadline. */ 23 public const ERROR_BUDGET_EXHAUSTED = 'budget_exhausted'; 24 25 /** Top-level key every service response carries. */ 26 private const REQUIRED_KEYS = [ 'version' ]; 27 28 /** Seconds a retry needs on top of the backoff before it is worth attempting. */ 29 private const RETRY_MIN_REMAINING = 2.0; 30 31 /** 32 * Seconds the cloud calls of this request may take together, armed 33 * into a deadline by the first attempt (see set_budget()), or null. 34 */ 35 private static ?float $budget = null; 36 37 /** Unix timestamp (float) by which every cloud call must have returned, or null. */ 38 private static ?float $deadline = null; 39 40 /** Whether a call was skipped or cut short by the deadline since it was set. */ 41 private static bool $budget_exhausted = false; 42 43 /** 44 * Give the cloud calls of this request a shared budget. The clock 45 * starts at the first call attempted, not here: an inline audit runs 46 * its local checks first (two loopback fetches can take ten seconds on 47 * a slow host) and those must not eat the cloud checks' seconds. Until 48 * a call arms it, remaining() is null and nothing is bounded — so with 49 * consent off (no call is ever attempted) the self-fetch keeps its own 50 * bound only. Null clears budget and deadline. 51 * 52 * @param float|null $seconds Budget in seconds, or null. 53 */ 54 public static function set_budget( ?float $seconds ): void { 55 self::$budget = null === $seconds ? null : max( 0.0, $seconds ); 56 self::$deadline = null; 57 self::$budget_exhausted = false; 58 } 59 60 /** 61 * Bound every cloud call made from now on: each request's timeout is 62 * cut to what is left before $deadline, a call with under a second left 63 * is not made at all, and either case answers `budget_exhausted` (see 64 * budget_exhausted()). Null lifts the bound (the default: 25 s per call). 65 * Unlike set_budget(), the clock is already running. 66 * 67 * @param float|null $deadline Unix timestamp (microtime(true) scale), or null. 68 */ 69 public static function set_deadline( ?float $deadline ): void { 70 self::$budget = null; 71 self::$deadline = $deadline; 72 self::$budget_exhausted = false; 73 } 74 75 /** 76 * Seconds left before the deadline (never below 0), or null without one 77 * (no deadline set, or a budget no call has armed yet). 78 */ 79 public static function remaining(): ?float { 80 if ( null === self::$deadline ) { 81 return null; 82 } 83 84 return max( 0.0, self::$deadline - microtime( true ) ); 85 } 86 87 /** 88 * Whether any call since the last set_budget() / set_deadline() / 89 * clear_budget_exhausted() was skipped or cut short by the deadline. 90 * The audit runner reads this after each check to mark rows `pending`. 91 */ 92 public static function budget_exhausted(): bool { 93 return self::$budget_exhausted; 94 } 95 96 /** 97 * Reset the exhausted flag without touching the budget or deadline, so 98 * it can be read per check. 99 */ 100 public static function clear_budget_exhausted(): void { 101 self::$budget_exhausted = false; 102 } 103 104 /** 105 * Start the budget clock on the first attempt (no-op once armed, or 106 * without a budget). 107 */ 108 private static function arm(): void { 109 if ( null === self::$deadline && null !== self::$budget ) { 110 self::$deadline = microtime( true ) + self::$budget; 111 } 112 } 113 16 114 /** 17 115 * POST a request to the Blaze Commerce cloud API. … … 21 119 * to typed WP_Error codes. 22 120 * 23 * @param string $endpoint Endpoint path relative to the base URL, e.g. "crawler-access". 24 * @param array $body Request body fields (merged with site/site_token/plugin). 121 * A 2xx counts as a success only when the response is JSON 122 * (Content-Type) and decodes to an object carrying `version` plus every 123 * key in $required_keys; anything else (a Cloudflare challenge, an HTML 124 * error page served with 200) is `blazeaid_bad_payload`, so callers 125 * never cache an empty "result". 126 * 127 * Transient failures — a connection error, 429, any 5xx — are retried 128 * once after a short backoff, never past the deadline. A timeout is not 129 * retried: the service is slow, and the retry would only wait again. 130 * 131 * @param string $endpoint Endpoint path relative to the base URL, e.g. "crawler-access". 132 * @param array $body Request body fields (merged with site/site_token/plugin). 133 * @param string[] $required_keys Top-level keys the decoded response must carry, on top of `version`. 25 134 * @return array|\WP_Error Decoded JSON response on success. 26 135 */ 27 public static function post( string $endpoint, array $body ) {136 public static function post( string $endpoint, array $body, array $required_keys = [] ) { 28 137 if ( ! Consent::granted() ) { 29 138 return new \WP_Error( … … 49 158 ); 50 159 51 $url = rtrim( $base_url, '/' ) . '/' . ltrim( $endpoint, '/' ); 160 $url = rtrim( $base_url, '/' ) . '/' . ltrim( $endpoint, '/' ); 161 $json = wp_json_encode( $payload ); 162 163 $result = self::attempt( $url, $json, $required_keys ); 164 165 if ( self::is_transient( $result ) && self::can_retry() ) { 166 $delay = self::retry_delay(); 167 if ( $delay > 0 ) { 168 usleep( (int) round( $delay * 1000000 ) ); 169 } 170 $result = self::attempt( $url, $json, $required_keys ); 171 } 172 173 return $result; 174 } 175 176 /** 177 * One HTTP attempt, bounded by the deadline. 178 * 179 * @param string $url Full endpoint URL. 180 * @param string $json Encoded request body. 181 * @param string[] $required_keys Extra top-level keys the response must carry. 182 * @return array|\WP_Error 183 */ 184 private static function attempt( string $url, string $json, array $required_keys ) { 185 self::arm(); 186 187 $timeout = self::TIMEOUT; 188 $remaining = self::remaining(); 189 if ( null !== $remaining ) { 190 if ( $remaining < 1 ) { 191 return self::budget_error(); 192 } 193 $timeout = (int) min( self::TIMEOUT, ceil( $remaining ) ); 194 } 52 195 53 196 $response = wp_remote_post( 54 197 $url, 55 198 [ 56 'timeout' => 25,199 'timeout' => $timeout, 57 200 'headers' => [ 58 201 'Content-Type' => 'application/json', 59 202 'User-Agent' => 'BlazeAiDiscovery/' . ( defined( 'BLAZEAID_VERSION' ) ? BLAZEAID_VERSION : '0.0.0' ), 60 203 ], 61 'body' => wp_json_encode( $payload ),204 'body' => $json, 62 205 ] 63 206 ); 64 207 65 208 if ( is_wp_error( $response ) ) { 209 // A transport failure right at the deadline is the deadline. 210 $left = self::remaining(); 211 if ( null !== $left && $left < 1 ) { 212 return self::budget_error(); 213 } 214 66 215 return $response; 67 216 } … … 71 220 72 221 if ( $code >= 200 && $code < 300 ) { 73 return is_array( $data ) ? $data : []; 222 if ( ! self::is_json_response( $response ) || ! self::is_expected_payload( $data, $required_keys ) ) { 223 return new \WP_Error( 224 self::ERROR_BAD_PAYLOAD, 225 __( 'Blaze Commerce cloud returned an unexpected response.', 'blaze-ai-discovery-for-woocommerce' ), 226 [ 227 'status' => $code, 228 'notices' => [], 229 ] 230 ); 231 } 232 233 return $data; 74 234 } 75 235 … … 98 258 ); 99 259 } 260 261 private static function budget_error(): \WP_Error { 262 self::$budget_exhausted = true; 263 264 return new \WP_Error( 265 self::ERROR_BUDGET_EXHAUSTED, 266 __( 'The cloud check did not finish within this request; it continues in the background.', 'blaze-ai-discovery-for-woocommerce' ), 267 [ 268 'status' => 0, 269 'notices' => [], 270 ] 271 ); 272 } 273 274 /** 275 * Content-Type says JSON (application/json, application/problem+json, ...). 276 * 277 * @param array $response wp_remote_post() result. 278 */ 279 private static function is_json_response( array $response ): bool { 280 $headers = wp_remote_retrieve_headers( $response ); 281 if ( is_object( $headers ) && method_exists( $headers, 'getAll' ) ) { 282 $headers = $headers->getAll(); 283 } 284 if ( ! is_array( $headers ) ) { 285 return false; 286 } 287 288 $headers = array_change_key_case( $headers, CASE_LOWER ); 289 $type = $headers['content-type'] ?? ''; 290 if ( is_array( $type ) ) { 291 $type = implode( ',', $type ); 292 } 293 $type = strtolower( (string) $type ); 294 295 return false !== strpos( $type, 'application/json' ) || false !== strpos( $type, '+json' ); 296 } 297 298 /** 299 * Decoded body is an object (string keys) carrying `version` and every 300 * required key. 301 * 302 * @param mixed $data json_decode() result. 303 * @param string[] $required_keys Extra keys. 304 */ 305 private static function is_expected_payload( $data, array $required_keys ): bool { 306 if ( ! is_array( $data ) || empty( $data ) ) { 307 return false; 308 } 309 310 foreach ( array_merge( self::REQUIRED_KEYS, $required_keys ) as $key ) { 311 if ( ! array_key_exists( $key, $data ) ) { 312 return false; 313 } 314 } 315 316 return true; 317 } 318 319 /** 320 * A failure worth one retry: connection-level error (not a timeout), 321 * 429, or any 5xx. 322 * 323 * @param mixed $result attempt() result. 324 */ 325 private static function is_transient( $result ): bool { 326 if ( ! is_wp_error( $result ) ) { 327 return false; 328 } 329 330 $code = $result->get_error_code(); 331 if ( in_array( $code, [ self::ERROR_BUDGET_EXHAUSTED, self::ERROR_BAD_PAYLOAD, 'consent_required' ], true ) ) { 332 return false; 333 } 334 335 $data = $result->get_error_data(); 336 $status = ( is_array( $data ) && isset( $data['status'] ) ) ? (int) $data['status'] : null; 337 338 if ( null !== $status && $status > 0 ) { 339 return 429 === $status || $status >= 500; 340 } 341 342 // Transport error: retry unless it was a timeout. 343 return 1 !== preg_match( '/timed? ?out|cURL error 28\b/i', $result->get_error_message() ); 344 } 345 346 /** 347 * A retry fits when there is no deadline, or backoff plus a couple of 348 * seconds still fit before it. 349 */ 350 private static function can_retry(): bool { 351 $remaining = self::remaining(); 352 if ( null === $remaining ) { 353 return true; 354 } 355 356 return $remaining >= self::retry_delay() + self::RETRY_MIN_REMAINING; 357 } 358 359 /** 360 * Backoff before the single retry, seconds. `BLAZEAID_CLOUD_RETRY_DELAY` 361 * (a constant, used by the test runtime) sets the default of 1 s; the 362 * `blazeaid_cloud_retry_delay` filter can change it per site. 363 */ 364 private static function retry_delay(): float { 365 $default = defined( 'BLAZEAID_CLOUD_RETRY_DELAY' ) ? (float) BLAZEAID_CLOUD_RETRY_DELAY : 1.0; 366 367 /** 368 * Filter the backoff before the one retry of a failed cloud call. 369 * 370 * @param float $delay Seconds (0 disables the wait, not the retry). 371 */ 372 $delay = apply_filters( 'blazeaid_cloud_retry_delay', $default ); 373 374 return max( 0.0, (float) $delay ); 375 } 100 376 } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Cloud/PayloadCache.php
r3670977 r3673252 24 24 25 25 /** 26 * An empty payload is never cached: it is what a broken response used to 27 * decode to, and caching it turned a minutes-long incident into a day 28 * of "no data" answers. 29 * 26 30 * @param string $key Cache key (without the transient prefix). 27 31 * @param array $payload Payload to cache. 28 32 * @param int $ttl Time to live, in seconds. 33 * @return bool Whether the payload was stored. 29 34 */ 30 public static function set( string $key, array $payload, int $ttl ): void { 31 set_transient( self::PREFIX . $key, $payload, $ttl ); 35 public static function set( string $key, array $payload, int $ttl ): bool { 36 if ( empty( $payload ) ) { 37 return false; 38 } 39 40 return (bool) set_transient( self::PREFIX . $key, $payload, $ttl ); 32 41 } 33 42 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Cloud/VisibilityClient.php
r3670977 r3673252 32 32 33 33 /** 34 * A 2xx that was not the display payload (an HTML error page, a 35 * challenge) is not cached as data; the local notice for it is kept 36 * only briefly so the next refresh retries soon. 37 */ 38 private const BAD_PAYLOAD_TTL = 300; 39 40 /** Top-level keys the display payload must carry (on top of `version`). */ 41 private const REQUIRED_KEYS = [ 'sections' ]; 42 43 /** 34 44 * @return array|null Sanitised payload from the transient cache, or null. 35 45 */ … … 49 59 } 50 60 51 $result = CloudClient::post( self::ENDPOINT, self::request_body() );61 $result = CloudClient::post( self::ENDPOINT, self::request_body(), self::REQUIRED_KEYS ); 52 62 update_option( self::OPTION_LAST_RUN, current_time( 'mysql', true ), false ); 53 63 … … 55 65 $data = $result->get_error_data(); 56 66 $notices = ( is_array( $data ) && isset( $data['notices'] ) ) ? $data['notices'] : []; 57 $payload = self::notices_only( $result->get_error_code(), $notices ); 58 PayloadCache::set( self::CACHE_KEY, $payload, self::ERROR_TTL ); 67 $ttl = CloudClient::ERROR_BAD_PAYLOAD === $result->get_error_code() ? self::BAD_PAYLOAD_TTL : self::ERROR_TTL; 68 $payload = self::notices_only( $result->get_error_code(), $notices, $ttl ); 69 PayloadCache::set( self::CACHE_KEY, $payload, $ttl ); 59 70 return $payload; 60 71 } … … 134 145 * and any sanitised notices the service sent alongside the error. 135 146 * 136 * @param string $code consent_off | site_verification_failed | rate_limited | disabled | http_error.147 * @param string $code consent_off | site_verification_failed | rate_limited | disabled | blazeaid_bad_payload | http_error. 137 148 * @param array $notices Server notices carried on the WP_Error. 149 * @param int $ttl Cache lifetime reported in the payload. 138 150 */ 139 private static function notices_only( string $code, array $notices = [] ): array {151 private static function notices_only( string $code, array $notices = [], int $ttl = self::ERROR_TTL ): array { 140 152 $texts = [ 141 'consent_off' => __( 'Cloud checks are not enabled for this site, so AI visibility data is not being fetched.', 'blaze-ai-discovery-for-woocommerce' ), 142 'site_verification_failed' => __( 'Blaze Commerce could not verify this site. Make sure the store is publicly reachable and try again.', 'blaze-ai-discovery-for-woocommerce' ), 143 'rate_limited' => __( 'Rate limit reached for AI visibility refreshes. Please try again tomorrow.', 'blaze-ai-discovery-for-woocommerce' ), 144 'disabled' => __( 'The AI visibility service is temporarily unavailable. Data will refresh automatically when it returns.', 'blaze-ai-discovery-for-woocommerce' ), 153 'consent_off' => __( 'Cloud checks are not enabled for this site, so AI visibility data is not being fetched.', 'blaze-ai-discovery-for-woocommerce' ), 154 'site_verification_failed' => __( 'Blaze Commerce could not verify this site. Make sure the store is publicly reachable and try again.', 'blaze-ai-discovery-for-woocommerce' ), 155 'rate_limited' => __( 'Rate limit reached for AI visibility refreshes. Please try again tomorrow.', 'blaze-ai-discovery-for-woocommerce' ), 156 'disabled' => __( 'The AI visibility service is temporarily unavailable. Data will refresh automatically when it returns.', 'blaze-ai-discovery-for-woocommerce' ), 157 CloudClient::ERROR_BAD_PAYLOAD => __( 'The AI visibility service answered with something other than a report (a network or firewall page, most likely). It will be retried shortly.', 'blaze-ai-discovery-for-woocommerce' ), 145 158 ]; 146 159 if ( ! isset( $texts[ $code ] ) ) { … … 157 170 return [ 158 171 'version' => 1, 159 'ttl' => self::ERROR_TTL,172 'ttl' => $ttl, 160 173 'generated_at' => gmdate( 'c' ), 161 174 'period' => null, -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Database/DatabaseModule.php
r3670977 r3673252 1 1 <?php 2 2 /** 3 * Database module — owns retention scheduling.3 * Database module — owns schema self-repair and retention scheduling. 4 4 * 5 5 * @package BlazeAiDiscovery … … 17 17 private Container $container; 18 18 private RetentionCleanup $cleanup; 19 private Migrator $migrator; 19 20 20 21 public function __construct( Container $container ) { 21 22 $this->container = $container; 22 23 $this->cleanup = new RetentionCleanup(); 24 $this->migrator = new Migrator(); 23 25 } 24 26 … … 29 31 public function register(): void { 30 32 $this->cleanup->register(); 33 34 // Every request (cron, REST, front end): one autoloaded option read. 35 // A site whose schema was never installed - activated before 36 // WooCommerce, cloned without custom tables, a DB user that could not 37 // CREATE at activation - repairs itself here instead of failing every 38 // insert silently until someone reactivates the plugin. 39 $this->migrator->maybe_run( false ); 40 41 add_action( 'admin_init', [ $this, 'maybe_migrate' ], 5 ); 31 42 add_action( 'admin_init', [ $this, 'maybe_schedule' ] ); 43 add_action( 'admin_notices', [ $this, 'render_schema_notice' ] ); 32 44 } 33 45 34 46 public function boot(): void {} 47 48 /** 49 * admin_init: the deeper check (SHOW TABLES, once per request) that also 50 * catches a dropped table when the version option says all is well. 51 */ 52 public function maybe_migrate(): void { 53 if ( wp_doing_ajax() ) { 54 return; 55 } 56 $this->migrator->maybe_run( true ); 57 } 35 58 36 59 /** … … 42 65 } 43 66 } 67 68 /** 69 * Tell the store owner which tables are missing and why that usually 70 * happens, instead of a dashboard that silently never fills. 71 */ 72 public function render_schema_notice(): void { 73 if ( ! current_user_can( 'manage_woocommerce' ) ) { 74 return; 75 } 76 77 $notice = $this->schema_notice(); 78 if ( null === $notice ) { 79 return; 80 } 81 82 echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses( $notice, [ 'code' => [], 'strong' => [] ] ) . '</p></div>'; 83 } 84 85 /** 86 * The schema notice text (HTML with code/strong only), or null when the 87 * schema is complete. 88 */ 89 public function schema_notice(): ?string { 90 $missing = $this->migrator->missing_tables(); 91 if ( [] === $missing && $this->migrator->is_current() ) { 92 return null; 93 } 94 95 $failure = $this->migrator->last_failure(); 96 if ( [] === $missing && null !== $failure ) { 97 $missing = $failure['missing']; 98 } 99 100 $tables = implode( 101 ', ', 102 array_map( 103 static function ( string $table ): string { 104 return '<code>' . esc_html( $table ) . '</code>'; 105 }, 106 $missing 107 ) 108 ); 109 110 $text = sprintf( 111 /* translators: %s: comma-separated list of database table names. */ 112 esc_html__( 'Blaze AI Discovery could not create its database tables: %s. The database user WordPress connects with usually lacks the CREATE TABLE privilege; grant it (or ask your host to) and the plugin retries automatically within a few minutes.', 'blaze-ai-discovery-for-woocommerce' ), 113 '' === $tables ? esc_html__( 'schema version not recorded', 'blaze-ai-discovery-for-woocommerce' ) : $tables 114 ); 115 116 if ( null !== $failure && '' !== $failure['error'] ) { 117 $text .= ' ' . sprintf( 118 /* translators: %s: the last MySQL error message. */ 119 esc_html__( 'Last database error: %s', 'blaze-ai-discovery-for-woocommerce' ), 120 '<code>' . esc_html( $failure['error'] ) . '</code>' 121 ); 122 } 123 124 return '<strong>' . esc_html__( 'Blaze AI Discovery', 'blaze-ai-discovery-for-woocommerce' ) . '</strong> ' . $text; 125 } 44 126 } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Database/Migrator.php
r3666933 r3673252 3 3 * Versioned schema migrations using dbDelta. 4 4 * 5 * The schema version is recorded only after every expected table has been 6 * verified to exist, so a failed CREATE (restricted DB user, strict-mode 7 * index errors) leaves the version behind and the migrator retries instead 8 * of reporting success over an empty database. 9 * 5 10 * @package BlazeAiDiscovery 6 11 */ … … 12 17 class Migrator { 13 18 14 private const VERSION_OPTION = 'blazeaid_db_version'; 15 private const TARGET_VERSION = 1; 16 17 public function run(): void { 18 $current = (int) get_option( self::VERSION_OPTION, 0 ); 19 20 if ( $current >= self::TARGET_VERSION ) { 21 return; 22 } 23 24 require_once ABSPATH . 'wp-admin/includes/upgrade.php'; 25 26 if ( $current < 1 ) { 27 $this->migrate_v1(); 28 } 29 30 update_option( self::VERSION_OPTION, self::TARGET_VERSION ); 19 public const VERSION_OPTION = 'blazeaid_db_version'; 20 public const TARGET_VERSION = 1; 21 22 /** 23 * Transient set after a failed attempt so a broken database is retried 24 * every few minutes rather than on every request. Holds the wpdb error 25 * and the missing tables for the admin notice. 26 */ 27 public const RETRY_TRANSIENT = 'blazeaid_db_retry'; 28 29 /** Seconds between attempts while tables cannot be created. */ 30 public const RETRY_INTERVAL = 5 * MINUTE_IN_SECONDS; 31 32 /** 33 * Per-request cache of the missing-table check, keyed by table prefix so 34 * switch_to_blog() never reuses another site's answer. 35 * 36 * @var array<string, string[]> 37 */ 38 private static array $missing_cache = []; 39 40 /** 41 * True when the recorded schema version is at the target. 42 */ 43 public function is_current(): bool { 44 return (int) get_option( self::VERSION_OPTION, 0 ) >= self::TARGET_VERSION; 45 } 46 47 /** 48 * Run the migration when it is needed: the version option is behind 49 * (never installed, activated before WooCommerce, a future schema bump 50 * applied by plugin update, or an earlier attempt that could not create 51 * the tables), or - when $verify_tables is set - any expected table is 52 * missing (site cloned without custom tables, a multisite subsite, a 53 * table dropped by hand). 54 * 55 * The version compare is a single autoloaded option read, so the 56 * $verify_tables = false form is cheap enough for every request; the 57 * table check costs one SHOW TABLES per request and belongs on admin_init. 58 * 59 * @param bool $verify_tables Also check that every table exists. 60 * @return bool True when the schema is complete after this call. 61 */ 62 public function maybe_run( bool $verify_tables = true ): bool { 63 if ( $this->is_current() ) { 64 if ( ! $verify_tables ) { 65 return true; 66 } 67 if ( [] === $this->missing_tables() ) { 68 return true; 69 } 70 } 71 72 if ( false !== get_transient( self::RETRY_TRANSIENT ) ) { 73 // A recent attempt failed; do not hammer a database that cannot create tables. 74 return false; 75 } 76 77 return $this->run(); 78 } 79 80 /** 81 * Apply the schema and record the version once every table is present. 82 * 83 * dbDelta is idempotent, so this is safe to call from activation, from 84 * admin_init, per site under switch_to_blog(), and again after a failure. 85 * 86 * @return bool True when every expected table exists afterwards. 87 */ 88 public function run(): bool { 89 global $wpdb; 90 91 if ( ! function_exists( 'dbDelta' ) ) { 92 require_once ABSPATH . 'wp-admin/includes/upgrade.php'; 93 } 94 95 $wpdb->last_error = ''; 96 $this->migrate_v1(); 97 $error = (string) $wpdb->last_error; 98 99 $missing = $this->missing_tables( true ); 100 101 if ( [] === $missing ) { 102 update_option( self::VERSION_OPTION, self::TARGET_VERSION ); 103 delete_transient( self::RETRY_TRANSIENT ); 104 return true; 105 } 106 107 set_transient( 108 self::RETRY_TRANSIENT, 109 [ 110 'error' => $error, 111 'missing' => $missing, 112 'at' => time(), 113 ], 114 self::RETRY_INTERVAL 115 ); 116 117 return false; 31 118 } 32 119 … … 35 122 */ 36 123 public function needs_migration(): bool { 37 return (int) get_option( self::VERSION_OPTION, 0 ) < self::TARGET_VERSION; 124 return ! $this->is_current() || [] !== $this->missing_tables(); 125 } 126 127 /** 128 * Expected tables that do not exist for the current site prefix. One 129 * SHOW TABLES per request per prefix; pass $refresh after a schema change. 130 * 131 * @param bool $refresh Ignore the per-request cache. 132 * @return string[] Fully prefixed table names. 133 */ 134 public function missing_tables( bool $refresh = false ): array { 135 global $wpdb; 136 137 $prefix = (string) $wpdb->prefix; 138 if ( ! $refresh && isset( self::$missing_cache[ $prefix ] ) ) { 139 return self::$missing_cache[ $prefix ]; 140 } 141 142 $like = $wpdb->esc_like( $prefix . 'blazeaid_' ) . '%'; 143 $existing = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $like ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 144 $existing = array_map( 'strtolower', array_map( 'strval', is_array( $existing ) ? $existing : [] ) ); 145 146 $missing = []; 147 foreach ( Tables::all() as $table ) { 148 if ( ! in_array( strtolower( $table ), $existing, true ) ) { 149 $missing[] = $table; 150 } 151 } 152 153 self::$missing_cache[ $prefix ] = $missing; 154 return $missing; 155 } 156 157 /** 158 * Details of the last failed attempt, for the admin notice. 159 * 160 * @return array{error: string, missing: string[], at: int}|null 161 */ 162 public function last_failure(): ?array { 163 $failure = get_transient( self::RETRY_TRANSIENT ); 164 if ( ! is_array( $failure ) ) { 165 return null; 166 } 167 return [ 168 'error' => isset( $failure['error'] ) && is_string( $failure['error'] ) ? $failure['error'] : '', 169 'missing' => isset( $failure['missing'] ) && is_array( $failure['missing'] ) ? array_map( 'strval', $failure['missing'] ) : [], 170 'at' => isset( $failure['at'] ) ? (int) $failure['at'] : 0, 171 ]; 172 } 173 174 /** 175 * Forget the per-request table cache (tests, and after DROP TABLE). 176 */ 177 public static function reset_cache(): void { 178 self::$missing_cache = []; 38 179 } 39 180 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Database/RetentionCleanup.php
r3666933 r3673252 2 2 /** 3 3 * Scheduled data retention enforcement. 4 * 5 * Attribution data (visits, attributed orders) and the crawler endpoint log 6 * are deleted once older than the retention period, in batches of 7 * BATCH_SIZE rows until nothing older remains or the run's time budget is 8 * spent — a single capped delete cannot keep up with the daily write caps 9 * (5,000 visits, 2,000 log rows). 4 10 * 5 11 * @package BlazeAiDiscovery … … 19 25 private const DEFAULT_RETENTION_DAYS = 90; 20 26 27 /** Rows per DELETE statement. */ 28 public const BATCH_SIZE = 1000; 29 30 /** Seconds one cleanup run may spend deleting, across all tables. */ 31 public const TIME_BUDGET = 10.0; 32 21 33 public function register(): void { 22 34 add_action( self::HOOK, [ $this, 'cleanup' ] ); … … 35 47 } 36 48 37 public function cleanup(): void { 49 /** 50 * Delete everything older than the retention period from the tables 51 * under the policy, then trim audits to the last 10. 52 * 53 * @return array<string, int> Rows deleted per table. 54 */ 55 public function cleanup(): array { 38 56 global $wpdb; 39 57 40 58 $days = (int) apply_filters( 'blazeaid_retention_days', self::DEFAULT_RETENTION_DAYS ); 41 59 $threshold = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) ); 60 $start = microtime( true ); 61 $deleted = []; 42 62 43 // Clean visits. 44 $wpdb->query( 45 $wpdb->prepare( 46 'DELETE FROM %i WHERE visited_at < %s LIMIT 1000', 47 Tables::visits(), 48 $threshold 49 ) 50 ); 51 52 // Clean endpoint log. 53 $wpdb->query( 54 $wpdb->prepare( 55 'DELETE FROM %i WHERE requested_at < %s LIMIT 1000', 56 Tables::endpoint_log(), 57 $threshold 58 ) 59 ); 63 foreach ( self::retained_tables() as $table => $column ) { 64 $deleted[ $table ] = $this->purge( $table, $column, $threshold, $start ); 65 } 60 66 61 67 // Clean old audits (keep last 10). … … 76 82 ); 77 83 } 84 85 return $deleted; 86 } 87 88 /** 89 * Tables under the retention period and their timestamp column. 90 * 91 * @return array<string, string> Table name => datetime column. 92 */ 93 public static function retained_tables(): array { 94 return [ 95 Tables::visits() => 'visited_at', 96 Tables::orders() => 'attributed_at', 97 Tables::endpoint_log() => 'requested_at', 98 ]; 99 } 100 101 /** 102 * Delete rows older than $threshold in batches until none remain or 103 * the shared time budget (measured from $start) is used up. 104 * 105 * @return int Rows deleted. 106 */ 107 private function purge( string $table, string $column, string $threshold, float $start ): int { 108 global $wpdb; 109 110 $total = 0; 111 do { 112 $deleted = $wpdb->query( 113 $wpdb->prepare( 114 'DELETE FROM %i WHERE %i < %s LIMIT %d', 115 $table, 116 $column, 117 $threshold, 118 self::BATCH_SIZE 119 ) 120 ); 121 $deleted = is_int( $deleted ) ? $deleted : 0; // false on error: stop. 122 $total += $deleted; 123 } while ( self::BATCH_SIZE === $deleted && ( microtime( true ) - $start ) < $this->time_budget() ); 124 125 return $total; 126 } 127 128 /** 129 * Seam for tests: seconds a run may spend deleting. 130 */ 131 protected function time_budget(): float { 132 return self::TIME_BUDGET; 78 133 } 79 134 } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Feed/ChatGptFeedGenerator.php
r3670977 r3673252 7 7 * target_countries, is_eligible_search, is_eligible_checkout. 8 8 * 9 * The catalogue is walked in pages of PAGE_SIZE product IDs, each page is 10 * hydrated, streamed to the feed files and released from the object cache 11 * before the next, so a 5,000-product store generates at the 128M PHP 12 * default. Progress is recorded per page for the admin UI. 13 * 9 14 * @package BlazeAiDiscovery 10 15 */ … … 18 23 class ChatGptFeedGenerator { 19 24 20 /** 21 * Generate the feed as an array of product objects. 25 /** Product IDs fetched and hydrated per page. */ 26 public const PAGE_SIZE = 200; 27 28 /** Catalogue size up to which POST /feed/generate may run on the request thread. */ 29 public const INLINE_LIMIT = 500; 30 31 public const PROGRESS_OPTION = 'blazeaid_feed_progress'; 32 33 /** Transient held while a run is in progress; refreshed per page. */ 34 public const LOCK_TRANSIENT = 'blazeaid_feed_lock'; 35 36 private const LOCK_TTL = 600; 37 38 /** Seconds a run may take; raised where the host allows it. */ 39 private const TIME_LIMIT = 600; 40 41 /** 42 * Published parent products — the progress denominator and the size 43 * check for the inline path. Cheap: a post-status count, no hydration. 44 */ 45 public static function count_products(): int { 46 $counts = wp_count_posts( 'product' ); 47 return (int) ( $counts->publish ?? 0 ); 48 } 49 50 /** 51 * Generate the feed as an array of product objects. Holds every entry 52 * in memory — only for small catalogues and tests; generate_file() 53 * streams instead. 22 54 * 23 55 * @return array[] Array of product feed entries. 24 56 */ 25 57 public static function generate(): array { 26 $products = wc_get_products( [27 'status' => 'publish',28 'limit' => -1,29 'return' => 'objects',30 'type' => [ 'simple', 'external' ],31 ] );32 33 // Also get the default variation of variable products.34 $variable = wc_get_products( [35 'status' => 'publish',36 'limit' => -1,37 'return' => 'objects',38 'type' => [ 'variable' ],39 ] );40 41 58 $feed = []; 42 43 foreach ( $products as $product ) { 59 self::each_entry( 60 static function ( array $entry ) use ( &$feed ): void { 61 $feed[] = $entry; 62 } 63 ); 64 return $feed; 65 } 66 67 /** 68 * Walk the catalogue page by page and hand every feed entry to $sink. 69 * 70 * @param callable $sink Receives one entry array at a time. 71 * @param callable $on_page Optional; receives ( int $products_done, int $products_total ) after each page. 72 * @return int Entries emitted. 73 */ 74 public static function each_entry( callable $sink, ?callable $on_page = null ): int { 75 $total = self::count_products(); 76 $page = 1; 77 $done = 0; 78 $entries = 0; 79 80 do { 81 $ids = wc_get_products( 82 [ 83 'status' => 'publish', 84 'type' => [ 'simple', 'external', 'variable' ], 85 'limit' => self::PAGE_SIZE, 86 'page' => $page, 87 'orderby' => 'ID', 88 'order' => 'ASC', 89 'return' => 'ids', 90 ] 91 ); 92 $ids = is_array( $ids ) ? array_map( 'intval', $ids ) : []; 93 $fetched = count( $ids ); 94 $touched = $ids; 95 96 foreach ( $ids as $id ) { 97 $product = wc_get_product( $id ); 98 if ( $product ) { 99 $entries += self::emit_product( $product, $sink, $touched ); 100 } 101 $done++; 102 } 103 104 if ( $on_page ) { 105 $on_page( $done, max( $total, $done ) ); 106 } 107 self::release_page_cache( $touched ); 108 $page++; 109 } while ( self::PAGE_SIZE === $fetched ); 110 111 return $entries; 112 } 113 114 /** 115 * Emit the entries for one parent product (each published, purchasable 116 * variation for variable products). 117 * 118 * @param \WC_Product $product Parent product. 119 * @param callable $sink Entry receiver. 120 * @param int[] $touched Product IDs loaded during this page (variations are appended). 121 * @return int Entries emitted. 122 */ 123 private static function emit_product( \WC_Product $product, callable $sink, array &$touched ): int { 124 if ( ! $product->is_type( 'variable' ) ) { 44 125 $entry = self::build_entry( $product ); 45 126 if ( $entry ) { 46 $feed[] = $entry; 47 } 48 } 49 50 foreach ( $variable as $product ) { 51 $children = $product->get_children(); 52 if ( empty( $children ) ) { 53 continue; 54 } 55 // Include each visible variation. 56 foreach ( $children as $var_id ) { 57 $variation = wc_get_product( $var_id ); 58 if ( $variation && $variation->is_purchasable() && 'publish' === $variation->get_status() ) { 59 $entry = self::build_entry( $variation, $product ); 60 if ( $entry ) { 61 $feed[] = $entry; 62 } 127 $sink( $entry ); 128 return 1; 129 } 130 return 0; 131 } 132 133 $emitted = 0; 134 foreach ( $product->get_children() as $var_id ) { 135 $var_id = (int) $var_id; 136 $touched[] = $var_id; 137 $variation = wc_get_product( $var_id ); 138 if ( $variation && $variation->is_purchasable() && 'publish' === $variation->get_status() ) { 139 $entry = self::build_entry( $variation, $product ); 140 if ( $entry ) { 141 $sink( $entry ); 142 $emitted++; 63 143 } 64 144 } 65 145 } 66 67 return $feed; 146 return $emitted; 147 } 148 149 /** 150 * Drop what this page loaded from the in-request object cache. Every 151 * product hydration pumps posts, post meta and terms into the runtime 152 * cache; without this a 5,000-product walk exhausts 128M. The runtime 153 * flush leaves a persistent object cache (Redis, Memcached) untouched; 154 * drop-ins without flush_runtime fall back to per-post deletes. 155 * 156 * @param int[] $ids Product and variation IDs loaded during the page. 157 */ 158 private static function release_page_cache( array $ids ): void { 159 if ( function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) && function_exists( 'wp_cache_flush_runtime' ) ) { 160 wp_cache_flush_runtime(); 161 return; 162 } 163 if ( ! function_exists( 'wp_cache_delete' ) ) { 164 return; 165 } 166 foreach ( array_unique( $ids ) as $id ) { 167 wp_cache_delete( $id, 'posts' ); 168 wp_cache_delete( $id, 'post_meta' ); 169 } 68 170 } 69 171 … … 138 240 'mpn' => mb_substr( (string) $product->get_sku(), 0, 70 ), 139 241 'condition' => 'new', 140 'is_eligible_search' => FeedFormatter::bool( true ), 242 'is_eligible_search' => FeedFormatter::bool( self::is_eligible_search( $product, $source ) ), 243 // Checkout eligibility stays false at launch: instant checkout needs the merchant programme's checkout integration. 141 244 'is_eligible_checkout' => FeedFormatter::bool( false ), 142 245 'target_countries' => implode( ',', TargetCountries::list() ), … … 158 261 159 262 /** 263 * A product can be surfaced in ChatGPT search when it is published, can 264 * be bought, is in stock and is not hidden from the catalogue. 265 * 266 * @param \WC_Product $product The product or variation. 267 * @param \WC_Product $source The product whose catalogue visibility applies (the parent for variations). 268 */ 269 public static function is_eligible_search( \WC_Product $product, \WC_Product $source ): bool { 270 return 'publish' === $product->get_status() 271 && $product->is_purchasable() 272 && $product->is_in_stock() 273 && 'hidden' !== $source->get_catalog_visibility(); 274 } 275 276 /** 160 277 * Determine the OpenAI availability value for a product. 161 278 * … … 169 286 170 287 /** 171 * Generate and save the feed to a file. 172 * 173 * @return string|false File path on success, false on failure. 174 */ 175 public static function generate_file(): string { 176 $feed = self::generate(); 177 178 $upload_dir = wp_upload_dir(); 179 $dir = $upload_dir['basedir'] . '/blazeaid'; 180 181 if ( ! file_exists( $dir ) ) { 182 wp_mkdir_p( $dir ); 183 } 184 185 // Initialize WP Filesystem. 186 global $wp_filesystem; 187 if ( ! function_exists( 'WP_Filesystem' ) ) { 188 require_once ABSPATH . 'wp-admin/includes/file.php'; 189 } 190 WP_Filesystem(); 191 192 // Write JSON feed. 193 $json_path = $dir . '/chatgpt-product-feed.json'; 194 $written = $wp_filesystem->put_contents( 195 $json_path, 196 wp_json_encode( $feed, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ), 197 FS_CHMOD_FILE 198 ); 199 200 if ( ! $written ) { 201 return ''; 202 } 203 204 // Write CSV feed (the format OpenAI ingests). 205 $csv_path = $dir . '/chatgpt-product-feed.csv'; 206 $csv_written = $wp_filesystem->put_contents( $csv_path, FeedFormatter::to_csv( $feed ), FS_CHMOD_FILE ); 207 if ( ! $csv_written ) { 208 return ''; 209 } 210 211 // Protect directory. 212 $htaccess = $dir . '/.htaccess'; 213 if ( ! $wp_filesystem->exists( $htaccess ) ) { 214 $wp_filesystem->put_contents( $htaccess, "Options -Indexes\n", FS_CHMOD_FILE ); 215 } 288 * Generate the feed, streaming CSV and JSON to the uploads directory. 289 * 290 * @return string|\WP_Error JSON file path on success. 291 */ 292 public static function generate_file() { 293 $dir = FeedStorage::dir(); 294 if ( is_wp_error( $dir ) ) { 295 self::set_progress( 'error', 0, self::count_products(), $dir->get_error_message() ); 296 return $dir; 297 } 298 299 if ( ! self::lock() ) { 300 return new \WP_Error( 'blazeaid_feed_running', __( 'A feed generation is already running.', 'blaze-ai-discovery-for-woocommerce' ) ); 301 } 302 303 if ( function_exists( 'set_time_limit' ) ) { 304 set_time_limit( self::TIME_LIMIT ); 305 } 306 307 $total = self::count_products(); 308 self::set_progress( 'running', 0, $total ); 309 310 $csv = FeedWriter::open( $dir . '/' . FeedStorage::CSV_FILE ); 311 if ( is_wp_error( $csv ) ) { 312 return self::fail( $csv, $total ); 313 } 314 $json = FeedWriter::open( $dir . '/' . FeedStorage::JSON_FILE ); 315 if ( is_wp_error( $json ) ) { 316 $csv->abort(); 317 return self::fail( $json, $total ); 318 } 319 320 $csv->write( FeedFormatter::csv_header() ); 321 $json->write( "[\n" ); 322 323 $count = 0; 324 $sink = static function ( array $entry ) use ( $csv, $json, &$count ): void { 325 $csv->write( FeedFormatter::csv_row( $entry ) ); 326 $json->write( ( $count ? ",\n" : '' ) . wp_json_encode( $entry, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); 327 $count++; 328 }; 329 $on_page = static function ( int $done, int $total ): void { 330 self::set_progress( 'running', $done, $total ); 331 set_transient( self::LOCK_TRANSIENT, time(), self::LOCK_TTL ); 332 }; 333 334 try { 335 self::each_entry( $sink, $on_page ); 336 } catch ( \Throwable $e ) { 337 $csv->abort(); 338 $json->abort(); 339 return self::fail( new \WP_Error( 'blazeaid_feed_exception', $e->getMessage() ), $total ); 340 } 341 342 $json->write( "\n]\n" ); 343 344 $committed = $csv->commit(); 345 if ( is_wp_error( $committed ) ) { 346 $json->abort(); 347 return self::fail( $committed, $total ); 348 } 349 $committed = $json->commit(); 350 if ( is_wp_error( $committed ) ) { 351 return self::fail( $committed, $total ); 352 } 353 354 FeedStorage::protect_dir( $dir ); 216 355 217 356 // Store metadata. 218 357 update_option( 'blazeaid_feed_generated_at', current_time( 'mysql', true ) ); 219 update_option( 'blazeaid_feed_product_count', count( $feed ) ); 220 221 return $json_path; 358 update_option( 'blazeaid_feed_product_count', $count ); 359 self::set_progress( 'done', $total, $total ); 360 self::unlock(); 361 362 return $json->path(); 363 } 364 365 /** 366 * Record a queued run so the admin UI shows it before the worker starts. 367 */ 368 public static function mark_queued(): void { 369 $progress = self::progress(); 370 if ( 'running' === $progress['state'] ) { 371 return; 372 } 373 self::set_progress( 'queued', 0, self::count_products() ); 374 } 375 376 /** 377 * Progress of the current or last run. A run that stopped reporting 378 * for longer than the lock TTL (killed by memory or time) is reported 379 * as an error rather than running forever. 380 * 381 * @return array{state: string, done: int, total: int, updated_at: string, error: string|null} 382 */ 383 public static function progress(): array { 384 $defaults = [ 385 'state' => 'idle', 386 'done' => 0, 387 'total' => 0, 388 'updated_at' => '', 389 'error' => null, 390 ]; 391 $stored = get_option( self::PROGRESS_OPTION, [] ); 392 $progress = is_array( $stored ) ? array_merge( $defaults, array_intersect_key( $stored, $defaults ) ) : $defaults; 393 394 if ( in_array( $progress['state'], [ 'running', 'queued' ], true ) && '' !== $progress['updated_at'] ) { 395 $age = time() - (int) strtotime( $progress['updated_at'] . ' UTC' ); 396 if ( 'running' === $progress['state'] && $age > self::LOCK_TTL ) { 397 $progress['state'] = 'error'; 398 $progress['error'] = __( 'The last feed run stopped without finishing (out of memory or time?). Try again.', 'blaze-ai-discovery-for-woocommerce' ); 399 } 400 } 401 402 return $progress; 403 } 404 405 /** 406 * @return \WP_Error The error, after recording it. 407 */ 408 private static function fail( \WP_Error $error, int $total ): \WP_Error { 409 self::set_progress( 'error', 0, $total, $error->get_error_message() ); 410 self::unlock(); 411 return $error; 412 } 413 414 private static function set_progress( string $state, int $done, int $total, ?string $error = null ): void { 415 update_option( 416 self::PROGRESS_OPTION, 417 [ 418 'state' => $state, 419 'done' => $done, 420 'total' => $total, 421 'updated_at' => gmdate( 'Y-m-d H:i:s' ), 422 'error' => $error, 423 ], 424 false 425 ); 426 } 427 428 private static function lock(): bool { 429 if ( false !== get_transient( self::LOCK_TRANSIENT ) ) { 430 return false; 431 } 432 set_transient( self::LOCK_TRANSIENT, time(), self::LOCK_TTL ); 433 return true; 434 } 435 436 private static function unlock(): void { 437 delete_transient( self::LOCK_TRANSIENT ); 222 438 } 223 439 … … 226 442 */ 227 443 public static function get_feed_url(): string { 228 $upload_dir = wp_upload_dir(); 229 return $upload_dir['baseurl'] . '/blazeaid/chatgpt-product-feed.csv'; 444 return FeedStorage::csv_url(); 230 445 } 231 446 … … 234 449 */ 235 450 public static function get_json_url(): string { 236 $upload_dir = wp_upload_dir(); 237 return $upload_dir['baseurl'] . '/blazeaid/chatgpt-product-feed.json'; 451 return FeedStorage::json_url(); 238 452 } 239 453 } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Feed/FeedFormatter.php
r3668873 r3673252 56 56 */ 57 57 public static function to_csv( array $feed ): string { 58 $out = self:: row( self::COLUMNS);58 $out = self::csv_header(); 59 59 foreach ( $feed as $entry ) { 60 $cells = []; 61 foreach ( self::COLUMNS as $column ) { 62 $cells[] = isset( $entry[ $column ] ) ? (string) $entry[ $column ] : ''; 63 } 64 $out .= self::row( $cells ); 60 $out .= self::csv_row( $entry ); 65 61 } 66 62 return $out; 63 } 64 65 /** 66 * The CSV header line. 67 */ 68 public static function csv_header(): string { 69 return self::row( self::COLUMNS ); 70 } 71 72 /** 73 * One CSV line for an entry keyed by COLUMNS names (missing keys become empty cells). 74 */ 75 public static function csv_row( array $entry ): string { 76 $cells = []; 77 foreach ( self::COLUMNS as $column ) { 78 $cells[] = isset( $entry[ $column ] ) ? (string) $entry[ $column ] : ''; 79 } 80 return self::row( $cells ); 67 81 } 68 82 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Feed/FeedScheduler.php
r3666933 r3673252 1 1 <?php 2 2 /** 3 * Schedules daily feed regeneration via Action Scheduler. 3 * Schedules feed regeneration via Action Scheduler: a daily recurring 4 * refresh plus on-demand runs queued by POST /feed/generate. 4 5 * 5 6 * @package BlazeAiDiscovery … … 12 13 class FeedScheduler { 13 14 14 private const HOOK = 'blazeaid_feed_refresh'; 15 public const HOOK = 'blazeaid_feed_refresh'; 16 public const GROUP = 'blazeaid'; 17 18 /** Args of an on-demand run; distinguishes it from the daily recurring action (no args). */ 19 public const MANUAL_ARGS = [ 'trigger' => 'manual' ]; 15 20 16 21 public function register(): void { … … 22 27 */ 23 28 public function schedule(): void { 24 if ( false === as_has_scheduled_action( self::HOOK ) ) {29 if ( false === as_has_scheduled_action( self::HOOK, [], self::GROUP ) ) { 25 30 as_schedule_recurring_action( 26 31 strtotime( 'tomorrow 4:00am' ), … … 28 33 self::HOOK, 29 34 [], 30 'blazeaid'35 self::GROUP 31 36 ); 32 37 } … … 34 39 35 40 /** 36 * Refresh the feed file. 41 * Queue an on-demand run (no duplicate while one is pending). 42 * 43 * @return bool False when Action Scheduler is unavailable. 44 */ 45 public static function enqueue(): bool { 46 if ( ! function_exists( 'as_enqueue_async_action' ) || ! function_exists( 'as_has_scheduled_action' ) ) { 47 return false; 48 } 49 if ( ! as_has_scheduled_action( self::HOOK, self::MANUAL_ARGS, self::GROUP ) ) { 50 as_enqueue_async_action( self::HOOK, self::MANUAL_ARGS, self::GROUP ); 51 } 52 return true; 53 } 54 55 /** 56 * Refresh the feed file (daily and on-demand runs alike). Errors are 57 * recorded in the feed progress option, where the admin page reads them. 37 58 */ 38 59 public function refresh(): void { -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Feed/FeedValidator.php
r3668873 r3673252 26 26 ]; 27 27 28 /** Both eligibility flags are validated the same way. */ 29 private const ELIGIBILITY_FLAGS = [ 'is_eligible_search', 'is_eligible_checkout' ]; 30 31 /** Rows listed under "issues"; counts keep going past this. */ 32 public const MAX_LISTED_ISSUES = 500; 33 28 34 /** 29 35 * Validate a feed and return issues. 30 36 * 31 37 * @param array[] $feed Array of feed entries. 32 * @return array{valid: int, invalid: int, i ssues: array}38 * @return array{valid: int, invalid: int, ineligible: int, issues: array, checked: int, truncated: bool} 33 39 */ 34 40 public static function validate( array $feed ): array { 35 $valid = 0; 36 $invalid = 0; 37 $issues = []; 41 $result = self::empty_result(); 42 foreach ( $feed as $entry ) { 43 self::tally( (array) $entry, $result ); 44 } 45 return $result; 46 } 38 47 39 foreach ( $feed as $entry ) { 40 $entry_issues = self::validate_entry( $entry ); 48 /** 49 * Validate the written CSV feed line by line, up to $limit rows, so a 50 * large catalogue is never loaded into memory to validate it. 51 * 52 * @param string $path CSV file path. 53 * @param int $limit Rows to check; the result says whether it stopped early. 54 * @return array{valid: int, invalid: int, ineligible: int, issues: array, checked: int, truncated: bool} 55 */ 56 public static function validate_file( string $path, int $limit = 2000 ): array { 57 $result = self::empty_result(); 41 58 42 if ( empty( $entry_issues ) ) { 43 $valid++; 44 } else { 45 $invalid++; 46 $issues[] = [ 47 'product_id' => $entry['item_id'] ?? 'unknown', 48 'title' => $entry['title'] ?? 'Unknown', 49 'issues' => $entry_issues, 50 ]; 51 } 59 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- line-by-line read; WP_Filesystem has no streaming read. 60 $handle = is_readable( $path ) ? fopen( $path, 'rb' ) : false; 61 if ( false === $handle ) { 62 $result['error'] = __( 'The feed file could not be read.', 'blaze-ai-discovery-for-woocommerce' ); 63 return $result; 52 64 } 53 65 66 // Explicit escape '' (no escape character): FeedFormatter writes RFC 67 // 4180 rows that double quotes and never backslash-escape, so a 68 // literal backslash before a quote must stay literal; and PHP 8.4 69 // deprecates relying on the default (one notice per row otherwise). 70 $header = fgetcsv( $handle, null, ',', '"', '' ); 71 if ( ! is_array( $header ) ) { 72 fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose 73 $result['error'] = __( 'The feed file has no header row.', 'blaze-ai-discovery-for-woocommerce' ); 74 return $result; 75 } 76 77 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition 78 while ( false !== ( $row = fgetcsv( $handle, null, ',', '"', '' ) ) ) { 79 if ( [ null ] === $row ) { 80 continue; // Blank line. 81 } 82 if ( $result['checked'] >= $limit ) { 83 $result['truncated'] = true; 84 break; 85 } 86 $entry = []; 87 foreach ( $header as $i => $column ) { 88 $entry[ (string) $column ] = $row[ $i ] ?? ''; 89 } 90 self::tally( $entry, $result ); 91 } 92 93 fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose 94 95 return $result; 96 } 97 98 /** 99 * @return array{valid: int, invalid: int, ineligible: int, issues: array, checked: int, truncated: bool} 100 */ 101 public static function empty_result(): array { 54 102 return [ 55 'valid' => $valid, 56 'invalid' => $invalid, 57 'issues' => $issues, 103 'valid' => 0, 104 'invalid' => 0, 105 'ineligible' => 0, 106 'issues' => [], 107 'checked' => 0, 108 'truncated' => false, 58 109 ]; 110 } 111 112 /** 113 * Count one entry. Hard issues make it invalid; a false search flag is 114 * counted separately (the product is fine, it just will not be surfaced 115 * right now — out of stock, not purchasable) and listed with the reason. 116 */ 117 private static function tally( array $entry, array &$result ): void { 118 $issues = self::validate_entry( $entry ); 119 $eligible = 'true' === ( $entry['is_eligible_search'] ?? '' ); 120 121 $result['checked']++; 122 if ( empty( $issues ) ) { 123 $result['valid']++; 124 } else { 125 $result['invalid']++; 126 } 127 if ( ! $eligible ) { 128 $result['ineligible']++; 129 $issues[] = __( 'is_eligible_search is false (out of stock, not purchasable or hidden from the catalogue) — this product will not appear in ChatGPT search until that changes.', 'blaze-ai-discovery-for-woocommerce' ); 130 } 131 132 if ( ! empty( $issues ) && count( $result['issues'] ) < self::MAX_LISTED_ISSUES ) { 133 $result['issues'][] = [ 134 'product_id' => $entry['item_id'] ?? 'unknown', 135 'title' => $entry['title'] ?? 'Unknown', 136 'issues' => $issues, 137 'eligible' => $eligible, 138 ]; 139 } 59 140 } 60 141 … … 69 150 70 151 foreach ( self::REQUIRED_FIELDS as $field ) { 71 if ( empty( $entry[ $field ] )) {152 if ( ! isset( $entry[ $field ] ) || '' === (string) $entry[ $field ] ) { 72 153 $issues[] = sprintf( 73 154 /* translators: %s: field name */ … … 90 171 } 91 172 92 if ( isset( $entry['is_eligible_search'] ) && 'true' !== $entry['is_eligible_search'] ) { 93 $issues[] = __( 'is_eligible_search is false — this product will not appear in ChatGPT search.', 'blaze-ai-discovery-for-woocommerce' ); 173 foreach ( self::ELIGIBILITY_FLAGS as $flag ) { 174 if ( isset( $entry[ $flag ] ) && '' !== $entry[ $flag ] && ! in_array( $entry[ $flag ], [ 'true', 'false' ], true ) ) { 175 $issues[] = sprintf( 176 /* translators: %s: field name */ 177 __( '%s must be "true" or "false".', 'blaze-ai-discovery-for-woocommerce' ), 178 $flag 179 ); 180 } 94 181 } 95 182 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/LlmsTxt/LlmsTxtRewriter.php
r3670977 r3673252 12 12 class LlmsTxtRewriter { 13 13 14 /** Regex key of the rule in $wp_rewrite->extra_rules_top. */ 15 public const RULE_REGEX = '^llms\.txt$'; 16 17 /** Query string the rule rewrites to. */ 18 public const RULE_TARGET = 'index.php?blazeaid_llms_txt=1'; 19 20 /** 21 * Option set by the install flow; the next init adds the rule and then 22 * flushes, so the persisted rules contain it. The activation request 23 * itself cannot do that in general: the plugin file is included after 24 * init has fired, so a flush there runs before the rule exists. 25 * 26 * Consumed by writing 0, never deleted: maybe_flush() reads it on every 27 * request, and a missing option is a SELECT per request on a site 28 * without a persistent object cache, while a present one rides along 29 * with the autoloaded options. 30 */ 31 public const FLUSH_OPTION = 'blazeaid_flush_rewrite'; 32 33 /** init priority of the deferred flush; after every add_rewrite_rule() at the default priority. */ 34 public const FLUSH_PRIORITY = 99; 35 14 36 public function register(): void { 15 37 add_action( 'init', [ $this, 'add_rewrite_rule' ] ); 38 add_action( 'init', [ $this, 'maybe_flush' ], self::FLUSH_PRIORITY ); 16 39 add_filter( 'query_vars', [ $this, 'add_query_var' ] ); 40 add_filter( 'redirect_canonical', [ $this, 'skip_canonical_redirect' ], 10, 2 ); 17 41 add_action( 'template_redirect', [ $this, 'serve' ] ); 18 42 } 19 43 44 /** 45 * redirect_canonical: with a trailing-slash permalink structure, core 46 * answers /llms.txt with a 301 to /llms.txt/ before our template_redirect 47 * runs. The file is the canonical URL; serve it at 200 directly. 48 * 49 * @param string|false $redirect_url Where core wants to send the request. 50 * @param string $requested_url The URL requested. 51 * @return string|false False for our request (no redirect), else unchanged. 52 */ 53 public function skip_canonical_redirect( $redirect_url, $requested_url = '' ) { 54 if ( get_query_var( 'blazeaid_llms_txt' ) ) { 55 return false; 56 } 57 58 $path = is_string( $requested_url ) ? (string) wp_parse_url( $requested_url, PHP_URL_PATH ) : ''; 59 if ( 'llms.txt' === basename( $path ) && '/' !== substr( $path, -1 ) ) { 60 return false; 61 } 62 63 return $redirect_url; 64 } 65 20 66 public function add_rewrite_rule(): void { 21 add_rewrite_rule( '^llms\.txt$', 'index.php?blazeaid_llms_txt=1', 'top' ); 67 add_rewrite_rule( self::RULE_REGEX, self::RULE_TARGET, 'top' ); 68 } 69 70 /** 71 * Take the rule out of the in-memory rewrite object so a flush that 72 * follows (deactivation) persists rules without it. 73 */ 74 public function remove_rewrite_rule(): void { 75 global $wp_rewrite; 76 if ( is_object( $wp_rewrite ) && isset( $wp_rewrite->extra_rules_top ) && is_array( $wp_rewrite->extra_rules_top ) ) { 77 unset( $wp_rewrite->extra_rules_top[ self::RULE_REGEX ] ); 78 } 79 } 80 81 /** 82 * Ask the next init to flush (after the rule is added). Per site, so it 83 * is the right call under switch_to_blog() too. 84 */ 85 public static function schedule_flush(): void { 86 update_option( self::FLUSH_OPTION, 1 ); 87 } 88 89 /** 90 * init:99 — consume the flush request: rule first, then a soft flush. 91 */ 92 public function maybe_flush(): void { 93 if ( ! get_option( self::FLUSH_OPTION ) ) { 94 return; 95 } 96 self::consume_flush(); 97 $this->add_rewrite_rule(); 98 flush_rewrite_rules( false ); 99 } 100 101 /** 102 * Single-site activation: add the rule, then flush, in this request, so 103 * /llms.txt answers straight away instead of on the next init. 104 */ 105 public function flush_now(): void { 106 self::consume_flush(); 107 $this->add_rewrite_rule(); 108 flush_rewrite_rules(); 109 } 110 111 /** 112 * Deactivation: the plugin is loaded, so init added the rule; drop it 113 * before flushing or /llms.txt keeps answering with the homepage. 114 */ 115 public function flush_without_rule(): void { 116 $this->remove_rewrite_rule(); 117 flush_rewrite_rules(); 118 } 119 120 /** 121 * Deactivation of a site we are switched into (network deactivation): 122 * flush_rewrite_rules() would persist the *current* site's rewrite 123 * structure — $wp_rewrite is not per site — into this one. Drop the 124 * persisted rules instead; core regenerates them, without our rule, 125 * on that site's next request. 126 */ 127 public function drop_persisted_rules(): void { 128 $this->remove_rewrite_rule(); 129 delete_option( 'rewrite_rules' ); 130 } 131 132 /** Mark the deferred flush done, keeping the option autoloaded (see FLUSH_OPTION). */ 133 private static function consume_flush(): void { 134 update_option( self::FLUSH_OPTION, 0 ); 22 135 } 23 136 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Rest/AuditController.php
r3672021 r3673252 10 10 class AuditController { 11 11 12 /** PHP time limit for a forced inline run: t wo self-fetches plus a 25 s cloud call. */12 /** PHP time limit for a forced inline run: the loopback checks plus the 12 s cloud budget. */ 13 13 public const INLINE_TIME_LIMIT = 90; 14 14 … … 87 87 /** 88 88 * Run the audit on the request thread. A forced run raises the time 89 * limit where the host allows it and drops the still-pending queued90 * copy of the action first, so the queue does not repeat this audit91 * later. A copy already being processed by a cron run is not affected92 * and may still finish; whichever run saves last is the latest audit.89 * limit where the host allows it and, when Action Scheduler can pick 90 * the rest up, gives the cloud checks a shared budget 91 * (AuditRunner::INLINE_CLOUD_BUDGET): local rows come back complete, 92 * cloud rows that did not fit come back `pending`. 93 93 * 94 * @return array{results: array, overall_status: string} 94 * The queued copy of the action is touched only after the inline result 95 * is saved — a proxy or PHP-FPM kill mid-run leaves the queue as it was. 96 * Then: rows pending → make sure a background audit is queued to 97 * replace them; nothing pending → drop the queued copy so the queue 98 * does not repeat this audit. A copy already being processed by a cron 99 * run is not affected; whichever run saves last is the latest audit. 100 * 101 * @return array{results: array, overall_status: string, pending: bool} 95 102 */ 96 103 private function run_inline( bool $force ): array { 97 if ( $force ) { 98 if ( function_exists( 'set_time_limit' ) ) { 99 set_time_limit( self::INLINE_TIME_LIMIT ); 100 } 101 if ( function_exists( 'as_unschedule_action' ) ) { 104 if ( $force && function_exists( 'set_time_limit' ) ) { 105 set_time_limit( self::INLINE_TIME_LIMIT ); 106 } 107 108 $budgeted = $force && $this->scheduler_available(); 109 $options = $budgeted ? [ 'cloud_budget' => $this->inline_cloud_budget() ] : []; 110 111 $audit = ( new AuditRunner() )->run( $options ); 112 113 if ( $force && $this->scheduler_available() ) { 114 if ( ! empty( $audit['pending'] ) ) { 115 if ( ! as_has_scheduled_action( AuditModule::AUDIT_HOOK, null, AuditModule::AUDIT_GROUP ) ) { 116 as_enqueue_async_action( AuditModule::AUDIT_HOOK, [], AuditModule::AUDIT_GROUP ); 117 } 118 } elseif ( function_exists( 'as_unschedule_action' ) ) { 102 119 as_unschedule_action( AuditModule::AUDIT_HOOK, [], AuditModule::AUDIT_GROUP ); 103 120 } 104 121 } 105 122 106 $runner = new AuditRunner(); 107 return $runner->run(); 123 return $audit; 124 } 125 126 /** 127 * Seam for tests: seconds the cloud checks share on a forced inline run. 128 */ 129 protected function inline_cloud_budget(): float { 130 return (float) AuditRunner::INLINE_CLOUD_BUDGET; 108 131 } 109 132 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Rest/FeedController.php
r3668873 r3673252 6 6 7 7 use BlazeAiDiscovery\Feed\ChatGptFeedGenerator; 8 use BlazeAiDiscovery\Feed\FeedScheduler; 9 use BlazeAiDiscovery\Feed\FeedStorage; 8 10 use BlazeAiDiscovery\Feed\FeedValidator; 9 11 10 12 class FeedController { 13 14 /** Rows of the written CSV that GET /feed/validate checks. */ 15 public const VALIDATE_ROWS = 2000; 11 16 12 17 public function register(): void { … … 21 26 'callback' => [ $this, 'generate' ], 22 27 'permission_callback' => [ $this, 'check_permission' ], 28 'args' => [ 29 'force' => [ 30 'type' => 'boolean', 31 'default' => false, 32 'description' => 'Generate on this request instead of queueing; honoured only for catalogues up to the inline limit.', 33 ], 34 ], 23 35 ] ); 24 36 … … 40 52 } 41 53 42 public function generate(): \WP_REST_Response { 43 $path = ChatGptFeedGenerator::generate_file(); 54 /** 55 * Queue a feed run on Action Scheduler and answer 202 {queued, progress}; 56 * the client polls GET /feed/status until progress.state is done or 57 * error. `{ force: true }` runs it on this request (200) when the 58 * catalogue is small enough to hydrate within a request's memory and 59 * time; the inline path is also used when Action Scheduler is missing. 60 * 61 * @param \WP_REST_Request|null $request Null only from direct callers (tests). 62 */ 63 public function generate( $request = null ): \WP_REST_Response { 64 $force = is_object( $request ) && method_exists( $request, 'get_param' ) 65 ? rest_sanitize_boolean( $request->get_param( 'force' ) ) 66 : false; 44 67 45 if ( empty( $path ) ) { 46 return new \WP_REST_Response( [ 'error' => 'Failed to generate feed file.' ], 500 ); 68 $total = ChatGptFeedGenerator::count_products(); 69 $scheduler = $this->scheduler_available(); 70 71 if ( ! $scheduler && $total > ChatGptFeedGenerator::INLINE_LIMIT ) { 72 // Nothing can run this in the background, and running it on the 73 // request would hit the memory or time limit part way through. 74 return new \WP_REST_Response( 75 [ 76 'error' => sprintf( 77 /* translators: 1: number of products in the catalogue, 2: largest catalogue generated on a request */ 78 __( 'This catalogue has %1$s products, more than the %2$s a single request can generate, and Action Scheduler (part of WooCommerce) is not available to run it in the background. Make sure WooCommerce is active and up to date, then try again.', 'blaze-ai-discovery-for-woocommerce' ), 79 number_format_i18n( $total ), 80 number_format_i18n( ChatGptFeedGenerator::INLINE_LIMIT ) 81 ), 82 'code' => 'blazeaid_feed_no_scheduler', 83 ] + $this->status_payload(), 84 503 85 ); 47 86 } 48 87 49 $upload_dir = wp_upload_dir(); 50 $csv_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.csv'; 51 $json_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.json'; 88 $inline = ! $scheduler || ( $force && $total <= ChatGptFeedGenerator::INLINE_LIMIT ); 52 89 53 return new \WP_REST_Response( [ 54 'message' => __( 'Feed generated successfully.', 'blaze-ai-discovery-for-woocommerce' ), 55 'download_url' => file_exists( $csv_path ) ? ChatGptFeedGenerator::get_feed_url() : null, 56 'json_url' => file_exists( $json_path ) ? ChatGptFeedGenerator::get_json_url() : null, 57 'product_count' => (int) get_option( 'blazeaid_feed_product_count', 0 ), 58 'generated_at' => get_option( 'blazeaid_feed_generated_at', '' ), 59 ] ); 90 if ( $inline ) { 91 $result = ChatGptFeedGenerator::generate_file(); 92 if ( is_wp_error( $result ) ) { 93 $status = 'blazeaid_feed_running' === $result->get_error_code() ? 409 : 500; 94 return new \WP_REST_Response( 95 [ 96 'error' => $result->get_error_message(), 97 'code' => $result->get_error_code(), 98 ] + $this->status_payload(), 99 $status 100 ); 101 } 102 return new \WP_REST_Response( 103 [ 'message' => __( 'Feed generated successfully.', 'blaze-ai-discovery-for-woocommerce' ) ] + $this->status_payload() 104 ); 105 } 106 107 FeedScheduler::enqueue(); 108 ChatGptFeedGenerator::mark_queued(); 109 110 return new \WP_REST_Response( [ 'queued' => true ] + $this->status_payload(), 202 ); 60 111 } 61 112 62 113 public function get_status(): \WP_REST_Response { 63 $generated = get_option( 'blazeaid_feed_generated_at', '' ); 64 65 $upload_dir = wp_upload_dir(); 66 $csv_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.csv'; 67 $json_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.json'; 68 69 return new \WP_REST_Response( [ 70 'generated_at' => $generated, 71 'product_count' => (int) get_option( 'blazeaid_feed_product_count', 0 ), 72 'download_url' => file_exists( $csv_path ) ? ChatGptFeedGenerator::get_feed_url() : null, 73 'json_url' => file_exists( $json_path ) ? ChatGptFeedGenerator::get_json_url() : null, 74 ] ); 114 return new \WP_REST_Response( $this->status_payload() ); 75 115 } 76 116 117 /** 118 * Validate the written CSV, up to VALIDATE_ROWS rows, without loading 119 * the catalogue. 120 */ 77 121 public function validate(): \WP_REST_Response { 78 $feed = ChatGptFeedGenerator::generate(); 79 $validation = FeedValidator::validate( $feed ); 122 $path = FeedStorage::csv_path(); 123 if ( ! file_exists( $path ) ) { 124 return new \WP_REST_Response( FeedValidator::empty_result() + [ 'available' => false ] ); 125 } 80 126 81 return new \WP_REST_Response( $validation ); 127 return new \WP_REST_Response( FeedValidator::validate_file( $path, self::VALIDATE_ROWS ) + [ 'available' => true ] ); 128 } 129 130 /** 131 * @return array{generated_at: string, product_count: int, download_url: ?string, json_url: ?string, progress: array, total_products: int, inline_limit: int} 132 */ 133 private function status_payload(): array { 134 return [ 135 'generated_at' => (string) get_option( 'blazeaid_feed_generated_at', '' ), 136 'product_count' => (int) get_option( 'blazeaid_feed_product_count', 0 ), 137 'download_url' => file_exists( FeedStorage::csv_path() ) ? FeedStorage::csv_url() : null, 138 'json_url' => file_exists( FeedStorage::json_path() ) ? FeedStorage::json_url() : null, 139 'progress' => ChatGptFeedGenerator::progress(), 140 'total_products' => ChatGptFeedGenerator::count_products(), 141 'inline_limit' => ChatGptFeedGenerator::INLINE_LIMIT, 142 ]; 143 } 144 145 /** 146 * Seam for tests: whether Action Scheduler's enqueue/lookup functions exist. 147 */ 148 protected function scheduler_available(): bool { 149 return function_exists( 'as_enqueue_async_action' ) && function_exists( 'as_has_scheduled_action' ); 82 150 } 83 151 } -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Schema/CompatibilityDetector.php
r3666933 r3673252 3 3 * Detects which SEO/schema plugin owns Product schema output. 4 4 * 5 * Only ONE system owns Product schema at a time (Yoast and Rank Math both6 * disable WooCommerce's native WC_Structured_Data when active).5 * Only the Yoast WooCommerce SEO add-on and Rank Math (with its WooCommerce 6 * module) replace WooCommerce's native WC_Structured_Data; Yoast free does not. 7 7 * 8 8 * @package BlazeAiDiscovery … … 22 22 23 23 /** 24 * Test seam: when non-null, used instead of the live environment. 25 * 26 * @var array|null 27 */ 28 public static $environment_override = null; 29 30 /** 31 * What is installed, as booleans. Product-schema OWNERSHIP is decided in detect(). 32 */ 33 protected static function environment(): array { 34 if ( null !== self::$environment_override ) { 35 return self::$environment_override; 36 } 37 return [ 38 'yoast' => defined( 'WPSEO_VERSION' ), 39 'yoast_woo' => defined( 'WPSEO_WOO_VERSION' ) || class_exists( 'WPSEO_WooCommerce_Schema' ), 40 'rank_math' => defined( 'RANK_MATH_VERSION' ), 41 'schema_pro' => class_exists( 'Schema_Pro_Core' ) || defined( 'BSF_SCHEMAS_VERSION' ), 42 'wc_structured_data' => class_exists( 'WC_Structured_Data' ), 43 ]; 44 } 45 46 /** 24 47 * Detect which schema system is active. 25 48 * … … 27 50 */ 28 51 public static function detect(): string { 29 // Priority order: Yoast > Rank Math > Schema Pro > WooCommerce native > standalone. 30 if ( defined( 'WPSEO_VERSION' ) ) { 52 $env = self::environment(); 53 54 // Yoast owns Product schema only with the WooCommerce SEO add-on. 55 // Yoast free leaves WooCommerce's own Product JSON-LD in place (adm-F6). 56 if ( $env['yoast'] && $env['yoast_woo'] ) { 31 57 return self::YOAST; 32 58 } 33 59 34 if ( defined( 'RANK_MATH_VERSION' )) {60 if ( $env['rank_math'] ) { 35 61 return self::RANK_MATH; 36 62 } 37 63 38 if ( class_exists( 'Schema_Pro_Core' ) || defined( 'BSF_SCHEMAS_VERSION' )) {64 if ( $env['schema_pro'] ) { 39 65 return self::SCHEMA_PRO; 40 66 } 41 67 42 if ( class_exists( 'WC_Structured_Data' )) {68 if ( $env['wc_structured_data'] ) { 43 69 return self::WOOCOMMERCE_NATIVE; 44 70 } 45 71 46 72 return self::STANDALONE; 73 } 74 75 /** 76 * Whether a given plugin/add-on is installed, independent of schema 77 * ownership. Reads the same environment array as detect() (including 78 * the test override), so callers never need defined() directly. 79 * 80 * @param string $flag One of the environment() array keys, e.g. 'yoast'. 81 */ 82 public static function installed( string $flag ): bool { 83 $env = self::environment(); 84 85 return ! empty( $env[ $flag ] ); 47 86 } 48 87 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Schema/SchemaModule.php
r3666933 r3673252 28 28 29 29 public function register(): void { 30 // Schema strategy selection runs immediately (needs to hook early). 31 $this->orchestrator->init(); 30 // Plugin load order is alphabetical, so this module's register() (on 31 // plugins_loaded) can run before an SEO plugin has bootstrapped - 32 // e.g. Rank Math's \RankMath\Helper::is_module_active() would then 33 // report every module off, and RankMathStrategy would wrongly 34 // register the native WooCommerce fallback alongside Rank Math's own 35 // Product block. Defer to init:0, after every plugin's plugins_loaded 36 // callback has run; the augment filters themselves fire far later 37 // (wp_footer / structured-data generation), so nothing is lost. 38 add_action( 'init', [ $this->orchestrator, 'init' ], 0 ); 32 39 } 33 40 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Schema/SchemaOrchestrator.php
r3666933 r3673252 42 42 43 43 case CompatibilityDetector::SCHEMA_PRO: 44 // Schema Pro has limited filter API — use standalone with @id references. 45 $this->strategy = new StandaloneStrategy(); 44 // Schema Pro does not replace WC_Structured_Data — augment 45 // WooCommerce's block; a second standalone block would 46 // duplicate Product with conflicting prices (adm-F8). 47 $this->strategy = new WooCommerceNativeStrategy(); 46 48 break; 47 49 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Schema/Strategies/RankMathStrategy.php
r3666933 r3673252 4 4 * 5 5 * Uses rank_math/json_ld (priority 15) to modify the Product node. 6 * Handles both single-object and @graph structures. 6 * Handles @graph structures, Rank Math's real flat keyed entity map 7 * (@context/@graph are added after this filter runs), and single-object 8 * structures. 7 9 * 8 10 * @package BlazeAiDiscovery … … 19 21 public function register(): void { 20 22 add_filter( 'rank_math/json_ld', [ $this, 'augment' ], 15, 2 ); 23 24 $module_on = false; 25 if ( class_exists( '\RankMath\Helper' ) && method_exists( '\RankMath\Helper', 'is_module_active' ) ) { 26 $module_on = (bool) \RankMath\Helper::is_module_active( 'woocommerce' ); 27 } 28 29 // Rank Math leaves WooCommerce's native Product block in place 30 // unless its "Remove Schema.org Markup" toggle is on. We augment 31 // the WC block only when Rank Math's WooCommerce module is off 32 // (Rank Math then emits no Product node of its own); when the 33 // module is on we never touch the WC block, so we don't extend a 34 // duplicate-block configuration. 35 if ( ! $module_on ) { 36 add_filter( 'woocommerce_structured_data_product', [ new WooCommerceNativeStrategy(), 'augment' ], 20, 2 ); 37 } 21 38 } 22 39 … … 46 63 } 47 64 return $json_ld; 65 } 66 67 // Rank Math passes a flat keyed map of entities and wraps it in 68 // @context/@graph AFTER this filter (adm-F7). Augment any 69 // Product-like value; leave every other entity untouched. Gated on 70 // the payload itself not being a typed node — otherwise a single 71 // Product node with a nested Product-like property (e.g. 72 // isRelatedTo) would have only the nested node augmented here, 73 // short-circuiting before the top-level node is ever touched. 74 if ( ! isset( $json_ld['@type'] ) ) { 75 $augmented = false; 76 foreach ( $json_ld as $key => $value ) { 77 if ( is_array( $value ) && isset( $value['@type'] ) && $this->is_product_type( $value['@type'] ) ) { 78 $json_ld[ $key ] = $this->augment_product_node( $value, $product ); 79 $augmented = true; 80 } 81 } 82 if ( $augmented ) { 83 return $json_ld; 84 } 48 85 } 49 86 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Schema/Strategies/StandaloneStrategy.php
r3666933 r3673252 14 14 use BlazeAiDiscovery\Schema\Builders\ProductSchemaBuilder; 15 15 16 // Unreachable in production: WooCommerce is a hard requirement (Requires 17 // Plugins in the plugin header), so WC_Structured_Data always exists and 18 // CompatibilityDetector never returns STANDALONE on a real store. Kept only 19 // so the detector's STANDALONE branch has a strategy to instantiate. 16 20 class StandaloneStrategy implements StrategyInterface { 17 21 -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Scoring/BatchScorer.php
r3671993 r3673252 4 4 * 5 5 * Processes up to 50 products per chunk, checks memory/time between each, 6 * schedules next chunk with 5s delay. Progress stored in transient. 6 * schedules the next chunk with a 5 s delay. Progress lives in a transient; 7 * a lock option keeps a second chain from starting while one runs. 8 * 9 * Every chunk resumes from the last product id actually scored (an SQL 10 * `ID > last LIMIT 50` cursor), so a chunk cut short by the time or memory 11 * limit continues where it stopped instead of being counted complete. A 12 * chunk that makes no progress at all is retried at most three times, and a 13 * chunk that dies without reporting back is restarted by the healthcheck at 14 * most three times; after that the run is marked `failed` with a reason. 7 15 * 8 16 * @package BlazeAiDiscovery … … 19 27 private const HEALTHCHECK = 'blazeaid_batch_score_healthcheck'; 20 28 public const PROGRESS_KEY = 'blazeaid_scoring_progress'; 29 public const LOCK_OPTION = 'blazeaid_scoring_lock'; 21 30 private const CHUNK_SIZE = 50; 22 31 private const DELAY_SECONDS = 5; … … 24 33 private const MEMORY_PERCENT = 90; 25 34 35 /** Progress transient lifetime: a large catalogue on a WP-Cron-paced queue takes hours, not one. */ 36 private const PROGRESS_TTL = DAY_IN_SECONDS; 37 38 /** A lock older than this (no chunk has reported back) belongs to a dead chain. */ 39 public const LOCK_TTL = 15 * MINUTE_IN_SECONDS; 40 41 /** Attempts a chunk gets before the run is marked failed (both no-progress retries and healthcheck restarts). */ 42 public const MAX_CHUNK_ATTEMPTS = 3; 43 26 44 /** 27 45 * Register hooks. … … 34 52 /** 35 53 * Start a full catalog scoring run. 36 */ 37 public function start(): void { 54 * 55 * @return bool False when a chain is already running (fresh lock): nothing was started. 56 */ 57 public function start(): bool { 58 if ( self::locked() ) { 59 return false; 60 } 61 62 // A stale chain (lock expired) may still have chunk actions queued; 63 // they would score the same ids twice under the new run. 64 as_unschedule_all_actions( self::HOOK ); 65 38 66 $total = (int) wp_count_posts( 'product' )->publish; 39 67 … … 43 71 'total' => $total, 44 72 'started_at' => time(), 73 'updated_at' => time(), 45 74 'last_product_id' => 0, 46 ], HOUR_IN_SECONDS ); 75 'chunk_after_id' => 0, 76 'chunk_attempts' => 0, 77 'restart_from' => null, 78 'restarts' => 0, 79 ], self::PROGRESS_TTL ); 80 81 update_option( self::LOCK_OPTION, time(), false ); 47 82 48 83 // Schedule first chunk immediately. 49 as_enqueue_async_action( self::HOOK, [ 0 ], 'blazeaid');84 as_enqueue_async_action( self::HOOK, [ 0 ], self::GROUP ); 50 85 51 86 // Schedule healthcheck. … … 56 91 self::HEALTHCHECK, 57 92 [], 58 'blazeaid'93 self::GROUP 59 94 ); 60 95 } 96 97 return true; 98 } 99 100 /** 101 * Whether a chain is running and reported back within LOCK_TTL. 102 */ 103 public static function locked(): bool { 104 $progress = self::get_progress(); 105 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 106 return false; 107 } 108 109 $lock = (int) get_option( self::LOCK_OPTION, 0 ); 110 111 return $lock > 0 && ( time() - $lock ) < self::LOCK_TTL; 61 112 } 62 113 … … 67 118 */ 68 119 public function process_chunk( int $after_id ): void { 69 $scorer = new ProductScorer(); 70 $start = microtime( true ); 71 $scored = 0; 72 $last_id = $after_id; 73 74 $products = wc_get_products( [ 75 'status' => 'publish', 76 'limit' => self::CHUNK_SIZE, 77 'orderby' => 'ID', 78 'order' => 'ASC', 79 'return' => 'objects', 80 'type' => [ 'simple', 'variable', 'grouped', 'external' ], 81 'include' => [], 82 'exclude' => [], 83 // Get products with ID > $after_id. 84 ] ); 85 86 // Manual filter for ID > after_id since wc_get_products doesn't support it directly. 87 $filtered = []; 88 foreach ( $products as $product ) { 89 if ( $product->get_id() > $after_id ) { 90 $filtered[] = $product; 91 } 92 } 93 94 // If manual filter returned nothing, use a direct query. 95 if ( empty( $filtered ) ) { 96 global $wpdb; 97 $ids = $wpdb->get_col( 98 $wpdb->prepare( 99 "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' AND ID > %d ORDER BY ID ASC LIMIT %d", 100 $after_id, 101 self::CHUNK_SIZE 102 ) 103 ); 104 foreach ( $ids as $id ) { 105 $product = wc_get_product( (int) $id ); 106 if ( $product ) { 107 $filtered[] = $product; 108 } 109 } 110 } 111 112 foreach ( $filtered as $product ) { 120 $progress = self::get_progress(); 121 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 122 return; // Cancelled, failed or finished meanwhile. 123 } 124 125 $start = microtime( true ); 126 $scored = 0; 127 $last_id = $after_id; 128 $cut = false; 129 $ids = $this->product_ids_after( $after_id, self::CHUNK_SIZE ); 130 131 foreach ( $ids as $id ) { 113 132 // Check resource limits before each product. 114 133 if ( $this->time_exceeded( $start ) || $this->memory_exceeded() ) { 134 $cut = true; 115 135 break; 116 136 } 117 137 118 $result = $scorer->score( $product ); 119 ScoreStore::save( $product->get_id(), $result ); 120 121 $last_id = $product->get_id(); 138 $this->score_one( $id ); 139 140 $last_id = $id; 122 141 $scored++; 123 142 } 124 143 125 // Update progress. 126 $progress = get_transient( self::PROGRESS_KEY ); 127 if ( is_array( $progress ) ) { 128 $progress['scored'] += $scored; 129 $progress['last_product_id'] = $last_id; 130 131 if ( empty( $filtered ) || count( $filtered ) < self::CHUNK_SIZE ) { 132 // All done. 133 $progress['status'] = 'complete'; 134 as_unschedule_all_actions( self::HEALTHCHECK, [], 'blazeaid' ); 144 // Re-read: cancel() may have run meanwhile. 145 $progress = self::get_progress(); 146 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 147 return; 148 } 149 150 $progress['scored'] = (int) ( $progress['scored'] ?? 0 ) + $scored; 151 $progress['last_product_id'] = $last_id; 152 $progress['updated_at'] = time(); 153 154 if ( 0 === $scored && ! empty( $ids ) ) { 155 // Not one product fit: the host is out of time or memory before 156 // the first product. Retry this chunk a bounded number of times. 157 $attempts = ( (int) ( $progress['chunk_after_id'] ?? -1 ) === $after_id ) ? (int) ( $progress['chunk_attempts'] ?? 0 ) + 1 : 1; 158 159 $progress['chunk_after_id'] = $after_id; 160 $progress['chunk_attempts'] = $attempts; 161 162 if ( $attempts >= self::MAX_CHUNK_ATTEMPTS ) { 163 $this->fail( $progress, sprintf( 164 /* translators: 1: number of attempts, 2: product ID the chunk starts after */ 165 __( 'Scoring stopped: the chunk after product ID %2$d could not process a single product within the time or memory limit in %1$d attempts. Raise the PHP memory limit or run WP-Cron from a server cron, then click Recalculate All.', 'blaze-ai-discovery-for-woocommerce' ), 166 $attempts, 167 $after_id 168 ) ); 169 return; 135 170 } 136 171 137 set_transient( self::PROGRESS_KEY, $progress, HOUR_IN_SECONDS ); 138 } 139 140 // Schedule next chunk if there's more. 141 if ( ! empty( $filtered ) && count( $filtered ) >= self::CHUNK_SIZE ) { 142 as_schedule_single_action( 143 time() + self::DELAY_SECONDS, 144 self::HOOK, 145 [ $last_id ], 146 'blazeaid' 147 ); 148 } 149 } 150 151 /** 152 * Healthcheck: restart if progress stalled. 172 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 173 update_option( self::LOCK_OPTION, time(), false ); 174 $this->schedule_chunk( $after_id ); 175 return; 176 } 177 178 $progress['chunk_after_id'] = $last_id; 179 $progress['chunk_attempts'] = 0; 180 181 // Complete only when this was the last page and nothing cut it short. 182 if ( ! $cut && count( $ids ) < self::CHUNK_SIZE ) { 183 $progress['status'] = 'complete'; 184 $progress['completed_at'] = time(); 185 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 186 as_unschedule_all_actions( self::HEALTHCHECK ); 187 delete_option( self::LOCK_OPTION ); 188 return; 189 } 190 191 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 192 update_option( self::LOCK_OPTION, time(), false ); 193 $this->schedule_chunk( $last_id ); 194 } 195 196 /** 197 * Healthcheck: restart from the last scored id when no chunk is 198 * pending or in progress (the last one died without reporting back). Three restarts 199 * from the same position mean the chunk cannot run here; mark failed. 153 200 */ 154 201 public function check_health(): void { 155 $progress = get_transient( self::PROGRESS_KEY ); 156 157 if ( ! is_array( $progress ) || 'running' !== $progress['status'] ) { 158 as_unschedule_all_actions( self::HEALTHCHECK, [], 'blazeaid' ); 159 return; 160 } 161 162 // Check if there's already a pending chunk action. 163 $pending = as_get_scheduled_actions( [ 202 $progress = self::get_progress(); 203 204 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 205 as_unschedule_all_actions( self::HEALTHCHECK ); 206 return; 207 } 208 209 // A chunk that is pending OR currently executing is alive — a 210 // mid-execution chunk is not stalled, and restarting over it 211 // would start a duplicate chain (red-team verification finding, 212 // 2026-08-31). 213 $alive = as_get_scheduled_actions( [ 164 214 'hook' => self::HOOK, 165 'status' => \ActionScheduler_Store::STATUS_PENDING,166 'group' => 'blazeaid',215 'status' => [ \ActionScheduler_Store::STATUS_PENDING, \ActionScheduler_Store::STATUS_RUNNING ], 216 'group' => self::GROUP, 167 217 ] ); 168 218 169 if ( empty( $pending ) ) { 170 // Stalled — re-enqueue from last position. 171 as_enqueue_async_action( 172 self::HOOK, 173 [ $progress['last_product_id'] ], 174 'blazeaid' 175 ); 176 } 219 if ( ! empty( $alive ) ) { 220 return; 221 } 222 223 $from = (int) ( $progress['last_product_id'] ?? 0 ); 224 $restarts = ( isset( $progress['restart_from'] ) && (int) $progress['restart_from'] === $from ) ? (int) ( $progress['restarts'] ?? 0 ) + 1 : 1; 225 226 $progress['restart_from'] = $from; 227 $progress['restarts'] = $restarts; 228 229 if ( $restarts > self::MAX_CHUNK_ATTEMPTS ) { 230 $this->fail( $progress, sprintf( 231 /* translators: 1: number of restarts, 2: product ID scoring stalled after */ 232 __( 'Scoring stopped: the background job died after product ID %2$d and did not get further in %1$d restarts (a PHP fatal or a killed worker, most likely). Check the site\'s error log, then click Recalculate All.', 'blaze-ai-discovery-for-woocommerce' ), 233 self::MAX_CHUNK_ATTEMPTS, 234 $from 235 ) ); 236 return; 237 } 238 239 $progress['updated_at'] = time(); 240 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 241 update_option( self::LOCK_OPTION, time(), false ); 242 243 // Stalled — re-enqueue from last position. 244 as_enqueue_async_action( self::HOOK, [ $from ], self::GROUP ); 177 245 } 178 246 … … 191 259 */ 192 260 public function cancel(): void { 193 as_unschedule_all_actions( self::HOOK , [], 'blazeaid');194 as_unschedule_all_actions( self::HEALTHCHECK , [], 'blazeaid');261 as_unschedule_all_actions( self::HOOK ); 262 as_unschedule_all_actions( self::HEALTHCHECK ); 195 263 delete_transient( self::PROGRESS_KEY ); 196 } 197 198 private function time_exceeded( float $start ): bool { 264 delete_option( self::LOCK_OPTION ); 265 } 266 267 /** 268 * Mark the run failed with a reason the Products page can show, and 269 * tear the chain down. 270 */ 271 private function fail( array $progress, string $reason ): void { 272 $progress['status'] = 'failed'; 273 $progress['reason'] = $reason; 274 $progress['failed_at'] = time(); 275 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 276 277 as_unschedule_all_actions( self::HOOK ); 278 as_unschedule_all_actions( self::HEALTHCHECK ); 279 delete_option( self::LOCK_OPTION ); 280 } 281 282 private function schedule_chunk( int $after_id ): void { 283 as_schedule_single_action( 284 time() + self::DELAY_SECONDS, 285 self::HOOK, 286 [ $after_id ], 287 self::GROUP 288 ); 289 } 290 291 /** 292 * Published product ids after $after_id, ascending, at most $limit. 293 * 294 * @return int[] 295 */ 296 protected function product_ids_after( int $after_id, int $limit ): array { 297 global $wpdb; 298 299 $ids = $wpdb->get_col( 300 $wpdb->prepare( 301 "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' AND ID > %d ORDER BY ID ASC LIMIT %d", 302 $after_id, 303 $limit 304 ) 305 ); 306 307 return array_map( 'intval', is_array( $ids ) ? $ids : [] ); 308 } 309 310 /** 311 * Score and store one product. Products of a type the scorer does not 312 * handle (subscriptions, bundles) are skipped but still advance the 313 * cursor. Seam for tests. 314 */ 315 protected function score_one( int $product_id ): void { 316 $product = wc_get_product( $product_id ); 317 if ( ! $product || ! in_array( $product->get_type(), [ 'simple', 'variable', 'grouped', 'external' ], true ) ) { 318 return; 319 } 320 321 $result = ( new ProductScorer() )->score( $product ); 322 ScoreStore::save( $product_id, $result ); 323 } 324 325 protected function time_exceeded( float $start ): bool { 199 326 return ( microtime( true ) - $start ) > self::TIME_LIMIT; 200 327 } 201 328 202 pr ivatefunction memory_exceeded(): bool {329 protected function memory_exceeded(): bool { 203 330 $limit = $this->get_memory_limit(); 204 331 return ( memory_get_usage( true ) / $limit ) * 100 > self::MEMORY_PERCENT; -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/src/Scoring/Criteria/IdentifierPresence.php
r3666933 r3673252 52 52 $product_id = $product->get_id(); 53 53 54 // WooCommerce native GTIN field (added in WC 9.2+). 55 $gtin = $product->get_global_unique_id(); 56 if ( ! empty( $gtin ) ) { 57 return (string) $gtin; 54 // WooCommerce native GTIN field. The getter only exists from WC 9.2; 55 // on 8.0-9.1 an unguarded call fatals every product page and save. 56 if ( method_exists( $product, 'get_global_unique_id' ) ) { 57 $gtin = $product->get_global_unique_id(); 58 if ( ! empty( $gtin ) ) { 59 return (string) $gtin; 60 } 58 61 } 59 62 60 // Common meta keys from various plugins. 63 // Common meta keys from various plugins. `_global_unique_id` is the 64 // meta WC 9.2+ stores the native field in, so a store that ran a newer 65 // WooCommerce (or a migration that wrote it directly) keeps its GTINs 66 // on an older core too. 61 67 $meta_keys = [ 68 '_global_unique_id', 62 69 '_gtin', 63 70 'gtin', -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/uninstall.php
r3671993 r3673252 1 1 <?php 2 2 /** 3 * Clean uninstall — drop tables, remove options. 3 * Clean uninstall — drop tables, remove options. On multisite every site is 4 * cleaned (plugins can only be deleted from the network admin, so an 5 * uninstall there is always network-wide). 4 6 * 5 7 * @package BlazeAiDiscovery … … 8 10 defined( 'WP_UNINSTALL_PLUGIN' ) || exit; 9 11 10 global $wpdb; 12 /** 13 * Remove everything this plugin stored for the current site. 14 */ 15 function blazeaid_uninstall_site(): void { 16 global $wpdb; 11 17 12 // Drop custom tables.13 $blazeaid_tables = [14 $wpdb->prefix . 'blazeaid_visits',15 $wpdb->prefix . 'blazeaid_orders',16 $wpdb->prefix . 'blazeaid_scores',17 $wpdb->prefix . 'blazeaid_endpoint_log',18 $wpdb->prefix . 'blazeaid_audits',19 ];18 // Drop custom tables. 19 $blazeaid_tables = [ 20 $wpdb->prefix . 'blazeaid_visits', 21 $wpdb->prefix . 'blazeaid_orders', 22 $wpdb->prefix . 'blazeaid_scores', 23 $wpdb->prefix . 'blazeaid_endpoint_log', 24 $wpdb->prefix . 'blazeaid_audits', 25 ]; 20 26 21 foreach ( $blazeaid_tables as $blazeaid_table ) { 22 $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $blazeaid_table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 27 foreach ( $blazeaid_tables as $blazeaid_table ) { 28 $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $blazeaid_table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 29 } 30 31 // Remove options. 32 $blazeaid_options = [ 33 'blazeaid_db_version', 34 'blazeaid_version', 35 'blazeaid_pending_install', 36 'blazeaid_flush_rewrite', 37 'blazeaid_scoring_lock', 38 'blazeaid_feed_progress', 39 'blazeaid_payload_salt', 40 'blazeaid_visitor_salt', 41 'blazeaid_license_key', 42 'blazeaid_license_status', 43 'blazeaid_needs_activation_audit', 44 'blazeaid_llms_txt_content', 45 'blazeaid_return_policy', 46 'blazeaid_cloud_consent', 47 'blazeaid_feed_generated_at', 48 'blazeaid_feed_product_count', 49 'blazeaid_llms_txt_description', 50 'blazeaid_site_token', 51 'blazeaid_visibility_last_run', 52 'blazeaid_onboarding', 53 'blazeaid_installed_at', 54 'blazeaid_scoring_bootstrapped', 55 'blazeaid_needs_first_scoring', 56 ]; 57 58 foreach ( $blazeaid_options as $blazeaid_option ) { 59 delete_option( $blazeaid_option ); 60 } 61 62 // Unschedule Action Scheduler jobs: every hook by name, then the group. 63 if ( function_exists( 'as_unschedule_all_actions' ) ) { 64 try { 65 as_unschedule_all_actions( 'blazeaid_retention_cleanup' ); 66 as_unschedule_all_actions( 'blazeaid_batch_score' ); 67 as_unschedule_all_actions( 'blazeaid_batch_score_healthcheck' ); 68 as_unschedule_all_actions( 'blazeaid_feed_refresh' ); 69 as_unschedule_all_actions( 'blazeaid_run_audit' ); 70 as_unschedule_all_actions( 'blazeaid_visibility_refresh' ); 71 as_unschedule_all_actions( 'blazeaid_visibility_monthly' ); 72 as_unschedule_all_actions( '', [], 'blazeaid' ); 73 } catch ( \Throwable $blazeaid_e ) { 74 unset( $blazeaid_e ); // Action Scheduler tables gone: nothing to cancel. 75 } 76 } 77 78 delete_transient( 'blazeaid_scoring_progress' ); 79 80 $blazeaid_upload = wp_upload_dir(); 81 $blazeaid_feed_dir = trailingslashit( $blazeaid_upload['basedir'] ) . 'blazeaid'; 82 if ( is_dir( $blazeaid_feed_dir ) ) { 83 require_once ABSPATH . 'wp-admin/includes/file.php'; 84 if ( WP_Filesystem() ) { 85 global $wp_filesystem; 86 if ( $wp_filesystem instanceof WP_Filesystem_Base ) { 87 $wp_filesystem->delete( $blazeaid_feed_dir, true ); 88 } 89 } 90 } 91 92 // Transient-backed throttles, daily caps, the probe cache and the schema 93 // retry marker: delete them now rather than waiting for expiry (the 94 // timeout rows would otherwise linger until the next cron sweep). 95 // esc_like() turns every underscore in the prefix into an explicit `\_` 96 // so LIKE does not treat it as a wildcard. 97 $blazeaid_transient_like = $wpdb->esc_like( '_transient_blazeaid_' ) . '%'; 98 $blazeaid_timeout_like = $wpdb->esc_like( '_transient_timeout_blazeaid_' ) . '%'; 99 $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 100 $wpdb->prepare( 101 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared 102 $blazeaid_transient_like, 103 $blazeaid_timeout_like 104 ) 105 ); 23 106 } 24 107 25 // Remove options. 26 $blazeaid_options = [ 27 'blazeaid_db_version', 28 'blazeaid_payload_salt', 29 'blazeaid_visitor_salt', 30 'blazeaid_license_key', 31 'blazeaid_license_status', 32 'blazeaid_needs_activation_audit', 33 'blazeaid_llms_txt_content', 34 'blazeaid_return_policy', 35 'blazeaid_cloud_consent', 36 'blazeaid_feed_generated_at', 37 'blazeaid_feed_product_count', 38 'blazeaid_llms_txt_description', 39 'blazeaid_site_token', 40 'blazeaid_visibility_last_run', 41 'blazeaid_onboarding', 42 'blazeaid_installed_at', 43 'blazeaid_scoring_bootstrapped', 44 'blazeaid_needs_first_scoring', 45 ]; 46 47 foreach ( $blazeaid_options as $blazeaid_option ) { 48 delete_option( $blazeaid_option ); 108 if ( is_multisite() ) { 109 $blazeaid_site_ids = get_sites( 110 [ 111 'fields' => 'ids', 112 'number' => 0, 113 'deleted' => 0, 114 ] 115 ); 116 foreach ( (array) $blazeaid_site_ids as $blazeaid_site_id ) { 117 switch_to_blog( (int) $blazeaid_site_id ); 118 blazeaid_uninstall_site(); 119 restore_current_blog(); 120 } 121 } else { 122 blazeaid_uninstall_site(); 49 123 } 50 124 51 // Unschedule Action Scheduler jobs.52 if ( function_exists( 'as_unschedule_all_actions' ) ) {53 as_unschedule_all_actions( 'blazeaid_retention_cleanup' );54 as_unschedule_all_actions( 'blazeaid_batch_score' );55 as_unschedule_all_actions( 'blazeaid_feed_refresh' );56 }57 58 delete_transient( 'blazeaid_scoring_progress' );59 if ( function_exists( 'as_unschedule_all_actions' ) ) {60 as_unschedule_all_actions( 'blazeaid_run_audit' );61 as_unschedule_all_actions( 'blazeaid_batch_score_healthcheck' );62 as_unschedule_all_actions( 'blazeaid_visibility_refresh' );63 as_unschedule_all_actions( 'blazeaid_visibility_monthly' );64 }65 $blazeaid_upload = wp_upload_dir();66 $blazeaid_feed_dir = trailingslashit( $blazeaid_upload['basedir'] ) . 'blazeaid';67 if ( is_dir( $blazeaid_feed_dir ) ) {68 require_once ABSPATH . 'wp-admin/includes/file.php';69 if ( WP_Filesystem() ) {70 global $wp_filesystem;71 if ( $wp_filesystem instanceof WP_Filesystem_Base ) {72 $wp_filesystem->delete( $blazeaid_feed_dir, true );73 }74 }75 }76 // Transient-backed throttles, daily caps and the probe cache: delete them77 // now rather than waiting for expiry (the timeout rows would otherwise78 // linger until the next cron sweep). esc_like() turns every underscore in79 // the prefix into an explicit `\_` so LIKE does not treat it as a wildcard.80 $blazeaid_transient_like = $wpdb->esc_like( '_transient_blazeaid_' ) . '%';81 $blazeaid_timeout_like = $wpdb->esc_like( '_transient_timeout_blazeaid_' ) . '%';82 $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching83 $wpdb->prepare(84 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared85 $blazeaid_transient_like,86 $blazeaid_timeout_like87 )88 );89 125 wp_cache_flush(); -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/vendor/composer/autoload_classmap.php
r3672021 r3673252 33 33 'BlazeAiDiscovery\\Audit\\Checks\\RobotsTxt' => $baseDir . '/src/Audit/Checks/RobotsTxt.php', 34 34 'BlazeAiDiscovery\\Audit\\Checks\\SslActive' => $baseDir . '/src/Audit/Checks/SslActive.php', 35 'BlazeAiDiscovery\\Audit\\Checks\\StoreVisibility' => $baseDir . '/src/Audit/Checks/StoreVisibility.php', 35 36 'BlazeAiDiscovery\\Audit\\Checks\\WooCommerceVersion' => $baseDir . '/src/Audit/Checks/WooCommerceVersion.php', 36 37 'BlazeAiDiscovery\\Audit\\CrawlerAccess\\CrawlerAccessCheck' => $baseDir . '/src/Audit/CrawlerAccess/CrawlerAccessCheck.php', … … 53 54 'BlazeAiDiscovery\\Container' => $baseDir . '/src/Container.php', 54 55 'BlazeAiDiscovery\\Database\\DatabaseModule' => $baseDir . '/src/Database/DatabaseModule.php', 56 'BlazeAiDiscovery\\Database\\Installer' => $baseDir . '/src/Database/Installer.php', 55 57 'BlazeAiDiscovery\\Database\\Migrator' => $baseDir . '/src/Database/Migrator.php', 56 58 'BlazeAiDiscovery\\Database\\RetentionCleanup' => $baseDir . '/src/Database/RetentionCleanup.php', … … 60 62 'BlazeAiDiscovery\\Feed\\FeedModule' => $baseDir . '/src/Feed/FeedModule.php', 61 63 'BlazeAiDiscovery\\Feed\\FeedScheduler' => $baseDir . '/src/Feed/FeedScheduler.php', 64 'BlazeAiDiscovery\\Feed\\FeedStorage' => $baseDir . '/src/Feed/FeedStorage.php', 62 65 'BlazeAiDiscovery\\Feed\\FeedValidator' => $baseDir . '/src/Feed/FeedValidator.php', 66 'BlazeAiDiscovery\\Feed\\FeedWriter' => $baseDir . '/src/Feed/FeedWriter.php', 63 67 'BlazeAiDiscovery\\Feed\\TargetCountries' => $baseDir . '/src/Feed/TargetCountries.php', 64 68 'BlazeAiDiscovery\\Jobs\\JobsModule' => $baseDir . '/src/Jobs/JobsModule.php', -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/vendor/composer/autoload_static.php
r3672021 r3673252 48 48 'BlazeAiDiscovery\\Audit\\Checks\\RobotsTxt' => __DIR__ . '/../..' . '/src/Audit/Checks/RobotsTxt.php', 49 49 'BlazeAiDiscovery\\Audit\\Checks\\SslActive' => __DIR__ . '/../..' . '/src/Audit/Checks/SslActive.php', 50 'BlazeAiDiscovery\\Audit\\Checks\\StoreVisibility' => __DIR__ . '/../..' . '/src/Audit/Checks/StoreVisibility.php', 50 51 'BlazeAiDiscovery\\Audit\\Checks\\WooCommerceVersion' => __DIR__ . '/../..' . '/src/Audit/Checks/WooCommerceVersion.php', 51 52 'BlazeAiDiscovery\\Audit\\CrawlerAccess\\CrawlerAccessCheck' => __DIR__ . '/../..' . '/src/Audit/CrawlerAccess/CrawlerAccessCheck.php', … … 68 69 'BlazeAiDiscovery\\Container' => __DIR__ . '/../..' . '/src/Container.php', 69 70 'BlazeAiDiscovery\\Database\\DatabaseModule' => __DIR__ . '/../..' . '/src/Database/DatabaseModule.php', 71 'BlazeAiDiscovery\\Database\\Installer' => __DIR__ . '/../..' . '/src/Database/Installer.php', 70 72 'BlazeAiDiscovery\\Database\\Migrator' => __DIR__ . '/../..' . '/src/Database/Migrator.php', 71 73 'BlazeAiDiscovery\\Database\\RetentionCleanup' => __DIR__ . '/../..' . '/src/Database/RetentionCleanup.php', … … 75 77 'BlazeAiDiscovery\\Feed\\FeedModule' => __DIR__ . '/../..' . '/src/Feed/FeedModule.php', 76 78 'BlazeAiDiscovery\\Feed\\FeedScheduler' => __DIR__ . '/../..' . '/src/Feed/FeedScheduler.php', 79 'BlazeAiDiscovery\\Feed\\FeedStorage' => __DIR__ . '/../..' . '/src/Feed/FeedStorage.php', 77 80 'BlazeAiDiscovery\\Feed\\FeedValidator' => __DIR__ . '/../..' . '/src/Feed/FeedValidator.php', 81 'BlazeAiDiscovery\\Feed\\FeedWriter' => __DIR__ . '/../..' . '/src/Feed/FeedWriter.php', 78 82 'BlazeAiDiscovery\\Feed\\TargetCountries' => __DIR__ . '/../..' . '/src/Feed/TargetCountries.php', 79 83 'BlazeAiDiscovery\\Jobs\\JobsModule' => __DIR__ . '/../..' . '/src/Jobs/JobsModule.php', -
blaze-ai-discovery-for-woocommerce/tags/1.1.3/vendor/composer/installed.php
r3672021 r3673252 2 2 'root' => array( 3 3 'name' => 'blazecommerce/blaze-ai-discovery-for-woocommerce', 4 'pretty_version' => 'v1.1. 2',5 'version' => '1.1. 2.0',6 'reference' => ' 8d6a69dcebcc9972707017c5f3983098d6499808',4 'pretty_version' => 'v1.1.3', 5 'version' => '1.1.3.0', 6 'reference' => 'da0525d966c4d68fc334b81ad1ccd9c2bd7e259c', 7 7 'type' => 'wordpress-plugin', 8 8 'install_path' => __DIR__ . '/../../', … … 12 12 'versions' => array( 13 13 'blazecommerce/blaze-ai-discovery-for-woocommerce' => array( 14 'pretty_version' => 'v1.1. 2',15 'version' => '1.1. 2.0',16 'reference' => ' 8d6a69dcebcc9972707017c5f3983098d6499808',14 'pretty_version' => 'v1.1.3', 15 'version' => '1.1.3.0', 16 'reference' => 'da0525d966c4d68fc334b81ad1ccd9c2bd7e259c', 17 17 'type' => 'wordpress-plugin', 18 18 'install_path' => __DIR__ . '/../../', -
blaze-ai-discovery-for-woocommerce/trunk/assets/js/admin/pages/Audit.js
r3671993 r3673252 1 import { useState, useEffect } from '@wordpress/element';1 import { useState, useEffect, useRef } from '@wordpress/element'; 2 2 import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components'; 3 3 import { __, sprintf } from '@wordpress/i18n'; 4 4 import apiFetch from '@wordpress/api-fetch'; 5 5 import CloudConsentCard from '../components/CloudConsentCard'; 6 import RestErrorNotice, { classifyRestError, restErrorMessage } from '../components/restErrors'; 7 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 6 8 7 9 const statusIcon = ( status ) => { … … 10 12 case 'warning': return { icon: '\u26A0', color: '#856404', bg: '#fff3cd' }; 11 13 case 'fail': return { icon: '\u2717', color: '#721c24', bg: '#f8d7da' }; 14 case 'pending': return { icon: '\u2026', color: '#2271b1', bg: '#e7f0fa' }; 12 15 default: return { icon: '\u2139', color: '#004085', bg: '#cce5ff' }; 13 16 } 14 17 }; 18 19 // Rows the forced inline run could not finish within its cloud budget; the 20 // queued background audit replaces them. 21 const hasPending = ( audit ) => ( audit?.results || [] ).some( ( r ) => r && r.status === 'pending' ); 15 22 16 23 const verdictColors = ( verdict ) => { … … 225 232 const [ runNotice, setRunNotice ] = useState( null ); 226 233 const [ consent, setConsent ] = useState( null ); 234 // 401/403, non-JSON or no response from the REST API: shown as such 235 // rather than as "no audit yet". 236 const [ restError, setRestError ] = useState( null ); 237 const pollStop = useRef( null ); 238 239 const noteRestError = ( errOrKind ) => { 240 const kind = typeof errOrKind === 'string' ? errOrKind : classifyRestError( errOrKind ); 241 if ( restErrorMessage( kind ) ) { 242 setRestError( kind ); 243 } 244 return kind; 245 }; 246 247 const stopPolling = () => { 248 if ( pollStop.current ) { 249 pollStop.current(); 250 pollStop.current = null; 251 } 252 }; 227 253 228 254 const loadConsent = () => { … … 237 263 setLoading( false ); 238 264 } ) 239 .catch( () => setLoading( false ) ); 240 }; 241 242 useEffect( () => { loadAudit(); loadConsent(); }, [] ); 265 .catch( ( err ) => { 266 // 404 = no audit has run yet; anything else is worth a notice. 267 noteRestError( err ); 268 setLoading( false ); 269 } ); 270 }; 271 272 useEffect( () => { 273 loadAudit(); 274 loadConsent(); 275 return stopPolling; 276 }, [] ); // eslint-disable-line react-hooks/exhaustive-deps 243 277 244 278 // POST /audit/run answers 202 { queued: true } when the run is handed to 245 // Action Scheduler; poll GET /audit every 3 s (up to 90 s) until run_at 246 // moves past the previous audit. A 200 (no scheduler) carries the results. 279 // Action Scheduler; poll GET /audit every 3 s for 90 s, then every 30 s 280 // (20 min cap) until run_at moves past the previous audit and no row is 281 // still pending. A 200 (no scheduler, or a forced run) carries the results. 247 282 const POLL_INTERVAL_MS = 3000; 248 const POLL_TIMEOUT_MS = 90000; 249 250 const pollForNewAudit = ( previousRunAt, startedAt ) => { 251 apiFetch( { path: '/blazeaid/v1/audit' } ) 252 .then( ( data ) => { 283 const POLL_SLOW_AFTER_MS = 90000; 284 const POLL_SLOW_INTERVAL_MS = 30000; 285 286 const pollForNewAudit = ( previousRunAt ) => { 287 stopPolling(); 288 pollStop.current = startPoll( { 289 request: () => apiFetch( { path: '/blazeaid/v1/audit' } ), 290 onData: ( data ) => { 253 291 if ( data && data.run_at && data.run_at !== previousRunAt ) { 254 292 setAudit( data ); 255 setRunning( false );256 return;257 293 } 258 scheduleNextPoll( previousRunAt, startedAt ); 259 } ) 260 .catch( () => scheduleNextPoll( previousRunAt, startedAt ) ); 261 }; 262 263 const scheduleNextPoll = ( previousRunAt, startedAt ) => { 264 if ( Date.now() - startedAt >= POLL_TIMEOUT_MS ) { 265 setRunning( false ); 266 setRunNotice( __( 'Still running — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 267 return; 268 } 269 setTimeout( () => pollForNewAudit( previousRunAt, startedAt ), POLL_INTERVAL_MS ); 294 }, 295 isDone: ( data ) => !! ( data && data.run_at && data.run_at !== previousRunAt && ! hasPending( data ) ), 296 intervalMs: POLL_INTERVAL_MS, 297 slowAfterMs: POLL_SLOW_AFTER_MS, 298 slowIntervalMs: POLL_SLOW_INTERVAL_MS, 299 onSlow: () => setRunNotice( __( 'Still running — this page keeps checking for up to 20 minutes.', 'blaze-ai-discovery-for-woocommerce' ) ), 300 onStop: ( reason ) => { 301 pollStop.current = null; 302 setRunning( false ); 303 const kind = stopReasonToErrorKind( reason ); 304 if ( kind ) { 305 noteRestError( kind ); 306 setRunNotice( null ); 307 } else if ( reason === 'timeout' ) { 308 setRunNotice( __( 'Still running — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 309 } else { 310 setRunNotice( null ); 311 } 312 }, 313 } ); 270 314 }; 271 315 … … 277 321 .then( ( data ) => { 278 322 if ( data && data.queued ) { 279 scheduleNextPoll( previousRunAt, Date.now());323 pollForNewAudit( previousRunAt ); 280 324 return; 281 325 } 282 326 setAudit( data ); 283 327 setRunning( false ); 328 if ( hasPending( data ) ) { 329 // Cloud rows did not fit the request budget; the queued 330 // background audit fills them in. 331 setRunNotice( __( 'Cloud checks are still running in the background — the rows marked pending will update.', 'blaze-ai-discovery-for-woocommerce' ) ); 332 pollForNewAudit( data.run_at || previousRunAt ); 333 } 284 334 } ) 285 .catch( () => setRunning( false ) ); 335 .catch( ( err ) => { 336 setRunning( false ); 337 const kind = noteRestError( err ); 338 if ( ! restErrorMessage( kind ) ) { 339 setRunNotice( __( 'Could not start the audit. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 340 } 341 } ); 286 342 }; 287 343 … … 312 368 </Button> 313 369 </div> 370 371 { restError && <RestErrorNotice kind={ restError } /> } 314 372 315 373 { audit?.run_at && ( -
blaze-ai-discovery-for-woocommerce/trunk/assets/js/admin/pages/Dashboard.js
r3672021 r3673252 6 6 import CloudConsentCard from '../components/CloudConsentCard'; 7 7 import JobsHealthNotice, { fetchJobsHealth } from '../components/JobsHealthNotice'; 8 import RestErrorNotice, { classifyRestError, restErrorMessage } from '../components/restErrors'; 9 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 8 10 9 11 // First-run polling: GET /audit every 5 s for 3 min, then every 30 s up to … … 29 31 30 32 const probeRan = ( audit ) => crawlerAccessResult( audit )?.probe?.ran === true; 33 34 // Rows the forced inline run could not finish within its cloud budget; the 35 // queued background audit replaces them (F-011). 36 const pendingRows = ( audit ) => ( audit?.results || [] ).filter( ( r ) => r && r.status === 'pending' ); 37 const auditHasPending = ( audit ) => pendingRows( audit ).length > 0; 31 38 32 39 const blockedRetrievalCrawlers = ( result ) => … … 241 248 const warnings = results.filter( ( c ) => c && c.status === 'warning' ).length; 242 249 const issues = fails + warnings; 250 const pending = results.filter( ( c ) => c && c.status === 'pending' ).length; 243 251 const bg = fails > 0 ? '#f8d7da' : warnings > 0 ? '#fff3cd' : '#d4edda'; 244 252 const color = fails > 0 ? '#721c24' : warnings > 0 ? '#856404' : '#155724'; … … 256 264 results.length 257 265 ); 266 if ( pending > 0 ) { 267 body += ' · ' + sprintf( 268 /* translators: %d: number of audit rows whose cloud check is still running */ 269 _n( '%d cloud check still running', '%d cloud checks still running', pending, 'blaze-ai-discovery-for-woocommerce' ), 270 pending 271 ); 272 } 258 273 } else { 259 274 icon = <Bubble bg="#f0f0f0" color="#757575" fontSize={ 24 }>?</Bubble>; … … 369 384 const [ probeState, setProbeState ] = useState( null ); // null | 'waiting' | 'done' 370 385 const [ reminderOpen, setReminderOpen ] = useState( false ); 371 372 // One live poll at a time; bumping the token cancels the previous one (and all on unmount). 373 const pollToken = useRef( 0 ); 386 // A REST failure that is not "nothing yet": 401/403 (session expired or a 387 // security plugin), non-JSON, or no response. Shown instead of the 388 // "background jobs haven't run" copy, which used to swallow all of them. 389 const [ restError, setRestError ] = useState( null ); 390 391 // One live audit poll at a time; stop() cancels the previous one (and all on unmount). 392 const pollStop = useRef( null ); 374 393 const firstRunStarted = useRef( false ); 375 394 const modalOffered = useRef( false ); 376 395 const reminderRecorded = useRef( false ); 377 396 const dismissedWithAudit = useRef( false ); 378 useEffect( () => () => { pollToken.current += 1; }, [] ); 397 const stopAuditPoll = () => { 398 if ( pollStop.current ) { 399 pollStop.current(); 400 pollStop.current = null; 401 } 402 }; 403 useEffect( () => stopAuditPoll, [] ); 404 405 const noteRestError = ( errOrKind ) => { 406 const kind = typeof errOrKind === 'string' ? errOrKind : classifyRestError( errOrKind ); 407 if ( restErrorMessage( kind ) ) { 408 setRestError( kind ); 409 } 410 return kind; 411 }; 379 412 380 413 // Polls GET /audit until done(data) is true: every 5 s for 3 min, then 381 // (after calling onSlow once) every 30 s until 20 min have passed. 414 // (after calling onSlow once) every 30 s until 20 min have passed. Stops 415 // early on a 401/403 or three unexpected responses and says so. 382 416 const pollAudit = ( done, onSlow ) => { 383 const token = ++pollToken.current; 384 const startedAt = Date.now(); 385 let slowNotified = false; 386 const tick = () => { 387 if ( token !== pollToken.current ) { 388 return; 389 } 390 apiFetch( { path: '/blazeaid/v1/audit' } ) 391 .catch( () => null ) 392 .then( ( data ) => { 393 if ( token !== pollToken.current ) { 394 return; 395 } 396 if ( data && data.run_at ) { 397 setAudit( data ); 398 if ( done( data ) ) { 399 return; 400 } 401 } 402 const elapsed = Date.now() - startedAt; 403 if ( elapsed >= AUDIT_POLL_MAX_MS ) { 404 return; 405 } 406 if ( elapsed >= AUDIT_POLL_LIMIT_MS ) { 407 if ( ! slowNotified ) { 408 slowNotified = true; 409 if ( onSlow ) { 410 onSlow(); 411 } 412 } 413 setTimeout( tick, AUDIT_SLOW_POLL_MS ); 414 return; 415 } 416 setTimeout( tick, AUDIT_POLL_MS ); 417 } ); 418 }; 419 setTimeout( tick, AUDIT_POLL_MS ); 417 stopAuditPoll(); 418 pollStop.current = startPoll( { 419 request: () => apiFetch( { path: '/blazeaid/v1/audit' } ), 420 onData: ( data ) => { 421 if ( data && data.run_at ) { 422 setAudit( data ); 423 } 424 }, 425 isDone: ( data ) => !! ( data && data.run_at && done( data ) ), 426 intervalMs: AUDIT_POLL_MS, 427 slowAfterMs: AUDIT_POLL_LIMIT_MS, 428 slowIntervalMs: AUDIT_SLOW_POLL_MS, 429 onSlow, 430 maxMs: AUDIT_POLL_MAX_MS, 431 onStop: ( reason ) => { 432 pollStop.current = null; 433 const kind = stopReasonToErrorKind( reason ); 434 if ( kind ) { 435 noteRestError( kind ); 436 } 437 }, 438 } ); 420 439 }; 421 440 … … 448 467 } 449 468 setLoading( false ); 450 } ).catch( () => setLoading( false ) ); 451 }, [ days ] ); 469 } ).catch( ( err ) => { 470 noteRestError( err ); 471 setLoading( false ); 472 } ); 473 }, [ days ] ); // eslint-disable-line react-hooks/exhaustive-deps 452 474 453 475 // Cloud results arrive in the background: while the visibility report is 454 // pending, or consent is on but the crawler probe has not run yet, poll 455 // until they land (5 s, up to 3 min) instead of waiting for a reload. 456 const cloudPollToken = useRef( 0 ); 457 useEffect( () => () => { cloudPollToken.current += 1; }, [] ); 476 // pending, consent is on but the crawler probe has not run yet, or the 477 // forced inline audit left rows pending, poll until they land (5 s for 478 // 3 min, then 30 s, 20 min cap) instead of waiting for a reload. The 479 // effect depends on the pending *booleans*, not the audit object, so a 480 // poll that stores a fresh audit does not restart the clock (adm-F12). 481 const consentOn = consent ? !! consent.granted : false; 482 const crawlerRow = crawlerAccessResult( audit ); 483 const probePending = !! ( consentOn && crawlerRow && crawlerRow.probe && crawlerRow.probe.ran === false && crawlerRow.probe.notice === 'consent_off' ); 484 const rowsPending = auditHasPending( audit ); 485 const visibilityPending = visibility?.state === 'pending' || ( consentOn && visibility?.state === 'consent_off' ); 458 486 useEffect( () => { 459 const consentOn = consent ? !! consent.granted : false; 460 const crawlerRow = Array.isArray( audit?.results ) ? audit.results.find( ( c ) => c && c.crawlers ) : null; 461 const probePending = consentOn && crawlerRow && crawlerRow.probe && crawlerRow.probe.ran === false && crawlerRow.probe.notice === 'consent_off'; 462 const visibilityPending = visibility?.state === 'pending' || ( consentOn && visibility?.state === 'consent_off' ); 463 if ( loading || ( ! probePending && ! visibilityPending ) ) { 464 return; 465 } 466 const token = ++cloudPollToken.current; 467 const startedAt = Date.now(); 468 const tick = () => { 469 if ( token !== cloudPollToken.current || Date.now() - startedAt > AUDIT_POLL_LIMIT_MS ) { 470 return; 471 } 472 Promise.all( [ 473 visibilityPending ? apiFetch( { path: '/blazeaid/v1/visibility' } ).catch( () => null ) : Promise.resolve( undefined ), 474 probePending ? apiFetch( { path: '/blazeaid/v1/audit' } ).catch( () => null ) : Promise.resolve( undefined ), 475 ] ).then( ( [ v, a ] ) => { 476 if ( token !== cloudPollToken.current ) { 477 return; 478 } 479 if ( v !== undefined && v ) { 487 if ( loading || ( ! probePending && ! visibilityPending && ! rowsPending ) ) { 488 return undefined; 489 } 490 const wantVisibility = visibilityPending; 491 const wantAudit = probePending || rowsPending; 492 const stillPending = ( [ v, a ] ) => { 493 const stillVisibility = wantVisibility ? !! ( v && v.state === 'pending' ) : false; 494 const row = wantAudit ? crawlerAccessResult( a ) : null; 495 const stillProbe = wantAudit ? !! ( row && row.probe && row.probe.ran === false ) : false; 496 const stillRows = wantAudit ? auditHasPending( a ) : false; 497 return stillVisibility || stillProbe || stillRows; 498 }; 499 return startPoll( { 500 request: () => Promise.all( [ 501 wantVisibility ? apiFetch( { path: '/blazeaid/v1/visibility' } ) : Promise.resolve( undefined ), 502 wantAudit ? apiFetch( { path: '/blazeaid/v1/audit' } ) : Promise.resolve( undefined ), 503 ] ), 504 onData: ( [ v, a ] ) => { 505 if ( v ) { 480 506 setVisibility( v ); 481 507 } 482 if ( a !== undefined && a) {508 if ( a && a.run_at ) { 483 509 setAudit( a ); 484 510 } 485 const stillVisibility = v !== undefined ? ( v && v.state === 'pending' ) : false; 486 const row = a && Array.isArray( a.results ) ? a.results.find( ( c ) => c && c.crawlers ) : null; 487 const stillProbe = a !== undefined ? !! ( row && row.probe && row.probe.ran === false ) : false; 488 if ( stillVisibility || stillProbe ) { 489 setTimeout( tick, AUDIT_POLL_MS ); 511 }, 512 isDone: ( pair ) => ! stillPending( pair ), 513 intervalMs: AUDIT_POLL_MS, 514 slowAfterMs: AUDIT_POLL_LIMIT_MS, 515 slowIntervalMs: AUDIT_SLOW_POLL_MS, 516 maxMs: AUDIT_POLL_MAX_MS, 517 onStop: ( reason ) => { 518 const kind = stopReasonToErrorKind( reason ); 519 if ( kind ) { 520 noteRestError( kind ); 490 521 } 491 } ); 492 }; 493 setTimeout( tick, AUDIT_POLL_MS ); 494 }, [ loading, visibility?.state, consent?.granted, audit ] ); // eslint-disable-line react-hooks/exhaustive-deps 522 }, 523 } ); 524 }, [ loading, visibilityPending, probePending, rowsPending ] ); // eslint-disable-line react-hooks/exhaustive-deps 495 525 496 526 // First run: no audit yet, so the activation audit is still queued. Poll … … 498 528 // on the request thread (polling continues, slower, up to 20 min). 499 529 useEffect( () => { 500 if ( loading || audit || firstRunStarted.current ) {530 if ( loading || audit || restError || firstRunStarted.current ) { 501 531 return; 502 532 } … … 506 536 refreshJobsHealth(); 507 537 } ); 508 }, [ loading, audit ] ); // eslint-disable-line react-hooks/exhaustive-deps538 }, [ loading, audit, restError ] ); // eslint-disable-line react-hooks/exhaustive-deps 509 539 510 540 // While the first-run card is up, ask once (at 60 s) whether the queue is 511 541 // moving, so the background-jobs notice appears without a reload. 512 542 useEffect( () => { 513 if ( loading || audit ) {543 if ( loading || audit || restError ) { 514 544 return undefined; 515 545 } 516 546 const timer = setTimeout( refreshJobsHealth, JOBS_HEALTH_CHECK_MS ); 517 547 return () => clearTimeout( timer ); 518 }, [ loading, audit ] ); // eslint-disable-line react-hooks/exhaustive-deps548 }, [ loading, audit, restError ] ); // eslint-disable-line react-hooks/exhaustive-deps 519 549 520 550 // The cloud-checks offer: once per plugin version while consent is off. … … 547 577 // Run the audit on this request (force) and show the result at once. 548 578 // A run that fails (timeout, 5xx) restarts the first-run poll: the 549 // queued copy may still land, or the owner can click again. 579 // queued copy may still land, or the owner can click again. A 401/403 580 // or a non-JSON answer is reported as such instead. 550 581 const runAuditNow = () => { 551 582 setRunningNow( true ); 552 583 setRunNowError( false ); 553 pollToken.current += 1; // stop the first-run poll;the result arrives here.554 const failed = ( ) => {584 stopAuditPoll(); // the result arrives here. 585 const failed = ( err ) => { 555 586 setRunNowError( true ); 587 const kind = err ? noteRestError( err ) : null; 588 if ( kind === 'auth' || kind === 'html' ) { 589 return false; 590 } 556 591 setFirstRunSlow( true ); 557 592 if ( ! audit ) { … … 567 602 return true; 568 603 } 569 return failed( );604 return failed( null ); 570 605 } ) 571 606 .catch( failed ) … … 721 756 ) } 722 757 758 { restError && <RestErrorNotice kind={ restError } /> } 759 723 760 <JobsHealthNotice health={ jobsHealth } audit={ audit } onRunNow={ afterJobsRan } onRunAudit={ runAuditNow } /> 724 761 725 { ! audit && (762 { ! audit && ! restError && ( 726 763 <FirstRunCard slow={ firstRunSlow } running={ runningNow } error={ runNowError } onRunNow={ runAuditNow } /> 727 764 ) } -
blaze-ai-discovery-for-woocommerce/trunk/assets/js/admin/pages/Feed.js
r3668873 r3673252 1 import { useState, useEffect } from '@wordpress/element';2 import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components';3 import { __ } from '@wordpress/i18n';1 import { useState, useEffect, useRef } from '@wordpress/element'; 2 import { Card, CardHeader, CardBody, Button, Spinner, Notice } from '@wordpress/components'; 3 import { __, sprintf } from '@wordpress/i18n'; 4 4 import apiFetch from '@wordpress/api-fetch'; 5 import { classifyRestError, restErrorMessage } from '../components/restErrors'; 6 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 7 8 // A queued run is polled every POLL_MS until it finishes. startPoll() ends 9 // the poll at its 20-minute cap, on a 401/403 and after three unexpected 10 // responses, and stop() clears the timer when the page is left. 11 const POLL_MS = 3000; 12 13 const isActive = ( progress ) => !! progress && ( progress.state === 'queued' || progress.state === 'running' ); 5 14 6 15 export default function Feed() { … … 9 18 const [ loading, setLoading ] = useState( true ); 10 19 const [ generating, setGenerating ] = useState( false ); 20 const [ error, setError ] = useState( null ); 21 // The live poll's stop(); one at a time, cleared on unmount. 22 const pollStop = useRef( null ); 23 24 const stopPolling = () => { 25 if ( pollStop.current ) { 26 pollStop.current(); 27 pollStop.current = null; 28 } 29 }; 30 31 const loadValidation = () => 32 apiFetch( { path: '/blazeaid/v1/feed/validate' } ) 33 .then( setValidation ) 34 .catch( () => {} ); 35 36 const watchProgress = () => { 37 stopPolling(); 38 setGenerating( true ); 39 let last = null; 40 pollStop.current = startPoll( { 41 request: () => apiFetch( { path: '/blazeaid/v1/feed/status' } ), 42 onData: ( s ) => { 43 last = s; 44 setStatus( s ); 45 }, 46 isDone: ( s ) => ! isActive( s && s.progress ), 47 intervalMs: POLL_MS, 48 onStop: ( reason ) => { 49 pollStop.current = null; 50 setGenerating( false ); 51 if ( reason === 'done' ) { 52 if ( last && last.progress && last.progress.state === 'error' ) { 53 setError( last.progress.error || __( 'Feed generation failed.', 'blaze-ai-discovery-for-woocommerce' ) ); 54 } 55 loadValidation(); 56 return; 57 } 58 if ( reason === 'timeout' ) { 59 setError( __( 'The feed is still queued. Background jobs may not be running on this site — check the Jobs page, then try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 60 return; 61 } 62 const kind = stopReasonToErrorKind( reason ); 63 setError( restErrorMessage( kind ) || __( 'Feed generation failed.', 'blaze-ai-discovery-for-woocommerce' ) ); 64 }, 65 } ); 66 }; 11 67 12 68 useEffect( () => { … … 19 75 setValidation( v ); 20 76 setLoading( false ); 21 } ).catch( () => setLoading( false ) ); 22 }, [] ); 77 if ( isActive( s.progress ) ) { 78 watchProgress(); 79 } 80 } ).catch( ( err ) => { 81 setLoading( false ); 82 const message = restErrorMessage( classifyRestError( err ) ); 83 if ( message ) { 84 setError( message ); 85 } 86 } ); 87 return stopPolling; 88 }, [] ); // eslint-disable-line react-hooks/exhaustive-deps 23 89 24 90 const generateFeed = () => { 25 91 setGenerating( true ); 26 apiFetch( { path: '/blazeaid/v1/feed/generate', method: 'POST' } ) 92 setError( null ); 93 // Small catalogues run on the request and come back finished; larger ones are queued and polled. 94 const inline = !! status && status.total_products <= status.inline_limit; 95 apiFetch( { path: '/blazeaid/v1/feed/generate', method: 'POST', data: { force: inline } } ) 27 96 .then( ( data ) => { 28 97 setStatus( data ); 98 if ( data.queued ) { 99 watchProgress(); 100 return; 101 } 29 102 setGenerating( false ); 103 loadValidation(); 30 104 } ) 31 .catch( () => setGenerating( false ) ); 105 .catch( ( err ) => { 106 setGenerating( false ); 107 // A blocked REST API, an HTML page or no response get the shared 108 // sentence; a JSON error (503 no scheduler, 500 write failure, 109 // 409 already running) carries its own message. 110 const kind = classifyRestError( err ); 111 const shared = kind === 'other' ? null : restErrorMessage( kind ); 112 setError( shared || ( err && ( err.error || err.message ) ) || __( 'Feed generation failed.', 'blaze-ai-discovery-for-woocommerce' ) ); 113 } ); 32 114 }; 33 115 … … 40 122 } 41 123 124 const progress = status?.progress; 125 let buttonLabel = __( 'Generate Feed', 'blaze-ai-discovery-for-woocommerce' ); 126 if ( generating ) { 127 if ( progress?.state === 'running' && progress.total > 0 ) { 128 buttonLabel = sprintf( 129 /* translators: 1: products processed, 2: products total */ 130 __( 'Generating… %1$s of %2$s', 'blaze-ai-discovery-for-woocommerce' ), 131 progress.done, 132 progress.total 133 ); 134 } else if ( progress?.state === 'queued' ) { 135 buttonLabel = __( 'Queued…', 'blaze-ai-discovery-for-woocommerce' ); 136 } else { 137 buttonLabel = __( 'Generating…', 'blaze-ai-discovery-for-woocommerce' ); 138 } 139 } 140 42 141 return ( 43 142 <div style={ { maxWidth: 900, margin: '20px auto' } }> 44 143 <h1>{ __( 'ChatGPT Merchant Feed', 'blaze-ai-discovery-for-woocommerce' ) }</h1> 144 145 { error && ( 146 <Notice status="error" isDismissible onRemove={ () => setError( null ) }> 147 { error } 148 </Notice> 149 ) } 45 150 46 151 { /* Feed status */ } … … 60 165 </p> 61 166 ) } 167 { generating && progress?.state === 'queued' && ( 168 <p style={ { margin: '8px 0 0', color: '#757575', fontSize: 13 } }> 169 { __( 'Queued as a background job — this page updates when it finishes.', 'blaze-ai-discovery-for-woocommerce' ) } 170 </p> 171 ) } 62 172 </div> 63 173 <div style={ { display: 'flex', gap: 8 } }> 64 174 <Button variant="primary" onClick={ generateFeed } disabled={ generating }> 65 { generating ? __( 'Generating…', 'blaze-ai-discovery-for-woocommerce' ) : __( 'Generate Feed', 'blaze-ai-discovery-for-woocommerce' )}175 { buttonLabel } 66 176 </Button> 67 177 { status?.download_url && ( … … 86 196 </CardHeader> 87 197 <CardBody> 88 { validation ? (198 { validation && validation.available !== false ? ( 89 199 <div> 90 200 <p> … … 93 203 <span style={ { color: '#d63638', fontWeight: 600, marginLeft: 16 } }>{ validation.invalid } { __( 'invalid', 'blaze-ai-discovery-for-woocommerce' ) }</span> 94 204 ) } 205 { validation.ineligible > 0 && ( 206 <span style={ { color: '#996800', fontWeight: 600, marginLeft: 16 } }>{ validation.ineligible } { __( 'not searchable yet', 'blaze-ai-discovery-for-woocommerce' ) }</span> 207 ) } 95 208 </p> 209 { validation.truncated && ( 210 <p style={ { color: '#757575', fontSize: 13 } }> 211 { sprintf( 212 /* translators: %s: number of rows checked */ 213 __( 'Checked the first %s rows of the feed.', 'blaze-ai-discovery-for-woocommerce' ), 214 validation.checked 215 ) } 216 </p> 217 ) } 96 218 { validation.issues?.length > 0 && ( 97 219 <div style={ { marginTop: 12 } }> -
blaze-ai-discovery-for-woocommerce/trunk/assets/js/admin/pages/Products.js
r3672021 r3673252 1 1 import { useState, useEffect } from '@wordpress/element'; 2 import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components';2 import { Card, CardHeader, CardBody, Button, Spinner, Notice } from '@wordpress/components'; 3 3 import { __, sprintf } from '@wordpress/i18n'; 4 4 import apiFetch from '@wordpress/api-fetch'; 5 5 import JobsHealthNotice, { fetchJobsHealth } from '../components/JobsHealthNotice'; 6 import RestErrorNotice, { classifyRestError, restErrorMessage } from '../components/restErrors'; 7 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 8 9 // GET /scores/progress every 3 s while a run is in flight; 20 min cap. 10 const PROGRESS_POLL_MS = 3000; 6 11 7 12 const severityStyle = ( severity ) => { … … 125 130 const [ scoring, setScoring ] = useState( false ); 126 131 const [ jobsHealth, setJobsHealth ] = useState( null ); 132 // 401/403, non-JSON or no response from the REST API. 133 const [ restError, setRestError ] = useState( null ); 134 const [ scoringNotice, setScoringNotice ] = useState( null ); 135 136 const noteRestError = ( errOrKind ) => { 137 const kind = typeof errOrKind === 'string' ? errOrKind : classifyRestError( errOrKind ); 138 if ( restErrorMessage( kind ) ) { 139 setRestError( kind ); 140 } 141 return kind; 142 }; 127 143 128 144 // Refetch everything; `initial` shows the page spinner (which would … … 149 165 } 150 166 setLoading( false ); 151 } ).catch( () => setLoading( false ) ); 167 } ).catch( ( err ) => { 168 noteRestError( err ); 169 setLoading( false ); 170 } ); 152 171 }; 153 172 154 useEffect( () => loadData( true ), [] ); 155 173 useEffect( () => loadData( true ), [] ); // eslint-disable-line react-hooks/exhaustive-deps 174 175 // While a run is in flight: poll progress until it completes or fails. 176 // Bounded (20 min), stops on a 401/403 or three unexpected responses, 177 // and the timer is cleared when the page unmounts. 156 178 useEffect( () => { 157 if ( ! scoring ) return; 158 const interval = setInterval( () => { 159 apiFetch( { path: '/blazeaid/v1/scores/progress' } ).then( ( pr ) => { 179 if ( ! scoring ) { 180 return undefined; 181 } 182 let last = null; 183 const isOver = ( pr ) => !! pr && ( pr.status === 'complete' || pr.status === 'idle' || pr.status === 'failed' ); 184 return startPoll( { 185 request: () => apiFetch( { path: '/blazeaid/v1/scores/progress' } ), 186 onData: ( pr ) => { 187 last = pr; 160 188 setProgress( pr ); 161 if ( pr.status === 'complete' || pr.status === 'idle' ) { 162 setScoring( false ); 163 loadData(); 189 }, 190 isDone: isOver, 191 intervalMs: PROGRESS_POLL_MS, 192 onStop: ( reason ) => { 193 setScoring( false ); 194 if ( reason === 'done' ) { 195 if ( last && last.status !== 'failed' ) { 196 loadData( false ); 197 } 198 return; 199 } 200 if ( reason === 'timeout' ) { 201 setScoringNotice( __( 'Scoring is still running in the background — reload the page later to see the result.', 'blaze-ai-discovery-for-woocommerce' ) ); 202 return; 203 } 204 const kind = stopReasonToErrorKind( reason ); 205 if ( kind ) { 206 noteRestError( kind ); 207 } 208 }, 209 } ); 210 }, [ scoring ] ); // eslint-disable-line react-hooks/exhaustive-deps 211 212 const startScoring = () => { 213 setScoringNotice( null ); 214 setScoring( true ); 215 apiFetch( { path: '/blazeaid/v1/scores/recalculate', method: 'POST' } ) 216 .then( ( r ) => { 217 if ( r && r.progress ) { 218 setProgress( r.progress ); 219 } 220 } ) 221 .catch( ( err ) => { 222 setScoring( false ); 223 const kind = noteRestError( err ); 224 if ( ! restErrorMessage( kind ) ) { 225 setScoringNotice( __( 'Could not start scoring. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 164 226 } 165 227 } ); 166 }, 3000 );167 return () => clearInterval( interval );168 }, [ scoring ] );169 170 const startScoring = () => {171 setScoring( true );172 apiFetch( { path: '/blazeaid/v1/scores/recalculate', method: 'POST' } );173 228 }; 174 229 … … 194 249 </div> 195 250 251 { restError && <RestErrorNotice kind={ restError } /> } 252 196 253 <JobsHealthNotice health={ jobsHealth } onRunNow={ () => loadData( false ) } /> 254 255 { progress?.status === 'failed' && ( 256 <div style={ { display: 'grid', gap: 12, marginBottom: 16 } }> 257 <Notice status="error" isDismissible={ false }> 258 { progress.reason || __( 'The last scoring run stopped before it finished. Click Recalculate All to start again.', 'blaze-ai-discovery-for-woocommerce' ) } 259 </Notice> 260 </div> 261 ) } 262 263 { scoringNotice && ( 264 <div style={ { display: 'grid', gap: 12, marginBottom: 16 } }> 265 <Notice status="warning" onRemove={ () => setScoringNotice( null ) }>{ scoringNotice }</Notice> 266 </div> 267 ) } 197 268 198 269 { scoring && progress?.status === 'running' && ( -
blaze-ai-discovery-for-woocommerce/trunk/assets/js/admin/pages/Visibility.js
r3671993 r3673252 5 5 import CloudConsentCard from '../components/CloudConsentCard'; 6 6 import PayloadRenderer, { PayloadNotices } from '../components/PayloadRenderer'; 7 import { classifyRestError, restErrorMessage } from '../components/restErrors'; 8 import { startPoll, stopReasonToErrorKind } from '../components/polling'; 7 9 8 10 // GET /blazeaid/v1/visibility → { consent, payload, state } … … 29 31 const [ timedOut, setTimedOut ] = useState( false ); 30 32 const [ loadFailed, setLoadFailed ] = useState( false ); 31 const poll Timer= useRef( null );33 const pollStop = useRef( null ); 32 34 const unmounted = useRef( false ); 33 35 34 36 const stopPolling = () => { 35 if ( poll Timer.current ) {36 clearTimeout( pollTimer.current);37 poll Timer.current = null;37 if ( pollStop.current ) { 38 pollStop.current(); 39 pollStop.current = null; 38 40 } 39 41 }; … … 58 60 setLoading( false ); 59 61 if ( data?.state === 'pending' ) { 60 s cheduleNextPoll( Date.now());62 startPolling(); 61 63 } 62 64 } ) 63 .catch( ( ) => {65 .catch( ( err ) => { 64 66 if ( unmounted.current ) { 65 67 return; … … 69 71 setLoadFailed( true ); 70 72 setLoading( false ); 71 setNotice( __( 'Could not load AI visibility data. Reload the page to try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 73 // 401/403 or a non-JSON answer is named as such; anything else gets the generic line. 74 setNotice( restErrorMessage( classifyRestError( err ) ) || __( 'Could not load AI visibility data. Reload the page to try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 72 75 } ); 73 76 }; 74 77 75 78 // Poll GET /visibility every 5 s (up to 2 min) until the background 76 // refresh has cached a payload and the state moves off `pending`. 77 const poll = ( startedAt ) => {78 apiFetch( { path: '/blazeaid/v1/visibility' } )79 .then( ( data ) => {80 if ( unmounted.current ){81 return;82 }79 // refresh has cached a payload and the state moves off `pending`. Stops 80 // early on a 401/403 or three unexpected responses. 81 const startPolling = () => { 82 stopPolling(); 83 pollStop.current = startPoll( { 84 request: () => apiFetch( { path: '/blazeaid/v1/visibility' } ), 85 onData: ( data ) => { 83 86 if ( data && data.state !== 'pending' ) { 84 87 applyResponse( data ); 85 setRefreshing( false ); 86 return; 87 } 88 scheduleNextPoll( startedAt ); 89 } ) 90 .catch( () => scheduleNextPoll( startedAt ) ); 91 }; 92 93 const scheduleNextPoll = ( startedAt ) => { 94 if ( unmounted.current ) { 95 return; 96 } 97 if ( Date.now() - startedAt >= POLL_TIMEOUT_MS ) { 98 // The background job is still running; stop polling, keep the 99 // state as pending (so nothing claims there is no data) and let 100 // the user try Refresh again. 101 setRefreshing( false ); 102 setTimedOut( true ); 103 setNotice( __( 'Still fetching — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 104 return; 105 } 106 stopPolling(); 107 pollTimer.current = setTimeout( () => poll( startedAt ), POLL_INTERVAL_MS ); 88 } 89 }, 90 isDone: ( data ) => !! ( data && data.state !== 'pending' ), 91 intervalMs: POLL_INTERVAL_MS, 92 maxMs: POLL_TIMEOUT_MS, 93 onStop: ( reason ) => { 94 pollStop.current = null; 95 if ( unmounted.current ) { 96 return; 97 } 98 setRefreshing( false ); 99 if ( reason === 'timeout' ) { 100 // The background job is still running; keep the state as 101 // pending (so nothing claims there is no data) and let the 102 // user try Refresh again. 103 setTimedOut( true ); 104 setNotice( __( 'Still fetching — check back shortly.', 'blaze-ai-discovery-for-woocommerce' ) ); 105 return; 106 } 107 const kind = stopReasonToErrorKind( reason ); 108 if ( kind ) { 109 setLoadFailed( true ); 110 setNotice( restErrorMessage( kind ) ); 111 } 112 }, 113 } ); 108 114 }; 109 115 … … 130 136 setPayload( null ); 131 137 setState( 'pending' ); 132 s cheduleNextPoll( Date.now());138 startPolling(); 133 139 return; 134 140 } … … 149 155 // apiFetch rejects with the parsed JSON body of a non-2xx response, so the 150 156 // controller's 403 arrives as { queued: false, state: 'consent_off' }. 151 if ( err && ( err.state === 'consent_off' || ( err.data && err.data.status === 403 ) )) {157 if ( err && err.state === 'consent_off' ) { 152 158 setConsent( false ); 153 159 setPayload( null ); … … 155 161 return; 156 162 } 157 setNotice( __( 'Could not start a refresh. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) );163 setNotice( restErrorMessage( classifyRestError( err ) ) || __( 'Could not start a refresh. Please try again.', 'blaze-ai-discovery-for-woocommerce' ) ); 158 164 } ); 159 165 }; -
blaze-ai-discovery-for-woocommerce/trunk/blaze-ai-discovery-for-woocommerce.php
r3672021 r3673252 4 4 * Plugin URI: https://blazecommerce.io/blaze-ai-discovery/ 5 5 * Description: Make your WooCommerce store visible to AI shopping agents. Tracks AI-referred traffic, scores product AI-readiness, enhances Schema.org markup, and generates ChatGPT merchant feeds. 6 * Version: 1.1. 26 * Version: 1.1.3 7 7 * Author: Blaze Commerce 8 8 * Author URI: https://blazecommerce.io … … 22 22 defined( 'ABSPATH' ) || exit; 23 23 24 define( 'BLAZEAID_VERSION', '1.1. 2' );24 define( 'BLAZEAID_VERSION', '1.1.3' ); 25 25 define( 'BLAZEAID_FILE', __FILE__ ); 26 26 define( 'BLAZEAID_PATH', plugin_dir_path( __FILE__ ) ); … … 57 57 printf( 58 58 '<div class="notice notice-error"><p>%s</p></div>', 59 esc_html__( ' WooCommerce AI Discovery requires WooCommerce to be installed and active.', 'blaze-ai-discovery-for-woocommerce' )59 esc_html__( 'Blaze AI Discovery needs WooCommerce. Install and activate WooCommerce and the setup completes automatically.', 'blaze-ai-discovery-for-woocommerce' ) 60 60 ); 61 61 } ); … … 73 73 } 74 74 75 // One autoloaded option compare per request. Out of sync when the plugin 76 // was activated before WooCommerce (WP 6.4 has no Requires Plugins gate; 77 // WP-CLI and bulk activation run the hooks alphabetically) or updated in 78 // place without an activation hook (zip upload, WP.org auto-update): 79 // finish the install or run the upgrade on init, once WooCommerce has 80 // registered its post types and before our rewrite flush at init:99. 81 if ( \BlazeAiDiscovery\Database\Installer::needs_sync() ) { 82 add_action( 'init', [ \BlazeAiDiscovery\Database\Installer::class, 'sync' ], 20 ); 83 } 84 75 85 $plugin = \BlazeAiDiscovery\Plugin::get_instance(); 76 86 $plugin->init(); … … 79 89 80 90 /** 91 * Whether the Composer autoloader shipped (a GitHub "Download ZIP" install 92 * has none); the lifecycle hooks must not fatal without it. 93 */ 94 function blazeaid_autoload(): bool { 95 if ( ! file_exists( BLAZEAID_PATH . 'vendor/autoload.php' ) ) { 96 return false; 97 } 98 require_once BLAZEAID_PATH . 'vendor/autoload.php'; 99 return true; 100 } 101 102 /** 81 103 * Activation hook. 104 * 105 * @param bool $network_wide Activated from the network admin. 82 106 */ 83 function blazeaid_activate( ): void {84 if ( ! class_exists( 'WooCommerce') ) {107 function blazeaid_activate( $network_wide = false ): void { 108 if ( ! blazeaid_autoload() ) { 85 109 return; 86 110 } 87 111 88 require_once BLAZEAID_PATH . 'vendor/autoload.php'; 89 90 $migrator = new \BlazeAiDiscovery\Database\Migrator(); 91 $migrator->run(); 92 93 // Generate payload signature salt. 94 if ( ! get_option( 'blazeaid_payload_salt' ) ) { 95 update_option( 'blazeaid_payload_salt', wp_generate_password( 64, true, true ) ); 112 if ( ! class_exists( 'WooCommerce' ) ) { 113 // Nothing can be installed yet; blazeaid_boot() finishes it when WooCommerce appears. 114 \BlazeAiDiscovery\Database\Installer::mark_pending( (bool) $network_wide ); 115 return; 96 116 } 97 117 98 // Generate visitor identification salt. 99 if ( ! get_option( 'blazeaid_visitor_salt' ) ) { 100 update_option( 'blazeaid_visitor_salt', wp_generate_password( 64, true, true ) ); 101 } 102 103 // Record when tracking started (kept across re-activations; removed on uninstall). 104 \BlazeAiDiscovery\Onboarding\Onboarding::ensure_installed_at(); 105 106 // Queue the first audit now (falls back to the admin_init flag without Action Scheduler). 107 \BlazeAiDiscovery\Onboarding\Onboarding::schedule_first_audit(); 108 109 // Score the catalog in the background so the Products page has numbers without a click. 110 \BlazeAiDiscovery\Onboarding\Onboarding::schedule_first_scoring(); 118 // Schema, salts, install date, first audit + scoring, llms.txt rewrite 119 // rule then flush - on every site of the network for a network activation. 120 \BlazeAiDiscovery\Database\Installer::activate( (bool) $network_wide ); 111 121 112 122 // Open the dashboard on the next admin load: single activation only, … … 116 126 $blazeaid_request['activate-multi'] = true; 117 127 } 118 if ( isset( $_REQUEST['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only guard, no state change.128 if ( isset( $_REQUEST['action'] ) && is_string( $_REQUEST['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only guard, no state change. 119 129 $blazeaid_request['action'] = sanitize_key( wp_unslash( $_REQUEST['action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended 120 130 } … … 122 132 \BlazeAiDiscovery\Onboarding\Onboarding::arm_redirect(); 123 133 } 124 125 flush_rewrite_rules();126 134 } 127 135 register_activation_hook( __FILE__, 'blazeaid_activate' ); 128 136 129 137 /** 130 * Deactivation hook. 138 * Deactivation hook: cancel every queued job (all seven hooks plus a group 139 * sweep), drop progress transients, flush the rewrite rules without ours. 140 * 141 * @param bool $network_wide Deactivated from the network admin. 131 142 */ 132 function blazeaid_deactivate(): void { 133 // Unschedule Action Scheduler jobs. 134 if ( function_exists( 'as_unschedule_all_actions' ) ) { 135 as_unschedule_all_actions( 'blazeaid_retention_cleanup' ); 136 as_unschedule_all_actions( 'blazeaid_batch_score' ); 137 as_unschedule_all_actions( 'blazeaid_feed_refresh' ); 138 as_unschedule_all_actions( 'blazeaid_run_audit' ); 139 as_unschedule_all_actions( 'blazeaid_visibility_monthly' ); 140 as_unschedule_all_actions( 'blazeaid_visibility_refresh' ); 143 function blazeaid_deactivate( $network_wide = false ): void { 144 if ( ! blazeaid_autoload() ) { 145 return; 141 146 } 142 delete_transient( 'blazeaid_visibility_sched' ); 143 144 flush_rewrite_rules(); 147 \BlazeAiDiscovery\Database\Installer::deactivate( (bool) $network_wide ); 145 148 } 146 149 register_deactivation_hook( __FILE__, 'blazeaid_deactivate' ); 150 151 /** 152 * New subsite on a network where the plugin is network-active: install for 153 * it (priority 20 - after core and WooCommerce created the site's tables). 154 */ 155 add_action( 'wp_initialize_site', static function ( $new_site ) { 156 if ( class_exists( \BlazeAiDiscovery\Database\Installer::class ) ) { 157 \BlazeAiDiscovery\Database\Installer::on_new_site( $new_site ); 158 } 159 }, 20 ); 147 160 148 161 /** -
blaze-ai-discovery-for-woocommerce/trunk/build/index.asset.php
r3672021 r3673252 1 <?php return array('dependencies' => array('react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => ' d252e97fd979af6f6e74');1 <?php return array('dependencies' => array('react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => 'c23c16312ac595e8533f'); -
blaze-ai-discovery-for-woocommerce/trunk/build/index.js
r3672021 r3673252 1 (()=>{"use strict";var e={n:r=>{var o=r&&r.__esModule?()=>r.default:()=>r;return e.d(o,{a:o}),o},d:(r,o)=>{for(var t in o)e.o(o,t)&&!e.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:o[t]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)};const r=window.wp.element,o=window.wp.components,t=window.wp.i18n,i=window.wp.apiFetch;var a=e.n(i);const s=window.ReactJSXRuntime,n=()=>(0,t.__)("Free, no account, no API key. Runs on our infrastructure. Sends your store URL, one product URL and a few category names (publicly available information) to api.blazecommerce.io — never customer or order data. One toggle to turn off.","blaze-ai-discovery-for-woocommerce");function l({style:e}){return(0,s.jsxs)("p",{style:{margin:"8px 0 0",fontSize:13,...e||{}},children:[(0,s.jsx)("a",{href:window.blazeaid?.privacyUrl||"https://blazecommerce.io/privacy-policy/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Privacy policy","blaze-ai-discovery-for-woocommerce")})," · ",(0,s.jsx)("a",{href:window.blazeaid?.disclosureUrl||"https://wordpress.org/plugins/blaze-ai-discovery-for-woocommerce/#faq",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Full disclosure","blaze-ai-discovery-for-woocommerce")})]})}function c({onEnable:e,onDismiss:i,busy:a}){const[c,d]=(0,r.useState)(!1);return(0,s.jsxs)(o.Modal,{title:(0,t.__)("See what AI assistants actually see","blaze-ai-discovery-for-woocommerce"),onRequestClose:()=>!a&&i(),shouldCloseOnClickOutside:!1,style:{maxWidth:560},className:"blazeaid-cloud-checks-modal",children:[(0,s.jsx)("p",{style:{marginTop:0},children:(0,t.__)("Your store audit is already running. Turn on cloud checks and you also get:","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("ul",{style:{margin:"0 0 16px",paddingLeft:0,listStyle:"none"},children:[{title:(0,t.__)("Crawler access from the open internet","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("We fetch your pages as GPTBot, OAI-SearchBot, ClaudeBot and PerplexityBot from outside your network — the only way to catch a Cloudflare or firewall block your own server can't see.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Core Web Vitals from real shoppers","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("Google's field data for your store on mobile — LCP, INP, CLS — not a lab test.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Your AI Visibility report","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("How often ChatGPT and Google AI mention your store, which pages they cite, and who gets named instead. Refreshed monthly.","blaze-ai-discovery-for-woocommerce")}].map(e=>(0,s.jsxs)("li",{style:{margin:"0 0 12px"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("p",{style:{margin:"2px 0 0",color:"#50575e",fontSize:13},children:e.body})]},e.title))}),(0,s.jsxs)("p",{style:{color:"#50575e",fontSize:12,margin:"0 0 4px"},children:[n()," ",(0,s.jsx)(o.Button,{variant:"link",onClick:()=>d(!c),"aria-expanded":c,style:{fontSize:12,textDecoration:"underline"},children:(0,t.__)("Details","blaze-ai-discovery-for-woocommerce")})]}),c&&(0,s.jsxs)("div",{style:{background:"#f6f7f7",borderRadius:4,padding:"10px 12px",margin:"8px 0 12px",fontSize:12,color:"#3c434a"},children:[(0,s.jsx)("ul",{style:{margin:0,paddingLeft:18},children:[(0,t.__)("Crawler access: your store URL, one public product URL, and the plugin, WordPress, WooCommerce and PHP version numbers. Returns what each AI crawler saw.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("Core Web Vitals: your store URL. Returns Google's Chrome UX Report figures for your origin.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("AI Visibility: your domain, store country, site locale and up to five product category names. Returns the monthly mentions report.","blaze-ai-discovery-for-woocommerce")].map(e=>(0,s.jsx)("li",{style:{margin:"0 0 6px"},children:e},e))}),(0,s.jsx)("p",{style:{margin:"8px 0 0"},children:(0,t.__)("All of it is publicly available information; nothing about customers, orders or users ever leaves your site.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(l,{style:{fontSize:12}})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:16},children:[(0,s.jsx)(o.Button,{variant:"tertiary",onClick:i,disabled:a,children:(0,t.__)("Not now","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:e,isBusy:a,disabled:a,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})]})}function d({consent:e,onToggle:r,busy:i,style:a}){if(!e)return null;const c=!!e.granted;return(0,s.jsx)(o.Card,{style:{marginBottom:16,...a||{}},id:"blazeaid-cloud-consent",children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:c?(0,t.__)("Cloud checks: on","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Cloud checks: off","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[c?(0,t.__)("Your store is checked from outside your network: AI crawler access, Core Web Vitals and your AI Visibility report.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Test your store from outside your network and see your AI Visibility report.","blaze-ai-discovery-for-woocommerce")," ",n()]}),(0,s.jsx)(l,{style:{margin:"4px 0 0"}})]}),(0,s.jsx)(o.Button,{variant:c?"secondary":"primary",onClick:()=>r(!c),disabled:i,isBusy:i,children:c?(0,t.__)("Turn off","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}const u=()=>a()({path:"/blazeaid/v1/jobs/health"}).catch(()=>null);function m({health:e,audit:i,onRunNow:n,onRunAudit:l}){const[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[h,f]=(0,r.useState)(null);if(!e||c)return null;const y=l?((e,r)=>{const o=(e?.failed||[]).find(e=>e&&"blazeaid_run_audit"===e.hook);return o&&(o.at||0)>(e=>{if(!e||!e.run_at)return 0;const r=Date.parse(String(e.run_at).replace(" ","T")+"Z");return Number.isFinite(r)?r/1e3:0})(r)?o:null})(e,i):null;if(!y&&!e.stuck)return null;let p;if(y)p=y.message?(0,t.sprintf)(/* translators: %s: the Action Scheduler log line for the failed action */ /* translators: %s: the Action Scheduler log line for the failed action */2 (0,t.__)("The last background audit failed: %s","blaze-ai-discovery-for-woocommerce"), y.message):(0,t.__)("The last background audit failed.","blaze-ai-discovery-for-woocommerce");else{const r=(e=>{const r=e?.past_due;return"number"==typeof r?Math.max(0,r-(e.pending_due||0)):r||0})(e),o=(e=>{const r=Math.max(0,Number(e)||0);if(r<3600){const e=Math.max(1,Math.round(r/60));1 (()=>{"use strict";var e={n:r=>{var o=r&&r.__esModule?()=>r.default:()=>r;return e.d(o,{a:o}),o},d:(r,o)=>{for(var t in o)e.o(o,t)&&!e.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:o[t]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)};const r=window.wp.element,o=window.wp.components,t=window.wp.i18n,i=window.wp.apiFetch;var n=e.n(i);const s=window.ReactJSXRuntime,a=()=>(0,t.__)("Free, no account, no API key. Runs on our infrastructure. Sends your store URL, one product URL and a few category names (publicly available information) to api.blazecommerce.io — never customer or order data. One toggle to turn off.","blaze-ai-discovery-for-woocommerce");function l({style:e}){return(0,s.jsxs)("p",{style:{margin:"8px 0 0",fontSize:13,...e||{}},children:[(0,s.jsx)("a",{href:window.blazeaid?.privacyUrl||"https://blazecommerce.io/privacy-policy/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Privacy policy","blaze-ai-discovery-for-woocommerce")})," · ",(0,s.jsx)("a",{href:window.blazeaid?.disclosureUrl||"https://wordpress.org/plugins/blaze-ai-discovery-for-woocommerce/#faq",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("Full disclosure","blaze-ai-discovery-for-woocommerce")})]})}function c({onEnable:e,onDismiss:i,busy:n}){const[c,d]=(0,r.useState)(!1);return(0,s.jsxs)(o.Modal,{title:(0,t.__)("See what AI assistants actually see","blaze-ai-discovery-for-woocommerce"),onRequestClose:()=>!n&&i(),shouldCloseOnClickOutside:!1,style:{maxWidth:560},className:"blazeaid-cloud-checks-modal",children:[(0,s.jsx)("p",{style:{marginTop:0},children:(0,t.__)("Your store audit is already running. Turn on cloud checks and you also get:","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("ul",{style:{margin:"0 0 16px",paddingLeft:0,listStyle:"none"},children:[{title:(0,t.__)("Crawler access from the open internet","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("We fetch your pages as GPTBot, OAI-SearchBot, ClaudeBot and PerplexityBot from outside your network — the only way to catch a Cloudflare or firewall block your own server can't see.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Core Web Vitals from real shoppers","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("Google's field data for your store on mobile — LCP, INP, CLS — not a lab test.","blaze-ai-discovery-for-woocommerce")},{title:(0,t.__)("Your AI Visibility report","blaze-ai-discovery-for-woocommerce"),body:(0,t.__)("How often ChatGPT and Google AI mention your store, which pages they cite, and who gets named instead. Refreshed monthly.","blaze-ai-discovery-for-woocommerce")}].map(e=>(0,s.jsxs)("li",{style:{margin:"0 0 12px"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("p",{style:{margin:"2px 0 0",color:"#50575e",fontSize:13},children:e.body})]},e.title))}),(0,s.jsxs)("p",{style:{color:"#50575e",fontSize:12,margin:"0 0 4px"},children:[a()," ",(0,s.jsx)(o.Button,{variant:"link",onClick:()=>d(!c),"aria-expanded":c,style:{fontSize:12,textDecoration:"underline"},children:(0,t.__)("Details","blaze-ai-discovery-for-woocommerce")})]}),c&&(0,s.jsxs)("div",{style:{background:"#f6f7f7",borderRadius:4,padding:"10px 12px",margin:"8px 0 12px",fontSize:12,color:"#3c434a"},children:[(0,s.jsx)("ul",{style:{margin:0,paddingLeft:18},children:[(0,t.__)("Crawler access: your store URL, one public product URL, and the plugin, WordPress, WooCommerce and PHP version numbers. Returns what each AI crawler saw.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("Core Web Vitals: your store URL. Returns Google's Chrome UX Report figures for your origin.","blaze-ai-discovery-for-woocommerce"),(0,t.__)("AI Visibility: your domain, store country, site locale and up to five product category names. Returns the monthly mentions report.","blaze-ai-discovery-for-woocommerce")].map(e=>(0,s.jsx)("li",{style:{margin:"0 0 6px"},children:e},e))}),(0,s.jsx)("p",{style:{margin:"8px 0 0"},children:(0,t.__)("All of it is publicly available information; nothing about customers, orders or users ever leaves your site.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(l,{style:{fontSize:12}})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:16},children:[(0,s.jsx)(o.Button,{variant:"tertiary",onClick:i,disabled:n,children:(0,t.__)("Not now","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:e,isBusy:n,disabled:n,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})]})}function d({consent:e,onToggle:r,busy:i,style:n}){if(!e)return null;const c=!!e.granted;return(0,s.jsx)(o.Card,{style:{marginBottom:16,...n||{}},id:"blazeaid-cloud-consent",children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:c?(0,t.__)("Cloud checks: on","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Cloud checks: off","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[c?(0,t.__)("Your store is checked from outside your network: AI crawler access, Core Web Vitals and your AI Visibility report.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Test your store from outside your network and see your AI Visibility report.","blaze-ai-discovery-for-woocommerce")," ",a()]}),(0,s.jsx)(l,{style:{margin:"4px 0 0"}})]}),(0,s.jsx)(o.Button,{variant:c?"secondary":"primary",onClick:()=>r(!c),disabled:i,isBusy:i,children:c?(0,t.__)("Turn off","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}const u=()=>n()({path:"/blazeaid/v1/jobs/health"}).catch(()=>null);function m({health:e,audit:i,onRunNow:a,onRunAudit:l}){const[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[h,f]=(0,r.useState)(null);if(!e||c)return null;const p=l?((e,r)=>{const o=(e?.failed||[]).find(e=>e&&"blazeaid_run_audit"===e.hook);return o&&(o.at||0)>(e=>{if(!e||!e.run_at)return 0;const r=Date.parse(String(e.run_at).replace(" ","T")+"Z");return Number.isFinite(r)?r/1e3:0})(r)?o:null})(e,i):null;if(!p&&!e.stuck)return null;let y;if(p)y=p.message?(0,t.sprintf)(/* translators: %s: the Action Scheduler log line for the failed action */ /* translators: %s: the Action Scheduler log line for the failed action */ 2 (0,t.__)("The last background audit failed: %s","blaze-ai-discovery-for-woocommerce"),p.message):(0,t.__)("The last background audit failed.","blaze-ai-discovery-for-woocommerce");else{const r=(e=>{const r=e?.past_due;return"number"==typeof r?Math.max(0,r-(e.pending_due||0)):r||0})(e),o=(e=>{const r=Math.max(0,Number(e)||0);if(r<3600){const e=Math.max(1,Math.round(r/60)); 3 3 /* translators: %d: number of minutes */return(0,t.sprintf)((0,t._n)("%d minute","%d minutes",e,"blaze-ai-discovery-for-woocommerce"),e)}if(r<86400){const e=Math.round(r/3600); 4 4 /* translators: %d: number of hours */return(0,t.sprintf)((0,t._n)("%d hour","%d hours",e,"blaze-ai-discovery-for-woocommerce"),e)}const o=Math.round(r/86400); … … 6 6 (0,t.__)("queued %1$s ago; %2$s other tasks are waiting","blaze-ai-discovery-for-woocommerce"),o,r):r>0?(0,t.sprintf)(/* translators: 1: how long ago, e.g. "13 minutes"; 2: number of other past-due tasks */ /* translators: 1: how long ago, e.g. "13 minutes"; 2: number of other past-due tasks */ 7 7 (0,t._n)("queued %1$s ago; %2$d other task is waiting","queued %1$s ago; %2$d other tasks are waiting",r,"blaze-ai-discovery-for-woocommerce"),o,r):(0,t.sprintf)(/* translators: %s: how long ago, e.g. "13 minutes" */ /* translators: %s: how long ago, e.g. "13 minutes" */ 8 (0,t.__)("queued %s ago","blaze-ai-discovery-for-woocommerce"),o);const a=e.wp_cron_disabled?(0,t.__)("WP-Cron is disabled on this site (DISABLE_WP_CRON); jobs run only from a server cron.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("WP-Cron runs only when the site gets visits, so on quiet or shared hosts this can take a while.","blaze-ai-discovery-for-woocommerce");p=(0,t.sprintf)(/* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */ /* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */9 (0,t.__)("Your site's background job queue hasn't run Blaze AI Discovery's tasks yet (%1$s). %2$s","blaze-ai-discovery-for-woocommerce"),i, a)}let b=null;if(h&&h.error)b=(0,t.__)("Could not run the queue — try again or use the link.","blaze-ai-discovery-for-woocommerce");else if(h){const e=h.processed||0,r=h.remaining_due||0;b=(0,t.sprintf)(/* translators: %d: number of tasks processed */ /* translators: %d: number of tasks processed */8 (0,t.__)("queued %s ago","blaze-ai-discovery-for-woocommerce"),o);const n=e.wp_cron_disabled?(0,t.__)("WP-Cron is disabled on this site (DISABLE_WP_CRON); jobs run only from a server cron.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("WP-Cron runs only when the site gets visits, so on quiet or shared hosts this can take a while.","blaze-ai-discovery-for-woocommerce");y=(0,t.sprintf)(/* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */ /* translators: 1: "queued 13 minutes ago; 48 other tasks are waiting"; 2: the sentence explaining why */ 9 (0,t.__)("Your site's background job queue hasn't run Blaze AI Discovery's tasks yet (%1$s). %2$s","blaze-ai-discovery-for-woocommerce"),i,n)}let g=null;if(h&&h.error)g=(0,t.__)("Could not run the queue — try again or use the link.","blaze-ai-discovery-for-woocommerce");else if(h){const e=h.processed||0,r=h.remaining_due||0;g=(0,t.sprintf)(/* translators: %d: number of tasks processed */ /* translators: %d: number of tasks processed */ 10 10 (0,t._n)("Ran %d task","Ran %d tasks",e,"blaze-ai-discovery-for-woocommerce"),e)+"; "+(0,t.sprintf)(/* translators: %d: number of tasks still due */ /* translators: %d: number of tasks still due */ 11 (0,t._n)("%d task still due.","%d tasks still due.",r,"blaze-ai-discovery-for-woocommerce"),r)}return(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"warning",onRemove:()=>d(!0),className:"blazeaid-jobs-health",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsxs)("span",{style:{flex:1,minWidth:0},children:[p,b&&(0,s.jsx)("span",{style:{display:"block",marginTop:4,color:"#555"},children:b})]}),(0,s.jsx)(o.Button,{variant:"primary",onClick:y?()=>{m(!0),Promise.resolve(l()).finally(()=>m(!1))}:()=>{m(!0),f(null),a()({path:"/blazeaid/v1/jobs/run-now",method:"POST"}).then(e=>{f(e||{}),n&&n(e)}).catch(()=>f({error:!0})).finally(()=>m(!1))},isBusy:u,disabled:u,children:(0,t.__)("Run now","blaze-ai-discovery-for-woocommerce")}),e.faq_url&&(0,s.jsx)("a",{href:e.faq_url,target:"_blank",rel:"noreferrer",children:(0,t.__)("How to fix","blaze-ai-discovery-for-woocommerce")})]})})})}const h=5e3,f=18e4,y=e=>(e?.results||[]).filter(e=>"fail"===e.status||"warning"===e.status).length,p=e=>a()({path:"/blazeaid/v1/onboarding",method:"POST",data:{event:e}}),b=e=>(e?.results||[]).find(e=>Array.isArray(e.crawlers))||null,g={blocked_edge:3,blocked_robots:2,challenged:1};function x({result:e}){const r=(e=>(e?.crawlers||[]).filter(e=>"retrieval"===e.class&&"string"==typeof e.verdict&&e.verdict.startsWith("blocked_")))(e);if(!r.length)return null;const i=((e,r)=>{const o=e?.fix_links||[],t=r.reduce((e,r)=>!e||(g[r.verdict]||0)>(g[e.verdict]||0)?r:e,null);return(t&&t.layer?o.find(e=>e.layer===t.layer):null)||o[0]||null})(e,r),a=r.map(e=>e.name).join(", "),n=1===r.length?(0,t.sprintf)(/* translators: %s: crawler name */ /* translators: %s: crawler name */ 12 (0,t.__)("%s is blocked, so the AI assistant behind it cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),a):(0,t.sprintf)(/* translators: %s: comma-separated list of crawler names */ /* translators: %s: comma-separated list of crawler names */ 13 (0,t.__)("%s are blocked, so the AI assistants behind them cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),a);return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:"4px solid #d63638"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:(0,t.__)("AI shopping assistants can't reach your store","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:n})]}),(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexShrink:0},children:[i&&(0,s.jsx)(o.Button,{variant:"primary",href:i.url,target:"_blank",rel:"noopener noreferrer",children:i.label}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("View audit","blaze-ai-discovery-for-woocommerce")})]})]})})}function _({slow:e,running:r,error:i,onRunNow:a}){return(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(!e||r)&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Still queued — your site's background jobs haven't run it yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Your first store audit is running — results in about a minute.","blaze-ai-discovery-for-woocommerce")}),e&&(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:i?(0,t.__)("The audit could not run on this request. Try again, or check the notice above.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("You can run it on this page load instead — it takes up to a minute.","blaze-ai-discovery-for-woocommerce")})]}),e&&(0,s.jsx)(o.Button,{variant:"primary",onClick:a,isBusy:r,disabled:r,children:(0,t.__)("Run audit now","blaze-ai-discovery-for-woocommerce")})]})})}function v({done:e}){return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:e?"4px solid #00a32a":"4px solid #2271b1"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[!e&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsx)("div",{style:{minWidth:0,flex:1},children:(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Cloud checks are on — your store was checked from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Checking your store from outside your network…","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("See crawler results","blaze-ai-discovery-for-woocommerce")})]})})}const j={chatgpt:"ChatGPT",openai:"ChatGPT",perplexity:"Perplexity",copilot:"Microsoft Copilot",bing:"Microsoft Copilot",gemini:"Google Gemini",google_ai:"Google AI Mode",claude:"Claude",grok:"Grok",mistral:"Mistral",meta:"Meta AI"},w=/^no ai mentions/i,z=(e,r)=>new Intl.DateTimeFormat(void 0,{day:"numeric",month:"short",...r?{year:"numeric"}:{}}).format(e);function k({bg:e,color:r,fontSize:o,children:t}){return(0,s.jsx)("div",{style:{fontSize:o,fontWeight:"bold",width:56,height:56,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:e,color:r,flexShrink:0},children:t})}function S({icon:e,title:r,body:t,href:i,linkLabel:a}){return(0,s.jsx)(o.Card,{children:(0,s.jsxs)(o.CardBody,{style:{padding:20,display:"flex",alignItems:"center",gap:16},children:[e,(0,s.jsxs)("div",{style:{minWidth:0},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600},children:r}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13},children:t}),(0,s.jsx)("p",{style:{margin:"4px 0 0",fontSize:13},children:(0,s.jsx)("a",{href:i,children:a})})]})]})})}function C({audit:e}){const r=Array.isArray(e?.results)?e.results:null;let o,i;if(r){const e=r.filter(e=>e&&"fail"===e.status).length,a=r.filter(e=>e&&"warning"===e.status).length,n=e+a,l=e>0?"#f8d7da":a>0?"#fff3cd":"#d4edda",c=e>0?"#721c24":a>0?"#856404":"#155724";o=(0,s.jsx)(k,{bg:l,color:c,fontSize:24,children:e>0?"✗":a>0?"⚠":"✓"}),i=n>0?(0,t.sprintf)(/* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ /* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ 14 (0,t._n)("%1$d issue across %2$d checks","%1$d issues across %2$d checks",n,"blaze-ai-discovery-for-woocommerce"),n,r.length):(0,t.sprintf)(/* translators: %d: total number of audit rows */ /* translators: %d: total number of audit rows */ 15 (0,t.__)("All %d checks passed","blaze-ai-discovery-for-woocommerce"),r.length)}else o=(0,s.jsx)(k,{bg:"#f0f0f0",color:"#757575",fontSize:24,children:"?"}),i=(0,t.__)("No audit result yet","blaze-ai-discovery-for-woocommerce");return(0,s.jsx)(S,{icon:o,title:(0,t.__)("Store audit","blaze-ai-discovery-for-woocommerce"),body:i,href:"admin.php?page=blazeaid-audit",linkLabel:(0,t.__)("Open Store Audit","blaze-ai-discovery-for-woocommerce")})}function A({storeScore:e}){const r="number"==typeof e?.average&&Number.isFinite(e.average),o=r?e.average:0;let i="#f0f0f0",a="#757575";return r&&(i=o>=70?"#d4edda":o>=40?"#fff3cd":"#f8d7da",a=o>=70?"#155724":o>=40?"#856404":"#721c24"),(0,s.jsx)(S,{icon:(0,s.jsx)(k,{bg:i,color:a,fontSize:32,children:r?Math.round(o):"—"}),title:(0,t.__)("Product AI readiness","blaze-ai-discovery-for-woocommerce"),body:e?(0,t.sprintf)(/* translators: 1: number of scored products, 2: total number of products */ /* translators: 1: number of scored products, 2: total number of products */ 16 (0,t.__)("%1$s / %2$s products scored","blaze-ai-discovery-for-woocommerce"),e.scored_products??0,e.total_products??0):(0,t.__)("Not yet scored","blaze-ai-discovery-for-woocommerce"),href:"admin.php?page=blazeaid-products",linkLabel:(0,t.__)("See products","blaze-ai-discovery-for-woocommerce")})}function B({visibility:e,consentGranted:r}){const o=(e=>{const r=(e=>{if(!e||"ready"!==e.state)return null;const r=(e.payload?.sections||[]).find(e=>e&&"mentions"===e.id);return(r?.blocks||[]).find(e=>e&&"stat"===e.type)||null})(e);return r&&"number"==typeof r.value&&Number.isFinite(r.value)&&!(e=>(e?.payload?.notices||[]).some(e=>e&&(e.code||w.test("string"==typeof e.text?e.text:""))))(e)?r.value:null})(e),i=null!==o,a=e?.payload?.period?.label;let n;return n=i?a?(0,t.sprintf)(/* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ /* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ 17 (0,t.__)("mentions, %s","blaze-ai-discovery-for-woocommerce"),a):(0,t.__)("mentions","blaze-ai-discovery-for-woocommerce"):r?"pending"===e?.state?(0,t.__)("fetching your first report…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("no data yet","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(S,{icon:(0,s.jsx)(k,{bg:i?"#e7f0fa":"#f0f0f0",color:i?"#2271b1":"#757575",fontSize:22,children:i?(new Intl.NumberFormat).format(o):"—"}),title:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce"),body:n,href:"admin.php?page=blazeaid-visibility",linkLabel:(0,t.__)("Open AI Visibility","blaze-ai-discovery-for-woocommerce")})}function I({value:e,label:r}){return(0,s.jsxs)("div",{children:[(0,s.jsx)("h2",{style:{fontSize:36,margin:"0 0 4px"},children:e}),(0,s.jsx)("p",{style:{color:"#757575",margin:0,fontSize:14},children:r})]})}function T(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)([]),[g,w]=(0,r.useState)([]),[k,S]=(0,r.useState)(null),[T,R]=(0,r.useState)(null),[P,W]=(0,r.useState)(null),[N,$]=(0,r.useState)("30"),[L,F]=(0,r.useState)(!0),[O,D]=(0,r.useState)(window.blazeaid?.consent||null),[G,M]=(0,r.useState)(window.blazeaid?.onboarding||{}),[E,H]=(0,r.useState)(!1),[V,q]=(0,r.useState)(!1),[U,Y]=(0,r.useState)(!1),[X,J]=(0,r.useState)(!1),[Z,K]=(0,r.useState)(!1),[Q,ee]=(0,r.useState)(!1),[re,oe]=(0,r.useState)(null),[te,ie]=(0,r.useState)(null),[ae,se]=(0,r.useState)(!1),ne=(0,r.useRef)(0),le=(0,r.useRef)(!1),ce=(0,r.useRef)(!1),de=(0,r.useRef)(!1),ue=(0,r.useRef)(!1);(0,r.useEffect)(()=>()=>{ne.current+=1},[]);const me=(e,r)=>{const o=++ne.current,t=Date.now();let i=!1;const s=()=>{o===ne.current&&a()({path:"/blazeaid/v1/audit"}).catch(()=>null).then(a=>{if(o!==ne.current)return;if(a&&a.run_at&&(S(a),e(a)))return;const n=Date.now()-t;return n>=12e5?void 0:n>=f?(i||(i=!0,r&&r()),void setTimeout(s,3e4)):void setTimeout(s,h)})};setTimeout(s,h)},he=()=>u().then(e=>(e&&oe(e),e));(0,r.useEffect)(()=>{F(!0),Promise.all([a()({path:`/blazeaid/v1/attribution/summary?days=${N}`}),a()({path:`/blazeaid/v1/attribution/products?days=${N}`}),a()({path:`/blazeaid/v1/attribution/trend?days=${N}`}),a()({path:"/blazeaid/v1/audit"}).catch(()=>null),a()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),a()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t,a,s,n])=>{i(e),l(r),w(o),S(t),R(a),W(s),n&&oe(n),F(!1)}).catch(()=>F(!1))},[N]);const fe=(0,r.useRef)(0);(0,r.useEffect)(()=>()=>{fe.current+=1},[]),(0,r.useEffect)(()=>{const e=!!O&&!!O.granted,r=Array.isArray(k?.results)?k.results.find(e=>e&&e.crawlers):null,o=e&&r&&r.probe&&!1===r.probe.ran&&"consent_off"===r.probe.notice,t="pending"===P?.state||e&&"consent_off"===P?.state;if(L||!o&&!t)return;const i=++fe.current,s=Date.now(),n=()=>{i!==fe.current||Date.now()-s>f||Promise.all([t?a()({path:"/blazeaid/v1/visibility"}).catch(()=>null):Promise.resolve(void 0),o?a()({path:"/blazeaid/v1/audit"}).catch(()=>null):Promise.resolve(void 0)]).then(([e,r])=>{if(i!==fe.current)return;void 0!==e&&e&&W(e),void 0!==r&&r&&S(r);const o=void 0!==e&&e&&"pending"===e.state,t=r&&Array.isArray(r.results)?r.results.find(e=>e&&e.crawlers):null,a=void 0!==r&&!(!t||!t.probe||!1!==t.probe.ran);(o||a)&&setTimeout(n,h)})};setTimeout(n,h)},[L,P?.state,O?.granted,k]),(0,r.useEffect)(()=>{L||k||le.current||(le.current=!0,me(e=>!!e.run_at,()=>{J(!0),he()}))},[L,k]),(0,r.useEffect)(()=>{if(L||k)return;const e=setTimeout(he,6e4);return()=>clearTimeout(e)},[L,k]),(0,r.useEffect)(()=>{L||!O||O.granted||ce.current||G.modal_shown_version===(window.blazeaid?.version||"")||(ce.current=!0,H(!0))},[L]),(0,r.useEffect)(()=>{L||E||!k||!O||O.granted||!G.dismissed_at||G.reminder_shown||de.current||ue.current||(de.current=!0,se(!0),p("reminder_shown").then(M).catch(()=>{}))},[L,E,k,O,G]);const ye=()=>{K(!0),ee(!1),ne.current+=1;const e=()=>(ee(!0),J(!0),k||me(e=>!!e.run_at,()=>J(!0)),!1);return a()({path:"/blazeaid/v1/audit/run",method:"POST",data:{force:!0}}).then(r=>r&&r.results?(S(r),he(),!0):e()).catch(e).finally(()=>K(!1))},pe=()=>(Y(!0),a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!0}}).then(e=>(D(e),se(!1),ie("waiting"),a()({path:"/blazeaid/v1/audit/run",method:"POST"}).catch(()=>null))).then(e=>{if(e&&e.results)return S(e),void ie("done");me(e=>!!(e=>!0===b(e)?.probe?.ran)(e)&&(ie("done"),!0),()=>ie("done"))}).finally(()=>Y(!1)));if(L)return(0,s.jsxs)("div",{style:{padding:"40px",textAlign:"center"},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{children:(0,t.__)("Loading AI traffic data…","blaze-ai-discovery-for-woocommerce")})]});const be=(()=>{const e=window.blazeaid?.installedAt;if("string"!=typeof e||!e)return null;const r=new Date(e.replace(" ","T")+"Z");return Number.isNaN(r.getTime())?null:r})(),ge=parseInt(N,10)||30,xe=be?(_e=be,Math.max(0,Math.floor((Date.now()-_e.getTime())/864e5))):null;var _e;const ve=be&&ge>xe?(0,t.sprintf)(/* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ /* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ 18 (0,t.__)("Last %1$d days (tracking since %2$s)","blaze-ai-discovery-for-woocommerce"),ge,z(be,!1)):(0,t.sprintf)(/* translators: %d: number of days in the selected period */ /* translators: %d: number of days in the selected period */ 19 (0,t.__)("Last %d days","blaze-ai-discovery-for-woocommerce"),ge),je=be?(0,t.sprintf)(/* translators: %s: date tracking started, e.g. "30 Aug 2026" */ /* translators: %s: date tracking started, e.g. "30 Aug 2026" */ 20 (0,t.__)("Tracking since %s — the plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),z(be,!0)):(0,t.__)("The plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),we="number"==typeof e?.total_visits?e.total_visits:0,ze=Array.isArray(e?.platforms)?e.platforms.filter(e=>e&&e.platform):[],ke=Array.isArray(n)?n.filter(e=>e&&e.product_id):[],Se=(ze.length?1:0)+(ke.length?1:0);return(0,s.jsxs)("div",{className:"blazeaid-dashboard",style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsx)("h1",{style:{marginBottom:20},children:(0,t.__)("AI Discovery Dashboard","blaze-ai-discovery-for-woocommerce")}),E&&(0,s.jsx)(c,{onEnable:()=>{q(!0),pe().then(()=>p("modal_shown")).then(M).catch(()=>{}).finally(()=>{q(!1),H(!1)})},onDismiss:()=>{ue.current=!!k,H(!1),p("dismissed").then(M).catch(()=>{})},busy:V}),ae&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"info",onRemove:()=>se(!1),className:"blazeaid-onboarding-reminder",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsx)("span",{style:{flex:1,minWidth:0},children:(0,t.sprintf)(/* translators: %d: number of failed or warning audit rows */ /* translators: %d: number of failed or warning audit rows */ 21 (0,t._n)("Your local audit found %d issue. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.","Your local audit found %d issues. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.",y(k),"blaze-ai-discovery-for-woocommerce"),y(k))}),(0,s.jsx)(o.Button,{variant:"primary",onClick:pe,isBusy:U,disabled:U,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}),(0,s.jsx)(m,{health:re,audit:k,onRunNow:()=>{Promise.all([a()({path:"/blazeaid/v1/audit"}).catch(()=>null),a()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),a()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t])=>{e&&e.run_at&&S(e),r&&R(r),o&&W(o),t&&oe(t)})},onRunAudit:ye}),!k&&(0,s.jsx)(_,{slow:X,running:Z,error:Q,onRunNow:ye}),te&&(0,s.jsx)(v,{done:"done"===te}),(0,s.jsx)(x,{result:b(k)}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,marginBottom:16},children:[(0,s.jsx)(C,{audit:k}),(0,s.jsx)(A,{storeScore:T}),(0,s.jsx)(B,{visibility:P,consentGranted:O?!!O.granted:"consent_off"!==P?.state})]}),O&&!O.granted&&!E&&(0,s.jsx)(d,{consent:O,onToggle:e=>e?pe():(Y(!0),a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!1}}).then(e=>{D(e),ie(null)}).catch(()=>{}).finally(()=>Y(!1))),busy:U}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsxs)(o.CardHeader,{style:{flexWrap:"wrap",gap:12},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("AI traffic","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13,fontWeight:"normal"},children:je})]}),(0,s.jsx)(o.SelectControl,{value:N,options:[{label:(0,t.__)("Last 7 days","blaze-ai-discovery-for-woocommerce"),value:"7"},{label:(0,t.__)("Last 30 days","blaze-ai-discovery-for-woocommerce"),value:"30"},{label:(0,t.__)("Last 90 days","blaze-ai-discovery-for-woocommerce"),value:"90"}],onChange:$,__nextHasNoMarginBottom:!0})]}),(0,s.jsxs)(o.CardBody,{children:[0===we?(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No AI-referred visits recorded yet. Visits from ChatGPT, Perplexity, Copilot, Gemini and Claude will appear here.","blaze-ai-discovery-for-woocommerce")}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("p",{style:{color:"#757575",margin:"0 0 12px",fontSize:13},children:ve}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16},children:[(0,s.jsx)(I,{value:(new Intl.NumberFormat).format(we),label:(0,t.__)("AI-referred visitors","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(I,{value:(new Intl.NumberFormat).format(e?.orders?.count??0),label:(0,t.__)("AI-attributed orders","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(I,{value:new Intl.NumberFormat(void 0,{style:"currency",currency:window.blazeaid?.currency||"USD"}).format(e?.orders?.revenue??0),label:(0,t.__)("AI-attributed revenue","blaze-ai-discovery-for-woocommerce")})]})]}),(0,s.jsx)("p",{style:{color:"#757575",fontSize:13,margin:"16px 0 0"},children:(0,t.__)("Industry benchmarks show ~70% of AI traffic arrives without identifiable headers. Your actual AI traffic is likely higher than what we can detect. We track referrer headers, UTM parameters, and URL text fragments to capture as much as possible.","blaze-ai-discovery-for-woocommerce")})]})]}),Se>0&&(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:2===Se?"1fr 1fr":"1fr",gap:16},children:[ze.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Visits by platform","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Platform","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:ze.map(e=>{return(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0",textTransform:"capitalize"},children:(r=e.platform,j[String(r).toLowerCase()]||String(r).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.count})]},e.platform);var r})})]})})]}),ke.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Top products","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("AI visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:ke.map(e=>(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0"},children:e.url?(0,s.jsx)("a",{href:e.url,children:e.name}):e.name}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.visit_count})]},e.product_id))})]})})]})]})]})}function R({product:e}){const[o,i]=(0,r.useState)(!1),a=e.issues||[],n=a.filter(e=>"error"===e.severity||"warning"===e.severity).length;return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("tr",{onClick:()=>a.length>0&&i(!o),style:{cursor:a.length>0?"pointer":"default"},children:[(0,s.jsx)("td",{style:{padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[a.length>0&&(0,s.jsx)("span",{style:{fontSize:11,color:"#757575",transition:"transform 0.2s",transform:o?"rotate(90deg)":"none"},children:"▶"}),(0,s.jsx)("span",{children:e.product_name}),n>0&&(0,s.jsxs)("span",{style:{fontSize:11,color:"#757575",background:"#f0f0f0",padding:"1px 6px",borderRadius:8},children:[n," ",1===n?"issue":"issues"]})]})}),(0,s.jsx)("td",{style:{textAlign:"center",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsx)("span",{style:{display:"inline-block",padding:"2px 12px",borderRadius:12,fontSize:13,fontWeight:600,background:e.total_score>=70?"#d4edda":e.total_score>=40?"#fff3cd":"#f8d7da",color:e.total_score>=70?"#155724":e.total_score>=40?"#856404":"#721c24"},children:e.total_score})}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:e.edit_url&&(0,s.jsx)("a",{href:e.edit_url,onClick:e=>e.stopPropagation(),style:{fontSize:13},children:(0,t.__)("Edit","blaze-ai-discovery-for-woocommerce")})})]}),o&&(0,s.jsx)("tr",{children:(0,s.jsx)("td",{colSpan:"3",style:{padding:"0 0 12px 28px",borderBottom:"1px solid #eee"},children:(0,s.jsxs)("div",{style:{background:"#f9f9f9",borderRadius:6,padding:16},children:[(0,s.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[["title_score","Title",15],["description_score","Description",15],["image_score","Images",10],["brand_score","Brand",10],["category_score","Category",10],["attributes_score","Attributes",15],["price_score","Price",5],["identifier_score","Identifiers",10],["rating_score","Reviews",5],["policy_score","Policies",5]].map(([r,o,t])=>{const i=parseInt(e[r])||0,a=Math.round(i/t*100);return(0,s.jsxs)("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:4,background:a>=80?"#d4edda":a>=40?"#fff3cd":"#f8d7da",color:a>=80?"#155724":a>=40?"#856404":"#721c24"},children:[o," ",i,"/",t]},r)})}),a.length>0&&(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontWeight:600,fontSize:13,margin:"0 0 8px"},children:(0,t.__)("How to improve this product:","blaze-ai-discovery-for-woocommerce")}),a.map((e,r)=>{const o=(e=>{switch(e){case"error":return{color:"#721c24",icon:"✗"};case"warning":return{color:"#856404",icon:"⚠"};default:return{color:"#004085",icon:"ℹ"}}})(e.severity);return(0,s.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",marginBottom:6},children:[(0,s.jsx)("span",{style:{color:o.color,fontSize:12,flexShrink:0,marginTop:1},children:o.icon}),(0,s.jsxs)("span",{style:{fontSize:13,color:"#333"},children:[(0,s.jsxs)("strong",{style:{color:o.color},children:[e.name,":"]})," ",e.message]})]},r)})]})]})})})]})}const P=e=>{switch(e){case"pass":return{icon:"✓",color:"#00a32a",bg:"#d4edda"};case"warning":return{icon:"⚠",color:"#856404",bg:"#fff3cd"};case"fail":return{icon:"✗",color:"#721c24",bg:"#f8d7da"};default:return{icon:"ℹ",color:"#004085",bg:"#cce5ff"}}},W=e=>{switch(e){case"allowed":return(0,t.__)("allowed","blaze-ai-discovery-for-woocommerce");case"blocked_robots":return(0,t.__)("blocked by robots.txt","blaze-ai-discovery-for-woocommerce");case"blocked_edge":return(0,t.__)("blocked at the edge","blaze-ai-discovery-for-woocommerce");case"challenged":return(0,t.__)("challenged","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("unknown","blaze-ai-discovery-for-woocommerce")}},N=e=>{switch(e){case"high":return(0,t.__)("high confidence","blaze-ai-discovery-for-woocommerce");case"medium":return(0,t.__)("medium confidence","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("low confidence","blaze-ai-discovery-for-woocommerce")}},$=(e,r)=>{const o={display:"inline-block",width:8,height:8,borderRadius:"50%",border:`1.5px solid ${r}`,boxSizing:"border-box",flexShrink:0};return"high"===e?{...o,background:r}:"medium"===e?{...o,background:`linear-gradient(90deg, ${r} 50%, transparent 50%)`}:{...o,background:"transparent"}};function L({check:e,consentGranted:r}){const o=e.crawlers||[],i=e.fix_links||[],a=e.probe||{};let n=null;return!1===a.ran&&(n="consent_off"===a.notice?r?(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce")}):(0,t.sprintf)(/* translators: %s: reason code, e.g. rate_limited */ /* translators: %s: reason code, e.g. rate_limited */ 22 (0,t.__)("Outside-in probe unavailable (%s); results are based on robots.txt and your server log only.","blaze-ai-discovery-for-woocommerce"),a.notice||"unavailable")),(0,s.jsxs)("div",{style:{marginTop:8},children:[(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:o.map(e=>{const r="allowed"===(o=e.verdict)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:o&&o.startsWith("blocked_")?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:"challenged"===o?{color:"#856404",bg:"#fff3cd",border:"#ffe08a"}:{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"};var o;const t=[`${e.name}: ${W(e.verdict)} (${N(e.confidence)})`,e.evidence&&e.evidence.length?e.evidence[0]:null].filter(Boolean).join(" — ");return(0,s.jsxs)("span",{title:t,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("span",{style:$(e.confidence,r.color),"aria-hidden":"true"}),e.name]},e.name)})}),n&&(0,s.jsx)("p",{style:{margin:"8px 0 0",color:"#555",fontSize:13},children:n}),i.length>0&&(0,s.jsx)("ul",{style:{margin:"8px 0 0",paddingLeft:18,fontSize:13},children:i.map(e=>(0,s.jsx)("li",{children:(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.label})},e.layer))}),o.length>0&&(0,s.jsxs)("details",{style:{marginTop:8,fontSize:13},children:[(0,s.jsx)("summary",{style:{cursor:"pointer",color:"#2271b1"},children:(0,t.__)("Evidence","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("dl",{style:{margin:"8px 0 0"},children:o.map(e=>(0,s.jsxs)("div",{style:{marginBottom:6},children:[(0,s.jsxs)("dt",{style:{fontWeight:600},children:[e.name," — ",W(e.verdict),", ",N(e.confidence)]}),(e.evidence||[]).map((e,r)=>(0,s.jsx)("dd",{style:{margin:"2px 0 0 12px",color:"#555"},children:e},r))]},e.name))})]})]})}const F=e=>{switch(e){case"good":return(0,t.__)("good","blaze-ai-discovery-for-woocommerce");case"poor":return(0,t.__)("poor","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("needs improvement","blaze-ai-discovery-for-woocommerce")}};function O({cwv:e}){const r=Object.values(e?.metrics||{}).filter(e=>e&&e.label);return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:r.map(e=>{const r="good"===(o=e.rating)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:"poor"===o?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};var o;return(0,s.jsxs)("span",{title:`${e.label}: ${F(e.rating)}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("strong",{children:e.label}),e.display]},e.label)})}):null}const D=e=>"number"==typeof e&&Number.isFinite(e)?(new Intl.NumberFormat).format(e):String(e??"");function G({delta:e,deltaLabel:r}){const o="number"==typeof e&&Number.isFinite(e);if(!o&&!r)return null;let t="",i="#757575";return o&&e>0?(t="▲ ",i="#00a32a"):o&&e<0&&(t="▼ ",i="#d63638"),(0,s.jsxs)("p",{style:{margin:"4px 0 0",fontSize:13,color:i},children:[o&&(0,s.jsxs)("span",{children:[t,D(Math.abs(e))]}),o&&r?" ":"",r&&(0,s.jsx)("span",{style:{color:"#757575"},children:r})]})}function M({block:e}){return(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontSize:32,fontWeight:"bold",lineHeight:1.2},children:D(e.value)}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:14},children:e.label}),(0,s.jsx)(G,{delta:e.delta,deltaLabel:e.delta_label})]})}function E({block:e}){const r=Array.isArray(e.columns)?e.columns:[],o=Array.isArray(e.rows)?e.rows:[];if(!r.length&&!o.length)return null;const t=(e,r)=>({textAlign:"number"==typeof e?"right":"left",padding:"8px 12px 8px 0",borderBottom:r?"1px solid #ddd":"1px solid #f0f0f1",whiteSpace:"nowrap"}),i=o[0]||[];return(0,s.jsx)("div",{style:{overflowX:"auto"},children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[r.length>0&&(0,s.jsx)("thead",{children:(0,s.jsx)("tr",{children:r.map((e,r)=>(0,s.jsx)("th",{style:t(i[r],!0),children:e},r))})}),(0,s.jsx)("tbody",{children:o.map((e,r)=>(0,s.jsx)("tr",{children:(Array.isArray(e)?e:[]).map((e,r)=>(0,s.jsx)("td",{style:t(e,!1),children:"number"==typeof e?D(e):e},r))},r))})]})})}function H({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("ul",{style:{margin:"4px 0",paddingLeft:18},children:r.map((e,r)=>(0,s.jsx)("li",{style:{marginBottom:4},children:e.url?(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.text}):e.text},r))}):null}function V({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:r.map((e,r)=>{const o=(e=>["pass","warning","fail"].includes(e)?e:"unknown")(e.status),t=(e=>{switch(e){case"pass":return{color:"#155724",bg:"#d4edda",border:"#8fd19e"};case"warning":return{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};case"fail":return{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"};default:return{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"}}})(o);return(0,s.jsx)("span",{className:`blazeaid-chip blazeaid-chip--${o}`,style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:t.color,background:t.bg,border:`1px solid ${t.border}`},children:e.label},r)})}):null}function q({block:e}){return e.html?(0,s.jsx)("div",{className:"blazeaid-payload-text",style:{fontSize:13,color:"#50575e"},dangerouslySetInnerHTML:{__html:e.html}}):null}function U(e){const r=[];return(Array.isArray(e)?e:[]).forEach(e=>{const o=r[r.length-1];e&&"stat"===e.type?o&&"stats"===o.kind?o.items.push(e):r.push({kind:"stats",items:[e]}):r.push({kind:"block",block:e})}),r}function Y({block:e}){if(!e||"object"!=typeof e)return null;switch(e.type){case"stat":return(0,s.jsx)(M,{block:e});case"table":return(0,s.jsx)(E,{block:e});case"list":return(0,s.jsx)(H,{block:e});case"chips":return(0,s.jsx)(V,{block:e});case"text":return(0,s.jsx)(q,{block:e});default:return null}}function X({notices:e}){const r=Array.isArray(e)?e:[];return r.length?(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:r.map((e,r)=>{return(0,s.jsxs)(o.Notice,{status:(t=e.level,["info","warning","error"].includes(t)?t:"info"),isDismissible:!1,children:[e.text,e.link&&e.link.url&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:"_blank",rel:"noopener noreferrer",children:e.link.label||e.link.url})]})]},r);var t})}):null}function J({payload:e}){if(!e||"object"!=typeof e)return null;const r=Array.isArray(e.sections)?e.sections:[];return(0,s.jsxs)("div",{className:"blazeaid-payload",children:[(0,s.jsx)(X,{notices:e.notices}),r.map((e,r)=>{const i=Array.isArray(e.blocks)?e.blocks:[];return(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:e.title||(0,t.__)("Untitled section","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:i.length?U(i).map((e,r,o)=>(0,s.jsx)("div",{style:{marginBottom:r<o.length-1?16:0},children:"stats"===e.kind?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"16px 48px"},children:e.items.map((e,r)=>(0,s.jsx)("div",{style:{minWidth:160},children:(0,s.jsx)(Y,{block:e})},r))}):(0,s.jsx)(Y,{block:e.block})},r)):(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No data for this period.","blaze-ai-discovery-for-woocommerce")})})]},e.id||r)})]})}const Z={blazeaid:T,"blazeaid-products":function(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)([]),[c,d]=(0,r.useState)(null),[h,f]=(0,r.useState)(!0),[y,p]=(0,r.useState)(!1),[b,g]=(0,r.useState)(null),x=(e=!0)=>{e&&f(!0),Promise.all([a()({path:"/blazeaid/v1/scores/summary"}),a()({path:"/blazeaid/v1/scores/products?per_page=100&order=ASC"}),a()({path:"/blazeaid/v1/scores/progress"}),u()]).then(([e,r,o,t])=>{i(e),l(r),d(o),t&&g(t),"running"===o?.status&&p(!0),f(!1)}).catch(()=>f(!1))};if((0,r.useEffect)(()=>x(!0),[]),(0,r.useEffect)(()=>{if(!y)return;const e=setInterval(()=>{a()({path:"/blazeaid/v1/scores/progress"}).then(e=>{d(e),"complete"!==e.status&&"idle"!==e.status||(p(!1),x())})},3e3);return()=>clearInterval(e)},[y]),h)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const _=c?.total>0?Math.round(c.scored/c.total*100):0;return(0,s.jsxs)("div",{style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Product AI Readiness","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{p(!0),a()({path:"/blazeaid/v1/scores/recalculate",method:"POST"})},disabled:y,children:y?(0,t.__)("Scoring...","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Recalculate All","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsx)(m,{health:b,onRunNow:()=>x(!1)}),y&&"running"===c?.status&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{padding:20},children:[(0,s.jsxs)("p",{children:[(0,t.__)("Scoring products...","blaze-ai-discovery-for-woocommerce")," ",c.scored," / ",c.total," (",_,"%)"]}),(0,s.jsx)("div",{style:{background:"#e0e0e0",borderRadius:4,height:8},children:(0,s.jsx)("div",{style:{background:"#007cba",borderRadius:4,height:8,width:`${_}%`,transition:"width 0.3s"}})})]})}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{style:{padding:24},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:24},children:[(0,s.jsx)("div",{style:{fontSize:48,fontWeight:"bold",color:e?.average>=70?"#00a32a":e?.average>=40?"#dba617":"#d63638"},children:e?.average??0}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontSize:18,margin:0},children:(0,t.__)("Product AI Readiness Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:"running"===c?.status?(0,t.sprintf)(/* translators: 1: products scored so far, 2: total products */ /* translators: 1: products scored so far, 2: total products */ 23 (0,t.__)("Scoring your products… %1$d / %2$d","blaze-ai-discovery-for-woocommerce"),c.scored??0,c.total??0):`${e?.scored_products??0} / ${e?.total_products??0} ${(0,t.__)("products scored","blaze-ai-discovery-for-woocommerce")}`})]})]})})}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Products by AI Readiness (lowest first)","blaze-ai-discovery-for-woocommerce"),(0,s.jsx)("span",{style:{fontWeight:"normal",fontSize:13,color:"#757575",marginLeft:8},children:(0,t.__)("Click a row to see recommendations","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)(o.CardBody,{children:n.length>0?(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"2px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"center",padding:"8px 0",borderBottom:"2px solid #ddd",width:100},children:(0,t.__)("Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"2px solid #ddd",width:80},children:(0,t.__)("Action","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:n.map(e=>(0,s.jsx)(R,{product:e},e.product_id))})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No products scored yet. Click "Recalculate All" to scan your catalog.',"blaze-ai-discovery-for-woocommerce")})})]})]})},"blazeaid-audit":function(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)(!0),[c,u]=(0,r.useState)(!1),[m,h]=(0,r.useState)(null),[f,y]=(0,r.useState)(null);(0,r.useEffect)(()=>{l(!0),a()({path:"/blazeaid/v1/audit"}).then(e=>{i(e),l(!1)}).catch(()=>l(!1)),a()({path:"/blazeaid/v1/cloud/consent"}).then(y).catch(()=>y(null))},[]);const p=(e,r)=>{if(Date.now()-r>=9e4)return u(!1),void h((0,t.__)("Still running — check back shortly.","blaze-ai-discovery-for-woocommerce"));setTimeout(()=>((e,r)=>{a()({path:"/blazeaid/v1/audit"}).then(o=>{if(o&&o.run_at&&o.run_at!==e)return i(o),void u(!1);p(e,r)}).catch(()=>p(e,r))})(e,r),3e3)},b=()=>{u(!0),h(null);const r=e?.run_at||null;a()({path:"/blazeaid/v1/audit/run",method:"POST"}).then(e=>{e&&e.queued?p(r,Date.now()):(i(e),u(!1))}).catch(()=>u(!1))};if(n)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const g=e?.results||[],x=e?.overall_status||"unknown",_=(0,s.jsx)(d,{consent:f,onToggle:e=>{a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(e=>{y(e),b()})},busy:c,style:{marginTop:16}});return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Store Readiness Audit","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:b,disabled:c,children:c?(0,t.__)("Running…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Re-run Audit","blaze-ai-discovery-for-woocommerce")})]}),e?.run_at&&(0,s.jsxs)("p",{style:{color:"#757575",marginBottom:16},children:[(0,t.__)("Last run:","blaze-ai-discovery-for-woocommerce")," ",e.run_at]}),(c||m)&&(0,s.jsxs)("div",{style:{display:"grid",gap:12,marginBottom:16},children:[c&&(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("Running… this can take up to a minute while the store is checked from outside your network.","blaze-ai-discovery-for-woocommerce")}),m&&(0,s.jsx)("p",{style:{color:"#856404",margin:0},children:m})]}),!f?.granted&&_,(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Readiness Checklist","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:12,...P(x)},children:x.toUpperCase()})]})}),(0,s.jsx)(o.CardBody,{children:g.length>0?(0,s.jsx)("div",{children:g.map((e,r)=>{const o=P(e.status);return(0,s.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:"12px 0",borderBottom:r<g.length-1?"1px solid #eee":"none"},children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",background:o.bg,color:o.color,fontWeight:"bold",fontSize:14,flexShrink:0},children:o.icon}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:e.check}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[e.message,e.link&&!Array.isArray(e.crawlers)&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:e.link.url.startsWith("http")&&!e.link.url.includes("/wp-admin/")?"_blank":"_self",rel:"noopener noreferrer",children:e.link.label})]})]}),Array.isArray(e.crawlers)&&(0,s.jsx)(L,{check:e,consentGranted:!!f?.granted}),e.cwv&&(0,s.jsx)(O,{cwv:e.cwv})]})]},r)})}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No audit has been run yet. Click "Re-run Audit" to check your store.',"blaze-ai-discovery-for-woocommerce")})})]}),f?.granted&&_]})},"blazeaid-feed":function(){const[e,i]=(0,r.useState)(null),[n,l]=(0,r.useState)(null),[c,d]=(0,r.useState)(!0),[u,m]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{d(!0),Promise.all([a()({path:"/blazeaid/v1/feed/status"}),a()({path:"/blazeaid/v1/feed/validate"})]).then(([e,r])=>{i(e),l(r),d(!1)}).catch(()=>d(!1))},[]),c?(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})}):(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsx)("h1",{children:(0,t.__)("ChatGPT Merchant Feed","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Status","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{style:{margin:"0 0 8px"},children:[(0,s.jsx)("strong",{children:(0,t.__)("Products in feed:","blaze-ai-discovery-for-woocommerce")})," ",e?.product_count??0]}),e?.generated_at&&(0,s.jsxs)("p",{style:{margin:0,color:"#757575",fontSize:13},children:[(0,t.__)("Last generated:","blaze-ai-discovery-for-woocommerce")," ",e.generated_at]})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{m(!0),a()({path:"/blazeaid/v1/feed/generate",method:"POST"}).then(e=>{i(e),m(!1)}).catch(()=>m(!1))},disabled:u,children:u?(0,t.__)("Generating…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Generate Feed","blaze-ai-discovery-for-woocommerce")}),e?.download_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.download_url,target:"_blank",children:(0,t.__)("Download CSV","blaze-ai-discovery-for-woocommerce")}),e?.json_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.json_url,target:"_blank",children:(0,t.__)("View JSON","blaze-ai-discovery-for-woocommerce")})]})]})})]}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Validation","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:n?(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{children:[(0,s.jsxs)("span",{style:{color:"#00a32a",fontWeight:600},children:[n.valid," ",(0,t.__)("valid","blaze-ai-discovery-for-woocommerce")]}),n.invalid>0&&(0,s.jsxs)("span",{style:{color:"#d63638",fontWeight:600,marginLeft:16},children:[n.invalid," ",(0,t.__)("invalid","blaze-ai-discovery-for-woocommerce")]})]}),n.issues?.length>0&&(0,s.jsxs)("div",{style:{marginTop:12},children:[(0,s.jsx)("h4",{children:(0,t.__)("Issues to fix:","blaze-ai-discovery-for-woocommerce")}),n.issues.map((e,r)=>(0,s.jsxs)("div",{style:{padding:"8px 0",borderBottom:"1px solid #eee"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("ul",{style:{margin:"4px 0 0",paddingLeft:20},children:e.issues.map((e,r)=>(0,s.jsx)("li",{style:{fontSize:13,color:"#555"},children:e},r))})]},r))]})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)("Generate a feed to see validation results.","blaze-ai-discovery-for-woocommerce")})})]}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("How to Submit to ChatGPT","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("ol",{style:{lineHeight:1.8},children:[(0,s.jsx)("li",{children:(0,t.__)('Click "Generate Feed", then "Download CSV" — CSV is the format OpenAI ingests.',"blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Apply to the merchant programme at","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://chatgpt.com/merchants",target:"_blank",rel:"noopener noreferrer",children:"chatgpt.com/merchants"}),"."]}),(0,s.jsx)("li",{children:(0,t.__)("Once approved, OpenAI gives you an SFTP endpoint. Upload the CSV there and re-upload whenever your catalogue changes.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Want automatic SFTP delivery or help with merchant-programme onboarding? Ask on the","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://wordpress.org/support/plugin/blaze-ai-discovery-for-woocommerce/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("support forum","blaze-ai-discovery-for-woocommerce")})," ",(0,t.__)("and we will work with you.","blaze-ai-discovery-for-woocommerce")]})]})})]})]})},"blazeaid-visibility":function(){const[e,i]=(0,r.useState)(!0),[n,l]=(0,r.useState)(null),[c,u]=(0,r.useState)(null),[m,h]=(0,r.useState)(!1),[f,y]=(0,r.useState)(!1),[p,b]=(0,r.useState)(null),[g,x]=(0,r.useState)(!1),[_,v]=(0,r.useState)(!1),j=(0,r.useRef)(null),w=(0,r.useRef)(!1),z=()=>{j.current&&(clearTimeout(j.current),j.current=null)},k=e=>{h(!!e?.consent),u(e?.payload||null),l(e?.state||"empty")},S=()=>{i(!0),b(null),x(!1),v(!1),a()({path:"/blazeaid/v1/visibility"}).then(e=>{w.current||(k(e),i(!1),"pending"===e?.state&&C(Date.now()))}).catch(()=>{w.current||(l(null),v(!0),i(!1),b((0,t.__)("Could not load AI visibility data. Reload the page to try again.","blaze-ai-discovery-for-woocommerce")))})},C=e=>{if(!w.current){if(Date.now()-e>=12e4)return y(!1),x(!0),void b((0,t.__)("Still fetching — check back shortly.","blaze-ai-discovery-for-woocommerce"));z(),j.current=setTimeout(()=>(e=>{a()({path:"/blazeaid/v1/visibility"}).then(r=>{if(!w.current)return r&&"pending"!==r.state?(k(r),void y(!1)):void C(e)}).catch(()=>C(e))})(e),5e3)}};(0,r.useEffect)(()=>(w.current=!1,S(),()=>{w.current=!0,z()}),[]);const A=e=>{y(!0),a()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(()=>{w.current||(y(!1),z(),S())}).catch(()=>y(!1))};if(e)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const B=c?.period?.label||(0,t.__)("last 30 days","blaze-ai-discovery-for-woocommerce"),I=(Array.isArray(c?.sections)?c.sections:[]).length>0,T="empty"===n||"ready"===n&&!I,R="pending"===n&&!g,P=m&&"consent_off"!==n&&!R&&!f;return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20,gap:16,flexWrap:"wrap"},children:[(0,s.jsx)("h1",{style:{margin:0},children:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==n&&(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{y(!0),b(null),x(!1),v(!1),a()({path:"/blazeaid/v1/visibility/refresh",method:"POST"}).then(e=>{if(!w.current){if(e&&e.queued)return u(null),l("pending"),void C(Date.now());e&&e.payload?(u(e.payload),l("ready")):l("empty"),y(!1)}}).catch(e=>{if(!w.current){if(y(!1),e&&("consent_off"===e.state||e.data&&403===e.data.status))return h(!1),u(null),void l("consent_off");b((0,t.__)("Could not start a refresh. Please try again.","blaze-ai-discovery-for-woocommerce"))}})},disabled:!P,children:R||f?(0,t.__)("Refreshing…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Refresh","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsx)("p",{style:{color:"#757575",marginBottom:16},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ /* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ 24 (0,t.__)("How often AI assistants (ChatGPT, Google AI) mentioned your store over the %s, and who gets named instead.","blaze-ai-discovery-for-woocommerce"),B)}),p&&(0,s.jsx)("p",{style:{color:_?"#d63638":"#856404",marginBottom:16},role:_?"alert":"status",children:p}),"consent_off"===n&&(0,s.jsx)(d,{consent:{granted:!1,decided:!0},onToggle:A,busy:f,style:{marginTop:16}}),R&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:12},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{style:{margin:0,color:"#555"},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "last 30 days" */ /* translators: %s: reporting window, e.g. "last 30 days" */ 25 (0,t.__)("Fetching AI visibility data for the %s — this runs in the background and usually takes under a minute.","blaze-ai-discovery-for-woocommerce"),B)})]})}),"ready"===n&&I&&(0,s.jsx)(J,{payload:c}),T&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(X,{notices:c?.notices}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("p",{style:{margin:0,color:"#555"},children:["ready"===n?(0,t.__)("No AI visibility data is available for this period yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("AI visibility data has not been fetched yet. Background scheduling is unavailable on this site, so use Refresh to fetch it now.","blaze-ai-discovery-for-woocommerce")," ",(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")]})})})]}),"ready"===n&&I&&(0,s.jsx)("p",{style:{color:"#757575",fontSize:13},children:(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==n&&(0,s.jsx)(d,{consent:{granted:!0,decided:!0},onToggle:A,busy:f,style:{marginTop:16}})]})}},K=document.getElementById("blazeaid-root");if(K){const e=Z[window.blazeaid?.currentPage||"blazeaid"]||T;(0,r.render)((0,s.jsx)(e,{}),K)}})(); 11 (0,t._n)("%d task still due.","%d tasks still due.",r,"blaze-ai-discovery-for-woocommerce"),r)}return(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"warning",onRemove:()=>d(!0),className:"blazeaid-jobs-health",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsxs)("span",{style:{flex:1,minWidth:0},children:[y,g&&(0,s.jsx)("span",{style:{display:"block",marginTop:4,color:"#555"},children:g})]}),(0,s.jsx)(o.Button,{variant:"primary",onClick:p?()=>{m(!0),Promise.resolve(l()).finally(()=>m(!1))}:()=>{m(!0),f(null),n()({path:"/blazeaid/v1/jobs/run-now",method:"POST"}).then(e=>{f(e||{}),a&&a(e)}).catch(()=>f({error:!0})).finally(()=>m(!1))},isBusy:u,disabled:u,children:(0,t.__)("Run now","blaze-ai-discovery-for-woocommerce")}),e.faq_url&&(0,s.jsx)("a",{href:e.faq_url,target:"_blank",rel:"noreferrer",children:(0,t.__)("How to fix","blaze-ai-discovery-for-woocommerce")})]})})})}const h=["rest_forbidden","rest_cookie_invalid_nonce","rest_not_logged_in","rest_forbidden_context"],f=e=>{if(!e||"object"!=typeof e)return"other";const r=Number(e.data&&e.data.status),o="string"==typeof e.code?e.code:"";return 401===r||403===r||h.includes(o)?"auth":"invalid_json"===o?"html":"fetch_error"===o?"network":404===r?"not_found":"other"},p=(0,t.__)("Your session expired or a security plugin is blocking the WordPress REST API for logged-in requests — reload the page.","blaze-ai-discovery-for-woocommerce"),y=(0,t.__)("Unexpected response from your site's REST API (not JSON — a firewall page, a maintenance page or a PHP error printed before the data). Reload the page; if it keeps happening, check the site's error log.","blaze-ai-discovery-for-woocommerce"),g=(0,t.__)("Could not reach your site. Check your connection and reload the page.","blaze-ai-discovery-for-woocommerce"),b=e=>{switch(e){case"auth":return p;case"html":case"other":return y;case"network":return g;default:return null}};function x({kind:e}){const r=b(e);return r?(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"error",isDismissible:!1,className:"blazeaid-rest-error",children:r})}):null}const _=12e5;function v({request:e,onData:r,isDone:o,intervalMs:t,firstDelayMs:i,slowAfterMs:n,slowIntervalMs:s,onSlow:a,maxMs:l,onStop:c}){const d=Math.min(_,"number"==typeof l&&l>0?l:_),u=Date.now();let m=null,h=!1,p=!1,y=0,g=null;const b=()=>{h=!0,m&&(clearTimeout(m),m=null)},x=e=>{b(),c&&c(e)},v=()=>{if(h)return;const e=Date.now()-u;if(e>=d)return void x("timeout");let r=t;"number"==typeof n&&e>=n&&(p||(p=!0,a&&a()),r=s||t),m=setTimeout(w,r)},w=()=>{m=null,h||Promise.resolve().then(e).then(e=>{h||(y=0,g=null,r&&r(e),o&&o(e)?x("done"):v())}).catch(e=>{if(h)return;const r=f(e);if("auth"!==r){if("not_found"===r)return y=0,void v();y+=1,g=r,y>=3?x("network"===g?"network":"unexpected"):v()}else x("auth")})};return m=setTimeout(w,"number"==typeof i?i:t),b}const w=e=>{switch(e){case"auth":return"auth";case"unexpected":return"html";case"network":return"network";default:return null}},j=18e4,z=12e5,k=e=>(e?.results||[]).filter(e=>"fail"===e.status||"warning"===e.status).length,S=e=>n()({path:"/blazeaid/v1/onboarding",method:"POST",data:{event:e}}),C=e=>(e?.results||[]).find(e=>Array.isArray(e.crawlers))||null,A=e=>(e=>(e?.results||[]).filter(e=>e&&"pending"===e.status))(e).length>0,B={blocked_edge:3,blocked_robots:2,challenged:1};function I({result:e}){const r=(e=>(e?.crawlers||[]).filter(e=>"retrieval"===e.class&&"string"==typeof e.verdict&&e.verdict.startsWith("blocked_")))(e);if(!r.length)return null;const i=((e,r)=>{const o=e?.fix_links||[],t=r.reduce((e,r)=>!e||(B[r.verdict]||0)>(B[e.verdict]||0)?r:e,null);return(t&&t.layer?o.find(e=>e.layer===t.layer):null)||o[0]||null})(e,r),n=r.map(e=>e.name).join(", "),a=1===r.length?(0,t.sprintf)(/* translators: %s: crawler name */ /* translators: %s: crawler name */ 12 (0,t.__)("%s is blocked, so the AI assistant behind it cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),n):(0,t.sprintf)(/* translators: %s: comma-separated list of crawler names */ /* translators: %s: comma-separated list of crawler names */ 13 (0,t.__)("%s are blocked, so the AI assistants behind them cannot read your product pages when a shopper asks about them.","blaze-ai-discovery-for-woocommerce"),n);return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:"4px solid #d63638"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:(0,t.__)("AI shopping assistants can't reach your store","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:a})]}),(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexShrink:0},children:[i&&(0,s.jsx)(o.Button,{variant:"primary",href:i.url,target:"_blank",rel:"noopener noreferrer",children:i.label}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("View audit","blaze-ai-discovery-for-woocommerce")})]})]})})}function T({slow:e,running:r,error:i,onRunNow:n}){return(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[(!e||r)&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Still queued — your site's background jobs haven't run it yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Your first store audit is running — results in about a minute.","blaze-ai-discovery-for-woocommerce")}),e&&(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:i?(0,t.__)("The audit could not run on this request. Try again, or check the notice above.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("You can run it on this page load instead — it takes up to a minute.","blaze-ai-discovery-for-woocommerce")})]}),e&&(0,s.jsx)(o.Button,{variant:"primary",onClick:n,isBusy:r,disabled:r,children:(0,t.__)("Run audit now","blaze-ai-discovery-for-woocommerce")})]})})}function R({done:e}){return(0,s.jsx)(o.Card,{style:{marginBottom:16,borderLeft:e?"4px solid #00a32a":"4px solid #2271b1"},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[!e&&(0,s.jsx)(o.Spinner,{style:{margin:0}}),(0,s.jsx)("div",{style:{minWidth:0,flex:1},children:(0,s.jsx)("p",{style:{margin:0,fontWeight:600,fontSize:15},children:e?(0,t.__)("Cloud checks are on — your store was checked from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Checking your store from outside your network…","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)("a",{href:"admin.php?page=blazeaid-audit",children:(0,t.__)("See crawler results","blaze-ai-discovery-for-woocommerce")})]})})}const P={chatgpt:"ChatGPT",openai:"ChatGPT",perplexity:"Perplexity",copilot:"Microsoft Copilot",bing:"Microsoft Copilot",gemini:"Google Gemini",google_ai:"Google AI Mode",claude:"Claude",grok:"Grok",mistral:"Mistral",meta:"Meta AI"},W=/^no ai mentions/i,N=(e,r)=>new Intl.DateTimeFormat(void 0,{day:"numeric",month:"short",...r?{year:"numeric"}:{}}).format(e);function M({bg:e,color:r,fontSize:o,children:t}){return(0,s.jsx)("div",{style:{fontSize:o,fontWeight:"bold",width:56,height:56,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:e,color:r,flexShrink:0},children:t})}function $({icon:e,title:r,body:t,href:i,linkLabel:n}){return(0,s.jsx)(o.Card,{children:(0,s.jsxs)(o.CardBody,{style:{padding:20,display:"flex",alignItems:"center",gap:16},children:[e,(0,s.jsxs)("div",{style:{minWidth:0},children:[(0,s.jsx)("p",{style:{margin:0,fontWeight:600},children:r}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13},children:t}),(0,s.jsx)("p",{style:{margin:"4px 0 0",fontSize:13},children:(0,s.jsx)("a",{href:i,children:n})})]})]})})}function D({audit:e}){const r=Array.isArray(e?.results)?e.results:null;let o,i;if(r){const e=r.filter(e=>e&&"fail"===e.status).length,n=r.filter(e=>e&&"warning"===e.status).length,a=e+n,l=r.filter(e=>e&&"pending"===e.status).length,c=e>0?"#f8d7da":n>0?"#fff3cd":"#d4edda",d=e>0?"#721c24":n>0?"#856404":"#155724";o=(0,s.jsx)(M,{bg:c,color:d,fontSize:24,children:e>0?"✗":n>0?"⚠":"✓"}),i=a>0?(0,t.sprintf)(/* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ /* translators: 1: number of failed or warning audit rows, 2: total number of audit rows */ 14 (0,t._n)("%1$d issue across %2$d checks","%1$d issues across %2$d checks",a,"blaze-ai-discovery-for-woocommerce"),a,r.length):(0,t.sprintf)(/* translators: %d: total number of audit rows */ /* translators: %d: total number of audit rows */ 15 (0,t.__)("All %d checks passed","blaze-ai-discovery-for-woocommerce"),r.length),l>0&&(i+=" · "+(0,t.sprintf)(/* translators: %d: number of audit rows whose cloud check is still running */ /* translators: %d: number of audit rows whose cloud check is still running */ 16 (0,t._n)("%d cloud check still running","%d cloud checks still running",l,"blaze-ai-discovery-for-woocommerce"),l))}else o=(0,s.jsx)(M,{bg:"#f0f0f0",color:"#757575",fontSize:24,children:"?"}),i=(0,t.__)("No audit result yet","blaze-ai-discovery-for-woocommerce");return(0,s.jsx)($,{icon:o,title:(0,t.__)("Store audit","blaze-ai-discovery-for-woocommerce"),body:i,href:"admin.php?page=blazeaid-audit",linkLabel:(0,t.__)("Open Store Audit","blaze-ai-discovery-for-woocommerce")})}function L({storeScore:e}){const r="number"==typeof e?.average&&Number.isFinite(e.average),o=r?e.average:0;let i="#f0f0f0",n="#757575";return r&&(i=o>=70?"#d4edda":o>=40?"#fff3cd":"#f8d7da",n=o>=70?"#155724":o>=40?"#856404":"#721c24"),(0,s.jsx)($,{icon:(0,s.jsx)(M,{bg:i,color:n,fontSize:32,children:r?Math.round(o):"—"}),title:(0,t.__)("Product AI readiness","blaze-ai-discovery-for-woocommerce"),body:e?(0,t.sprintf)(/* translators: 1: number of scored products, 2: total number of products */ /* translators: 1: number of scored products, 2: total number of products */ 17 (0,t.__)("%1$s / %2$s products scored","blaze-ai-discovery-for-woocommerce"),e.scored_products??0,e.total_products??0):(0,t.__)("Not yet scored","blaze-ai-discovery-for-woocommerce"),href:"admin.php?page=blazeaid-products",linkLabel:(0,t.__)("See products","blaze-ai-discovery-for-woocommerce")})}function F({visibility:e,consentGranted:r}){const o=(e=>{const r=(e=>{if(!e||"ready"!==e.state)return null;const r=(e.payload?.sections||[]).find(e=>e&&"mentions"===e.id);return(r?.blocks||[]).find(e=>e&&"stat"===e.type)||null})(e);return r&&"number"==typeof r.value&&Number.isFinite(r.value)&&!(e=>(e?.payload?.notices||[]).some(e=>e&&(e.code||W.test("string"==typeof e.text?e.text:""))))(e)?r.value:null})(e),i=null!==o,n=e?.payload?.period?.label;let a;return a=i?n?(0,t.sprintf)(/* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ /* translators: %s: reporting window from the service, e.g. "30 days to 28 Aug 2026" */ 18 (0,t.__)("mentions, %s","blaze-ai-discovery-for-woocommerce"),n):(0,t.__)("mentions","blaze-ai-discovery-for-woocommerce"):r?"pending"===e?.state?(0,t.__)("fetching your first report…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("no data yet","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)($,{icon:(0,s.jsx)(M,{bg:i?"#e7f0fa":"#f0f0f0",color:i?"#2271b1":"#757575",fontSize:22,children:i?(new Intl.NumberFormat).format(o):"—"}),title:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce"),body:a,href:"admin.php?page=blazeaid-visibility",linkLabel:(0,t.__)("Open AI Visibility","blaze-ai-discovery-for-woocommerce")})}function O({value:e,label:r}){return(0,s.jsxs)("div",{children:[(0,s.jsx)("h2",{style:{fontSize:36,margin:"0 0 4px"},children:e}),(0,s.jsx)("p",{style:{color:"#757575",margin:0,fontSize:14},children:r})]})}function q(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)([]),[h,p]=(0,r.useState)([]),[y,g]=(0,r.useState)(null),[_,B]=(0,r.useState)(null),[W,M]=(0,r.useState)(null),[$,q]=(0,r.useState)("30"),[G,E]=(0,r.useState)(!0),[H,V]=(0,r.useState)(window.blazeaid?.consent||null),[U,Y]=(0,r.useState)(window.blazeaid?.onboarding||{}),[J,X]=(0,r.useState)(!1),[Q,Z]=(0,r.useState)(!1),[K,ee]=(0,r.useState)(!1),[re,oe]=(0,r.useState)(!1),[te,ie]=(0,r.useState)(!1),[ne,se]=(0,r.useState)(!1),[ae,le]=(0,r.useState)(null),[ce,de]=(0,r.useState)(null),[ue,me]=(0,r.useState)(!1),[he,fe]=(0,r.useState)(null),pe=(0,r.useRef)(null),ye=(0,r.useRef)(!1),ge=(0,r.useRef)(!1),be=(0,r.useRef)(!1),xe=(0,r.useRef)(!1),_e=()=>{pe.current&&(pe.current(),pe.current=null)};(0,r.useEffect)(()=>_e,[]);const ve=e=>{const r="string"==typeof e?e:f(e);return b(r)&&fe(r),r},we=(e,r)=>{_e(),pe.current=v({request:()=>n()({path:"/blazeaid/v1/audit"}),onData:e=>{e&&e.run_at&&g(e)},isDone:r=>!!(r&&r.run_at&&e(r)),intervalMs:5e3,slowAfterMs:j,slowIntervalMs:3e4,onSlow:r,maxMs:z,onStop:e=>{pe.current=null;const r=w(e);r&&ve(r)}})},je=()=>u().then(e=>(e&&le(e),e));(0,r.useEffect)(()=>{E(!0),Promise.all([n()({path:`/blazeaid/v1/attribution/summary?days=${$}`}),n()({path:`/blazeaid/v1/attribution/products?days=${$}`}),n()({path:`/blazeaid/v1/attribution/trend?days=${$}`}),n()({path:"/blazeaid/v1/audit"}).catch(()=>null),n()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),n()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t,n,s,a])=>{i(e),l(r),p(o),g(t),B(n),M(s),a&&le(a),E(!1)}).catch(e=>{ve(e),E(!1)})},[$]);const ze=!!H&&!!H.granted,ke=C(y),Se=!!(ze&&ke&&ke.probe&&!1===ke.probe.ran&&"consent_off"===ke.probe.notice),Ce=A(y),Ae="pending"===W?.state||ze&&"consent_off"===W?.state;(0,r.useEffect)(()=>{if(G||!Se&&!Ae&&!Ce)return;const e=Ae,r=Se||Ce;return v({request:()=>Promise.all([e?n()({path:"/blazeaid/v1/visibility"}):Promise.resolve(void 0),r?n()({path:"/blazeaid/v1/audit"}):Promise.resolve(void 0)]),onData:([e,r])=>{e&&M(e),r&&r.run_at&&g(r)},isDone:o=>!(([o,t])=>{const i=!!e&&!(!o||"pending"!==o.state),n=r?C(t):null,s=!!r&&!(!n||!n.probe||!1!==n.probe.ran),a=!!r&&A(t);return i||s||a})(o),intervalMs:5e3,slowAfterMs:j,slowIntervalMs:3e4,maxMs:z,onStop:e=>{const r=w(e);r&&ve(r)}})},[G,Ae,Se,Ce]),(0,r.useEffect)(()=>{G||y||he||ye.current||(ye.current=!0,we(e=>!!e.run_at,()=>{oe(!0),je()}))},[G,y,he]),(0,r.useEffect)(()=>{if(G||y||he)return;const e=setTimeout(je,6e4);return()=>clearTimeout(e)},[G,y,he]),(0,r.useEffect)(()=>{G||!H||H.granted||ge.current||U.modal_shown_version===(window.blazeaid?.version||"")||(ge.current=!0,X(!0))},[G]),(0,r.useEffect)(()=>{G||J||!y||!H||H.granted||!U.dismissed_at||U.reminder_shown||be.current||xe.current||(be.current=!0,me(!0),S("reminder_shown").then(Y).catch(()=>{}))},[G,J,y,H,U]);const Be=()=>{ie(!0),se(!1),_e();const e=e=>{se(!0);const r=e?ve(e):null;return"auth"===r||"html"===r||(oe(!0),y||we(e=>!!e.run_at,()=>oe(!0))),!1};return n()({path:"/blazeaid/v1/audit/run",method:"POST",data:{force:!0}}).then(r=>r&&r.results?(g(r),je(),!0):e(null)).catch(e).finally(()=>ie(!1))},Ie=()=>(ee(!0),n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!0}}).then(e=>(V(e),me(!1),de("waiting"),n()({path:"/blazeaid/v1/audit/run",method:"POST"}).catch(()=>null))).then(e=>{if(e&&e.results)return g(e),void de("done");we(e=>!!(e=>!0===C(e)?.probe?.ran)(e)&&(de("done"),!0),()=>de("done"))}).finally(()=>ee(!1)));if(G)return(0,s.jsxs)("div",{style:{padding:"40px",textAlign:"center"},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{children:(0,t.__)("Loading AI traffic data…","blaze-ai-discovery-for-woocommerce")})]});const Te=(()=>{const e=window.blazeaid?.installedAt;if("string"!=typeof e||!e)return null;const r=new Date(e.replace(" ","T")+"Z");return Number.isNaN(r.getTime())?null:r})(),Re=parseInt($,10)||30,Pe=Te?(We=Te,Math.max(0,Math.floor((Date.now()-We.getTime())/864e5))):null;var We;const Ne=Te&&Re>Pe?(0,t.sprintf)(/* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ /* translators: 1: number of days in the selected period, 2: install date, e.g. "30 Aug" */ 19 (0,t.__)("Last %1$d days (tracking since %2$s)","blaze-ai-discovery-for-woocommerce"),Re,N(Te,!1)):(0,t.sprintf)(/* translators: %d: number of days in the selected period */ /* translators: %d: number of days in the selected period */ 20 (0,t.__)("Last %d days","blaze-ai-discovery-for-woocommerce"),Re),Me=Te?(0,t.sprintf)(/* translators: %s: date tracking started, e.g. "30 Aug 2026" */ /* translators: %s: date tracking started, e.g. "30 Aug 2026" */ 21 (0,t.__)("Tracking since %s — the plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),N(Te,!0)):(0,t.__)("The plugin cannot see visits from before it was installed.","blaze-ai-discovery-for-woocommerce"),$e="number"==typeof e?.total_visits?e.total_visits:0,De=Array.isArray(e?.platforms)?e.platforms.filter(e=>e&&e.platform):[],Le=Array.isArray(a)?a.filter(e=>e&&e.product_id):[],Fe=(De.length?1:0)+(Le.length?1:0);return(0,s.jsxs)("div",{className:"blazeaid-dashboard",style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsx)("h1",{style:{marginBottom:20},children:(0,t.__)("AI Discovery Dashboard","blaze-ai-discovery-for-woocommerce")}),J&&(0,s.jsx)(c,{onEnable:()=>{Z(!0),Ie().then(()=>S("modal_shown")).then(Y).catch(()=>{}).finally(()=>{Z(!1),X(!1)})},onDismiss:()=>{xe.current=!!y,X(!1),S("dismissed").then(Y).catch(()=>{})},busy:Q}),ue&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"info",onRemove:()=>me(!1),className:"blazeaid-onboarding-reminder",children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,s.jsx)("span",{style:{flex:1,minWidth:0},children:(0,t.sprintf)(/* translators: %d: number of failed or warning audit rows */ /* translators: %d: number of failed or warning audit rows */ 22 (0,t._n)("Your local audit found %d issue. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.","Your local audit found %d issues. Turn on cloud checks to test your store from outside your network and see your AI Visibility report.",k(y),"blaze-ai-discovery-for-woocommerce"),k(y))}),(0,s.jsx)(o.Button,{variant:"primary",onClick:Ie,isBusy:K,disabled:K,children:(0,t.__)("Turn on cloud checks","blaze-ai-discovery-for-woocommerce")})]})})}),he&&(0,s.jsx)(x,{kind:he}),(0,s.jsx)(m,{health:ae,audit:y,onRunNow:()=>{Promise.all([n()({path:"/blazeaid/v1/audit"}).catch(()=>null),n()({path:"/blazeaid/v1/scores/summary"}).catch(()=>null),n()({path:"/blazeaid/v1/visibility"}).catch(()=>null),u()]).then(([e,r,o,t])=>{e&&e.run_at&&g(e),r&&B(r),o&&M(o),t&&le(t)})},onRunAudit:Be}),!y&&!he&&(0,s.jsx)(T,{slow:re,running:te,error:ne,onRunNow:Be}),ce&&(0,s.jsx)(R,{done:"done"===ce}),(0,s.jsx)(I,{result:C(y)}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,marginBottom:16},children:[(0,s.jsx)(D,{audit:y}),(0,s.jsx)(L,{storeScore:_}),(0,s.jsx)(F,{visibility:W,consentGranted:H?!!H.granted:"consent_off"!==W?.state})]}),H&&!H.granted&&!J&&(0,s.jsx)(d,{consent:H,onToggle:e=>e?Ie():(ee(!0),n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:!1}}).then(e=>{V(e),de(null)}).catch(()=>{}).finally(()=>ee(!1))),busy:K}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsxs)(o.CardHeader,{style:{flexWrap:"wrap",gap:12},children:[(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("AI traffic","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:13,fontWeight:"normal"},children:Me})]}),(0,s.jsx)(o.SelectControl,{value:$,options:[{label:(0,t.__)("Last 7 days","blaze-ai-discovery-for-woocommerce"),value:"7"},{label:(0,t.__)("Last 30 days","blaze-ai-discovery-for-woocommerce"),value:"30"},{label:(0,t.__)("Last 90 days","blaze-ai-discovery-for-woocommerce"),value:"90"}],onChange:q,__nextHasNoMarginBottom:!0})]}),(0,s.jsxs)(o.CardBody,{children:[0===$e?(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No AI-referred visits recorded yet. Visits from ChatGPT, Perplexity, Copilot, Gemini and Claude will appear here.","blaze-ai-discovery-for-woocommerce")}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("p",{style:{color:"#757575",margin:"0 0 12px",fontSize:13},children:Ne}),(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16},children:[(0,s.jsx)(O,{value:(new Intl.NumberFormat).format($e),label:(0,t.__)("AI-referred visitors","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(O,{value:(new Intl.NumberFormat).format(e?.orders?.count??0),label:(0,t.__)("AI-attributed orders","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(O,{value:new Intl.NumberFormat(void 0,{style:"currency",currency:window.blazeaid?.currency||"USD"}).format(e?.orders?.revenue??0),label:(0,t.__)("AI-attributed revenue","blaze-ai-discovery-for-woocommerce")})]})]}),(0,s.jsx)("p",{style:{color:"#757575",fontSize:13,margin:"16px 0 0"},children:(0,t.__)("Industry benchmarks show ~70% of AI traffic arrives without identifiable headers. Your actual AI traffic is likely higher than what we can detect. We track referrer headers, UTM parameters, and URL text fragments to capture as much as possible.","blaze-ai-discovery-for-woocommerce")})]})]}),Fe>0&&(0,s.jsxs)("div",{style:{display:"grid",gridTemplateColumns:2===Fe?"1fr 1fr":"1fr",gap:16},children:[De.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Visits by platform","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Platform","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:De.map(e=>{return(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0",textTransform:"capitalize"},children:(r=e.platform,P[String(r).toLowerCase()]||String(r).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.count})]},e.platform);var r})})]})})]}),Le.length>0&&(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Top products","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"1px solid #ddd"},children:(0,t.__)("AI visits","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:Le.map(e=>(0,s.jsxs)("tr",{children:[(0,s.jsx)("td",{style:{padding:"8px 0"},children:e.url?(0,s.jsx)("a",{href:e.url,children:e.name}):e.name}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"8px 0"},children:e.visit_count})]},e.product_id))})]})})]})]})]})}function G({product:e}){const[o,i]=(0,r.useState)(!1),n=e.issues||[],a=n.filter(e=>"error"===e.severity||"warning"===e.severity).length;return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("tr",{onClick:()=>n.length>0&&i(!o),style:{cursor:n.length>0?"pointer":"default"},children:[(0,s.jsx)("td",{style:{padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.length>0&&(0,s.jsx)("span",{style:{fontSize:11,color:"#757575",transition:"transform 0.2s",transform:o?"rotate(90deg)":"none"},children:"▶"}),(0,s.jsx)("span",{children:e.product_name}),a>0&&(0,s.jsxs)("span",{style:{fontSize:11,color:"#757575",background:"#f0f0f0",padding:"1px 6px",borderRadius:8},children:[a," ",1===a?"issue":"issues"]})]})}),(0,s.jsx)("td",{style:{textAlign:"center",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:(0,s.jsx)("span",{style:{display:"inline-block",padding:"2px 12px",borderRadius:12,fontSize:13,fontWeight:600,background:e.total_score>=70?"#d4edda":e.total_score>=40?"#fff3cd":"#f8d7da",color:e.total_score>=70?"#155724":e.total_score>=40?"#856404":"#721c24"},children:e.total_score})}),(0,s.jsx)("td",{style:{textAlign:"right",padding:"10px 0",borderBottom:o?"none":"1px solid #eee"},children:e.edit_url&&(0,s.jsx)("a",{href:e.edit_url,onClick:e=>e.stopPropagation(),style:{fontSize:13},children:(0,t.__)("Edit","blaze-ai-discovery-for-woocommerce")})})]}),o&&(0,s.jsx)("tr",{children:(0,s.jsx)("td",{colSpan:"3",style:{padding:"0 0 12px 28px",borderBottom:"1px solid #eee"},children:(0,s.jsxs)("div",{style:{background:"#f9f9f9",borderRadius:6,padding:16},children:[(0,s.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[["title_score","Title",15],["description_score","Description",15],["image_score","Images",10],["brand_score","Brand",10],["category_score","Category",10],["attributes_score","Attributes",15],["price_score","Price",5],["identifier_score","Identifiers",10],["rating_score","Reviews",5],["policy_score","Policies",5]].map(([r,o,t])=>{const i=parseInt(e[r])||0,n=Math.round(i/t*100);return(0,s.jsxs)("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:4,background:n>=80?"#d4edda":n>=40?"#fff3cd":"#f8d7da",color:n>=80?"#155724":n>=40?"#856404":"#721c24"},children:[o," ",i,"/",t]},r)})}),n.length>0&&(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontWeight:600,fontSize:13,margin:"0 0 8px"},children:(0,t.__)("How to improve this product:","blaze-ai-discovery-for-woocommerce")}),n.map((e,r)=>{const o=(e=>{switch(e){case"error":return{color:"#721c24",icon:"✗"};case"warning":return{color:"#856404",icon:"⚠"};default:return{color:"#004085",icon:"ℹ"}}})(e.severity);return(0,s.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",marginBottom:6},children:[(0,s.jsx)("span",{style:{color:o.color,fontSize:12,flexShrink:0,marginTop:1},children:o.icon}),(0,s.jsxs)("span",{style:{fontSize:13,color:"#333"},children:[(0,s.jsxs)("strong",{style:{color:o.color},children:[e.name,":"]})," ",e.message]})]},r)})]})]})})})]})}const E=e=>{switch(e){case"pass":return{icon:"✓",color:"#00a32a",bg:"#d4edda"};case"warning":return{icon:"⚠",color:"#856404",bg:"#fff3cd"};case"fail":return{icon:"✗",color:"#721c24",bg:"#f8d7da"};case"pending":return{icon:"…",color:"#2271b1",bg:"#e7f0fa"};default:return{icon:"ℹ",color:"#004085",bg:"#cce5ff"}}},H=e=>(e?.results||[]).some(e=>e&&"pending"===e.status),V=e=>{switch(e){case"allowed":return(0,t.__)("allowed","blaze-ai-discovery-for-woocommerce");case"blocked_robots":return(0,t.__)("blocked by robots.txt","blaze-ai-discovery-for-woocommerce");case"blocked_edge":return(0,t.__)("blocked at the edge","blaze-ai-discovery-for-woocommerce");case"challenged":return(0,t.__)("challenged","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("unknown","blaze-ai-discovery-for-woocommerce")}},U=e=>{switch(e){case"high":return(0,t.__)("high confidence","blaze-ai-discovery-for-woocommerce");case"medium":return(0,t.__)("medium confidence","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("low confidence","blaze-ai-discovery-for-woocommerce")}},Y=(e,r)=>{const o={display:"inline-block",width:8,height:8,borderRadius:"50%",border:`1.5px solid ${r}`,boxSizing:"border-box",flexShrink:0};return"high"===e?{...o,background:r}:"medium"===e?{...o,background:`linear-gradient(90deg, ${r} 50%, transparent 50%)`}:{...o,background:"transparent"}};function J({check:e,consentGranted:r}){const o=e.crawlers||[],i=e.fix_links||[],n=e.probe||{};let a=null;return!1===n.ran&&(a="consent_off"===n.notice?r?(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce"):(0,s.jsx)("a",{href:"#blazeaid-cloud-consent",children:(0,t.__)("Enable cloud checks to test from outside your network.","blaze-ai-discovery-for-woocommerce")}):(0,t.sprintf)(/* translators: %s: reason code, e.g. rate_limited */ /* translators: %s: reason code, e.g. rate_limited */ 23 (0,t.__)("Outside-in probe unavailable (%s); results are based on robots.txt and your server log only.","blaze-ai-discovery-for-woocommerce"),n.notice||"unavailable")),(0,s.jsxs)("div",{style:{marginTop:8},children:[(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:o.map(e=>{const r="allowed"===(o=e.verdict)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:o&&o.startsWith("blocked_")?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:"challenged"===o?{color:"#856404",bg:"#fff3cd",border:"#ffe08a"}:{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"};var o;const t=[`${e.name}: ${V(e.verdict)} (${U(e.confidence)})`,e.evidence&&e.evidence.length?e.evidence[0]:null].filter(Boolean).join(" — ");return(0,s.jsxs)("span",{title:t,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("span",{style:Y(e.confidence,r.color),"aria-hidden":"true"}),e.name]},e.name)})}),a&&(0,s.jsx)("p",{style:{margin:"8px 0 0",color:"#555",fontSize:13},children:a}),i.length>0&&(0,s.jsx)("ul",{style:{margin:"8px 0 0",paddingLeft:18,fontSize:13},children:i.map(e=>(0,s.jsx)("li",{children:(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.label})},e.layer))}),o.length>0&&(0,s.jsxs)("details",{style:{marginTop:8,fontSize:13},children:[(0,s.jsx)("summary",{style:{cursor:"pointer",color:"#2271b1"},children:(0,t.__)("Evidence","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("dl",{style:{margin:"8px 0 0"},children:o.map(e=>(0,s.jsxs)("div",{style:{marginBottom:6},children:[(0,s.jsxs)("dt",{style:{fontWeight:600},children:[e.name," — ",V(e.verdict),", ",U(e.confidence)]}),(e.evidence||[]).map((e,r)=>(0,s.jsx)("dd",{style:{margin:"2px 0 0 12px",color:"#555"},children:e},r))]},e.name))})]})]})}const X=e=>{switch(e){case"good":return(0,t.__)("good","blaze-ai-discovery-for-woocommerce");case"poor":return(0,t.__)("poor","blaze-ai-discovery-for-woocommerce");default:return(0,t.__)("needs improvement","blaze-ai-discovery-for-woocommerce")}};function Q({cwv:e}){const r=Object.values(e?.metrics||{}).filter(e=>e&&e.label);return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:r.map(e=>{const r="good"===(o=e.rating)?{color:"#155724",bg:"#d4edda",border:"#8fd19e"}:"poor"===o?{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"}:{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};var o;return(0,s.jsxs)("span",{title:`${e.label}: ${X(e.rating)}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:r.color,background:r.bg,border:`1px solid ${r.border}`,cursor:"default"},children:[(0,s.jsx)("strong",{children:e.label}),e.display]},e.label)})}):null}const Z=e=>!!e&&("queued"===e.state||"running"===e.state),K=e=>"number"==typeof e&&Number.isFinite(e)?(new Intl.NumberFormat).format(e):String(e??"");function ee({delta:e,deltaLabel:r}){const o="number"==typeof e&&Number.isFinite(e);if(!o&&!r)return null;let t="",i="#757575";return o&&e>0?(t="▲ ",i="#00a32a"):o&&e<0&&(t="▼ ",i="#d63638"),(0,s.jsxs)("p",{style:{margin:"4px 0 0",fontSize:13,color:i},children:[o&&(0,s.jsxs)("span",{children:[t,K(Math.abs(e))]}),o&&r?" ":"",r&&(0,s.jsx)("span",{style:{color:"#757575"},children:r})]})}function re({block:e}){return(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontSize:32,fontWeight:"bold",lineHeight:1.2},children:K(e.value)}),(0,s.jsx)("p",{style:{margin:"4px 0 0",color:"#757575",fontSize:14},children:e.label}),(0,s.jsx)(ee,{delta:e.delta,deltaLabel:e.delta_label})]})}function oe({block:e}){const r=Array.isArray(e.columns)?e.columns:[],o=Array.isArray(e.rows)?e.rows:[];if(!r.length&&!o.length)return null;const t=(e,r)=>({textAlign:"number"==typeof e?"right":"left",padding:"8px 12px 8px 0",borderBottom:r?"1px solid #ddd":"1px solid #f0f0f1",whiteSpace:"nowrap"}),i=o[0]||[];return(0,s.jsx)("div",{style:{overflowX:"auto"},children:(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[r.length>0&&(0,s.jsx)("thead",{children:(0,s.jsx)("tr",{children:r.map((e,r)=>(0,s.jsx)("th",{style:t(i[r],!0),children:e},r))})}),(0,s.jsx)("tbody",{children:o.map((e,r)=>(0,s.jsx)("tr",{children:(Array.isArray(e)?e:[]).map((e,r)=>(0,s.jsx)("td",{style:t(e,!1),children:"number"==typeof e?K(e):e},r))},r))})]})})}function te({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("ul",{style:{margin:"4px 0",paddingLeft:18},children:r.map((e,r)=>(0,s.jsx)("li",{style:{marginBottom:4},children:e.url?(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",children:e.text}):e.text},r))}):null}function ie({block:e}){const r=Array.isArray(e.items)?e.items:[];return r.length?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:r.map((e,r)=>{const o=(e=>["pass","warning","fail"].includes(e)?e:"unknown")(e.status),t=(e=>{switch(e){case"pass":return{color:"#155724",bg:"#d4edda",border:"#8fd19e"};case"warning":return{color:"#856404",bg:"#fff3cd",border:"#ffe08a"};case"fail":return{color:"#721c24",bg:"#f8d7da",border:"#f1aeb5"};default:return{color:"#50575e",bg:"#f0f0f1",border:"#c3c4c7"}}})(o);return(0,s.jsx)("span",{className:`blazeaid-chip blazeaid-chip--${o}`,style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:12,fontSize:12,lineHeight:"18px",color:t.color,background:t.bg,border:`1px solid ${t.border}`},children:e.label},r)})}):null}function ne({block:e}){return e.html?(0,s.jsx)("div",{className:"blazeaid-payload-text",style:{fontSize:13,color:"#50575e"},dangerouslySetInnerHTML:{__html:e.html}}):null}function se(e){const r=[];return(Array.isArray(e)?e:[]).forEach(e=>{const o=r[r.length-1];e&&"stat"===e.type?o&&"stats"===o.kind?o.items.push(e):r.push({kind:"stats",items:[e]}):r.push({kind:"block",block:e})}),r}function ae({block:e}){if(!e||"object"!=typeof e)return null;switch(e.type){case"stat":return(0,s.jsx)(re,{block:e});case"table":return(0,s.jsx)(oe,{block:e});case"list":return(0,s.jsx)(te,{block:e});case"chips":return(0,s.jsx)(ie,{block:e});case"text":return(0,s.jsx)(ne,{block:e});default:return null}}function le({notices:e}){const r=Array.isArray(e)?e:[];return r.length?(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:r.map((e,r)=>{return(0,s.jsxs)(o.Notice,{status:(t=e.level,["info","warning","error"].includes(t)?t:"info"),isDismissible:!1,children:[e.text,e.link&&e.link.url&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:"_blank",rel:"noopener noreferrer",children:e.link.label||e.link.url})]})]},r);var t})}):null}function ce({payload:e}){if(!e||"object"!=typeof e)return null;const r=Array.isArray(e.sections)?e.sections:[];return(0,s.jsxs)("div",{className:"blazeaid-payload",children:[(0,s.jsx)(le,{notices:e.notices}),r.map((e,r)=>{const i=Array.isArray(e.blocks)?e.blocks:[];return(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:e.title||(0,t.__)("Untitled section","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:i.length?se(i).map((e,r,o)=>(0,s.jsx)("div",{style:{marginBottom:r<o.length-1?16:0},children:"stats"===e.kind?(0,s.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"16px 48px"},children:e.items.map((e,r)=>(0,s.jsx)("div",{style:{minWidth:160},children:(0,s.jsx)(ae,{block:e})},r))}):(0,s.jsx)(ae,{block:e.block})},r)):(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("No data for this period.","blaze-ai-discovery-for-woocommerce")})})]},e.id||r)})]})}const de={blazeaid:q,"blazeaid-products":function(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)([]),[c,d]=(0,r.useState)(null),[h,p]=(0,r.useState)(!0),[y,g]=(0,r.useState)(!1),[_,j]=(0,r.useState)(null),[z,k]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),A=e=>{const r="string"==typeof e?e:f(e);return b(r)&&k(r),r},B=(e=!0)=>{e&&p(!0),Promise.all([n()({path:"/blazeaid/v1/scores/summary"}),n()({path:"/blazeaid/v1/scores/products?per_page=100&order=ASC"}),n()({path:"/blazeaid/v1/scores/progress"}),u()]).then(([e,r,o,t])=>{i(e),l(r),d(o),t&&j(t),"running"===o?.status&&g(!0),p(!1)}).catch(e=>{A(e),p(!1)})};if((0,r.useEffect)(()=>B(!0),[]),(0,r.useEffect)(()=>{if(!y)return;let e=null;return v({request:()=>n()({path:"/blazeaid/v1/scores/progress"}),onData:r=>{e=r,d(r)},isDone:e=>!!e&&("complete"===e.status||"idle"===e.status||"failed"===e.status),intervalMs:3e3,onStop:r=>{if(g(!1),"done"===r)return void(e&&"failed"!==e.status&&B(!1));if("timeout"===r)return void C((0,t.__)("Scoring is still running in the background — reload the page later to see the result.","blaze-ai-discovery-for-woocommerce"));const o=w(r);o&&A(o)}})},[y]),h)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const I=c?.total>0?Math.round(c.scored/c.total*100):0;return(0,s.jsxs)("div",{style:{maxWidth:1200,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Product AI Readiness","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{C(null),g(!0),n()({path:"/blazeaid/v1/scores/recalculate",method:"POST"}).then(e=>{e&&e.progress&&d(e.progress)}).catch(e=>{g(!1);const r=A(e);b(r)||C((0,t.__)("Could not start scoring. Please try again.","blaze-ai-discovery-for-woocommerce"))})},disabled:y,children:y?(0,t.__)("Scoring...","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Recalculate All","blaze-ai-discovery-for-woocommerce")})]}),z&&(0,s.jsx)(x,{kind:z}),(0,s.jsx)(m,{health:_,onRunNow:()=>B(!1)}),"failed"===c?.status&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"error",isDismissible:!1,children:c.reason||(0,t.__)("The last scoring run stopped before it finished. Click Recalculate All to start again.","blaze-ai-discovery-for-woocommerce")})}),S&&(0,s.jsx)("div",{style:{display:"grid",gap:12,marginBottom:16},children:(0,s.jsx)(o.Notice,{status:"warning",onRemove:()=>C(null),children:S})}),y&&"running"===c?.status&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{padding:20},children:[(0,s.jsxs)("p",{children:[(0,t.__)("Scoring products...","blaze-ai-discovery-for-woocommerce")," ",c.scored," / ",c.total," (",I,"%)"]}),(0,s.jsx)("div",{style:{background:"#e0e0e0",borderRadius:4,height:8},children:(0,s.jsx)("div",{style:{background:"#007cba",borderRadius:4,height:8,width:`${I}%`,transition:"width 0.3s"}})})]})}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{style:{padding:24},children:(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:24},children:[(0,s.jsx)("div",{style:{fontSize:48,fontWeight:"bold",color:e?.average>=70?"#00a32a":e?.average>=40?"#dba617":"#d63638"},children:e?.average??0}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{style:{fontSize:18,margin:0},children:(0,t.__)("Product AI Readiness Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:"running"===c?.status?(0,t.sprintf)(/* translators: 1: products scored so far, 2: total products */ /* translators: 1: products scored so far, 2: total products */ 24 (0,t.__)("Scoring your products… %1$d / %2$d","blaze-ai-discovery-for-woocommerce"),c.scored??0,c.total??0):`${e?.scored_products??0} / ${e?.total_products??0} ${(0,t.__)("products scored","blaze-ai-discovery-for-woocommerce")}`})]})]})})}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Products by AI Readiness (lowest first)","blaze-ai-discovery-for-woocommerce"),(0,s.jsx)("span",{style:{fontWeight:"normal",fontSize:13,color:"#757575",marginLeft:8},children:(0,t.__)("Click a row to see recommendations","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)(o.CardBody,{children:a.length>0?(0,s.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse"},children:[(0,s.jsx)("thead",{children:(0,s.jsxs)("tr",{children:[(0,s.jsx)("th",{style:{textAlign:"left",padding:"8px 0",borderBottom:"2px solid #ddd"},children:(0,t.__)("Product","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"center",padding:"8px 0",borderBottom:"2px solid #ddd",width:100},children:(0,t.__)("Score","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)("th",{style:{textAlign:"right",padding:"8px 0",borderBottom:"2px solid #ddd",width:80},children:(0,t.__)("Action","blaze-ai-discovery-for-woocommerce")})]})}),(0,s.jsx)("tbody",{children:a.map(e=>(0,s.jsx)(G,{product:e},e.product_id))})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No products scored yet. Click "Recalculate All" to scan your catalog.',"blaze-ai-discovery-for-woocommerce")})})]})]})},"blazeaid-audit":function(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(!0),[c,u]=(0,r.useState)(!1),[m,h]=(0,r.useState)(null),[p,y]=(0,r.useState)(null),[g,_]=(0,r.useState)(null),j=(0,r.useRef)(null),z=e=>{const r="string"==typeof e?e:f(e);return b(r)&&_(r),r},k=()=>{j.current&&(j.current(),j.current=null)};(0,r.useEffect)(()=>(l(!0),n()({path:"/blazeaid/v1/audit"}).then(e=>{i(e),l(!1)}).catch(e=>{z(e),l(!1)}),n()({path:"/blazeaid/v1/cloud/consent"}).then(y).catch(()=>y(null)),k),[]);const S=e=>{k(),j.current=v({request:()=>n()({path:"/blazeaid/v1/audit"}),onData:r=>{r&&r.run_at&&r.run_at!==e&&i(r)},isDone:r=>!(!r||!r.run_at||r.run_at===e||H(r)),intervalMs:3e3,slowAfterMs:9e4,slowIntervalMs:3e4,onSlow:()=>h((0,t.__)("Still running — this page keeps checking for up to 20 minutes.","blaze-ai-discovery-for-woocommerce")),onStop:e=>{j.current=null,u(!1);const r=w(e);r?(z(r),h(null)):h("timeout"===e?(0,t.__)("Still running — check back shortly.","blaze-ai-discovery-for-woocommerce"):null)}})},C=()=>{u(!0),h(null);const r=e?.run_at||null;n()({path:"/blazeaid/v1/audit/run",method:"POST"}).then(e=>{e&&e.queued?S(r):(i(e),u(!1),H(e)&&(h((0,t.__)("Cloud checks are still running in the background — the rows marked pending will update.","blaze-ai-discovery-for-woocommerce")),S(e.run_at||r)))}).catch(e=>{u(!1);const r=z(e);b(r)||h((0,t.__)("Could not start the audit. Please try again.","blaze-ai-discovery-for-woocommerce"))})};if(a)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const A=e?.results||[],B=e?.overall_status||"unknown",I=(0,s.jsx)(d,{consent:p,onToggle:e=>{n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(e=>{y(e),C()})},busy:c,style:{marginTop:16}});return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20},children:[(0,s.jsx)("h1",{children:(0,t.__)("Store Readiness Audit","blaze-ai-discovery-for-woocommerce")}),(0,s.jsx)(o.Button,{variant:"primary",onClick:C,disabled:c,children:c?(0,t.__)("Running…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Re-run Audit","blaze-ai-discovery-for-woocommerce")})]}),g&&(0,s.jsx)(x,{kind:g}),e?.run_at&&(0,s.jsxs)("p",{style:{color:"#757575",marginBottom:16},children:[(0,t.__)("Last run:","blaze-ai-discovery-for-woocommerce")," ",e.run_at]}),(c||m)&&(0,s.jsxs)("div",{style:{display:"grid",gap:12,marginBottom:16},children:[c&&(0,s.jsx)("p",{style:{color:"#757575",margin:0},children:(0,t.__)("Running… this can take up to a minute while the store is checked from outside your network.","blaze-ai-discovery-for-woocommerce")}),m&&(0,s.jsx)("p",{style:{color:"#856404",margin:0},children:m})]}),!p?.granted&&I,(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsxs)("h3",{style:{margin:0},children:[(0,t.__)("Readiness Checklist","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:12,...E(B)},children:B.toUpperCase()})]})}),(0,s.jsx)(o.CardBody,{children:A.length>0?(0,s.jsx)("div",{children:A.map((e,r)=>{const o=E(e.status);return(0,s.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:"12px 0",borderBottom:r<A.length-1?"1px solid #eee":"none"},children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",background:o.bg,color:o.color,fontWeight:"bold",fontSize:14,flexShrink:0},children:o.icon}),(0,s.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,s.jsx)("strong",{children:e.check}),(0,s.jsxs)("p",{style:{margin:"4px 0 0",color:"#555",fontSize:13},children:[e.message,e.link&&!Array.isArray(e.crawlers)&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:e.link.url,target:e.link.url.startsWith("http")&&!e.link.url.includes("/wp-admin/")?"_blank":"_self",rel:"noopener noreferrer",children:e.link.label})]})]}),Array.isArray(e.crawlers)&&(0,s.jsx)(J,{check:e,consentGranted:!!p?.granted}),e.cwv&&(0,s.jsx)(Q,{cwv:e.cwv})]})]},r)})}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)('No audit has been run yet. Click "Re-run Audit" to check your store.',"blaze-ai-discovery-for-woocommerce")})})]}),p?.granted&&I]})},"blazeaid-feed":function(){const[e,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(null),[c,d]=(0,r.useState)(!0),[u,m]=(0,r.useState)(!1),[h,p]=(0,r.useState)(null),y=(0,r.useRef)(null),g=()=>{y.current&&(y.current(),y.current=null)},x=()=>n()({path:"/blazeaid/v1/feed/validate"}).then(l).catch(()=>{}),_=()=>{g(),m(!0);let e=null;y.current=v({request:()=>n()({path:"/blazeaid/v1/feed/status"}),onData:r=>{e=r,i(r)},isDone:e=>!Z(e&&e.progress),intervalMs:3e3,onStop:r=>{if(y.current=null,m(!1),"done"===r)return e&&e.progress&&"error"===e.progress.state&&p(e.progress.error||(0,t.__)("Feed generation failed.","blaze-ai-discovery-for-woocommerce")),void x();if("timeout"===r)return void p((0,t.__)("The feed is still queued. Background jobs may not be running on this site — check the Jobs page, then try again.","blaze-ai-discovery-for-woocommerce"));const o=w(r);p(b(o)||(0,t.__)("Feed generation failed.","blaze-ai-discovery-for-woocommerce"))}})};if((0,r.useEffect)(()=>(d(!0),Promise.all([n()({path:"/blazeaid/v1/feed/status"}),n()({path:"/blazeaid/v1/feed/validate"})]).then(([e,r])=>{i(e),l(r),d(!1),Z(e.progress)&&_()}).catch(e=>{d(!1);const r=b(f(e));r&&p(r)}),g),[]),c)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const j=e?.progress;let z=(0,t.__)("Generate Feed","blaze-ai-discovery-for-woocommerce");return u&&(z="running"===j?.state&&j.total>0?(0,t.sprintf)(/* translators: 1: products processed, 2: products total */ /* translators: 1: products processed, 2: products total */ 25 (0,t.__)("Generating… %1$s of %2$s","blaze-ai-discovery-for-woocommerce"),j.done,j.total):"queued"===j?.state?(0,t.__)("Queued…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Generating…","blaze-ai-discovery-for-woocommerce")),(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsx)("h1",{children:(0,t.__)("ChatGPT Merchant Feed","blaze-ai-discovery-for-woocommerce")}),h&&(0,s.jsx)(o.Notice,{status:"error",isDismissible:!0,onRemove:()=>p(null),children:h}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Status","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{style:{margin:"0 0 8px"},children:[(0,s.jsx)("strong",{children:(0,t.__)("Products in feed:","blaze-ai-discovery-for-woocommerce")})," ",e?.product_count??0]}),e?.generated_at&&(0,s.jsxs)("p",{style:{margin:0,color:"#757575",fontSize:13},children:[(0,t.__)("Last generated:","blaze-ai-discovery-for-woocommerce")," ",e.generated_at]}),u&&"queued"===j?.state&&(0,s.jsx)("p",{style:{margin:"8px 0 0",color:"#757575",fontSize:13},children:(0,t.__)("Queued as a background job — this page updates when it finishes.","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{m(!0),p(null);const r=!!e&&e.total_products<=e.inline_limit;n()({path:"/blazeaid/v1/feed/generate",method:"POST",data:{force:r}}).then(e=>{i(e),e.queued?_():(m(!1),x())}).catch(e=>{m(!1);const r=f(e),o="other"===r?null:b(r);p(o||e&&(e.error||e.message)||(0,t.__)("Feed generation failed.","blaze-ai-discovery-for-woocommerce"))})},disabled:u,children:z}),e?.download_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.download_url,target:"_blank",children:(0,t.__)("Download CSV","blaze-ai-discovery-for-woocommerce")}),e?.json_url&&(0,s.jsx)(o.Button,{variant:"secondary",href:e.json_url,target:"_blank",children:(0,t.__)("View JSON","blaze-ai-discovery-for-woocommerce")})]})]})})]}),(0,s.jsxs)(o.Card,{style:{marginBottom:16},children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("Feed Validation","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:a&&!1!==a.available?(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{children:[(0,s.jsxs)("span",{style:{color:"#00a32a",fontWeight:600},children:[a.valid," ",(0,t.__)("valid","blaze-ai-discovery-for-woocommerce")]}),a.invalid>0&&(0,s.jsxs)("span",{style:{color:"#d63638",fontWeight:600,marginLeft:16},children:[a.invalid," ",(0,t.__)("invalid","blaze-ai-discovery-for-woocommerce")]}),a.ineligible>0&&(0,s.jsxs)("span",{style:{color:"#996800",fontWeight:600,marginLeft:16},children:[a.ineligible," ",(0,t.__)("not searchable yet","blaze-ai-discovery-for-woocommerce")]})]}),a.truncated&&(0,s.jsx)("p",{style:{color:"#757575",fontSize:13},children:(0,t.sprintf)(/* translators: %s: number of rows checked */ /* translators: %s: number of rows checked */ 26 (0,t.__)("Checked the first %s rows of the feed.","blaze-ai-discovery-for-woocommerce"),a.checked)}),a.issues?.length>0&&(0,s.jsxs)("div",{style:{marginTop:12},children:[(0,s.jsx)("h4",{children:(0,t.__)("Issues to fix:","blaze-ai-discovery-for-woocommerce")}),a.issues.map((e,r)=>(0,s.jsxs)("div",{style:{padding:"8px 0",borderBottom:"1px solid #eee"},children:[(0,s.jsx)("strong",{children:e.title}),(0,s.jsx)("ul",{style:{margin:"4px 0 0",paddingLeft:20},children:e.issues.map((e,r)=>(0,s.jsx)("li",{style:{fontSize:13,color:"#555"},children:e},r))})]},r))]})]}):(0,s.jsx)("p",{style:{color:"#757575"},children:(0,t.__)("Generate a feed to see validation results.","blaze-ai-discovery-for-woocommerce")})})]}),(0,s.jsxs)(o.Card,{children:[(0,s.jsx)(o.CardHeader,{children:(0,s.jsx)("h3",{style:{margin:0},children:(0,t.__)("How to Submit to ChatGPT","blaze-ai-discovery-for-woocommerce")})}),(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("ol",{style:{lineHeight:1.8},children:[(0,s.jsx)("li",{children:(0,t.__)('Click "Generate Feed", then "Download CSV" — CSV is the format OpenAI ingests.',"blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Apply to the merchant programme at","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://chatgpt.com/merchants",target:"_blank",rel:"noopener noreferrer",children:"chatgpt.com/merchants"}),"."]}),(0,s.jsx)("li",{children:(0,t.__)("Once approved, OpenAI gives you an SFTP endpoint. Upload the CSV there and re-upload whenever your catalogue changes.","blaze-ai-discovery-for-woocommerce")}),(0,s.jsxs)("li",{children:[(0,t.__)("Want automatic SFTP delivery or help with merchant-programme onboarding? Ask on the","blaze-ai-discovery-for-woocommerce")," ",(0,s.jsx)("a",{href:"https://wordpress.org/support/plugin/blaze-ai-discovery-for-woocommerce/",target:"_blank",rel:"noopener noreferrer",children:(0,t.__)("support forum","blaze-ai-discovery-for-woocommerce")})," ",(0,t.__)("and we will work with you.","blaze-ai-discovery-for-woocommerce")]})]})})]})]})},"blazeaid-visibility":function(){const[e,i]=(0,r.useState)(!0),[a,l]=(0,r.useState)(null),[c,u]=(0,r.useState)(null),[m,h]=(0,r.useState)(!1),[p,y]=(0,r.useState)(!1),[g,x]=(0,r.useState)(null),[_,j]=(0,r.useState)(!1),[z,k]=(0,r.useState)(!1),S=(0,r.useRef)(null),C=(0,r.useRef)(!1),A=()=>{S.current&&(S.current(),S.current=null)},B=e=>{h(!!e?.consent),u(e?.payload||null),l(e?.state||"empty")},I=()=>{i(!0),x(null),j(!1),k(!1),n()({path:"/blazeaid/v1/visibility"}).then(e=>{C.current||(B(e),i(!1),"pending"===e?.state&&T())}).catch(e=>{C.current||(l(null),k(!0),i(!1),x(b(f(e))||(0,t.__)("Could not load AI visibility data. Reload the page to try again.","blaze-ai-discovery-for-woocommerce")))})},T=()=>{A(),S.current=v({request:()=>n()({path:"/blazeaid/v1/visibility"}),onData:e=>{e&&"pending"!==e.state&&B(e)},isDone:e=>!(!e||"pending"===e.state),intervalMs:5e3,maxMs:12e4,onStop:e=>{if(S.current=null,C.current)return;if(y(!1),"timeout"===e)return j(!0),void x((0,t.__)("Still fetching — check back shortly.","blaze-ai-discovery-for-woocommerce"));const r=w(e);r&&(k(!0),x(b(r)))}})};(0,r.useEffect)(()=>(C.current=!1,I(),()=>{C.current=!0,A()}),[]);const R=e=>{y(!0),n()({path:"/blazeaid/v1/cloud/consent",method:"POST",data:{granted:e}}).then(()=>{C.current||(y(!1),A(),I())}).catch(()=>y(!1))};if(e)return(0,s.jsx)("div",{style:{padding:40,textAlign:"center"},children:(0,s.jsx)(o.Spinner,{})});const P=c?.period?.label||(0,t.__)("last 30 days","blaze-ai-discovery-for-woocommerce"),W=(Array.isArray(c?.sections)?c.sections:[]).length>0,N="empty"===a||"ready"===a&&!W,M="pending"===a&&!_,$=m&&"consent_off"!==a&&!M&&!p;return(0,s.jsxs)("div",{style:{maxWidth:900,margin:"20px auto"},children:[(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20,gap:16,flexWrap:"wrap"},children:[(0,s.jsx)("h1",{style:{margin:0},children:(0,t.__)("AI Visibility","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==a&&(0,s.jsx)(o.Button,{variant:"primary",onClick:()=>{y(!0),x(null),j(!1),k(!1),n()({path:"/blazeaid/v1/visibility/refresh",method:"POST"}).then(e=>{if(!C.current){if(e&&e.queued)return u(null),l("pending"),void T();e&&e.payload?(u(e.payload),l("ready")):l("empty"),y(!1)}}).catch(e=>{if(!C.current){if(y(!1),e&&"consent_off"===e.state)return h(!1),u(null),void l("consent_off");x(b(f(e))||(0,t.__)("Could not start a refresh. Please try again.","blaze-ai-discovery-for-woocommerce"))}})},disabled:!$,children:M||p?(0,t.__)("Refreshing…","blaze-ai-discovery-for-woocommerce"):(0,t.__)("Refresh","blaze-ai-discovery-for-woocommerce")})]}),(0,s.jsx)("p",{style:{color:"#757575",marginBottom:16},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ /* translators: %s: reporting window, e.g. "30 days to 28 Aug 2026" or "last 30 days" */ 27 (0,t.__)("How often AI assistants (ChatGPT, Google AI) mentioned your store over the %s, and who gets named instead.","blaze-ai-discovery-for-woocommerce"),P)}),g&&(0,s.jsx)("p",{style:{color:z?"#d63638":"#856404",marginBottom:16},role:z?"alert":"status",children:g}),"consent_off"===a&&(0,s.jsx)(d,{consent:{granted:!1,decided:!0},onToggle:R,busy:p,style:{marginTop:16}}),M&&(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsxs)(o.CardBody,{style:{display:"flex",alignItems:"center",gap:12},children:[(0,s.jsx)(o.Spinner,{}),(0,s.jsx)("p",{style:{margin:0,color:"#555"},children:(0,t.sprintf)(/* translators: %s: reporting window, e.g. "last 30 days" */ /* translators: %s: reporting window, e.g. "last 30 days" */ 28 (0,t.__)("Fetching AI visibility data for the %s — this runs in the background and usually takes under a minute.","blaze-ai-discovery-for-woocommerce"),P)})]})}),"ready"===a&&W&&(0,s.jsx)(ce,{payload:c}),N&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(le,{notices:c?.notices}),(0,s.jsx)(o.Card,{style:{marginBottom:16},children:(0,s.jsx)(o.CardBody,{children:(0,s.jsxs)("p",{style:{margin:0,color:"#555"},children:["ready"===a?(0,t.__)("No AI visibility data is available for this period yet.","blaze-ai-discovery-for-woocommerce"):(0,t.__)("AI visibility data has not been fetched yet. Background scheduling is unavailable on this site, so use Refresh to fetch it now.","blaze-ai-discovery-for-woocommerce")," ",(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")]})})})]}),"ready"===a&&W&&(0,s.jsx)("p",{style:{color:"#757575",fontSize:13},children:(0,t.__)("Figures cover the 30 days before each refresh; the report refreshes automatically on the 2nd of every month.","blaze-ai-discovery-for-woocommerce")}),m&&"consent_off"!==a&&(0,s.jsx)(d,{consent:{granted:!0,decided:!0},onToggle:R,busy:p,style:{marginTop:16}})]})}},ue=document.getElementById("blazeaid-root");if(ue){const e=de[window.blazeaid?.currentPage||"blazeaid"]||q;(0,r.render)((0,s.jsx)(e,{}),ue)}})(); -
blaze-ai-discovery-for-woocommerce/trunk/readme.txt
r3672021 r3673252 5 5 Tested up to: 7.1 6 6 Requires PHP: 7.4 7 Stable tag: 1.1. 27 Stable tag: 1.1.3 8 8 License: GPLv2 or later 9 9 License URI: https://www.gnu.org/licenses/gpl-2.0.html … … 41 41 42 42 **Store audit, including Core Web Vitals** 43 Eleven diagnostic checks covering what affects AI discoverability: WooCommerce version, SSL, REST API, existing schema, product data quality, robots.txt rules for AI crawlers, crawler access, Google for WooCommerce status, existing feed plugins, llms.txt and — with cloud checks on — mobile Core Web Vitals measured from real Chrome users.43 Twelve diagnostic checks covering what affects AI discoverability: WooCommerce version, store visibility (WooCommerce "Coming soon" mode), SSL, REST API, existing schema, product data quality, robots.txt rules for AI crawlers, crawler access, Google for WooCommerce status, existing feed plugins, llms.txt and — with cloud checks on — mobile Core Web Vitals measured from real Chrome users. 44 44 45 45 = Key Features = … … 51 51 * AI traffic attribution dashboard with platform breakdown and revenue tracking 52 52 * Order attribution — traces AI-referred visits through to WooCommerce orders 53 * Enhanced Schema.org/JSON-LD that augments Yoast SEOor Rank Math (never duplicates)53 * Enhanced Schema.org/JSON-LD that augments your store's Product schema whether it is printed by WooCommerce, Yoast SEO (with its WooCommerce SEO add-on), or Rank Math (never duplicates) 54 54 * Google Merchant Center data quality audit 55 55 * Automatic llms.txt generation 56 * Store readiness audit with 1 1diagnostic checks56 * Store readiness audit with 12 diagnostic checks 57 57 * Core Web Vitals — mobile field data (LCP, INP, CLS, TTFB) from real Chrome users 58 58 * Zero-config — starts tracking the moment you activate … … 113 113 = Does it work with Yoast SEO or Rank Math? = 114 114 115 Yes. The plugin detects which SEO plugin you're using and augments its schema output using the plugin's ownfilter hooks. It never creates duplicate schema blocks. Tested with Yoast SEO, Yoast WooCommerce SEO, and Rank Math.115 Yes. The plugin detects which system prints your Product schema — WooCommerce itself, Yoast's WooCommerce SEO add-on, or Rank Math — and augments that output through its filter hooks. It never creates duplicate schema blocks. Tested with Yoast SEO, Yoast WooCommerce SEO, and Rank Math. 116 116 117 117 = What AI platforms can it detect? = … … 148 148 149 149 == Changelog == 150 151 = 1.1.3 = 152 * Fixed: product pages returned HTTP 500 and product saves failed on WooCommerce 8.0–9.1 (a WooCommerce 9.2+ method is now guarded) 153 * Fixed: orders placed through the Checkout block (Store API) are now attributed to AI referrals; previously only the classic shortcode checkout was 154 * Fixed: database tables are created on the first request with WooCommerce when the plugin was activated before WooCommerce, and repaired automatically if missing; the schema version is recorded only after every table exists, and a restricted database user sees a notice naming the missing tables 155 * Fixed: multisite — network activation installs every site, new subsites are installed automatically, network uninstall cleans every site 156 * Fixed: /llms.txt returned 404 after activation on some sites; the rewrite rule is registered before the rules are flushed and removed on deactivation 157 * Fixed: deactivation cancels the scoring healthcheck job along with every other background job 158 * Feed: generation runs as a background job with progress on the Feed page; products are processed in pages of 200 so large catalogues no longer exhaust memory (catalogues of 500 or fewer still generate instantly); works on hosts where WordPress cannot write files directly; write failures show an error instead of a blank 500 159 * Feed: is_eligible_search reflects stock, purchasability, status and visibility; validation reads the written file (first 2,000 rows) and lists not-yet-searchable products separately 160 * Attribution: the AI platform is derived on the server from the referrer host and utm_source, so visits from lookalike referrer domains are no longer credited to an AI platform; the tracker signature stays valid for 30 days and is refreshed automatically on long-cached pages (for up to 400 days from when the page was cached) 161 * Retention: cleanup deletes everything older than 90 days in batches (was capped at 1,000 rows a day) and now also covers attributed orders 162 * New "Store visibility" audit row: fails while WooCommerce "Coming soon" mode is on and links to Settings → Site visibility 163 * Audit: the REST API, robots.txt and llms.txt rows report "Could not verify" with the HTTP code when the site answers the plugin's own request with 401/403/407/429, a server error or a bot challenge, instead of a pass; the self-fetch also requests one published product page and never takes more than 20 s 164 * Audit: "Run audit now" finishes within a request — local checks run in full, cloud checks share a 12 s budget and rows that do not fit show as pending until the background audit fills them in 165 * Cloud: a response that is not the expected JSON is never cached as an empty result; transient failures (connection errors, 429, 5xx) are retried once; new filter blazeaid_cloud_retry_delay 166 * Scoring: batch scoring resumes from the last product actually scored, retries a stalled chunk three times and then marks the run failed with a reason; a second run cannot start while one is running 167 * Admin: pages say when the REST API is blocked (session expired or a security plugin) or answers with something other than JSON; every status poll stops after 20 minutes and when the page is left 168 * Schema: enhancement now works with Yoast SEO free and Rank Math — Yoast free stores augment WooCommerce's own Product block (only the Yoast WooCommerce SEO add-on replaces it), and the Rank Math integration now matches the payload Rank Math actually passes to its filter 169 * Schema: Schema Pro stores no longer get a second Product JSON-LD block from this plugin; the plugin augments WooCommerce's block instead 150 170 151 171 = 1.1.2 = … … 218 238 == Upgrade Notice == 219 239 240 = 1.1.3 = 241 Compatibility release: fixes product-page errors on WooCommerce 8.0–9.1, attribution for the Checkout block, feed generation on large catalogues, and installs where the plugin was activated before WooCommerce. Update recommended for every store. 242 220 243 = 1.1.2 = 221 244 The Dashboard keeps checking for the first audit and can run it immediately; background jobs can be run on demand when the site's queue is behind. Site verification works on sites whose security plugin rejects unauthenticated REST requests. Admin pages load on WordPress 6.4 and 6.5. -
blaze-ai-discovery-for-woocommerce/trunk/src/Attribution/CookieBridge.php
r3670977 r3673252 5 5 * JS sets cookies on AI referral detection. This class reads them at 6 6 * add-to-cart (always uncached) and stores attribution in the WC session 7 * so it survives through to checkout. 7 * so it survives through to checkout; OrderAttributor also reads the 8 * cookies directly for Store API (Checkout block) orders. 8 9 * 9 10 * @package BlazeAiDiscovery … … 47 48 } 48 49 50 $attribution = self::read_cookies(); 51 if ( null === $attribution ) { 52 return; 53 } 54 55 WC()->session->set( self::SESSION_KEY, $attribution ); 56 } 57 58 /** 59 * Read and normalise the tracker cookies on the current request. 60 * 61 * @return array{source: string, referred_at: int, landing_page: string}|null Null when no recognised source cookie is present. 62 */ 63 public static function read_cookies(): ?array { 49 64 // phpcs:disable WordPress.Security.ValidatedSanitizedInput 50 65 $source = isset( $_COOKIE[ self::COOKIE_SRC ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE_SRC ] ) ) : ''; … … 54 69 55 70 if ( empty( $source ) ) { 56 return ;71 return null; 57 72 } 58 73 59 74 $source = self::normalise_source( $source ); 60 $lp = self::normalise_landing( $lp );61 62 75 if ( null === $source ) { 63 return ;76 return null; 64 77 } 65 78 66 WC()->session->set( 67 self::SESSION_KEY, 68 [ 69 'source' => $source, 70 'referred_at' => $ts, 71 'landing_page' => $lp, 72 ] 73 ); 79 return [ 80 'source' => $source, 81 'referred_at' => $ts, 82 'landing_page' => self::normalise_landing( $lp ), 83 ]; 74 84 } 75 85 -
blaze-ai-discovery-for-woocommerce/trunk/src/Attribution/InlineTracker.php
r3670977 r3673252 5 5 * Modeled on Independent Analytics: inline script survives page caching, 6 6 * uses requestIdleCallback for zero Core Web Vitals impact, and sends 7 * data to a local REST endpoint via fetch with keepalive. 7 * data to a local REST endpoint via fetch with keepalive. Referrer hosts 8 * are matched host-anchored (the server re-derives the platform anyway), 9 * and a stale signature from a long-cached page is retried once with the 10 * fresh one the endpoint hands back. 8 11 * 9 12 * @package BlazeAiDiscovery … … 85 88 'var hash=window.location.hash||\'\';' . 86 89 'var platform=null;var method=null;' . 87 'var refLower=ref.toLowerCase();var rm=c.referrerMap;' . 88 'for(var domain in rm){if(refLower.indexOf(domain)!==-1){platform=rm[domain];method=\'referrer\';break;}}' . 90 // Host-anchored referrer match: exact host or a subdomain of it, plus the path prefix when the pattern has one. 91 'var refHost=\'\',refPath=\'/\';' . 92 'if(ref){try{var u=new URL(ref);refHost=(u.hostname||\'\').toLowerCase();refPath=u.pathname||\'/\';}catch(e){}}' . 93 'if(refHost){var rm=c.referrerMap;for(var d in rm){var i=d.indexOf(\'/\');var dh=i===-1?d:d.slice(0,i);var dp=i===-1?\'\':d.slice(i);' . 94 'if((refHost===dh||refHost.slice(-(dh.length+1))===\'.\'+dh)&&(!dp||refPath.indexOf(dp)===0)){platform=rm[d];method=\'referrer\';break;}}}' . 89 95 'if(!platform){var src=(params.get(\'utm_source\')||\'\').toLowerCase();if(src){var um=c.utmMap;if(um[src]){platform=um[src];method=\'utm\';}}}' . 90 96 'if(!platform&&hash.indexOf(\':~:text=\')!==-1){platform=\'google_ai\';method=\'text_fragment\';}' . … … 94 100 'utm_campaign:params.get(\'utm_campaign\')||null,search_query:params.get(\'q\')||params.get(\'query\')||null,' . 95 101 'payload:c.payload,signature:c.signature};' . 96 'var json=JSON.stringify(body);' . 97 'if(navigator.sendBeacon){navigator.sendBeacon(c.endpoint,new Blob([json],{type:\'application/json\'}));}' . 98 'else if(window.fetch){fetch(c.endpoint,{method:\'POST\',body:json,headers:{\'Content-Type\':\'application/json\'},keepalive:true});}' . 99 'else{var xhr=new XMLHttpRequest();xhr.open(\'POST\',c.endpoint);xhr.setRequestHeader(\'Content-Type\',\'application/json\');xhr.send(json);}' . 102 // fetch first: it returns the response, so a stale signature (page cached past the window) can be re-signed and retried once. 103 'var send=function(sig,retry){body.signature=sig;var json=JSON.stringify(body);' . 104 'if(window.fetch){fetch(c.endpoint,{method:\'POST\',body:json,headers:{\'Content-Type\':\'application/json\'},keepalive:true})' . 105 '.then(function(r){return r.json();}).then(function(d){if(retry&&d&&typeof d.resign===\'string\'&&d.resign){send(d.resign,false);}}).catch(function(){});}' . 106 'else if(navigator.sendBeacon){navigator.sendBeacon(c.endpoint,new Blob([json],{type:\'application/json\'}));}' . 107 'else{var xhr=new XMLHttpRequest();xhr.open(\'POST\',c.endpoint);xhr.setRequestHeader(\'Content-Type\',\'application/json\');xhr.send(json);}};' . 108 'send(c.signature,true);' . 100 109 'var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);var ex=\'expires=\'+d.toUTCString();' . 101 110 'var sec=(location.protocol===\'https:\')?\';Secure\':\'\';' . -
blaze-ai-discovery-for-woocommerce/trunk/src/Attribution/OrderAttributor.php
r3666933 r3673252 3 3 * Tags WooCommerce orders with AI attribution data. 4 4 * 5 * Reads from WC session (populated by CookieBridge) at checkout 6 * and writes HPOS-compatible order meta + blazeaid_orders table row. 5 * Reads the attribution captured by the tracker (WC session first, the 6 * tracker cookies as a fallback) when an order is created and writes 7 * HPOS-compatible order meta plus a blazeaid_orders table row. 7 8 * 8 9 * @package BlazeAiDiscovery … … 15 16 class OrderAttributor { 16 17 18 /** Order meta set once an order has been through attribution (dedupes the two checkout hooks). */ 19 public const ATTRIBUTED_META = '_blazeaid_attributed'; 20 17 21 public function register(): void { 18 // HPOS-compatible hook — fires for all order types.22 // Shortcode checkout: fired by WC_Checkout::create_order(). 19 23 add_action( 'woocommerce_checkout_order_created', [ $this, 'attribute_order' ], 10, 1 ); 24 25 // Checkout block / Store API: fired by the Store API checkout routes, 26 // which deliberately do not fire woocommerce_checkout_order_created. 27 add_action( 'woocommerce_store_api_checkout_order_processed', [ $this, 'attribute_order' ], 10, 1 ); 20 28 } 21 29 22 30 /** 23 * Attribute an order to an AI source if session has attribution data. 31 * Attribute an order to an AI source if the session or the tracker 32 * cookies carry attribution data. Idempotent per order. 24 33 * 25 34 * @param \WC_Order $order The newly created order. 26 35 */ 27 36 public function attribute_order( \WC_Order $order ): void { 28 $attribution = CookieBridge::get_from_session(); 37 if ( '' !== (string) $order->get_meta( self::ATTRIBUTED_META ) ) { 38 return; 39 } 40 41 // The Store API never renders the checkout form, so the session may 42 // be empty even though the tracker cookies are on the request. 43 $attribution = CookieBridge::get_from_session() ?? CookieBridge::read_cookies(); 29 44 30 45 if ( null === $attribution ) { … … 40 55 $order->update_meta_data( '_blazeaid_referred_at', $referred_at ); 41 56 $order->update_meta_data( '_blazeaid_landing_page', $landing ); 57 $order->update_meta_data( self::ATTRIBUTED_META, 1 ); 42 58 $order->save(); 43 59 44 // Write to attribution orders table .60 // Write to attribution orders table (order_id is unique there too). 45 61 global $wpdb; 46 62 -
blaze-ai-discovery-for-woocommerce/trunk/src/Attribution/PayloadSignature.php
r3670977 r3673252 3 3 * Cache-compatible payload signature (replaces WordPress nonces). 4 4 * 5 * HMAC-SHA256 over a UTC day bucket + canonical JSON. Standard WordPress 6 * nonces break with page caching because they expire and are embedded in 7 * cached HTML; a day-bucketed HMAC lets a page cached today still validate 8 * tomorrow while a scraped signature can't be replayed indefinitely. 5 * HMAC-SHA256 over a UTC day bucket + canonical JSON, prefixed with the 6 * bucket it was issued in: `<issued>.<hmac>`. Standard WordPress nonces 7 * break with page caching because they expire and are embedded in cached 8 * HTML; a day-bucketed HMAC lets a page cached today still validate for a 9 * month. A signature older than the window but still ours is re-issued 10 * once per request so the tracker on a long-cached page can retry; the 11 * renewed form `<issued>.<renewed>.<hmac>` keeps the original issue bucket, 12 * and nothing is renewed past STALE_DAYS after that original issue — so a 13 * scraped signature cannot be kept alive indefinitely by renewing it every 14 * month. 15 * 16 * Signatures without a prefix (pages cached before 1.1.3) are verified by 17 * trying each bucket of the window; they are gone from caches within 18 * WINDOW_DAYS of the upgrade. 9 19 * 10 20 * @package BlazeAiDiscovery … … 19 29 private const SALT_OPTION = 'blazeaid_payload_salt'; 20 30 21 /** 22 * HMAC-SHA256 over a UTC day bucket + canonical JSON. Cache-safe: a page cached 23 * today still validates for at least 48 hours (window = 3 buckets by default). 31 /** Buckets (UTC days) a signature stays valid for: covers pages cached for a month. */ 32 public const WINDOW_DAYS = 30; 33 34 /** 35 * Days after the ORIGINAL issue in which a signature is still recognised 36 * as ours and re-issued, though no longer accepted as-is. Renewal never 37 * moves this bound. 38 */ 39 public const STALE_DAYS = 400; 40 41 /** `<issued>.<hmac>` or `<issued>.<renewed>.<hmac>`; buckets are UTC Ymd. */ 42 private const PREFIXED = '/^(\d{8})(?:\.(\d{8}))?\.([0-9a-f]{64})$/'; 43 44 /** A signature from before 1.1.3: the bare HMAC. */ 45 private const PLAIN = '/^[0-9a-f]{64}$/'; 46 47 /** 48 * Sign a payload. 24 49 * 25 50 * @param array $payload Data to sign. 26 * @param string|null $bucket UTC Ymd; defaults to today. 27 * @return string HMAC-SHA256 hex signature. 28 */ 29 public static function generate( array $payload, ?string $bucket = null ): string { 51 * @param string|null $bucket UTC Ymd the signature is valid from; defaults to today. 52 * @param string|null $issued UTC Ymd of the original issue when renewing; defaults to $bucket. 53 * @return string `<issued>.<hmac>` (or `<issued>.<renewed>.<hmac>` when renewed). 54 */ 55 public static function generate( array $payload, ?string $bucket = null, ?string $issued = null ): string { 30 56 $bucket = $bucket ?? gmdate( 'Ymd' ); 31 return hash_hmac( 'sha256', $bucket . wp_json_encode( $payload ), self::get_salt() ); 32 } 33 34 /** 35 * Validate an incoming signature against a payload, accepting today's, yesterday's, 36 * and the day before's UTC day bucket — a guaranteed window of at least 48 hours even 37 * for a page cached right before a UTC day boundary (filterable via 38 * `blazeaid_signature_window_days`). 57 $issued = $issued ?? $bucket; 58 $prefix = $issued === $bucket ? $issued : $issued . '.' . $bucket; 59 60 return $prefix . '.' . self::hmac( $prefix, $payload ); 61 } 62 63 /** 64 * Validate an incoming signature against a payload: the bucket it is 65 * valid from must be today's or one of the previous WINDOW_DAYS - 1 UTC 66 * day buckets (filterable via `blazeaid_signature_window_days`). 67 * Full-page caches routinely keep a product page for a week (LiteSpeed 68 * default) or until purged (WP Rocket, Cloudflare), so the window has 69 * to outlive them. 39 70 * 40 71 * @param string $signature The signature to validate. … … 43 74 */ 44 75 public static function validate( string $signature, array $payload ): bool { 45 $window = max( 1, (int) apply_filters( 'blazeaid_signature_window_days', 3 ) ); 46 for ( $i = 0; $i < $window; $i++ ) { 47 $bucket = gmdate( 'Ymd', time() - $i * DAY_IN_SECONDS ); 48 if ( hash_equals( self::generate( $payload, $bucket ), $signature ) ) { 49 return true; 76 $parts = self::parse( $signature, $payload ); 77 if ( null !== $parts ) { 78 return $parts['age'] >= 0 && $parts['age'] < self::window(); 79 } 80 81 return null !== self::plain_bucket( $signature, $payload, 0, self::window() ); 82 } 83 84 /** 85 * Whether a signature is one we issued for this payload, but older than 86 * the accepted window (a page cached longer than WINDOW_DAYS) — and 87 * still within STALE_DAYS of its original issue, so it may be renewed. 88 */ 89 public static function is_stale( string $signature, array $payload ): bool { 90 return null !== self::stale_issue( $signature, $payload ); 91 } 92 93 /** 94 * A fresh signature for the payload when the presented one is stale, so a 95 * tracker running on a long-cached page can retry once and recover. The 96 * fresh signature carries the original issue bucket forward, so the 97 * renewal chain ends STALE_DAYS after the first issue. 98 * 99 * @return string|null Fresh signature, or null when the presented one is not ours or too old to renew. 100 */ 101 public static function resign_if_stale( string $signature, array $payload ): ?string { 102 $issued = self::stale_issue( $signature, $payload ); 103 104 return null === $issued ? null : self::generate( $payload, null, $issued ); 105 } 106 107 private static function window(): int { 108 return max( 1, (int) apply_filters( 'blazeaid_signature_window_days', self::WINDOW_DAYS ) ); 109 } 110 111 /** 112 * The original issue bucket of a stale signature, or null when it is 113 * not ours, still valid, or past STALE_DAYS. 114 */ 115 private static function stale_issue( string $signature, array $payload ): ?string { 116 $parts = self::parse( $signature, $payload ); 117 if ( null !== $parts ) { 118 if ( $parts['age'] < self::window() ) { 119 return null; // Valid (or from the future): nothing to renew. 50 120 } 51 } 52 return false; 121 $issued_age = self::age( $parts['issued'] ); 122 if ( null === $issued_age || $issued_age >= self::STALE_DAYS ) { 123 return null; 124 } 125 return $parts['issued']; 126 } 127 128 return self::plain_bucket( $signature, $payload, self::window(), self::STALE_DAYS ); 129 } 130 131 /** 132 * Verify a prefixed signature and read its buckets. 133 * 134 * @return array{issued: string, age: int}|null issued: original bucket; age: days since the bucket it is valid from. Null when malformed or not ours. 135 */ 136 private static function parse( string $signature, array $payload ): ?array { 137 if ( 1 !== preg_match( self::PREFIXED, $signature, $m ) ) { 138 return null; 139 } 140 $issued = $m[1]; 141 $renewed = '' === ( $m[2] ?? '' ) ? null : $m[2]; 142 $prefix = null === $renewed ? $issued : $issued . '.' . $renewed; 143 144 if ( ! hash_equals( self::hmac( $prefix, $payload ), $m[3] ) ) { 145 return null; 146 } 147 148 $age = self::age( $renewed ?? $issued ); 149 if ( null === $age || null === self::age( $issued ) ) { 150 return null; 151 } 152 153 return [ 154 'issued' => $issued, 155 'age' => $age, 156 ]; 157 } 158 159 /** 160 * Pre-1.1.3 form: constant-time comparison against every bucket from 161 * $from (inclusive) to $to (exclusive) days ago. 162 * 163 * @return string|null The matching bucket, or null. 164 */ 165 private static function plain_bucket( string $signature, array $payload, int $from, int $to ): ?string { 166 if ( 1 !== preg_match( self::PLAIN, $signature ) ) { 167 return null; 168 } 169 $now = time(); 170 for ( $i = $from; $i < $to; $i++ ) { 171 $bucket = gmdate( 'Ymd', $now - $i * DAY_IN_SECONDS ); 172 if ( hash_equals( self::hmac( $bucket, $payload ), $signature ) ) { 173 return $bucket; 174 } 175 } 176 return null; 177 } 178 179 /** 180 * Whole UTC days from a Ymd bucket to today (negative for a future 181 * bucket), or null when it is not a calendar date. 182 */ 183 private static function age( string $bucket ): ?int { 184 $year = (int) substr( $bucket, 0, 4 ); 185 $month = (int) substr( $bucket, 4, 2 ); 186 $day = (int) substr( $bucket, 6, 2 ); 187 if ( 8 !== strlen( $bucket ) || ! checkdate( $month, $day, $year ) ) { 188 return null; 189 } 190 191 $then = gmmktime( 0, 0, 0, $month, $day, $year ); 192 $today = gmmktime( 0, 0, 0, (int) gmdate( 'n' ), (int) gmdate( 'j' ), (int) gmdate( 'Y' ) ); 193 194 return (int) round( ( $today - $then ) / DAY_IN_SECONDS ); 195 } 196 197 private static function hmac( string $prefix, array $payload ): string { 198 return hash_hmac( 'sha256', $prefix . wp_json_encode( $payload ), self::get_salt() ); 53 199 } 54 200 -
blaze-ai-discovery-for-woocommerce/trunk/src/Attribution/Platforms.php
r3668873 r3673252 13 13 14 14 /** 15 * Layer 1: Referrer domain patterns for JS document.referrer matching. 16 * Key = platform slug, value = array of domain substrings. 15 * Layer 1: Referrer host patterns, matched host-anchored (exact host or 16 * subdomain) by the inline JS and again by the /track endpoint. An entry 17 * may carry a path prefix (x.com/i/grok). 18 * Key = platform slug, value = array of host[/path] patterns. 17 19 * 18 20 * @return array<string, string[]> … … 127 129 128 130 /** 131 * Resolve the platform a referrer URL belongs to. The host must be the 132 * pattern host or a subdomain of it (chat.openai.com matches 133 * "openai.com"-style patterns, "evilchatgpt.com" does not); patterns that 134 * carry a path (x.com/i/grok) also require that path prefix. 135 * 136 * @param string $referrer Full referrer URL. 137 * @return string|null Platform slug, or null when the host is not an AI platform. 138 */ 139 public static function platform_from_referrer( string $referrer ): ?string { 140 $host = strtolower( (string) wp_parse_url( $referrer, PHP_URL_HOST ) ); 141 if ( '' === $host ) { 142 return null; 143 } 144 $path = (string) wp_parse_url( $referrer, PHP_URL_PATH ); 145 146 foreach ( self::referrer_patterns() as $platform => $patterns ) { 147 foreach ( $patterns as $pattern ) { 148 $slash = strpos( $pattern, '/' ); 149 $pattern_host = false === $slash ? $pattern : substr( $pattern, 0, $slash ); 150 $pattern_path = false === $slash ? '' : substr( $pattern, $slash ); 151 152 if ( ! self::host_matches( $host, $pattern_host ) ) { 153 continue; 154 } 155 if ( '' !== $pattern_path && 0 !== strpos( $path, $pattern_path ) ) { 156 continue; 157 } 158 return $platform; 159 } 160 } 161 162 return null; 163 } 164 165 /** 166 * Whether $host is $domain or a subdomain of it. 167 */ 168 public static function host_matches( string $host, string $domain ): bool { 169 $host = strtolower( $host ); 170 $domain = strtolower( $domain ); 171 if ( '' === $host || '' === $domain ) { 172 return false; 173 } 174 if ( $host === $domain ) { 175 return true; 176 } 177 $suffix = '.' . $domain; 178 return substr( $host, -strlen( $suffix ) ) === $suffix; 179 } 180 181 /** 182 * Resolve the platform for a utm_source value (exact, case-insensitive). 183 * 184 * @return string|null Platform slug or null. 185 */ 186 public static function platform_from_utm_source( string $source ): ?string { 187 $source = strtolower( trim( $source ) ); 188 if ( '' === $source ) { 189 return null; 190 } 191 return self::js_utm_map()[ $source ] ?? null; 192 } 193 194 /** 129 195 * Build JS-compatible referrer pattern map for inline script. 130 196 * Returns a flat object: { "chatgpt.com": "chatgpt", "chat.openai.com": "chatgpt", ... } -
blaze-ai-discovery-for-woocommerce/trunk/src/Attribution/TrackingEndpoint.php
r3670977 r3673252 4 4 * 5 5 * Public endpoint (no auth) protected by payload signature validation. 6 * Receives AI referral data from the inline JS tracker and stores it. 6 * Receives AI referral data from the inline JS tracker and stores it; the 7 * platform is derived server-side from the referrer host and utm_source. 7 8 * 8 9 * @package BlazeAiDiscovery … … 34 35 * Handle an incoming tracking request. 35 36 * 37 * The platform is derived here from the referrer host and utm_source — 38 * never trusted from the body. A well-formed but expired signature (a 39 * page cached longer than the window) is answered with a fresh one so 40 * the tracker can retry once. 41 * 36 42 * @param \WP_REST_Request $request The request. 37 43 * @return \WP_REST_Response … … 39 45 public function handle_track( \WP_REST_Request $request ): \WP_REST_Response { 40 46 $body = $request->get_json_params(); 47 $body = is_array( $body ) ? $body : []; 41 48 42 49 // Validate required fields. … … 50 57 // Validate signature (silently reject — don't reveal failure reason). 51 58 if ( ! PayloadSignature::validate( $signature, $payload ) ) { 59 $fresh = PayloadSignature::resign_if_stale( $signature, $payload ); 60 if ( null !== $fresh ) { 61 return new \WP_REST_Response( [ 'success' => false, 'resign' => $fresh ], 200 ); 62 } 52 63 return new \WP_REST_Response( [ 'success' => false ], 200 ); 53 64 } 65 66 $detected = self::detect( $body ); 67 if ( null === $detected ) { 68 return new \WP_REST_Response( [ 'success' => false ], 200 ); 69 } 70 [ $platform, $detection_method ] = $detected; 54 71 55 72 $landing = is_string( $payload['url'] ?? null ) ? $payload['url'] : ''; … … 59 76 if ( ! WriteGuard::allow( 'visit:' . $hash . ':' . md5( $landing ), 10 * MINUTE_IN_SECONDS ) || ! WriteGuard::under_daily_cap( 'visits', (int) $caps['visits'] ) ) { 60 77 return new \WP_REST_Response( [ 'success' => true ], 200 ); // Accepted, deliberately not stored. 61 }62 63 $platform = sanitize_text_field( $body['platform'] ?? '' );64 $detection_method = sanitize_text_field( $body['detection_method'] ?? '' );65 66 if ( empty( $platform ) || empty( $detection_method ) ) {67 return new \WP_REST_Response( [ 'success' => false ], 200 );68 }69 70 $allowed_platforms = array_keys( Platforms::referrer_patterns() + [ 'google_ai' => [], 'other_ai' => [] ] );71 if ( ! in_array( $platform, $allowed_platforms, true ) ) {72 $platform = 'other_ai';73 }74 75 $allowed_methods = [ 'referrer', 'utm', 'text_fragment' ];76 if ( ! in_array( $detection_method, $allowed_methods, true ) ) {77 return new \WP_REST_Response( [ 'success' => false ], 200 );78 78 } 79 79 … … 108 108 109 109 /** 110 * Derive platform and detection method server-side, in the same order 111 * the tracker does: referrer host, then utm_source, then the text 112 * fragment (which never reaches the server, so the client's 113 * detection_method is accepted as a hint for that layer only and the 114 * platform is fixed to google_ai). The client's platform field is 115 * ignored. 116 * 117 * @param array $body Decoded request body. 118 * @return array{0: string, 1: string}|null [ platform, method ] or null when nothing is detected. 119 */ 120 public static function detect( array $body ): ?array { 121 $referrer = is_string( $body['referrer_url'] ?? null ) ? $body['referrer_url'] : ''; 122 if ( '' !== $referrer ) { 123 $platform = Platforms::platform_from_referrer( $referrer ); 124 if ( null !== $platform ) { 125 return [ $platform, 'referrer' ]; 126 } 127 } 128 129 $utm_source = is_string( $body['utm_source'] ?? null ) ? $body['utm_source'] : ''; 130 if ( '' !== $utm_source ) { 131 $platform = Platforms::platform_from_utm_source( $utm_source ); 132 if ( null !== $platform ) { 133 return [ $platform, 'utm' ]; 134 } 135 } 136 137 $hint = is_string( $body['detection_method'] ?? null ) ? $body['detection_method'] : ''; 138 if ( 'text_fragment' === $hint ) { 139 return [ 'google_ai', 'text_fragment' ]; 140 } 141 142 return null; 143 } 144 145 /** 110 146 * @param mixed $url Raw request value; must be typed-checked since callers 111 147 * send arbitrary JSON (arrays would otherwise crash esc_url_raw()). -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/AuditRunner.php
r3672021 r3673252 11 11 12 12 use BlazeAiDiscovery\Audit\Checks\CheckInterface; 13 use BlazeAiDiscovery\Cloud\CloudClient; 13 14 use BlazeAiDiscovery\Database\Tables; 14 15 … … 16 17 17 18 /** 19 * Seconds the cloud checks (Core Web Vitals, the outside-in crawler 20 * probe) may spend together when the audit runs on a request thread 21 * (POST /audit/run { force: true }). Two 25 s cloud timeouts in a row 22 * blew past 60 s proxies; local checks run in full, cloud rows that do 23 * not fit come back `pending` and the queued background audit fills 24 * them in. 25 */ 26 public const INLINE_CLOUD_BUDGET = 12; 27 28 /** Row status for a cloud check that did not finish within the budget. */ 29 public const STATUS_PENDING = 'pending'; 30 31 /** 18 32 * Run all audit checks and save results. 19 33 * 20 * @return array{results: array, overall_status: string} 21 */ 22 public function run(): array { 34 * @param array{cloud_budget?: float|int} $options `cloud_budget`: seconds the cloud calls may take in total (default: unbounded, 25 s per call). 35 * @return array{results: array, overall_status: string, pending: bool} 36 */ 37 public function run( array $options = [] ): array { 38 $budget = isset( $options['cloud_budget'] ) && is_numeric( $options['cloud_budget'] ) 39 ? (float) $options['cloud_budget'] 40 : null; 41 42 // The budget clock starts at the first cloud call, not now: the 43 // local checks (two loopback fetches, up to 10 s each on a slow 44 // host) run first and must not spend the cloud checks' seconds. 45 CloudClient::set_budget( $budget ); 46 47 try { 48 return $this->run_checks( null !== $budget ); 49 } finally { 50 CloudClient::set_budget( null ); 51 } 52 } 53 54 /** 55 * @param bool $budgeted Whether the cloud calls share a request budget. 56 * @return array{results: array, overall_status: string, pending: bool} 57 */ 58 private function run_checks( bool $budgeted ): array { 23 59 $checks = [ 24 60 new Checks\WooCommerceVersion(), 61 new Checks\StoreVisibility(), 25 62 new Checks\SslActive(), 26 63 new Checks\RestApiAccessible(), … … 44 81 $results = []; 45 82 $worst = 'pass'; 83 $pending = false; 46 84 47 85 foreach ( $checks as $check ) { 48 $result = $this->run_check( $check ); 49 $result['check'] = $check->name(); 50 $results[] = $result; 86 // The budget-exhausted flag is read per check. 87 CloudClient::clear_budget_exhausted(); 88 89 $result = $this->run_check( $check ); 90 91 if ( $budgeted && CloudClient::budget_exhausted() && self::STATUS_PENDING !== $result['status'] ) { 92 $result = self::as_pending( $result ); 93 } 94 95 $result['check'] = $check->name(); 96 if ( self::STATUS_PENDING === $result['status'] ) { 97 $result['pending'] = true; 98 $pending = true; 99 } 100 $results[] = $result; 51 101 52 102 if ( 'fail' === $result['status'] ) { … … 60 110 'results' => $results, 61 111 'overall_status' => $worst, 112 'pending' => $pending, 62 113 ]; 63 114 … … 65 116 66 117 return $audit; 118 } 119 120 /** 121 * A check whose cloud call was skipped or cut short by the request 122 * budget: keep whatever it gathered locally, but the row is `pending` 123 * — the background audit replaces it — rather than a warning that 124 * reads like a verdict. 125 * 126 * @param array{status: string, message: string} $result The check's own result. 127 * @return array{status: string, message: string} 128 */ 129 public static function as_pending( array $result ): array { 130 $result['status'] = self::STATUS_PENDING; 131 $result['message'] = __( 'Cloud check still running — this row will update when the background audit finishes.', 'blaze-ai-discovery-for-woocommerce' ); 132 133 return $result; 134 } 135 136 /** 137 * @param array $audit An audit as returned by run() or get_latest(). 138 */ 139 public static function has_pending( array $audit ): bool { 140 foreach ( $audit['results'] ?? [] as $row ) { 141 if ( is_array( $row ) && self::STATUS_PENDING === ( $row['status'] ?? '' ) ) { 142 return true; 143 } 144 } 145 146 return false; 67 147 } 68 148 … … 119 199 } 120 200 121 return[201 $audit = [ 122 202 'id' => (int) $row->id, 123 203 'run_at' => $row->run_at, … … 125 205 'overall_status' => $row->overall_status, 126 206 ]; 207 208 $audit['pending'] = self::has_pending( $audit ); 209 210 return $audit; 127 211 } 128 212 -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/Checks/CoreWebVitals.php
r3671993 r3673252 46 46 private const RATINGS = [ 'good', 'needs_improvement', 'poor' ]; 47 47 48 /** Top-level keys the /v1/cwv payload must carry (on top of `version`). */ 49 private const REQUIRED_KEYS = [ 'has_data' ]; 50 48 51 private const STATUS_BY_RATING = [ 49 52 'good' => 'pass', … … 78 81 79 82 if ( null === $payload ) { 80 $response = CloudClient::post( self::ENDPOINT, [] );83 $response = CloudClient::post( self::ENDPOINT, [], self::REQUIRED_KEYS ); 81 84 82 85 if ( is_wp_error( $response ) ) { … … 320 323 case 'disabled': 321 324 return $code; 325 case CloudClient::ERROR_BUDGET_EXHAUSTED: 326 return 'pending'; 327 case CloudClient::ERROR_BAD_PAYLOAD: 328 return 'bad_payload'; 322 329 default: 323 330 return 'http_error'; … … 330 337 * message; for errors it follows the local explanation. 331 338 * 332 * @param string $code consent_off | no_data | site_verification_failed | rate_limited | disabled | http_error | internal_error. 339 * A `pending` row (the inline audit's cloud budget ran out) carries 340 * status `pending`: the queued background audit replaces it. 341 * 342 * @param string $code consent_off | no_data | site_verification_failed | rate_limited | disabled | bad_payload | pending | http_error | internal_error. 333 343 * @param array $notices Raw server notices. 334 344 */ … … 343 353 344 354 $result = [ 345 'status' => ' warning',355 'status' => 'pending' === $code ? 'pending' : 'warning', 346 356 'message' => $message, 347 357 'notice' => $code, … … 371 381 case 'disabled': 372 382 return __( 'The Core Web Vitals service is temporarily unavailable. Re-run the audit later.', 'blaze-ai-discovery-for-woocommerce' ); 383 case 'pending': 384 return __( 'Cloud check still running — Core Web Vitals will appear here when the background audit finishes.', 'blaze-ai-discovery-for-woocommerce' ); 385 case 'bad_payload': 386 return __( 'The Core Web Vitals service answered with something other than a result (a network or firewall page, most likely). Re-run the audit later.', 'blaze-ai-discovery-for-woocommerce' ); 373 387 case 'internal_error': 374 388 return __( 'The Core Web Vitals check hit an unexpected error. Re-run the audit; if it keeps happening, contact Blaze Commerce support.', 'blaze-ai-discovery-for-woocommerce' ); -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/Checks/ExistingFeedPlugins.php
r3670977 r3673252 19 19 'wp-product-feed-manager/wp-product-feed-manager.php' => 'WP Product Feed Manager', 20 20 'woo-product-feed-pro/woocommerce-sea.php' => 'Product Feed PRO (alt)', 21 ' ctx-feed/ctx-feed.php'=> 'CTX Feed',21 'webappick-product-feed-for-woocommerce/woo-feed.php' => 'CTX Feed', 22 22 'pinterest-for-woocommerce/pinterest-for-woocommerce.php' => 'Pinterest for WooCommerce', 23 23 ]; -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/Checks/ExistingSchema.php
r3666933 r3673252 18 18 19 19 if ( CompatibilityDetector::YOAST === $detected ) { 20 $has_woo_seo = defined( 'WPSEO_WOO_VERSION' ); 21 if ( $has_woo_seo ) { 22 return [ 23 'status' => 'pass', 24 'message' => sprintf( 25 /* translators: %s: plugin name */ 26 __( '%s with WooCommerce SEO add-on detected. We augment its Product schema with additional AI-relevant properties.', 'blaze-ai-discovery-for-woocommerce' ), 27 $name 28 ), 29 ]; 30 } 20 // detect() only routes here once the WooCommerce SEO add-on is 21 // present (adm-F6); Yoast free is WOOCOMMERCE_NATIVE below. 31 22 return [ 32 23 'status' => 'pass', 33 24 'message' => sprintf( 34 25 /* translators: %s: plugin name */ 35 __( '%s detected. We augment its schema output. Consider adding Yoast WooCommerce SEO for richer Product schema.', 'blaze-ai-discovery-for-woocommerce' ),26 __( '%s with WooCommerce SEO add-on detected. We augment its Product schema with additional AI-relevant properties.', 'blaze-ai-discovery-for-woocommerce' ), 36 27 $name 37 28 ), … … 42 33 return [ 43 34 'status' => 'pass', 44 'message' => __( 'Rank Math detected. We augment its schema output with additional AI-relevant properties. ', 'blaze-ai-discovery-for-woocommerce' ),35 'message' => __( 'Rank Math detected. We augment its schema output with additional AI-relevant properties. If Rank Math\'s product schema is turned off, enable it or WooCommerce\'s own markup so a Product block is printed.', 'blaze-ai-discovery-for-woocommerce' ), 45 36 ]; 46 37 } … … 50 41 'status' => 'warning', 51 42 'message' => __( 'No SEO plugin detected. We generate standalone Product schema. Consider installing Yoast SEO or Rank Math for comprehensive site-wide schema.', 'blaze-ai-discovery-for-woocommerce' ), 43 ]; 44 } 45 46 if ( CompatibilityDetector::WOOCOMMERCE_NATIVE === $detected && CompatibilityDetector::installed( 'yoast' ) ) { 47 return [ 48 'status' => 'pass', 49 'message' => __( 'Yoast SEO is active without its WooCommerce SEO add-on, so WooCommerce prints your Product schema — we augment WooCommerce\'s output with AI-relevant properties. The add-on would give richer Product schema.', 'blaze-ai-discovery-for-woocommerce' ), 50 ]; 51 } 52 53 if ( CompatibilityDetector::SCHEMA_PRO === $detected ) { 54 return [ 55 'status' => 'pass', 56 'message' => __( 'Schema Pro detected. WooCommerce prints your Product schema and we augment it; Schema Pro\'s own Product schema, if enabled, should be turned off to avoid duplicates.', 'blaze-ai-discovery-for-woocommerce' ), 52 57 ]; 53 58 } -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/Checks/LlmsTxtExists.php
r3668873 r3673252 4 4 5 5 defined( 'ABSPATH' ) || exit; 6 7 use BlazeAiDiscovery\Audit\CrawlerAccess\SelfFetch; 6 8 7 9 class LlmsTxtExists implements CheckInterface { … … 24 26 } 25 27 28 // 401/403/407/429/5xx or a bot challenge: the file may well be served, 29 // the plugin's own request just could not get to it. 30 $unverifiable = SelfFetch::unverifiable( $response ); 31 if ( null !== $unverifiable ) { 32 return [ 33 'status' => 'warning', 34 'message' => SelfFetch::unverifiable_message( $unverifiable ), 35 ]; 36 } 37 26 38 $code = wp_remote_retrieve_response_code( $response ); 27 39 -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/Checks/RestApiAccessible.php
r3666933 r3673252 4 4 5 5 defined( 'ABSPATH' ) || exit; 6 7 use BlazeAiDiscovery\Audit\CrawlerAccess\SelfFetch; 6 8 7 9 class RestApiAccessible implements CheckInterface { … … 28 30 } 29 31 32 // 401/403/407/429/5xx or a bot challenge: the edge answered, not 33 // WordPress, so nothing is known about the REST API itself. 34 $unverifiable = SelfFetch::unverifiable( $response ); 35 if ( null !== $unverifiable ) { 36 return [ 37 'status' => 'warning', 38 'message' => SelfFetch::unverifiable_message( $unverifiable ), 39 ]; 40 } 41 30 42 $code = wp_remote_retrieve_response_code( $response ); 31 43 if ( $code >= 200 && $code < 500 ) { -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/Checks/RobotsTxt.php
r3670977 r3673252 47 47 } 48 48 49 $code = (int) wp_remote_retrieve_response_code( $response ); 50 if ( $code >= 500 ) { 49 // 401/403/407/429/5xx or a bot challenge: the rules could not be read, 50 // which is not the same as "no rules". 51 $unverifiable = SelfFetch::unverifiable( $response ); 52 if ( null !== $unverifiable ) { 51 53 return [ 52 54 'status' => 'warning', 53 'message' => __( 'Could not read robots.txt. Ensure it is accessible.', 'blaze-ai-discovery-for-woocommerce'),55 'message' => SelfFetch::unverifiable_message( $unverifiable ), 54 56 ]; 55 57 } 58 59 $code = (int) wp_remote_retrieve_response_code( $response ); 56 60 57 61 // A missing robots.txt (404) disallows nobody. -
blaze-ai-discovery-for-woocommerce/trunk/src/Audit/CrawlerAccess/SelfFetch.php
r3670977 r3673252 1 1 <?php 2 2 /** 3 * Self-request probe: fetch robots.txt and the home page as ourselves and4 * fingerprint the response headers for edge-security presence (Cloudflare,5 * Sucuri, Kinsta).3 * Self-request probe: fetch robots.txt, the home page and one product page 4 * as ourselves and fingerprint the response headers for edge-security 5 * presence (Cloudflare, Sucuri, Kinsta). 6 6 * 7 7 * @package BlazeAiDiscovery … … 15 15 16 16 /** 17 * Fetch robots.txt and the home page, and fingerprint the response headers. 18 * 19 * @return array{cf_present: bool, robots: ?string, robots_status: int, home_status: int, headers: array} 20 */ 21 public static function probe(): array { 22 $args = [ 23 'timeout' => 10, 17 * Upper bound on the wall-clock time probe() may spend across its 18 * fetches (robots.txt, home page, one product page): the per-request 19 * timeout is 10 s, so a host that drops loopback traffic on the floor 20 * cannot turn three fetches into thirty seconds. 21 */ 22 public const TOTAL_BUDGET = 20; 23 24 /** Per-request timeout, seconds. */ 25 private const REQUEST_TIMEOUT = 10; 26 27 /** 28 * Fetch robots.txt, the home page and one published product page as 29 * ourselves, and fingerprint the response headers. The product page is 30 * the one CrawlerAccessCheck::product_url() picks (the newest published, 31 * catalog-visible product) so the crawler-access signals cover the page 32 * a shopping assistant actually reads, not just `/`. 33 * 34 * Edge fingerprints (cf_present, host) are taken from the home and 35 * product responses together; a header seen on either counts. 36 * 37 * @param string|null $product_url Product page to fetch; null looks one up, '' skips it. 38 * @return array{cf_present: bool, robots: ?string, robots_status: int, home_status: int, product_status: int, product_url: ?string, headers: array} 39 */ 40 public static function probe( ?string $product_url = null ): array { 41 $started = microtime( true ); 42 43 if ( null === $product_url ) { 44 $product_url = self::product_url(); 45 } 46 if ( '' === $product_url ) { 47 $product_url = null; 48 } 49 50 $robots_response = self::fetch( self::robots_url(), $started ); 51 $home_response = self::fetch( home_url( '/' ), $started ); 52 $product_response = null === $product_url ? null : self::fetch( $product_url, $started ); 53 54 $robots_status = self::status_of( $robots_response ); 55 $robots_body = ( is_array( $robots_response ) ) ? wp_remote_retrieve_body( $robots_response ) : null; 56 57 $home_status = self::status_of( $home_response ); 58 $product_status = self::status_of( $product_response ); 59 60 // Home headers first; product headers fill in what home lacks. 61 $headers = self::response_headers( $home_response ); 62 $seen = array_change_key_case( $headers, CASE_LOWER ); 63 foreach ( self::response_headers( $product_response ) as $name => $value ) { 64 if ( ! isset( $seen[ strtolower( $name ) ] ) ) { 65 $headers[ $name ] = $value; 66 $seen[ strtolower( $name ) ] = $value; 67 } 68 } 69 70 $fingerprint = self::fingerprint_headers( $headers ); 71 72 return [ 73 'cf_present' => $fingerprint['cf_present'], 74 'robots' => $robots_body, 75 'robots_status' => $robots_status, 76 'home_status' => $home_status, 77 'product_status' => $product_status, 78 'product_url' => $product_url, 79 'headers' => $headers, 80 ]; 81 } 82 83 /** 84 * One self-fetch, its timeout cut to whatever is left of TOTAL_BUDGET 85 * (and of the cloud request deadline when an inline audit set one). 86 * Returns a WP_Error without a request once the budget is spent. 87 * 88 * @return array|\WP_Error 89 */ 90 private static function fetch( string $url, float $started ) { 91 $remaining = self::TOTAL_BUDGET - ( microtime( true ) - $started ); 92 $deadline = \BlazeAiDiscovery\Cloud\CloudClient::remaining(); 93 if ( null !== $deadline ) { 94 $remaining = min( $remaining, $deadline ); 95 } 96 97 if ( $remaining < 1 ) { 98 return new \WP_Error( 'blazeaid_self_fetch_budget', __( 'Self-fetch budget exhausted.', 'blaze-ai-discovery-for-woocommerce' ) ); 99 } 100 101 return wp_remote_get( $url, [ 102 'timeout' => (int) min( self::REQUEST_TIMEOUT, ceil( $remaining ) ), 24 103 'redirection' => 3, 25 104 'user-agent' => self::user_agent(), 105 ] ); 106 } 107 108 /** 109 * Permalink of one published product for the self-fetch, or null when 110 * WooCommerce (or a product) is missing. Never throws. 111 */ 112 public static function product_url(): ?string { 113 try { 114 return CrawlerAccessCheck::product_url(); 115 } catch ( \Throwable $e ) { 116 return null; 117 } 118 } 119 120 /** 121 * @param mixed $response wp_remote_get() result, or null when skipped. 122 */ 123 private static function status_of( $response ): int { 124 return is_array( $response ) ? (int) wp_remote_retrieve_response_code( $response ) : 0; 125 } 126 127 /** 128 * @param mixed $response wp_remote_get() result, or null when skipped. 129 * @return array<string, string> 130 */ 131 private static function response_headers( $response ): array { 132 return is_array( $response ) ? self::headers_to_array( wp_remote_retrieve_headers( $response ) ) : []; 133 } 134 135 /** 136 * HTTP statuses that mean something in front of WordPress (HTTP auth, 137 * a firewall, a bot challenge, an overloaded origin) answered the 138 * plugin's own request instead of the page. None of them says anything 139 * about what the page would serve, so a check must report "could not 140 * verify", never pass or fail. 141 */ 142 public const UNVERIFIABLE_STATUSES = [ 401, 403, 407, 429 ]; 143 144 /** 145 * Whether a self-fetch response cannot be read as the page's own answer: 146 * 401/403/407/429, any 5xx, or a Cloudflare challenge page (any status). 147 * 148 * @param mixed $response wp_remote_get() result. 149 * @return array{code: int, challenge: bool}|null Null when the response is the page's own answer (2xx, 404, ...). 150 */ 151 public static function unverifiable( $response ): ?array { 152 if ( ! is_array( $response ) ) { 153 return null; 154 } 155 156 $code = (int) wp_remote_retrieve_response_code( $response ); 157 $challenge = self::is_challenge( $response ); 158 159 if ( ! $challenge && ! in_array( $code, self::UNVERIFIABLE_STATUSES, true ) && $code < 500 ) { 160 return null; 161 } 162 163 return [ 164 'code' => $code, 165 'challenge' => $challenge, 26 166 ]; 27 28 $robots_response = wp_remote_get( self::robots_url(), $args ); 29 $home_response = wp_remote_get( home_url( '/' ), $args ); 30 31 $robots_status = is_wp_error( $robots_response ) ? 0 : (int) wp_remote_retrieve_response_code( $robots_response ); 32 $robots_body = is_wp_error( $robots_response ) ? null : wp_remote_retrieve_body( $robots_response ); 33 34 $home_status = is_wp_error( $home_response ) ? 0 : (int) wp_remote_retrieve_response_code( $home_response ); 35 $headers = is_wp_error( $home_response ) ? [] : self::headers_to_array( wp_remote_retrieve_headers( $home_response ) ); 36 37 $fingerprint = self::fingerprint_headers( $headers ); 38 39 return [ 40 'cf_present' => $fingerprint['cf_present'], 41 'robots' => $robots_body, 42 'robots_status' => $robots_status, 43 'home_status' => $home_status, 44 'headers' => $headers, 45 ]; 167 } 168 169 /** 170 * Cloudflare challenge fingerprint: the `cf-mitigated: challenge` header 171 * (managed / JS challenge, Bot Fight Mode), or the challenge page markup 172 * itself when the header was stripped. 173 * 174 * @param array $response wp_remote_get() result. 175 */ 176 public static function is_challenge( array $response ): bool { 177 $headers = array_change_key_case( self::headers_to_array( wp_remote_retrieve_headers( $response ) ), CASE_LOWER ); 178 if ( isset( $headers['cf-mitigated'] ) && false !== stripos( (string) $headers['cf-mitigated'], 'challenge' ) ) { 179 return true; 180 } 181 182 $body = (string) wp_remote_retrieve_body( $response ); 183 if ( '' === $body ) { 184 return false; 185 } 186 $head = substr( $body, 0, 8192 ); 187 188 return false !== strpos( $head, '/cdn-cgi/challenge-platform/' ) 189 || false !== strpos( $head, 'cf-chl' ) 190 || ( false !== stripos( $head, '<title>Just a moment...</title>' ) && false !== stripos( $head, 'cloudflare' ) ); 191 } 192 193 /** 194 * The one sentence every loopback check uses for an unverifiable answer. 195 * 196 * @param array{code: int, challenge: bool} $info unverifiable() result. 197 */ 198 public static function unverifiable_message( array $info ): string { 199 $message = sprintf( 200 /* translators: %d: HTTP status code the site answered with */ 201 __( 'Could not verify — your site answered HTTP %d to the plugin\'s own request (password protection, firewall or bot challenge).', 'blaze-ai-discovery-for-woocommerce' ), 202 $info['code'] 203 ); 204 205 if ( ! empty( $info['challenge'] ) ) { 206 $message .= ' ' . __( 'A Cloudflare challenge page was detected.', 'blaze-ai-discovery-for-woocommerce' ); 207 } 208 209 return $message; 46 210 } 47 211 -
blaze-ai-discovery-for-woocommerce/trunk/src/Cloud/CloudClient.php
r3670977 r3673252 14 14 public const BASE_URL = 'https://api.blazecommerce.io/v1/'; 15 15 16 /** Per-request timeout, seconds, when no deadline is set. */ 17 public const TIMEOUT = 25; 18 19 /** WP_Error code for a 2xx whose body is not the JSON object the service sends. */ 20 public const ERROR_BAD_PAYLOAD = 'blazeaid_bad_payload'; 21 22 /** WP_Error code for a call skipped or cut short by the request deadline. */ 23 public const ERROR_BUDGET_EXHAUSTED = 'budget_exhausted'; 24 25 /** Top-level key every service response carries. */ 26 private const REQUIRED_KEYS = [ 'version' ]; 27 28 /** Seconds a retry needs on top of the backoff before it is worth attempting. */ 29 private const RETRY_MIN_REMAINING = 2.0; 30 31 /** 32 * Seconds the cloud calls of this request may take together, armed 33 * into a deadline by the first attempt (see set_budget()), or null. 34 */ 35 private static ?float $budget = null; 36 37 /** Unix timestamp (float) by which every cloud call must have returned, or null. */ 38 private static ?float $deadline = null; 39 40 /** Whether a call was skipped or cut short by the deadline since it was set. */ 41 private static bool $budget_exhausted = false; 42 43 /** 44 * Give the cloud calls of this request a shared budget. The clock 45 * starts at the first call attempted, not here: an inline audit runs 46 * its local checks first (two loopback fetches can take ten seconds on 47 * a slow host) and those must not eat the cloud checks' seconds. Until 48 * a call arms it, remaining() is null and nothing is bounded — so with 49 * consent off (no call is ever attempted) the self-fetch keeps its own 50 * bound only. Null clears budget and deadline. 51 * 52 * @param float|null $seconds Budget in seconds, or null. 53 */ 54 public static function set_budget( ?float $seconds ): void { 55 self::$budget = null === $seconds ? null : max( 0.0, $seconds ); 56 self::$deadline = null; 57 self::$budget_exhausted = false; 58 } 59 60 /** 61 * Bound every cloud call made from now on: each request's timeout is 62 * cut to what is left before $deadline, a call with under a second left 63 * is not made at all, and either case answers `budget_exhausted` (see 64 * budget_exhausted()). Null lifts the bound (the default: 25 s per call). 65 * Unlike set_budget(), the clock is already running. 66 * 67 * @param float|null $deadline Unix timestamp (microtime(true) scale), or null. 68 */ 69 public static function set_deadline( ?float $deadline ): void { 70 self::$budget = null; 71 self::$deadline = $deadline; 72 self::$budget_exhausted = false; 73 } 74 75 /** 76 * Seconds left before the deadline (never below 0), or null without one 77 * (no deadline set, or a budget no call has armed yet). 78 */ 79 public static function remaining(): ?float { 80 if ( null === self::$deadline ) { 81 return null; 82 } 83 84 return max( 0.0, self::$deadline - microtime( true ) ); 85 } 86 87 /** 88 * Whether any call since the last set_budget() / set_deadline() / 89 * clear_budget_exhausted() was skipped or cut short by the deadline. 90 * The audit runner reads this after each check to mark rows `pending`. 91 */ 92 public static function budget_exhausted(): bool { 93 return self::$budget_exhausted; 94 } 95 96 /** 97 * Reset the exhausted flag without touching the budget or deadline, so 98 * it can be read per check. 99 */ 100 public static function clear_budget_exhausted(): void { 101 self::$budget_exhausted = false; 102 } 103 104 /** 105 * Start the budget clock on the first attempt (no-op once armed, or 106 * without a budget). 107 */ 108 private static function arm(): void { 109 if ( null === self::$deadline && null !== self::$budget ) { 110 self::$deadline = microtime( true ) + self::$budget; 111 } 112 } 113 16 114 /** 17 115 * POST a request to the Blaze Commerce cloud API. … … 21 119 * to typed WP_Error codes. 22 120 * 23 * @param string $endpoint Endpoint path relative to the base URL, e.g. "crawler-access". 24 * @param array $body Request body fields (merged with site/site_token/plugin). 121 * A 2xx counts as a success only when the response is JSON 122 * (Content-Type) and decodes to an object carrying `version` plus every 123 * key in $required_keys; anything else (a Cloudflare challenge, an HTML 124 * error page served with 200) is `blazeaid_bad_payload`, so callers 125 * never cache an empty "result". 126 * 127 * Transient failures — a connection error, 429, any 5xx — are retried 128 * once after a short backoff, never past the deadline. A timeout is not 129 * retried: the service is slow, and the retry would only wait again. 130 * 131 * @param string $endpoint Endpoint path relative to the base URL, e.g. "crawler-access". 132 * @param array $body Request body fields (merged with site/site_token/plugin). 133 * @param string[] $required_keys Top-level keys the decoded response must carry, on top of `version`. 25 134 * @return array|\WP_Error Decoded JSON response on success. 26 135 */ 27 public static function post( string $endpoint, array $body ) {136 public static function post( string $endpoint, array $body, array $required_keys = [] ) { 28 137 if ( ! Consent::granted() ) { 29 138 return new \WP_Error( … … 49 158 ); 50 159 51 $url = rtrim( $base_url, '/' ) . '/' . ltrim( $endpoint, '/' ); 160 $url = rtrim( $base_url, '/' ) . '/' . ltrim( $endpoint, '/' ); 161 $json = wp_json_encode( $payload ); 162 163 $result = self::attempt( $url, $json, $required_keys ); 164 165 if ( self::is_transient( $result ) && self::can_retry() ) { 166 $delay = self::retry_delay(); 167 if ( $delay > 0 ) { 168 usleep( (int) round( $delay * 1000000 ) ); 169 } 170 $result = self::attempt( $url, $json, $required_keys ); 171 } 172 173 return $result; 174 } 175 176 /** 177 * One HTTP attempt, bounded by the deadline. 178 * 179 * @param string $url Full endpoint URL. 180 * @param string $json Encoded request body. 181 * @param string[] $required_keys Extra top-level keys the response must carry. 182 * @return array|\WP_Error 183 */ 184 private static function attempt( string $url, string $json, array $required_keys ) { 185 self::arm(); 186 187 $timeout = self::TIMEOUT; 188 $remaining = self::remaining(); 189 if ( null !== $remaining ) { 190 if ( $remaining < 1 ) { 191 return self::budget_error(); 192 } 193 $timeout = (int) min( self::TIMEOUT, ceil( $remaining ) ); 194 } 52 195 53 196 $response = wp_remote_post( 54 197 $url, 55 198 [ 56 'timeout' => 25,199 'timeout' => $timeout, 57 200 'headers' => [ 58 201 'Content-Type' => 'application/json', 59 202 'User-Agent' => 'BlazeAiDiscovery/' . ( defined( 'BLAZEAID_VERSION' ) ? BLAZEAID_VERSION : '0.0.0' ), 60 203 ], 61 'body' => wp_json_encode( $payload ),204 'body' => $json, 62 205 ] 63 206 ); 64 207 65 208 if ( is_wp_error( $response ) ) { 209 // A transport failure right at the deadline is the deadline. 210 $left = self::remaining(); 211 if ( null !== $left && $left < 1 ) { 212 return self::budget_error(); 213 } 214 66 215 return $response; 67 216 } … … 71 220 72 221 if ( $code >= 200 && $code < 300 ) { 73 return is_array( $data ) ? $data : []; 222 if ( ! self::is_json_response( $response ) || ! self::is_expected_payload( $data, $required_keys ) ) { 223 return new \WP_Error( 224 self::ERROR_BAD_PAYLOAD, 225 __( 'Blaze Commerce cloud returned an unexpected response.', 'blaze-ai-discovery-for-woocommerce' ), 226 [ 227 'status' => $code, 228 'notices' => [], 229 ] 230 ); 231 } 232 233 return $data; 74 234 } 75 235 … … 98 258 ); 99 259 } 260 261 private static function budget_error(): \WP_Error { 262 self::$budget_exhausted = true; 263 264 return new \WP_Error( 265 self::ERROR_BUDGET_EXHAUSTED, 266 __( 'The cloud check did not finish within this request; it continues in the background.', 'blaze-ai-discovery-for-woocommerce' ), 267 [ 268 'status' => 0, 269 'notices' => [], 270 ] 271 ); 272 } 273 274 /** 275 * Content-Type says JSON (application/json, application/problem+json, ...). 276 * 277 * @param array $response wp_remote_post() result. 278 */ 279 private static function is_json_response( array $response ): bool { 280 $headers = wp_remote_retrieve_headers( $response ); 281 if ( is_object( $headers ) && method_exists( $headers, 'getAll' ) ) { 282 $headers = $headers->getAll(); 283 } 284 if ( ! is_array( $headers ) ) { 285 return false; 286 } 287 288 $headers = array_change_key_case( $headers, CASE_LOWER ); 289 $type = $headers['content-type'] ?? ''; 290 if ( is_array( $type ) ) { 291 $type = implode( ',', $type ); 292 } 293 $type = strtolower( (string) $type ); 294 295 return false !== strpos( $type, 'application/json' ) || false !== strpos( $type, '+json' ); 296 } 297 298 /** 299 * Decoded body is an object (string keys) carrying `version` and every 300 * required key. 301 * 302 * @param mixed $data json_decode() result. 303 * @param string[] $required_keys Extra keys. 304 */ 305 private static function is_expected_payload( $data, array $required_keys ): bool { 306 if ( ! is_array( $data ) || empty( $data ) ) { 307 return false; 308 } 309 310 foreach ( array_merge( self::REQUIRED_KEYS, $required_keys ) as $key ) { 311 if ( ! array_key_exists( $key, $data ) ) { 312 return false; 313 } 314 } 315 316 return true; 317 } 318 319 /** 320 * A failure worth one retry: connection-level error (not a timeout), 321 * 429, or any 5xx. 322 * 323 * @param mixed $result attempt() result. 324 */ 325 private static function is_transient( $result ): bool { 326 if ( ! is_wp_error( $result ) ) { 327 return false; 328 } 329 330 $code = $result->get_error_code(); 331 if ( in_array( $code, [ self::ERROR_BUDGET_EXHAUSTED, self::ERROR_BAD_PAYLOAD, 'consent_required' ], true ) ) { 332 return false; 333 } 334 335 $data = $result->get_error_data(); 336 $status = ( is_array( $data ) && isset( $data['status'] ) ) ? (int) $data['status'] : null; 337 338 if ( null !== $status && $status > 0 ) { 339 return 429 === $status || $status >= 500; 340 } 341 342 // Transport error: retry unless it was a timeout. 343 return 1 !== preg_match( '/timed? ?out|cURL error 28\b/i', $result->get_error_message() ); 344 } 345 346 /** 347 * A retry fits when there is no deadline, or backoff plus a couple of 348 * seconds still fit before it. 349 */ 350 private static function can_retry(): bool { 351 $remaining = self::remaining(); 352 if ( null === $remaining ) { 353 return true; 354 } 355 356 return $remaining >= self::retry_delay() + self::RETRY_MIN_REMAINING; 357 } 358 359 /** 360 * Backoff before the single retry, seconds. `BLAZEAID_CLOUD_RETRY_DELAY` 361 * (a constant, used by the test runtime) sets the default of 1 s; the 362 * `blazeaid_cloud_retry_delay` filter can change it per site. 363 */ 364 private static function retry_delay(): float { 365 $default = defined( 'BLAZEAID_CLOUD_RETRY_DELAY' ) ? (float) BLAZEAID_CLOUD_RETRY_DELAY : 1.0; 366 367 /** 368 * Filter the backoff before the one retry of a failed cloud call. 369 * 370 * @param float $delay Seconds (0 disables the wait, not the retry). 371 */ 372 $delay = apply_filters( 'blazeaid_cloud_retry_delay', $default ); 373 374 return max( 0.0, (float) $delay ); 375 } 100 376 } -
blaze-ai-discovery-for-woocommerce/trunk/src/Cloud/PayloadCache.php
r3670977 r3673252 24 24 25 25 /** 26 * An empty payload is never cached: it is what a broken response used to 27 * decode to, and caching it turned a minutes-long incident into a day 28 * of "no data" answers. 29 * 26 30 * @param string $key Cache key (without the transient prefix). 27 31 * @param array $payload Payload to cache. 28 32 * @param int $ttl Time to live, in seconds. 33 * @return bool Whether the payload was stored. 29 34 */ 30 public static function set( string $key, array $payload, int $ttl ): void { 31 set_transient( self::PREFIX . $key, $payload, $ttl ); 35 public static function set( string $key, array $payload, int $ttl ): bool { 36 if ( empty( $payload ) ) { 37 return false; 38 } 39 40 return (bool) set_transient( self::PREFIX . $key, $payload, $ttl ); 32 41 } 33 42 -
blaze-ai-discovery-for-woocommerce/trunk/src/Cloud/VisibilityClient.php
r3670977 r3673252 32 32 33 33 /** 34 * A 2xx that was not the display payload (an HTML error page, a 35 * challenge) is not cached as data; the local notice for it is kept 36 * only briefly so the next refresh retries soon. 37 */ 38 private const BAD_PAYLOAD_TTL = 300; 39 40 /** Top-level keys the display payload must carry (on top of `version`). */ 41 private const REQUIRED_KEYS = [ 'sections' ]; 42 43 /** 34 44 * @return array|null Sanitised payload from the transient cache, or null. 35 45 */ … … 49 59 } 50 60 51 $result = CloudClient::post( self::ENDPOINT, self::request_body() );61 $result = CloudClient::post( self::ENDPOINT, self::request_body(), self::REQUIRED_KEYS ); 52 62 update_option( self::OPTION_LAST_RUN, current_time( 'mysql', true ), false ); 53 63 … … 55 65 $data = $result->get_error_data(); 56 66 $notices = ( is_array( $data ) && isset( $data['notices'] ) ) ? $data['notices'] : []; 57 $payload = self::notices_only( $result->get_error_code(), $notices ); 58 PayloadCache::set( self::CACHE_KEY, $payload, self::ERROR_TTL ); 67 $ttl = CloudClient::ERROR_BAD_PAYLOAD === $result->get_error_code() ? self::BAD_PAYLOAD_TTL : self::ERROR_TTL; 68 $payload = self::notices_only( $result->get_error_code(), $notices, $ttl ); 69 PayloadCache::set( self::CACHE_KEY, $payload, $ttl ); 59 70 return $payload; 60 71 } … … 134 145 * and any sanitised notices the service sent alongside the error. 135 146 * 136 * @param string $code consent_off | site_verification_failed | rate_limited | disabled | http_error.147 * @param string $code consent_off | site_verification_failed | rate_limited | disabled | blazeaid_bad_payload | http_error. 137 148 * @param array $notices Server notices carried on the WP_Error. 149 * @param int $ttl Cache lifetime reported in the payload. 138 150 */ 139 private static function notices_only( string $code, array $notices = [] ): array {151 private static function notices_only( string $code, array $notices = [], int $ttl = self::ERROR_TTL ): array { 140 152 $texts = [ 141 'consent_off' => __( 'Cloud checks are not enabled for this site, so AI visibility data is not being fetched.', 'blaze-ai-discovery-for-woocommerce' ), 142 'site_verification_failed' => __( 'Blaze Commerce could not verify this site. Make sure the store is publicly reachable and try again.', 'blaze-ai-discovery-for-woocommerce' ), 143 'rate_limited' => __( 'Rate limit reached for AI visibility refreshes. Please try again tomorrow.', 'blaze-ai-discovery-for-woocommerce' ), 144 'disabled' => __( 'The AI visibility service is temporarily unavailable. Data will refresh automatically when it returns.', 'blaze-ai-discovery-for-woocommerce' ), 153 'consent_off' => __( 'Cloud checks are not enabled for this site, so AI visibility data is not being fetched.', 'blaze-ai-discovery-for-woocommerce' ), 154 'site_verification_failed' => __( 'Blaze Commerce could not verify this site. Make sure the store is publicly reachable and try again.', 'blaze-ai-discovery-for-woocommerce' ), 155 'rate_limited' => __( 'Rate limit reached for AI visibility refreshes. Please try again tomorrow.', 'blaze-ai-discovery-for-woocommerce' ), 156 'disabled' => __( 'The AI visibility service is temporarily unavailable. Data will refresh automatically when it returns.', 'blaze-ai-discovery-for-woocommerce' ), 157 CloudClient::ERROR_BAD_PAYLOAD => __( 'The AI visibility service answered with something other than a report (a network or firewall page, most likely). It will be retried shortly.', 'blaze-ai-discovery-for-woocommerce' ), 145 158 ]; 146 159 if ( ! isset( $texts[ $code ] ) ) { … … 157 170 return [ 158 171 'version' => 1, 159 'ttl' => self::ERROR_TTL,172 'ttl' => $ttl, 160 173 'generated_at' => gmdate( 'c' ), 161 174 'period' => null, -
blaze-ai-discovery-for-woocommerce/trunk/src/Database/DatabaseModule.php
r3670977 r3673252 1 1 <?php 2 2 /** 3 * Database module — owns retention scheduling.3 * Database module — owns schema self-repair and retention scheduling. 4 4 * 5 5 * @package BlazeAiDiscovery … … 17 17 private Container $container; 18 18 private RetentionCleanup $cleanup; 19 private Migrator $migrator; 19 20 20 21 public function __construct( Container $container ) { 21 22 $this->container = $container; 22 23 $this->cleanup = new RetentionCleanup(); 24 $this->migrator = new Migrator(); 23 25 } 24 26 … … 29 31 public function register(): void { 30 32 $this->cleanup->register(); 33 34 // Every request (cron, REST, front end): one autoloaded option read. 35 // A site whose schema was never installed - activated before 36 // WooCommerce, cloned without custom tables, a DB user that could not 37 // CREATE at activation - repairs itself here instead of failing every 38 // insert silently until someone reactivates the plugin. 39 $this->migrator->maybe_run( false ); 40 41 add_action( 'admin_init', [ $this, 'maybe_migrate' ], 5 ); 31 42 add_action( 'admin_init', [ $this, 'maybe_schedule' ] ); 43 add_action( 'admin_notices', [ $this, 'render_schema_notice' ] ); 32 44 } 33 45 34 46 public function boot(): void {} 47 48 /** 49 * admin_init: the deeper check (SHOW TABLES, once per request) that also 50 * catches a dropped table when the version option says all is well. 51 */ 52 public function maybe_migrate(): void { 53 if ( wp_doing_ajax() ) { 54 return; 55 } 56 $this->migrator->maybe_run( true ); 57 } 35 58 36 59 /** … … 42 65 } 43 66 } 67 68 /** 69 * Tell the store owner which tables are missing and why that usually 70 * happens, instead of a dashboard that silently never fills. 71 */ 72 public function render_schema_notice(): void { 73 if ( ! current_user_can( 'manage_woocommerce' ) ) { 74 return; 75 } 76 77 $notice = $this->schema_notice(); 78 if ( null === $notice ) { 79 return; 80 } 81 82 echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses( $notice, [ 'code' => [], 'strong' => [] ] ) . '</p></div>'; 83 } 84 85 /** 86 * The schema notice text (HTML with code/strong only), or null when the 87 * schema is complete. 88 */ 89 public function schema_notice(): ?string { 90 $missing = $this->migrator->missing_tables(); 91 if ( [] === $missing && $this->migrator->is_current() ) { 92 return null; 93 } 94 95 $failure = $this->migrator->last_failure(); 96 if ( [] === $missing && null !== $failure ) { 97 $missing = $failure['missing']; 98 } 99 100 $tables = implode( 101 ', ', 102 array_map( 103 static function ( string $table ): string { 104 return '<code>' . esc_html( $table ) . '</code>'; 105 }, 106 $missing 107 ) 108 ); 109 110 $text = sprintf( 111 /* translators: %s: comma-separated list of database table names. */ 112 esc_html__( 'Blaze AI Discovery could not create its database tables: %s. The database user WordPress connects with usually lacks the CREATE TABLE privilege; grant it (or ask your host to) and the plugin retries automatically within a few minutes.', 'blaze-ai-discovery-for-woocommerce' ), 113 '' === $tables ? esc_html__( 'schema version not recorded', 'blaze-ai-discovery-for-woocommerce' ) : $tables 114 ); 115 116 if ( null !== $failure && '' !== $failure['error'] ) { 117 $text .= ' ' . sprintf( 118 /* translators: %s: the last MySQL error message. */ 119 esc_html__( 'Last database error: %s', 'blaze-ai-discovery-for-woocommerce' ), 120 '<code>' . esc_html( $failure['error'] ) . '</code>' 121 ); 122 } 123 124 return '<strong>' . esc_html__( 'Blaze AI Discovery', 'blaze-ai-discovery-for-woocommerce' ) . '</strong> ' . $text; 125 } 44 126 } -
blaze-ai-discovery-for-woocommerce/trunk/src/Database/Migrator.php
r3666933 r3673252 3 3 * Versioned schema migrations using dbDelta. 4 4 * 5 * The schema version is recorded only after every expected table has been 6 * verified to exist, so a failed CREATE (restricted DB user, strict-mode 7 * index errors) leaves the version behind and the migrator retries instead 8 * of reporting success over an empty database. 9 * 5 10 * @package BlazeAiDiscovery 6 11 */ … … 12 17 class Migrator { 13 18 14 private const VERSION_OPTION = 'blazeaid_db_version'; 15 private const TARGET_VERSION = 1; 16 17 public function run(): void { 18 $current = (int) get_option( self::VERSION_OPTION, 0 ); 19 20 if ( $current >= self::TARGET_VERSION ) { 21 return; 22 } 23 24 require_once ABSPATH . 'wp-admin/includes/upgrade.php'; 25 26 if ( $current < 1 ) { 27 $this->migrate_v1(); 28 } 29 30 update_option( self::VERSION_OPTION, self::TARGET_VERSION ); 19 public const VERSION_OPTION = 'blazeaid_db_version'; 20 public const TARGET_VERSION = 1; 21 22 /** 23 * Transient set after a failed attempt so a broken database is retried 24 * every few minutes rather than on every request. Holds the wpdb error 25 * and the missing tables for the admin notice. 26 */ 27 public const RETRY_TRANSIENT = 'blazeaid_db_retry'; 28 29 /** Seconds between attempts while tables cannot be created. */ 30 public const RETRY_INTERVAL = 5 * MINUTE_IN_SECONDS; 31 32 /** 33 * Per-request cache of the missing-table check, keyed by table prefix so 34 * switch_to_blog() never reuses another site's answer. 35 * 36 * @var array<string, string[]> 37 */ 38 private static array $missing_cache = []; 39 40 /** 41 * True when the recorded schema version is at the target. 42 */ 43 public function is_current(): bool { 44 return (int) get_option( self::VERSION_OPTION, 0 ) >= self::TARGET_VERSION; 45 } 46 47 /** 48 * Run the migration when it is needed: the version option is behind 49 * (never installed, activated before WooCommerce, a future schema bump 50 * applied by plugin update, or an earlier attempt that could not create 51 * the tables), or - when $verify_tables is set - any expected table is 52 * missing (site cloned without custom tables, a multisite subsite, a 53 * table dropped by hand). 54 * 55 * The version compare is a single autoloaded option read, so the 56 * $verify_tables = false form is cheap enough for every request; the 57 * table check costs one SHOW TABLES per request and belongs on admin_init. 58 * 59 * @param bool $verify_tables Also check that every table exists. 60 * @return bool True when the schema is complete after this call. 61 */ 62 public function maybe_run( bool $verify_tables = true ): bool { 63 if ( $this->is_current() ) { 64 if ( ! $verify_tables ) { 65 return true; 66 } 67 if ( [] === $this->missing_tables() ) { 68 return true; 69 } 70 } 71 72 if ( false !== get_transient( self::RETRY_TRANSIENT ) ) { 73 // A recent attempt failed; do not hammer a database that cannot create tables. 74 return false; 75 } 76 77 return $this->run(); 78 } 79 80 /** 81 * Apply the schema and record the version once every table is present. 82 * 83 * dbDelta is idempotent, so this is safe to call from activation, from 84 * admin_init, per site under switch_to_blog(), and again after a failure. 85 * 86 * @return bool True when every expected table exists afterwards. 87 */ 88 public function run(): bool { 89 global $wpdb; 90 91 if ( ! function_exists( 'dbDelta' ) ) { 92 require_once ABSPATH . 'wp-admin/includes/upgrade.php'; 93 } 94 95 $wpdb->last_error = ''; 96 $this->migrate_v1(); 97 $error = (string) $wpdb->last_error; 98 99 $missing = $this->missing_tables( true ); 100 101 if ( [] === $missing ) { 102 update_option( self::VERSION_OPTION, self::TARGET_VERSION ); 103 delete_transient( self::RETRY_TRANSIENT ); 104 return true; 105 } 106 107 set_transient( 108 self::RETRY_TRANSIENT, 109 [ 110 'error' => $error, 111 'missing' => $missing, 112 'at' => time(), 113 ], 114 self::RETRY_INTERVAL 115 ); 116 117 return false; 31 118 } 32 119 … … 35 122 */ 36 123 public function needs_migration(): bool { 37 return (int) get_option( self::VERSION_OPTION, 0 ) < self::TARGET_VERSION; 124 return ! $this->is_current() || [] !== $this->missing_tables(); 125 } 126 127 /** 128 * Expected tables that do not exist for the current site prefix. One 129 * SHOW TABLES per request per prefix; pass $refresh after a schema change. 130 * 131 * @param bool $refresh Ignore the per-request cache. 132 * @return string[] Fully prefixed table names. 133 */ 134 public function missing_tables( bool $refresh = false ): array { 135 global $wpdb; 136 137 $prefix = (string) $wpdb->prefix; 138 if ( ! $refresh && isset( self::$missing_cache[ $prefix ] ) ) { 139 return self::$missing_cache[ $prefix ]; 140 } 141 142 $like = $wpdb->esc_like( $prefix . 'blazeaid_' ) . '%'; 143 $existing = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $like ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 144 $existing = array_map( 'strtolower', array_map( 'strval', is_array( $existing ) ? $existing : [] ) ); 145 146 $missing = []; 147 foreach ( Tables::all() as $table ) { 148 if ( ! in_array( strtolower( $table ), $existing, true ) ) { 149 $missing[] = $table; 150 } 151 } 152 153 self::$missing_cache[ $prefix ] = $missing; 154 return $missing; 155 } 156 157 /** 158 * Details of the last failed attempt, for the admin notice. 159 * 160 * @return array{error: string, missing: string[], at: int}|null 161 */ 162 public function last_failure(): ?array { 163 $failure = get_transient( self::RETRY_TRANSIENT ); 164 if ( ! is_array( $failure ) ) { 165 return null; 166 } 167 return [ 168 'error' => isset( $failure['error'] ) && is_string( $failure['error'] ) ? $failure['error'] : '', 169 'missing' => isset( $failure['missing'] ) && is_array( $failure['missing'] ) ? array_map( 'strval', $failure['missing'] ) : [], 170 'at' => isset( $failure['at'] ) ? (int) $failure['at'] : 0, 171 ]; 172 } 173 174 /** 175 * Forget the per-request table cache (tests, and after DROP TABLE). 176 */ 177 public static function reset_cache(): void { 178 self::$missing_cache = []; 38 179 } 39 180 -
blaze-ai-discovery-for-woocommerce/trunk/src/Database/RetentionCleanup.php
r3666933 r3673252 2 2 /** 3 3 * Scheduled data retention enforcement. 4 * 5 * Attribution data (visits, attributed orders) and the crawler endpoint log 6 * are deleted once older than the retention period, in batches of 7 * BATCH_SIZE rows until nothing older remains or the run's time budget is 8 * spent — a single capped delete cannot keep up with the daily write caps 9 * (5,000 visits, 2,000 log rows). 4 10 * 5 11 * @package BlazeAiDiscovery … … 19 25 private const DEFAULT_RETENTION_DAYS = 90; 20 26 27 /** Rows per DELETE statement. */ 28 public const BATCH_SIZE = 1000; 29 30 /** Seconds one cleanup run may spend deleting, across all tables. */ 31 public const TIME_BUDGET = 10.0; 32 21 33 public function register(): void { 22 34 add_action( self::HOOK, [ $this, 'cleanup' ] ); … … 35 47 } 36 48 37 public function cleanup(): void { 49 /** 50 * Delete everything older than the retention period from the tables 51 * under the policy, then trim audits to the last 10. 52 * 53 * @return array<string, int> Rows deleted per table. 54 */ 55 public function cleanup(): array { 38 56 global $wpdb; 39 57 40 58 $days = (int) apply_filters( 'blazeaid_retention_days', self::DEFAULT_RETENTION_DAYS ); 41 59 $threshold = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) ); 60 $start = microtime( true ); 61 $deleted = []; 42 62 43 // Clean visits. 44 $wpdb->query( 45 $wpdb->prepare( 46 'DELETE FROM %i WHERE visited_at < %s LIMIT 1000', 47 Tables::visits(), 48 $threshold 49 ) 50 ); 51 52 // Clean endpoint log. 53 $wpdb->query( 54 $wpdb->prepare( 55 'DELETE FROM %i WHERE requested_at < %s LIMIT 1000', 56 Tables::endpoint_log(), 57 $threshold 58 ) 59 ); 63 foreach ( self::retained_tables() as $table => $column ) { 64 $deleted[ $table ] = $this->purge( $table, $column, $threshold, $start ); 65 } 60 66 61 67 // Clean old audits (keep last 10). … … 76 82 ); 77 83 } 84 85 return $deleted; 86 } 87 88 /** 89 * Tables under the retention period and their timestamp column. 90 * 91 * @return array<string, string> Table name => datetime column. 92 */ 93 public static function retained_tables(): array { 94 return [ 95 Tables::visits() => 'visited_at', 96 Tables::orders() => 'attributed_at', 97 Tables::endpoint_log() => 'requested_at', 98 ]; 99 } 100 101 /** 102 * Delete rows older than $threshold in batches until none remain or 103 * the shared time budget (measured from $start) is used up. 104 * 105 * @return int Rows deleted. 106 */ 107 private function purge( string $table, string $column, string $threshold, float $start ): int { 108 global $wpdb; 109 110 $total = 0; 111 do { 112 $deleted = $wpdb->query( 113 $wpdb->prepare( 114 'DELETE FROM %i WHERE %i < %s LIMIT %d', 115 $table, 116 $column, 117 $threshold, 118 self::BATCH_SIZE 119 ) 120 ); 121 $deleted = is_int( $deleted ) ? $deleted : 0; // false on error: stop. 122 $total += $deleted; 123 } while ( self::BATCH_SIZE === $deleted && ( microtime( true ) - $start ) < $this->time_budget() ); 124 125 return $total; 126 } 127 128 /** 129 * Seam for tests: seconds a run may spend deleting. 130 */ 131 protected function time_budget(): float { 132 return self::TIME_BUDGET; 78 133 } 79 134 } -
blaze-ai-discovery-for-woocommerce/trunk/src/Feed/ChatGptFeedGenerator.php
r3670977 r3673252 7 7 * target_countries, is_eligible_search, is_eligible_checkout. 8 8 * 9 * The catalogue is walked in pages of PAGE_SIZE product IDs, each page is 10 * hydrated, streamed to the feed files and released from the object cache 11 * before the next, so a 5,000-product store generates at the 128M PHP 12 * default. Progress is recorded per page for the admin UI. 13 * 9 14 * @package BlazeAiDiscovery 10 15 */ … … 18 23 class ChatGptFeedGenerator { 19 24 20 /** 21 * Generate the feed as an array of product objects. 25 /** Product IDs fetched and hydrated per page. */ 26 public const PAGE_SIZE = 200; 27 28 /** Catalogue size up to which POST /feed/generate may run on the request thread. */ 29 public const INLINE_LIMIT = 500; 30 31 public const PROGRESS_OPTION = 'blazeaid_feed_progress'; 32 33 /** Transient held while a run is in progress; refreshed per page. */ 34 public const LOCK_TRANSIENT = 'blazeaid_feed_lock'; 35 36 private const LOCK_TTL = 600; 37 38 /** Seconds a run may take; raised where the host allows it. */ 39 private const TIME_LIMIT = 600; 40 41 /** 42 * Published parent products — the progress denominator and the size 43 * check for the inline path. Cheap: a post-status count, no hydration. 44 */ 45 public static function count_products(): int { 46 $counts = wp_count_posts( 'product' ); 47 return (int) ( $counts->publish ?? 0 ); 48 } 49 50 /** 51 * Generate the feed as an array of product objects. Holds every entry 52 * in memory — only for small catalogues and tests; generate_file() 53 * streams instead. 22 54 * 23 55 * @return array[] Array of product feed entries. 24 56 */ 25 57 public static function generate(): array { 26 $products = wc_get_products( [27 'status' => 'publish',28 'limit' => -1,29 'return' => 'objects',30 'type' => [ 'simple', 'external' ],31 ] );32 33 // Also get the default variation of variable products.34 $variable = wc_get_products( [35 'status' => 'publish',36 'limit' => -1,37 'return' => 'objects',38 'type' => [ 'variable' ],39 ] );40 41 58 $feed = []; 42 43 foreach ( $products as $product ) { 59 self::each_entry( 60 static function ( array $entry ) use ( &$feed ): void { 61 $feed[] = $entry; 62 } 63 ); 64 return $feed; 65 } 66 67 /** 68 * Walk the catalogue page by page and hand every feed entry to $sink. 69 * 70 * @param callable $sink Receives one entry array at a time. 71 * @param callable $on_page Optional; receives ( int $products_done, int $products_total ) after each page. 72 * @return int Entries emitted. 73 */ 74 public static function each_entry( callable $sink, ?callable $on_page = null ): int { 75 $total = self::count_products(); 76 $page = 1; 77 $done = 0; 78 $entries = 0; 79 80 do { 81 $ids = wc_get_products( 82 [ 83 'status' => 'publish', 84 'type' => [ 'simple', 'external', 'variable' ], 85 'limit' => self::PAGE_SIZE, 86 'page' => $page, 87 'orderby' => 'ID', 88 'order' => 'ASC', 89 'return' => 'ids', 90 ] 91 ); 92 $ids = is_array( $ids ) ? array_map( 'intval', $ids ) : []; 93 $fetched = count( $ids ); 94 $touched = $ids; 95 96 foreach ( $ids as $id ) { 97 $product = wc_get_product( $id ); 98 if ( $product ) { 99 $entries += self::emit_product( $product, $sink, $touched ); 100 } 101 $done++; 102 } 103 104 if ( $on_page ) { 105 $on_page( $done, max( $total, $done ) ); 106 } 107 self::release_page_cache( $touched ); 108 $page++; 109 } while ( self::PAGE_SIZE === $fetched ); 110 111 return $entries; 112 } 113 114 /** 115 * Emit the entries for one parent product (each published, purchasable 116 * variation for variable products). 117 * 118 * @param \WC_Product $product Parent product. 119 * @param callable $sink Entry receiver. 120 * @param int[] $touched Product IDs loaded during this page (variations are appended). 121 * @return int Entries emitted. 122 */ 123 private static function emit_product( \WC_Product $product, callable $sink, array &$touched ): int { 124 if ( ! $product->is_type( 'variable' ) ) { 44 125 $entry = self::build_entry( $product ); 45 126 if ( $entry ) { 46 $feed[] = $entry; 47 } 48 } 49 50 foreach ( $variable as $product ) { 51 $children = $product->get_children(); 52 if ( empty( $children ) ) { 53 continue; 54 } 55 // Include each visible variation. 56 foreach ( $children as $var_id ) { 57 $variation = wc_get_product( $var_id ); 58 if ( $variation && $variation->is_purchasable() && 'publish' === $variation->get_status() ) { 59 $entry = self::build_entry( $variation, $product ); 60 if ( $entry ) { 61 $feed[] = $entry; 62 } 127 $sink( $entry ); 128 return 1; 129 } 130 return 0; 131 } 132 133 $emitted = 0; 134 foreach ( $product->get_children() as $var_id ) { 135 $var_id = (int) $var_id; 136 $touched[] = $var_id; 137 $variation = wc_get_product( $var_id ); 138 if ( $variation && $variation->is_purchasable() && 'publish' === $variation->get_status() ) { 139 $entry = self::build_entry( $variation, $product ); 140 if ( $entry ) { 141 $sink( $entry ); 142 $emitted++; 63 143 } 64 144 } 65 145 } 66 67 return $feed; 146 return $emitted; 147 } 148 149 /** 150 * Drop what this page loaded from the in-request object cache. Every 151 * product hydration pumps posts, post meta and terms into the runtime 152 * cache; without this a 5,000-product walk exhausts 128M. The runtime 153 * flush leaves a persistent object cache (Redis, Memcached) untouched; 154 * drop-ins without flush_runtime fall back to per-post deletes. 155 * 156 * @param int[] $ids Product and variation IDs loaded during the page. 157 */ 158 private static function release_page_cache( array $ids ): void { 159 if ( function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) && function_exists( 'wp_cache_flush_runtime' ) ) { 160 wp_cache_flush_runtime(); 161 return; 162 } 163 if ( ! function_exists( 'wp_cache_delete' ) ) { 164 return; 165 } 166 foreach ( array_unique( $ids ) as $id ) { 167 wp_cache_delete( $id, 'posts' ); 168 wp_cache_delete( $id, 'post_meta' ); 169 } 68 170 } 69 171 … … 138 240 'mpn' => mb_substr( (string) $product->get_sku(), 0, 70 ), 139 241 'condition' => 'new', 140 'is_eligible_search' => FeedFormatter::bool( true ), 242 'is_eligible_search' => FeedFormatter::bool( self::is_eligible_search( $product, $source ) ), 243 // Checkout eligibility stays false at launch: instant checkout needs the merchant programme's checkout integration. 141 244 'is_eligible_checkout' => FeedFormatter::bool( false ), 142 245 'target_countries' => implode( ',', TargetCountries::list() ), … … 158 261 159 262 /** 263 * A product can be surfaced in ChatGPT search when it is published, can 264 * be bought, is in stock and is not hidden from the catalogue. 265 * 266 * @param \WC_Product $product The product or variation. 267 * @param \WC_Product $source The product whose catalogue visibility applies (the parent for variations). 268 */ 269 public static function is_eligible_search( \WC_Product $product, \WC_Product $source ): bool { 270 return 'publish' === $product->get_status() 271 && $product->is_purchasable() 272 && $product->is_in_stock() 273 && 'hidden' !== $source->get_catalog_visibility(); 274 } 275 276 /** 160 277 * Determine the OpenAI availability value for a product. 161 278 * … … 169 286 170 287 /** 171 * Generate and save the feed to a file. 172 * 173 * @return string|false File path on success, false on failure. 174 */ 175 public static function generate_file(): string { 176 $feed = self::generate(); 177 178 $upload_dir = wp_upload_dir(); 179 $dir = $upload_dir['basedir'] . '/blazeaid'; 180 181 if ( ! file_exists( $dir ) ) { 182 wp_mkdir_p( $dir ); 183 } 184 185 // Initialize WP Filesystem. 186 global $wp_filesystem; 187 if ( ! function_exists( 'WP_Filesystem' ) ) { 188 require_once ABSPATH . 'wp-admin/includes/file.php'; 189 } 190 WP_Filesystem(); 191 192 // Write JSON feed. 193 $json_path = $dir . '/chatgpt-product-feed.json'; 194 $written = $wp_filesystem->put_contents( 195 $json_path, 196 wp_json_encode( $feed, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ), 197 FS_CHMOD_FILE 198 ); 199 200 if ( ! $written ) { 201 return ''; 202 } 203 204 // Write CSV feed (the format OpenAI ingests). 205 $csv_path = $dir . '/chatgpt-product-feed.csv'; 206 $csv_written = $wp_filesystem->put_contents( $csv_path, FeedFormatter::to_csv( $feed ), FS_CHMOD_FILE ); 207 if ( ! $csv_written ) { 208 return ''; 209 } 210 211 // Protect directory. 212 $htaccess = $dir . '/.htaccess'; 213 if ( ! $wp_filesystem->exists( $htaccess ) ) { 214 $wp_filesystem->put_contents( $htaccess, "Options -Indexes\n", FS_CHMOD_FILE ); 215 } 288 * Generate the feed, streaming CSV and JSON to the uploads directory. 289 * 290 * @return string|\WP_Error JSON file path on success. 291 */ 292 public static function generate_file() { 293 $dir = FeedStorage::dir(); 294 if ( is_wp_error( $dir ) ) { 295 self::set_progress( 'error', 0, self::count_products(), $dir->get_error_message() ); 296 return $dir; 297 } 298 299 if ( ! self::lock() ) { 300 return new \WP_Error( 'blazeaid_feed_running', __( 'A feed generation is already running.', 'blaze-ai-discovery-for-woocommerce' ) ); 301 } 302 303 if ( function_exists( 'set_time_limit' ) ) { 304 set_time_limit( self::TIME_LIMIT ); 305 } 306 307 $total = self::count_products(); 308 self::set_progress( 'running', 0, $total ); 309 310 $csv = FeedWriter::open( $dir . '/' . FeedStorage::CSV_FILE ); 311 if ( is_wp_error( $csv ) ) { 312 return self::fail( $csv, $total ); 313 } 314 $json = FeedWriter::open( $dir . '/' . FeedStorage::JSON_FILE ); 315 if ( is_wp_error( $json ) ) { 316 $csv->abort(); 317 return self::fail( $json, $total ); 318 } 319 320 $csv->write( FeedFormatter::csv_header() ); 321 $json->write( "[\n" ); 322 323 $count = 0; 324 $sink = static function ( array $entry ) use ( $csv, $json, &$count ): void { 325 $csv->write( FeedFormatter::csv_row( $entry ) ); 326 $json->write( ( $count ? ",\n" : '' ) . wp_json_encode( $entry, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); 327 $count++; 328 }; 329 $on_page = static function ( int $done, int $total ): void { 330 self::set_progress( 'running', $done, $total ); 331 set_transient( self::LOCK_TRANSIENT, time(), self::LOCK_TTL ); 332 }; 333 334 try { 335 self::each_entry( $sink, $on_page ); 336 } catch ( \Throwable $e ) { 337 $csv->abort(); 338 $json->abort(); 339 return self::fail( new \WP_Error( 'blazeaid_feed_exception', $e->getMessage() ), $total ); 340 } 341 342 $json->write( "\n]\n" ); 343 344 $committed = $csv->commit(); 345 if ( is_wp_error( $committed ) ) { 346 $json->abort(); 347 return self::fail( $committed, $total ); 348 } 349 $committed = $json->commit(); 350 if ( is_wp_error( $committed ) ) { 351 return self::fail( $committed, $total ); 352 } 353 354 FeedStorage::protect_dir( $dir ); 216 355 217 356 // Store metadata. 218 357 update_option( 'blazeaid_feed_generated_at', current_time( 'mysql', true ) ); 219 update_option( 'blazeaid_feed_product_count', count( $feed ) ); 220 221 return $json_path; 358 update_option( 'blazeaid_feed_product_count', $count ); 359 self::set_progress( 'done', $total, $total ); 360 self::unlock(); 361 362 return $json->path(); 363 } 364 365 /** 366 * Record a queued run so the admin UI shows it before the worker starts. 367 */ 368 public static function mark_queued(): void { 369 $progress = self::progress(); 370 if ( 'running' === $progress['state'] ) { 371 return; 372 } 373 self::set_progress( 'queued', 0, self::count_products() ); 374 } 375 376 /** 377 * Progress of the current or last run. A run that stopped reporting 378 * for longer than the lock TTL (killed by memory or time) is reported 379 * as an error rather than running forever. 380 * 381 * @return array{state: string, done: int, total: int, updated_at: string, error: string|null} 382 */ 383 public static function progress(): array { 384 $defaults = [ 385 'state' => 'idle', 386 'done' => 0, 387 'total' => 0, 388 'updated_at' => '', 389 'error' => null, 390 ]; 391 $stored = get_option( self::PROGRESS_OPTION, [] ); 392 $progress = is_array( $stored ) ? array_merge( $defaults, array_intersect_key( $stored, $defaults ) ) : $defaults; 393 394 if ( in_array( $progress['state'], [ 'running', 'queued' ], true ) && '' !== $progress['updated_at'] ) { 395 $age = time() - (int) strtotime( $progress['updated_at'] . ' UTC' ); 396 if ( 'running' === $progress['state'] && $age > self::LOCK_TTL ) { 397 $progress['state'] = 'error'; 398 $progress['error'] = __( 'The last feed run stopped without finishing (out of memory or time?). Try again.', 'blaze-ai-discovery-for-woocommerce' ); 399 } 400 } 401 402 return $progress; 403 } 404 405 /** 406 * @return \WP_Error The error, after recording it. 407 */ 408 private static function fail( \WP_Error $error, int $total ): \WP_Error { 409 self::set_progress( 'error', 0, $total, $error->get_error_message() ); 410 self::unlock(); 411 return $error; 412 } 413 414 private static function set_progress( string $state, int $done, int $total, ?string $error = null ): void { 415 update_option( 416 self::PROGRESS_OPTION, 417 [ 418 'state' => $state, 419 'done' => $done, 420 'total' => $total, 421 'updated_at' => gmdate( 'Y-m-d H:i:s' ), 422 'error' => $error, 423 ], 424 false 425 ); 426 } 427 428 private static function lock(): bool { 429 if ( false !== get_transient( self::LOCK_TRANSIENT ) ) { 430 return false; 431 } 432 set_transient( self::LOCK_TRANSIENT, time(), self::LOCK_TTL ); 433 return true; 434 } 435 436 private static function unlock(): void { 437 delete_transient( self::LOCK_TRANSIENT ); 222 438 } 223 439 … … 226 442 */ 227 443 public static function get_feed_url(): string { 228 $upload_dir = wp_upload_dir(); 229 return $upload_dir['baseurl'] . '/blazeaid/chatgpt-product-feed.csv'; 444 return FeedStorage::csv_url(); 230 445 } 231 446 … … 234 449 */ 235 450 public static function get_json_url(): string { 236 $upload_dir = wp_upload_dir(); 237 return $upload_dir['baseurl'] . '/blazeaid/chatgpt-product-feed.json'; 451 return FeedStorage::json_url(); 238 452 } 239 453 } -
blaze-ai-discovery-for-woocommerce/trunk/src/Feed/FeedFormatter.php
r3668873 r3673252 56 56 */ 57 57 public static function to_csv( array $feed ): string { 58 $out = self:: row( self::COLUMNS);58 $out = self::csv_header(); 59 59 foreach ( $feed as $entry ) { 60 $cells = []; 61 foreach ( self::COLUMNS as $column ) { 62 $cells[] = isset( $entry[ $column ] ) ? (string) $entry[ $column ] : ''; 63 } 64 $out .= self::row( $cells ); 60 $out .= self::csv_row( $entry ); 65 61 } 66 62 return $out; 63 } 64 65 /** 66 * The CSV header line. 67 */ 68 public static function csv_header(): string { 69 return self::row( self::COLUMNS ); 70 } 71 72 /** 73 * One CSV line for an entry keyed by COLUMNS names (missing keys become empty cells). 74 */ 75 public static function csv_row( array $entry ): string { 76 $cells = []; 77 foreach ( self::COLUMNS as $column ) { 78 $cells[] = isset( $entry[ $column ] ) ? (string) $entry[ $column ] : ''; 79 } 80 return self::row( $cells ); 67 81 } 68 82 -
blaze-ai-discovery-for-woocommerce/trunk/src/Feed/FeedScheduler.php
r3666933 r3673252 1 1 <?php 2 2 /** 3 * Schedules daily feed regeneration via Action Scheduler. 3 * Schedules feed regeneration via Action Scheduler: a daily recurring 4 * refresh plus on-demand runs queued by POST /feed/generate. 4 5 * 5 6 * @package BlazeAiDiscovery … … 12 13 class FeedScheduler { 13 14 14 private const HOOK = 'blazeaid_feed_refresh'; 15 public const HOOK = 'blazeaid_feed_refresh'; 16 public const GROUP = 'blazeaid'; 17 18 /** Args of an on-demand run; distinguishes it from the daily recurring action (no args). */ 19 public const MANUAL_ARGS = [ 'trigger' => 'manual' ]; 15 20 16 21 public function register(): void { … … 22 27 */ 23 28 public function schedule(): void { 24 if ( false === as_has_scheduled_action( self::HOOK ) ) {29 if ( false === as_has_scheduled_action( self::HOOK, [], self::GROUP ) ) { 25 30 as_schedule_recurring_action( 26 31 strtotime( 'tomorrow 4:00am' ), … … 28 33 self::HOOK, 29 34 [], 30 'blazeaid'35 self::GROUP 31 36 ); 32 37 } … … 34 39 35 40 /** 36 * Refresh the feed file. 41 * Queue an on-demand run (no duplicate while one is pending). 42 * 43 * @return bool False when Action Scheduler is unavailable. 44 */ 45 public static function enqueue(): bool { 46 if ( ! function_exists( 'as_enqueue_async_action' ) || ! function_exists( 'as_has_scheduled_action' ) ) { 47 return false; 48 } 49 if ( ! as_has_scheduled_action( self::HOOK, self::MANUAL_ARGS, self::GROUP ) ) { 50 as_enqueue_async_action( self::HOOK, self::MANUAL_ARGS, self::GROUP ); 51 } 52 return true; 53 } 54 55 /** 56 * Refresh the feed file (daily and on-demand runs alike). Errors are 57 * recorded in the feed progress option, where the admin page reads them. 37 58 */ 38 59 public function refresh(): void { -
blaze-ai-discovery-for-woocommerce/trunk/src/Feed/FeedValidator.php
r3668873 r3673252 26 26 ]; 27 27 28 /** Both eligibility flags are validated the same way. */ 29 private const ELIGIBILITY_FLAGS = [ 'is_eligible_search', 'is_eligible_checkout' ]; 30 31 /** Rows listed under "issues"; counts keep going past this. */ 32 public const MAX_LISTED_ISSUES = 500; 33 28 34 /** 29 35 * Validate a feed and return issues. 30 36 * 31 37 * @param array[] $feed Array of feed entries. 32 * @return array{valid: int, invalid: int, i ssues: array}38 * @return array{valid: int, invalid: int, ineligible: int, issues: array, checked: int, truncated: bool} 33 39 */ 34 40 public static function validate( array $feed ): array { 35 $valid = 0; 36 $invalid = 0; 37 $issues = []; 41 $result = self::empty_result(); 42 foreach ( $feed as $entry ) { 43 self::tally( (array) $entry, $result ); 44 } 45 return $result; 46 } 38 47 39 foreach ( $feed as $entry ) { 40 $entry_issues = self::validate_entry( $entry ); 48 /** 49 * Validate the written CSV feed line by line, up to $limit rows, so a 50 * large catalogue is never loaded into memory to validate it. 51 * 52 * @param string $path CSV file path. 53 * @param int $limit Rows to check; the result says whether it stopped early. 54 * @return array{valid: int, invalid: int, ineligible: int, issues: array, checked: int, truncated: bool} 55 */ 56 public static function validate_file( string $path, int $limit = 2000 ): array { 57 $result = self::empty_result(); 41 58 42 if ( empty( $entry_issues ) ) { 43 $valid++; 44 } else { 45 $invalid++; 46 $issues[] = [ 47 'product_id' => $entry['item_id'] ?? 'unknown', 48 'title' => $entry['title'] ?? 'Unknown', 49 'issues' => $entry_issues, 50 ]; 51 } 59 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- line-by-line read; WP_Filesystem has no streaming read. 60 $handle = is_readable( $path ) ? fopen( $path, 'rb' ) : false; 61 if ( false === $handle ) { 62 $result['error'] = __( 'The feed file could not be read.', 'blaze-ai-discovery-for-woocommerce' ); 63 return $result; 52 64 } 53 65 66 // Explicit escape '' (no escape character): FeedFormatter writes RFC 67 // 4180 rows that double quotes and never backslash-escape, so a 68 // literal backslash before a quote must stay literal; and PHP 8.4 69 // deprecates relying on the default (one notice per row otherwise). 70 $header = fgetcsv( $handle, null, ',', '"', '' ); 71 if ( ! is_array( $header ) ) { 72 fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose 73 $result['error'] = __( 'The feed file has no header row.', 'blaze-ai-discovery-for-woocommerce' ); 74 return $result; 75 } 76 77 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition 78 while ( false !== ( $row = fgetcsv( $handle, null, ',', '"', '' ) ) ) { 79 if ( [ null ] === $row ) { 80 continue; // Blank line. 81 } 82 if ( $result['checked'] >= $limit ) { 83 $result['truncated'] = true; 84 break; 85 } 86 $entry = []; 87 foreach ( $header as $i => $column ) { 88 $entry[ (string) $column ] = $row[ $i ] ?? ''; 89 } 90 self::tally( $entry, $result ); 91 } 92 93 fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose 94 95 return $result; 96 } 97 98 /** 99 * @return array{valid: int, invalid: int, ineligible: int, issues: array, checked: int, truncated: bool} 100 */ 101 public static function empty_result(): array { 54 102 return [ 55 'valid' => $valid, 56 'invalid' => $invalid, 57 'issues' => $issues, 103 'valid' => 0, 104 'invalid' => 0, 105 'ineligible' => 0, 106 'issues' => [], 107 'checked' => 0, 108 'truncated' => false, 58 109 ]; 110 } 111 112 /** 113 * Count one entry. Hard issues make it invalid; a false search flag is 114 * counted separately (the product is fine, it just will not be surfaced 115 * right now — out of stock, not purchasable) and listed with the reason. 116 */ 117 private static function tally( array $entry, array &$result ): void { 118 $issues = self::validate_entry( $entry ); 119 $eligible = 'true' === ( $entry['is_eligible_search'] ?? '' ); 120 121 $result['checked']++; 122 if ( empty( $issues ) ) { 123 $result['valid']++; 124 } else { 125 $result['invalid']++; 126 } 127 if ( ! $eligible ) { 128 $result['ineligible']++; 129 $issues[] = __( 'is_eligible_search is false (out of stock, not purchasable or hidden from the catalogue) — this product will not appear in ChatGPT search until that changes.', 'blaze-ai-discovery-for-woocommerce' ); 130 } 131 132 if ( ! empty( $issues ) && count( $result['issues'] ) < self::MAX_LISTED_ISSUES ) { 133 $result['issues'][] = [ 134 'product_id' => $entry['item_id'] ?? 'unknown', 135 'title' => $entry['title'] ?? 'Unknown', 136 'issues' => $issues, 137 'eligible' => $eligible, 138 ]; 139 } 59 140 } 60 141 … … 69 150 70 151 foreach ( self::REQUIRED_FIELDS as $field ) { 71 if ( empty( $entry[ $field ] )) {152 if ( ! isset( $entry[ $field ] ) || '' === (string) $entry[ $field ] ) { 72 153 $issues[] = sprintf( 73 154 /* translators: %s: field name */ … … 90 171 } 91 172 92 if ( isset( $entry['is_eligible_search'] ) && 'true' !== $entry['is_eligible_search'] ) { 93 $issues[] = __( 'is_eligible_search is false — this product will not appear in ChatGPT search.', 'blaze-ai-discovery-for-woocommerce' ); 173 foreach ( self::ELIGIBILITY_FLAGS as $flag ) { 174 if ( isset( $entry[ $flag ] ) && '' !== $entry[ $flag ] && ! in_array( $entry[ $flag ], [ 'true', 'false' ], true ) ) { 175 $issues[] = sprintf( 176 /* translators: %s: field name */ 177 __( '%s must be "true" or "false".', 'blaze-ai-discovery-for-woocommerce' ), 178 $flag 179 ); 180 } 94 181 } 95 182 -
blaze-ai-discovery-for-woocommerce/trunk/src/LlmsTxt/LlmsTxtRewriter.php
r3670977 r3673252 12 12 class LlmsTxtRewriter { 13 13 14 /** Regex key of the rule in $wp_rewrite->extra_rules_top. */ 15 public const RULE_REGEX = '^llms\.txt$'; 16 17 /** Query string the rule rewrites to. */ 18 public const RULE_TARGET = 'index.php?blazeaid_llms_txt=1'; 19 20 /** 21 * Option set by the install flow; the next init adds the rule and then 22 * flushes, so the persisted rules contain it. The activation request 23 * itself cannot do that in general: the plugin file is included after 24 * init has fired, so a flush there runs before the rule exists. 25 * 26 * Consumed by writing 0, never deleted: maybe_flush() reads it on every 27 * request, and a missing option is a SELECT per request on a site 28 * without a persistent object cache, while a present one rides along 29 * with the autoloaded options. 30 */ 31 public const FLUSH_OPTION = 'blazeaid_flush_rewrite'; 32 33 /** init priority of the deferred flush; after every add_rewrite_rule() at the default priority. */ 34 public const FLUSH_PRIORITY = 99; 35 14 36 public function register(): void { 15 37 add_action( 'init', [ $this, 'add_rewrite_rule' ] ); 38 add_action( 'init', [ $this, 'maybe_flush' ], self::FLUSH_PRIORITY ); 16 39 add_filter( 'query_vars', [ $this, 'add_query_var' ] ); 40 add_filter( 'redirect_canonical', [ $this, 'skip_canonical_redirect' ], 10, 2 ); 17 41 add_action( 'template_redirect', [ $this, 'serve' ] ); 18 42 } 19 43 44 /** 45 * redirect_canonical: with a trailing-slash permalink structure, core 46 * answers /llms.txt with a 301 to /llms.txt/ before our template_redirect 47 * runs. The file is the canonical URL; serve it at 200 directly. 48 * 49 * @param string|false $redirect_url Where core wants to send the request. 50 * @param string $requested_url The URL requested. 51 * @return string|false False for our request (no redirect), else unchanged. 52 */ 53 public function skip_canonical_redirect( $redirect_url, $requested_url = '' ) { 54 if ( get_query_var( 'blazeaid_llms_txt' ) ) { 55 return false; 56 } 57 58 $path = is_string( $requested_url ) ? (string) wp_parse_url( $requested_url, PHP_URL_PATH ) : ''; 59 if ( 'llms.txt' === basename( $path ) && '/' !== substr( $path, -1 ) ) { 60 return false; 61 } 62 63 return $redirect_url; 64 } 65 20 66 public function add_rewrite_rule(): void { 21 add_rewrite_rule( '^llms\.txt$', 'index.php?blazeaid_llms_txt=1', 'top' ); 67 add_rewrite_rule( self::RULE_REGEX, self::RULE_TARGET, 'top' ); 68 } 69 70 /** 71 * Take the rule out of the in-memory rewrite object so a flush that 72 * follows (deactivation) persists rules without it. 73 */ 74 public function remove_rewrite_rule(): void { 75 global $wp_rewrite; 76 if ( is_object( $wp_rewrite ) && isset( $wp_rewrite->extra_rules_top ) && is_array( $wp_rewrite->extra_rules_top ) ) { 77 unset( $wp_rewrite->extra_rules_top[ self::RULE_REGEX ] ); 78 } 79 } 80 81 /** 82 * Ask the next init to flush (after the rule is added). Per site, so it 83 * is the right call under switch_to_blog() too. 84 */ 85 public static function schedule_flush(): void { 86 update_option( self::FLUSH_OPTION, 1 ); 87 } 88 89 /** 90 * init:99 — consume the flush request: rule first, then a soft flush. 91 */ 92 public function maybe_flush(): void { 93 if ( ! get_option( self::FLUSH_OPTION ) ) { 94 return; 95 } 96 self::consume_flush(); 97 $this->add_rewrite_rule(); 98 flush_rewrite_rules( false ); 99 } 100 101 /** 102 * Single-site activation: add the rule, then flush, in this request, so 103 * /llms.txt answers straight away instead of on the next init. 104 */ 105 public function flush_now(): void { 106 self::consume_flush(); 107 $this->add_rewrite_rule(); 108 flush_rewrite_rules(); 109 } 110 111 /** 112 * Deactivation: the plugin is loaded, so init added the rule; drop it 113 * before flushing or /llms.txt keeps answering with the homepage. 114 */ 115 public function flush_without_rule(): void { 116 $this->remove_rewrite_rule(); 117 flush_rewrite_rules(); 118 } 119 120 /** 121 * Deactivation of a site we are switched into (network deactivation): 122 * flush_rewrite_rules() would persist the *current* site's rewrite 123 * structure — $wp_rewrite is not per site — into this one. Drop the 124 * persisted rules instead; core regenerates them, without our rule, 125 * on that site's next request. 126 */ 127 public function drop_persisted_rules(): void { 128 $this->remove_rewrite_rule(); 129 delete_option( 'rewrite_rules' ); 130 } 131 132 /** Mark the deferred flush done, keeping the option autoloaded (see FLUSH_OPTION). */ 133 private static function consume_flush(): void { 134 update_option( self::FLUSH_OPTION, 0 ); 22 135 } 23 136 -
blaze-ai-discovery-for-woocommerce/trunk/src/Rest/AuditController.php
r3672021 r3673252 10 10 class AuditController { 11 11 12 /** PHP time limit for a forced inline run: t wo self-fetches plus a 25 s cloud call. */12 /** PHP time limit for a forced inline run: the loopback checks plus the 12 s cloud budget. */ 13 13 public const INLINE_TIME_LIMIT = 90; 14 14 … … 87 87 /** 88 88 * Run the audit on the request thread. A forced run raises the time 89 * limit where the host allows it and drops the still-pending queued90 * copy of the action first, so the queue does not repeat this audit91 * later. A copy already being processed by a cron run is not affected92 * and may still finish; whichever run saves last is the latest audit.89 * limit where the host allows it and, when Action Scheduler can pick 90 * the rest up, gives the cloud checks a shared budget 91 * (AuditRunner::INLINE_CLOUD_BUDGET): local rows come back complete, 92 * cloud rows that did not fit come back `pending`. 93 93 * 94 * @return array{results: array, overall_status: string} 94 * The queued copy of the action is touched only after the inline result 95 * is saved — a proxy or PHP-FPM kill mid-run leaves the queue as it was. 96 * Then: rows pending → make sure a background audit is queued to 97 * replace them; nothing pending → drop the queued copy so the queue 98 * does not repeat this audit. A copy already being processed by a cron 99 * run is not affected; whichever run saves last is the latest audit. 100 * 101 * @return array{results: array, overall_status: string, pending: bool} 95 102 */ 96 103 private function run_inline( bool $force ): array { 97 if ( $force ) { 98 if ( function_exists( 'set_time_limit' ) ) { 99 set_time_limit( self::INLINE_TIME_LIMIT ); 100 } 101 if ( function_exists( 'as_unschedule_action' ) ) { 104 if ( $force && function_exists( 'set_time_limit' ) ) { 105 set_time_limit( self::INLINE_TIME_LIMIT ); 106 } 107 108 $budgeted = $force && $this->scheduler_available(); 109 $options = $budgeted ? [ 'cloud_budget' => $this->inline_cloud_budget() ] : []; 110 111 $audit = ( new AuditRunner() )->run( $options ); 112 113 if ( $force && $this->scheduler_available() ) { 114 if ( ! empty( $audit['pending'] ) ) { 115 if ( ! as_has_scheduled_action( AuditModule::AUDIT_HOOK, null, AuditModule::AUDIT_GROUP ) ) { 116 as_enqueue_async_action( AuditModule::AUDIT_HOOK, [], AuditModule::AUDIT_GROUP ); 117 } 118 } elseif ( function_exists( 'as_unschedule_action' ) ) { 102 119 as_unschedule_action( AuditModule::AUDIT_HOOK, [], AuditModule::AUDIT_GROUP ); 103 120 } 104 121 } 105 122 106 $runner = new AuditRunner(); 107 return $runner->run(); 123 return $audit; 124 } 125 126 /** 127 * Seam for tests: seconds the cloud checks share on a forced inline run. 128 */ 129 protected function inline_cloud_budget(): float { 130 return (float) AuditRunner::INLINE_CLOUD_BUDGET; 108 131 } 109 132 -
blaze-ai-discovery-for-woocommerce/trunk/src/Rest/FeedController.php
r3668873 r3673252 6 6 7 7 use BlazeAiDiscovery\Feed\ChatGptFeedGenerator; 8 use BlazeAiDiscovery\Feed\FeedScheduler; 9 use BlazeAiDiscovery\Feed\FeedStorage; 8 10 use BlazeAiDiscovery\Feed\FeedValidator; 9 11 10 12 class FeedController { 13 14 /** Rows of the written CSV that GET /feed/validate checks. */ 15 public const VALIDATE_ROWS = 2000; 11 16 12 17 public function register(): void { … … 21 26 'callback' => [ $this, 'generate' ], 22 27 'permission_callback' => [ $this, 'check_permission' ], 28 'args' => [ 29 'force' => [ 30 'type' => 'boolean', 31 'default' => false, 32 'description' => 'Generate on this request instead of queueing; honoured only for catalogues up to the inline limit.', 33 ], 34 ], 23 35 ] ); 24 36 … … 40 52 } 41 53 42 public function generate(): \WP_REST_Response { 43 $path = ChatGptFeedGenerator::generate_file(); 54 /** 55 * Queue a feed run on Action Scheduler and answer 202 {queued, progress}; 56 * the client polls GET /feed/status until progress.state is done or 57 * error. `{ force: true }` runs it on this request (200) when the 58 * catalogue is small enough to hydrate within a request's memory and 59 * time; the inline path is also used when Action Scheduler is missing. 60 * 61 * @param \WP_REST_Request|null $request Null only from direct callers (tests). 62 */ 63 public function generate( $request = null ): \WP_REST_Response { 64 $force = is_object( $request ) && method_exists( $request, 'get_param' ) 65 ? rest_sanitize_boolean( $request->get_param( 'force' ) ) 66 : false; 44 67 45 if ( empty( $path ) ) { 46 return new \WP_REST_Response( [ 'error' => 'Failed to generate feed file.' ], 500 ); 68 $total = ChatGptFeedGenerator::count_products(); 69 $scheduler = $this->scheduler_available(); 70 71 if ( ! $scheduler && $total > ChatGptFeedGenerator::INLINE_LIMIT ) { 72 // Nothing can run this in the background, and running it on the 73 // request would hit the memory or time limit part way through. 74 return new \WP_REST_Response( 75 [ 76 'error' => sprintf( 77 /* translators: 1: number of products in the catalogue, 2: largest catalogue generated on a request */ 78 __( 'This catalogue has %1$s products, more than the %2$s a single request can generate, and Action Scheduler (part of WooCommerce) is not available to run it in the background. Make sure WooCommerce is active and up to date, then try again.', 'blaze-ai-discovery-for-woocommerce' ), 79 number_format_i18n( $total ), 80 number_format_i18n( ChatGptFeedGenerator::INLINE_LIMIT ) 81 ), 82 'code' => 'blazeaid_feed_no_scheduler', 83 ] + $this->status_payload(), 84 503 85 ); 47 86 } 48 87 49 $upload_dir = wp_upload_dir(); 50 $csv_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.csv'; 51 $json_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.json'; 88 $inline = ! $scheduler || ( $force && $total <= ChatGptFeedGenerator::INLINE_LIMIT ); 52 89 53 return new \WP_REST_Response( [ 54 'message' => __( 'Feed generated successfully.', 'blaze-ai-discovery-for-woocommerce' ), 55 'download_url' => file_exists( $csv_path ) ? ChatGptFeedGenerator::get_feed_url() : null, 56 'json_url' => file_exists( $json_path ) ? ChatGptFeedGenerator::get_json_url() : null, 57 'product_count' => (int) get_option( 'blazeaid_feed_product_count', 0 ), 58 'generated_at' => get_option( 'blazeaid_feed_generated_at', '' ), 59 ] ); 90 if ( $inline ) { 91 $result = ChatGptFeedGenerator::generate_file(); 92 if ( is_wp_error( $result ) ) { 93 $status = 'blazeaid_feed_running' === $result->get_error_code() ? 409 : 500; 94 return new \WP_REST_Response( 95 [ 96 'error' => $result->get_error_message(), 97 'code' => $result->get_error_code(), 98 ] + $this->status_payload(), 99 $status 100 ); 101 } 102 return new \WP_REST_Response( 103 [ 'message' => __( 'Feed generated successfully.', 'blaze-ai-discovery-for-woocommerce' ) ] + $this->status_payload() 104 ); 105 } 106 107 FeedScheduler::enqueue(); 108 ChatGptFeedGenerator::mark_queued(); 109 110 return new \WP_REST_Response( [ 'queued' => true ] + $this->status_payload(), 202 ); 60 111 } 61 112 62 113 public function get_status(): \WP_REST_Response { 63 $generated = get_option( 'blazeaid_feed_generated_at', '' ); 64 65 $upload_dir = wp_upload_dir(); 66 $csv_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.csv'; 67 $json_path = $upload_dir['basedir'] . '/blazeaid/chatgpt-product-feed.json'; 68 69 return new \WP_REST_Response( [ 70 'generated_at' => $generated, 71 'product_count' => (int) get_option( 'blazeaid_feed_product_count', 0 ), 72 'download_url' => file_exists( $csv_path ) ? ChatGptFeedGenerator::get_feed_url() : null, 73 'json_url' => file_exists( $json_path ) ? ChatGptFeedGenerator::get_json_url() : null, 74 ] ); 114 return new \WP_REST_Response( $this->status_payload() ); 75 115 } 76 116 117 /** 118 * Validate the written CSV, up to VALIDATE_ROWS rows, without loading 119 * the catalogue. 120 */ 77 121 public function validate(): \WP_REST_Response { 78 $feed = ChatGptFeedGenerator::generate(); 79 $validation = FeedValidator::validate( $feed ); 122 $path = FeedStorage::csv_path(); 123 if ( ! file_exists( $path ) ) { 124 return new \WP_REST_Response( FeedValidator::empty_result() + [ 'available' => false ] ); 125 } 80 126 81 return new \WP_REST_Response( $validation ); 127 return new \WP_REST_Response( FeedValidator::validate_file( $path, self::VALIDATE_ROWS ) + [ 'available' => true ] ); 128 } 129 130 /** 131 * @return array{generated_at: string, product_count: int, download_url: ?string, json_url: ?string, progress: array, total_products: int, inline_limit: int} 132 */ 133 private function status_payload(): array { 134 return [ 135 'generated_at' => (string) get_option( 'blazeaid_feed_generated_at', '' ), 136 'product_count' => (int) get_option( 'blazeaid_feed_product_count', 0 ), 137 'download_url' => file_exists( FeedStorage::csv_path() ) ? FeedStorage::csv_url() : null, 138 'json_url' => file_exists( FeedStorage::json_path() ) ? FeedStorage::json_url() : null, 139 'progress' => ChatGptFeedGenerator::progress(), 140 'total_products' => ChatGptFeedGenerator::count_products(), 141 'inline_limit' => ChatGptFeedGenerator::INLINE_LIMIT, 142 ]; 143 } 144 145 /** 146 * Seam for tests: whether Action Scheduler's enqueue/lookup functions exist. 147 */ 148 protected function scheduler_available(): bool { 149 return function_exists( 'as_enqueue_async_action' ) && function_exists( 'as_has_scheduled_action' ); 82 150 } 83 151 } -
blaze-ai-discovery-for-woocommerce/trunk/src/Schema/CompatibilityDetector.php
r3666933 r3673252 3 3 * Detects which SEO/schema plugin owns Product schema output. 4 4 * 5 * Only ONE system owns Product schema at a time (Yoast and Rank Math both6 * disable WooCommerce's native WC_Structured_Data when active).5 * Only the Yoast WooCommerce SEO add-on and Rank Math (with its WooCommerce 6 * module) replace WooCommerce's native WC_Structured_Data; Yoast free does not. 7 7 * 8 8 * @package BlazeAiDiscovery … … 22 22 23 23 /** 24 * Test seam: when non-null, used instead of the live environment. 25 * 26 * @var array|null 27 */ 28 public static $environment_override = null; 29 30 /** 31 * What is installed, as booleans. Product-schema OWNERSHIP is decided in detect(). 32 */ 33 protected static function environment(): array { 34 if ( null !== self::$environment_override ) { 35 return self::$environment_override; 36 } 37 return [ 38 'yoast' => defined( 'WPSEO_VERSION' ), 39 'yoast_woo' => defined( 'WPSEO_WOO_VERSION' ) || class_exists( 'WPSEO_WooCommerce_Schema' ), 40 'rank_math' => defined( 'RANK_MATH_VERSION' ), 41 'schema_pro' => class_exists( 'Schema_Pro_Core' ) || defined( 'BSF_SCHEMAS_VERSION' ), 42 'wc_structured_data' => class_exists( 'WC_Structured_Data' ), 43 ]; 44 } 45 46 /** 24 47 * Detect which schema system is active. 25 48 * … … 27 50 */ 28 51 public static function detect(): string { 29 // Priority order: Yoast > Rank Math > Schema Pro > WooCommerce native > standalone. 30 if ( defined( 'WPSEO_VERSION' ) ) { 52 $env = self::environment(); 53 54 // Yoast owns Product schema only with the WooCommerce SEO add-on. 55 // Yoast free leaves WooCommerce's own Product JSON-LD in place (adm-F6). 56 if ( $env['yoast'] && $env['yoast_woo'] ) { 31 57 return self::YOAST; 32 58 } 33 59 34 if ( defined( 'RANK_MATH_VERSION' )) {60 if ( $env['rank_math'] ) { 35 61 return self::RANK_MATH; 36 62 } 37 63 38 if ( class_exists( 'Schema_Pro_Core' ) || defined( 'BSF_SCHEMAS_VERSION' )) {64 if ( $env['schema_pro'] ) { 39 65 return self::SCHEMA_PRO; 40 66 } 41 67 42 if ( class_exists( 'WC_Structured_Data' )) {68 if ( $env['wc_structured_data'] ) { 43 69 return self::WOOCOMMERCE_NATIVE; 44 70 } 45 71 46 72 return self::STANDALONE; 73 } 74 75 /** 76 * Whether a given plugin/add-on is installed, independent of schema 77 * ownership. Reads the same environment array as detect() (including 78 * the test override), so callers never need defined() directly. 79 * 80 * @param string $flag One of the environment() array keys, e.g. 'yoast'. 81 */ 82 public static function installed( string $flag ): bool { 83 $env = self::environment(); 84 85 return ! empty( $env[ $flag ] ); 47 86 } 48 87 -
blaze-ai-discovery-for-woocommerce/trunk/src/Schema/SchemaModule.php
r3666933 r3673252 28 28 29 29 public function register(): void { 30 // Schema strategy selection runs immediately (needs to hook early). 31 $this->orchestrator->init(); 30 // Plugin load order is alphabetical, so this module's register() (on 31 // plugins_loaded) can run before an SEO plugin has bootstrapped - 32 // e.g. Rank Math's \RankMath\Helper::is_module_active() would then 33 // report every module off, and RankMathStrategy would wrongly 34 // register the native WooCommerce fallback alongside Rank Math's own 35 // Product block. Defer to init:0, after every plugin's plugins_loaded 36 // callback has run; the augment filters themselves fire far later 37 // (wp_footer / structured-data generation), so nothing is lost. 38 add_action( 'init', [ $this->orchestrator, 'init' ], 0 ); 32 39 } 33 40 -
blaze-ai-discovery-for-woocommerce/trunk/src/Schema/SchemaOrchestrator.php
r3666933 r3673252 42 42 43 43 case CompatibilityDetector::SCHEMA_PRO: 44 // Schema Pro has limited filter API — use standalone with @id references. 45 $this->strategy = new StandaloneStrategy(); 44 // Schema Pro does not replace WC_Structured_Data — augment 45 // WooCommerce's block; a second standalone block would 46 // duplicate Product with conflicting prices (adm-F8). 47 $this->strategy = new WooCommerceNativeStrategy(); 46 48 break; 47 49 -
blaze-ai-discovery-for-woocommerce/trunk/src/Schema/Strategies/RankMathStrategy.php
r3666933 r3673252 4 4 * 5 5 * Uses rank_math/json_ld (priority 15) to modify the Product node. 6 * Handles both single-object and @graph structures. 6 * Handles @graph structures, Rank Math's real flat keyed entity map 7 * (@context/@graph are added after this filter runs), and single-object 8 * structures. 7 9 * 8 10 * @package BlazeAiDiscovery … … 19 21 public function register(): void { 20 22 add_filter( 'rank_math/json_ld', [ $this, 'augment' ], 15, 2 ); 23 24 $module_on = false; 25 if ( class_exists( '\RankMath\Helper' ) && method_exists( '\RankMath\Helper', 'is_module_active' ) ) { 26 $module_on = (bool) \RankMath\Helper::is_module_active( 'woocommerce' ); 27 } 28 29 // Rank Math leaves WooCommerce's native Product block in place 30 // unless its "Remove Schema.org Markup" toggle is on. We augment 31 // the WC block only when Rank Math's WooCommerce module is off 32 // (Rank Math then emits no Product node of its own); when the 33 // module is on we never touch the WC block, so we don't extend a 34 // duplicate-block configuration. 35 if ( ! $module_on ) { 36 add_filter( 'woocommerce_structured_data_product', [ new WooCommerceNativeStrategy(), 'augment' ], 20, 2 ); 37 } 21 38 } 22 39 … … 46 63 } 47 64 return $json_ld; 65 } 66 67 // Rank Math passes a flat keyed map of entities and wraps it in 68 // @context/@graph AFTER this filter (adm-F7). Augment any 69 // Product-like value; leave every other entity untouched. Gated on 70 // the payload itself not being a typed node — otherwise a single 71 // Product node with a nested Product-like property (e.g. 72 // isRelatedTo) would have only the nested node augmented here, 73 // short-circuiting before the top-level node is ever touched. 74 if ( ! isset( $json_ld['@type'] ) ) { 75 $augmented = false; 76 foreach ( $json_ld as $key => $value ) { 77 if ( is_array( $value ) && isset( $value['@type'] ) && $this->is_product_type( $value['@type'] ) ) { 78 $json_ld[ $key ] = $this->augment_product_node( $value, $product ); 79 $augmented = true; 80 } 81 } 82 if ( $augmented ) { 83 return $json_ld; 84 } 48 85 } 49 86 -
blaze-ai-discovery-for-woocommerce/trunk/src/Schema/Strategies/StandaloneStrategy.php
r3666933 r3673252 14 14 use BlazeAiDiscovery\Schema\Builders\ProductSchemaBuilder; 15 15 16 // Unreachable in production: WooCommerce is a hard requirement (Requires 17 // Plugins in the plugin header), so WC_Structured_Data always exists and 18 // CompatibilityDetector never returns STANDALONE on a real store. Kept only 19 // so the detector's STANDALONE branch has a strategy to instantiate. 16 20 class StandaloneStrategy implements StrategyInterface { 17 21 -
blaze-ai-discovery-for-woocommerce/trunk/src/Scoring/BatchScorer.php
r3671993 r3673252 4 4 * 5 5 * Processes up to 50 products per chunk, checks memory/time between each, 6 * schedules next chunk with 5s delay. Progress stored in transient. 6 * schedules the next chunk with a 5 s delay. Progress lives in a transient; 7 * a lock option keeps a second chain from starting while one runs. 8 * 9 * Every chunk resumes from the last product id actually scored (an SQL 10 * `ID > last LIMIT 50` cursor), so a chunk cut short by the time or memory 11 * limit continues where it stopped instead of being counted complete. A 12 * chunk that makes no progress at all is retried at most three times, and a 13 * chunk that dies without reporting back is restarted by the healthcheck at 14 * most three times; after that the run is marked `failed` with a reason. 7 15 * 8 16 * @package BlazeAiDiscovery … … 19 27 private const HEALTHCHECK = 'blazeaid_batch_score_healthcheck'; 20 28 public const PROGRESS_KEY = 'blazeaid_scoring_progress'; 29 public const LOCK_OPTION = 'blazeaid_scoring_lock'; 21 30 private const CHUNK_SIZE = 50; 22 31 private const DELAY_SECONDS = 5; … … 24 33 private const MEMORY_PERCENT = 90; 25 34 35 /** Progress transient lifetime: a large catalogue on a WP-Cron-paced queue takes hours, not one. */ 36 private const PROGRESS_TTL = DAY_IN_SECONDS; 37 38 /** A lock older than this (no chunk has reported back) belongs to a dead chain. */ 39 public const LOCK_TTL = 15 * MINUTE_IN_SECONDS; 40 41 /** Attempts a chunk gets before the run is marked failed (both no-progress retries and healthcheck restarts). */ 42 public const MAX_CHUNK_ATTEMPTS = 3; 43 26 44 /** 27 45 * Register hooks. … … 34 52 /** 35 53 * Start a full catalog scoring run. 36 */ 37 public function start(): void { 54 * 55 * @return bool False when a chain is already running (fresh lock): nothing was started. 56 */ 57 public function start(): bool { 58 if ( self::locked() ) { 59 return false; 60 } 61 62 // A stale chain (lock expired) may still have chunk actions queued; 63 // they would score the same ids twice under the new run. 64 as_unschedule_all_actions( self::HOOK ); 65 38 66 $total = (int) wp_count_posts( 'product' )->publish; 39 67 … … 43 71 'total' => $total, 44 72 'started_at' => time(), 73 'updated_at' => time(), 45 74 'last_product_id' => 0, 46 ], HOUR_IN_SECONDS ); 75 'chunk_after_id' => 0, 76 'chunk_attempts' => 0, 77 'restart_from' => null, 78 'restarts' => 0, 79 ], self::PROGRESS_TTL ); 80 81 update_option( self::LOCK_OPTION, time(), false ); 47 82 48 83 // Schedule first chunk immediately. 49 as_enqueue_async_action( self::HOOK, [ 0 ], 'blazeaid');84 as_enqueue_async_action( self::HOOK, [ 0 ], self::GROUP ); 50 85 51 86 // Schedule healthcheck. … … 56 91 self::HEALTHCHECK, 57 92 [], 58 'blazeaid'93 self::GROUP 59 94 ); 60 95 } 96 97 return true; 98 } 99 100 /** 101 * Whether a chain is running and reported back within LOCK_TTL. 102 */ 103 public static function locked(): bool { 104 $progress = self::get_progress(); 105 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 106 return false; 107 } 108 109 $lock = (int) get_option( self::LOCK_OPTION, 0 ); 110 111 return $lock > 0 && ( time() - $lock ) < self::LOCK_TTL; 61 112 } 62 113 … … 67 118 */ 68 119 public function process_chunk( int $after_id ): void { 69 $scorer = new ProductScorer(); 70 $start = microtime( true ); 71 $scored = 0; 72 $last_id = $after_id; 73 74 $products = wc_get_products( [ 75 'status' => 'publish', 76 'limit' => self::CHUNK_SIZE, 77 'orderby' => 'ID', 78 'order' => 'ASC', 79 'return' => 'objects', 80 'type' => [ 'simple', 'variable', 'grouped', 'external' ], 81 'include' => [], 82 'exclude' => [], 83 // Get products with ID > $after_id. 84 ] ); 85 86 // Manual filter for ID > after_id since wc_get_products doesn't support it directly. 87 $filtered = []; 88 foreach ( $products as $product ) { 89 if ( $product->get_id() > $after_id ) { 90 $filtered[] = $product; 91 } 92 } 93 94 // If manual filter returned nothing, use a direct query. 95 if ( empty( $filtered ) ) { 96 global $wpdb; 97 $ids = $wpdb->get_col( 98 $wpdb->prepare( 99 "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' AND ID > %d ORDER BY ID ASC LIMIT %d", 100 $after_id, 101 self::CHUNK_SIZE 102 ) 103 ); 104 foreach ( $ids as $id ) { 105 $product = wc_get_product( (int) $id ); 106 if ( $product ) { 107 $filtered[] = $product; 108 } 109 } 110 } 111 112 foreach ( $filtered as $product ) { 120 $progress = self::get_progress(); 121 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 122 return; // Cancelled, failed or finished meanwhile. 123 } 124 125 $start = microtime( true ); 126 $scored = 0; 127 $last_id = $after_id; 128 $cut = false; 129 $ids = $this->product_ids_after( $after_id, self::CHUNK_SIZE ); 130 131 foreach ( $ids as $id ) { 113 132 // Check resource limits before each product. 114 133 if ( $this->time_exceeded( $start ) || $this->memory_exceeded() ) { 134 $cut = true; 115 135 break; 116 136 } 117 137 118 $result = $scorer->score( $product ); 119 ScoreStore::save( $product->get_id(), $result ); 120 121 $last_id = $product->get_id(); 138 $this->score_one( $id ); 139 140 $last_id = $id; 122 141 $scored++; 123 142 } 124 143 125 // Update progress. 126 $progress = get_transient( self::PROGRESS_KEY ); 127 if ( is_array( $progress ) ) { 128 $progress['scored'] += $scored; 129 $progress['last_product_id'] = $last_id; 130 131 if ( empty( $filtered ) || count( $filtered ) < self::CHUNK_SIZE ) { 132 // All done. 133 $progress['status'] = 'complete'; 134 as_unschedule_all_actions( self::HEALTHCHECK, [], 'blazeaid' ); 144 // Re-read: cancel() may have run meanwhile. 145 $progress = self::get_progress(); 146 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 147 return; 148 } 149 150 $progress['scored'] = (int) ( $progress['scored'] ?? 0 ) + $scored; 151 $progress['last_product_id'] = $last_id; 152 $progress['updated_at'] = time(); 153 154 if ( 0 === $scored && ! empty( $ids ) ) { 155 // Not one product fit: the host is out of time or memory before 156 // the first product. Retry this chunk a bounded number of times. 157 $attempts = ( (int) ( $progress['chunk_after_id'] ?? -1 ) === $after_id ) ? (int) ( $progress['chunk_attempts'] ?? 0 ) + 1 : 1; 158 159 $progress['chunk_after_id'] = $after_id; 160 $progress['chunk_attempts'] = $attempts; 161 162 if ( $attempts >= self::MAX_CHUNK_ATTEMPTS ) { 163 $this->fail( $progress, sprintf( 164 /* translators: 1: number of attempts, 2: product ID the chunk starts after */ 165 __( 'Scoring stopped: the chunk after product ID %2$d could not process a single product within the time or memory limit in %1$d attempts. Raise the PHP memory limit or run WP-Cron from a server cron, then click Recalculate All.', 'blaze-ai-discovery-for-woocommerce' ), 166 $attempts, 167 $after_id 168 ) ); 169 return; 135 170 } 136 171 137 set_transient( self::PROGRESS_KEY, $progress, HOUR_IN_SECONDS ); 138 } 139 140 // Schedule next chunk if there's more. 141 if ( ! empty( $filtered ) && count( $filtered ) >= self::CHUNK_SIZE ) { 142 as_schedule_single_action( 143 time() + self::DELAY_SECONDS, 144 self::HOOK, 145 [ $last_id ], 146 'blazeaid' 147 ); 148 } 149 } 150 151 /** 152 * Healthcheck: restart if progress stalled. 172 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 173 update_option( self::LOCK_OPTION, time(), false ); 174 $this->schedule_chunk( $after_id ); 175 return; 176 } 177 178 $progress['chunk_after_id'] = $last_id; 179 $progress['chunk_attempts'] = 0; 180 181 // Complete only when this was the last page and nothing cut it short. 182 if ( ! $cut && count( $ids ) < self::CHUNK_SIZE ) { 183 $progress['status'] = 'complete'; 184 $progress['completed_at'] = time(); 185 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 186 as_unschedule_all_actions( self::HEALTHCHECK ); 187 delete_option( self::LOCK_OPTION ); 188 return; 189 } 190 191 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 192 update_option( self::LOCK_OPTION, time(), false ); 193 $this->schedule_chunk( $last_id ); 194 } 195 196 /** 197 * Healthcheck: restart from the last scored id when no chunk is 198 * pending or in progress (the last one died without reporting back). Three restarts 199 * from the same position mean the chunk cannot run here; mark failed. 153 200 */ 154 201 public function check_health(): void { 155 $progress = get_transient( self::PROGRESS_KEY ); 156 157 if ( ! is_array( $progress ) || 'running' !== $progress['status'] ) { 158 as_unschedule_all_actions( self::HEALTHCHECK, [], 'blazeaid' ); 159 return; 160 } 161 162 // Check if there's already a pending chunk action. 163 $pending = as_get_scheduled_actions( [ 202 $progress = self::get_progress(); 203 204 if ( ! is_array( $progress ) || 'running' !== ( $progress['status'] ?? '' ) ) { 205 as_unschedule_all_actions( self::HEALTHCHECK ); 206 return; 207 } 208 209 // A chunk that is pending OR currently executing is alive — a 210 // mid-execution chunk is not stalled, and restarting over it 211 // would start a duplicate chain (red-team verification finding, 212 // 2026-08-31). 213 $alive = as_get_scheduled_actions( [ 164 214 'hook' => self::HOOK, 165 'status' => \ActionScheduler_Store::STATUS_PENDING,166 'group' => 'blazeaid',215 'status' => [ \ActionScheduler_Store::STATUS_PENDING, \ActionScheduler_Store::STATUS_RUNNING ], 216 'group' => self::GROUP, 167 217 ] ); 168 218 169 if ( empty( $pending ) ) { 170 // Stalled — re-enqueue from last position. 171 as_enqueue_async_action( 172 self::HOOK, 173 [ $progress['last_product_id'] ], 174 'blazeaid' 175 ); 176 } 219 if ( ! empty( $alive ) ) { 220 return; 221 } 222 223 $from = (int) ( $progress['last_product_id'] ?? 0 ); 224 $restarts = ( isset( $progress['restart_from'] ) && (int) $progress['restart_from'] === $from ) ? (int) ( $progress['restarts'] ?? 0 ) + 1 : 1; 225 226 $progress['restart_from'] = $from; 227 $progress['restarts'] = $restarts; 228 229 if ( $restarts > self::MAX_CHUNK_ATTEMPTS ) { 230 $this->fail( $progress, sprintf( 231 /* translators: 1: number of restarts, 2: product ID scoring stalled after */ 232 __( 'Scoring stopped: the background job died after product ID %2$d and did not get further in %1$d restarts (a PHP fatal or a killed worker, most likely). Check the site\'s error log, then click Recalculate All.', 'blaze-ai-discovery-for-woocommerce' ), 233 self::MAX_CHUNK_ATTEMPTS, 234 $from 235 ) ); 236 return; 237 } 238 239 $progress['updated_at'] = time(); 240 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 241 update_option( self::LOCK_OPTION, time(), false ); 242 243 // Stalled — re-enqueue from last position. 244 as_enqueue_async_action( self::HOOK, [ $from ], self::GROUP ); 177 245 } 178 246 … … 191 259 */ 192 260 public function cancel(): void { 193 as_unschedule_all_actions( self::HOOK , [], 'blazeaid');194 as_unschedule_all_actions( self::HEALTHCHECK , [], 'blazeaid');261 as_unschedule_all_actions( self::HOOK ); 262 as_unschedule_all_actions( self::HEALTHCHECK ); 195 263 delete_transient( self::PROGRESS_KEY ); 196 } 197 198 private function time_exceeded( float $start ): bool { 264 delete_option( self::LOCK_OPTION ); 265 } 266 267 /** 268 * Mark the run failed with a reason the Products page can show, and 269 * tear the chain down. 270 */ 271 private function fail( array $progress, string $reason ): void { 272 $progress['status'] = 'failed'; 273 $progress['reason'] = $reason; 274 $progress['failed_at'] = time(); 275 set_transient( self::PROGRESS_KEY, $progress, self::PROGRESS_TTL ); 276 277 as_unschedule_all_actions( self::HOOK ); 278 as_unschedule_all_actions( self::HEALTHCHECK ); 279 delete_option( self::LOCK_OPTION ); 280 } 281 282 private function schedule_chunk( int $after_id ): void { 283 as_schedule_single_action( 284 time() + self::DELAY_SECONDS, 285 self::HOOK, 286 [ $after_id ], 287 self::GROUP 288 ); 289 } 290 291 /** 292 * Published product ids after $after_id, ascending, at most $limit. 293 * 294 * @return int[] 295 */ 296 protected function product_ids_after( int $after_id, int $limit ): array { 297 global $wpdb; 298 299 $ids = $wpdb->get_col( 300 $wpdb->prepare( 301 "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' AND ID > %d ORDER BY ID ASC LIMIT %d", 302 $after_id, 303 $limit 304 ) 305 ); 306 307 return array_map( 'intval', is_array( $ids ) ? $ids : [] ); 308 } 309 310 /** 311 * Score and store one product. Products of a type the scorer does not 312 * handle (subscriptions, bundles) are skipped but still advance the 313 * cursor. Seam for tests. 314 */ 315 protected function score_one( int $product_id ): void { 316 $product = wc_get_product( $product_id ); 317 if ( ! $product || ! in_array( $product->get_type(), [ 'simple', 'variable', 'grouped', 'external' ], true ) ) { 318 return; 319 } 320 321 $result = ( new ProductScorer() )->score( $product ); 322 ScoreStore::save( $product_id, $result ); 323 } 324 325 protected function time_exceeded( float $start ): bool { 199 326 return ( microtime( true ) - $start ) > self::TIME_LIMIT; 200 327 } 201 328 202 pr ivatefunction memory_exceeded(): bool {329 protected function memory_exceeded(): bool { 203 330 $limit = $this->get_memory_limit(); 204 331 return ( memory_get_usage( true ) / $limit ) * 100 > self::MEMORY_PERCENT; -
blaze-ai-discovery-for-woocommerce/trunk/src/Scoring/Criteria/IdentifierPresence.php
r3666933 r3673252 52 52 $product_id = $product->get_id(); 53 53 54 // WooCommerce native GTIN field (added in WC 9.2+). 55 $gtin = $product->get_global_unique_id(); 56 if ( ! empty( $gtin ) ) { 57 return (string) $gtin; 54 // WooCommerce native GTIN field. The getter only exists from WC 9.2; 55 // on 8.0-9.1 an unguarded call fatals every product page and save. 56 if ( method_exists( $product, 'get_global_unique_id' ) ) { 57 $gtin = $product->get_global_unique_id(); 58 if ( ! empty( $gtin ) ) { 59 return (string) $gtin; 60 } 58 61 } 59 62 60 // Common meta keys from various plugins. 63 // Common meta keys from various plugins. `_global_unique_id` is the 64 // meta WC 9.2+ stores the native field in, so a store that ran a newer 65 // WooCommerce (or a migration that wrote it directly) keeps its GTINs 66 // on an older core too. 61 67 $meta_keys = [ 68 '_global_unique_id', 62 69 '_gtin', 63 70 'gtin', -
blaze-ai-discovery-for-woocommerce/trunk/uninstall.php
r3671993 r3673252 1 1 <?php 2 2 /** 3 * Clean uninstall — drop tables, remove options. 3 * Clean uninstall — drop tables, remove options. On multisite every site is 4 * cleaned (plugins can only be deleted from the network admin, so an 5 * uninstall there is always network-wide). 4 6 * 5 7 * @package BlazeAiDiscovery … … 8 10 defined( 'WP_UNINSTALL_PLUGIN' ) || exit; 9 11 10 global $wpdb; 12 /** 13 * Remove everything this plugin stored for the current site. 14 */ 15 function blazeaid_uninstall_site(): void { 16 global $wpdb; 11 17 12 // Drop custom tables.13 $blazeaid_tables = [14 $wpdb->prefix . 'blazeaid_visits',15 $wpdb->prefix . 'blazeaid_orders',16 $wpdb->prefix . 'blazeaid_scores',17 $wpdb->prefix . 'blazeaid_endpoint_log',18 $wpdb->prefix . 'blazeaid_audits',19 ];18 // Drop custom tables. 19 $blazeaid_tables = [ 20 $wpdb->prefix . 'blazeaid_visits', 21 $wpdb->prefix . 'blazeaid_orders', 22 $wpdb->prefix . 'blazeaid_scores', 23 $wpdb->prefix . 'blazeaid_endpoint_log', 24 $wpdb->prefix . 'blazeaid_audits', 25 ]; 20 26 21 foreach ( $blazeaid_tables as $blazeaid_table ) { 22 $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $blazeaid_table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 27 foreach ( $blazeaid_tables as $blazeaid_table ) { 28 $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $blazeaid_table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 29 } 30 31 // Remove options. 32 $blazeaid_options = [ 33 'blazeaid_db_version', 34 'blazeaid_version', 35 'blazeaid_pending_install', 36 'blazeaid_flush_rewrite', 37 'blazeaid_scoring_lock', 38 'blazeaid_feed_progress', 39 'blazeaid_payload_salt', 40 'blazeaid_visitor_salt', 41 'blazeaid_license_key', 42 'blazeaid_license_status', 43 'blazeaid_needs_activation_audit', 44 'blazeaid_llms_txt_content', 45 'blazeaid_return_policy', 46 'blazeaid_cloud_consent', 47 'blazeaid_feed_generated_at', 48 'blazeaid_feed_product_count', 49 'blazeaid_llms_txt_description', 50 'blazeaid_site_token', 51 'blazeaid_visibility_last_run', 52 'blazeaid_onboarding', 53 'blazeaid_installed_at', 54 'blazeaid_scoring_bootstrapped', 55 'blazeaid_needs_first_scoring', 56 ]; 57 58 foreach ( $blazeaid_options as $blazeaid_option ) { 59 delete_option( $blazeaid_option ); 60 } 61 62 // Unschedule Action Scheduler jobs: every hook by name, then the group. 63 if ( function_exists( 'as_unschedule_all_actions' ) ) { 64 try { 65 as_unschedule_all_actions( 'blazeaid_retention_cleanup' ); 66 as_unschedule_all_actions( 'blazeaid_batch_score' ); 67 as_unschedule_all_actions( 'blazeaid_batch_score_healthcheck' ); 68 as_unschedule_all_actions( 'blazeaid_feed_refresh' ); 69 as_unschedule_all_actions( 'blazeaid_run_audit' ); 70 as_unschedule_all_actions( 'blazeaid_visibility_refresh' ); 71 as_unschedule_all_actions( 'blazeaid_visibility_monthly' ); 72 as_unschedule_all_actions( '', [], 'blazeaid' ); 73 } catch ( \Throwable $blazeaid_e ) { 74 unset( $blazeaid_e ); // Action Scheduler tables gone: nothing to cancel. 75 } 76 } 77 78 delete_transient( 'blazeaid_scoring_progress' ); 79 80 $blazeaid_upload = wp_upload_dir(); 81 $blazeaid_feed_dir = trailingslashit( $blazeaid_upload['basedir'] ) . 'blazeaid'; 82 if ( is_dir( $blazeaid_feed_dir ) ) { 83 require_once ABSPATH . 'wp-admin/includes/file.php'; 84 if ( WP_Filesystem() ) { 85 global $wp_filesystem; 86 if ( $wp_filesystem instanceof WP_Filesystem_Base ) { 87 $wp_filesystem->delete( $blazeaid_feed_dir, true ); 88 } 89 } 90 } 91 92 // Transient-backed throttles, daily caps, the probe cache and the schema 93 // retry marker: delete them now rather than waiting for expiry (the 94 // timeout rows would otherwise linger until the next cron sweep). 95 // esc_like() turns every underscore in the prefix into an explicit `\_` 96 // so LIKE does not treat it as a wildcard. 97 $blazeaid_transient_like = $wpdb->esc_like( '_transient_blazeaid_' ) . '%'; 98 $blazeaid_timeout_like = $wpdb->esc_like( '_transient_timeout_blazeaid_' ) . '%'; 99 $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 100 $wpdb->prepare( 101 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared 102 $blazeaid_transient_like, 103 $blazeaid_timeout_like 104 ) 105 ); 23 106 } 24 107 25 // Remove options. 26 $blazeaid_options = [ 27 'blazeaid_db_version', 28 'blazeaid_payload_salt', 29 'blazeaid_visitor_salt', 30 'blazeaid_license_key', 31 'blazeaid_license_status', 32 'blazeaid_needs_activation_audit', 33 'blazeaid_llms_txt_content', 34 'blazeaid_return_policy', 35 'blazeaid_cloud_consent', 36 'blazeaid_feed_generated_at', 37 'blazeaid_feed_product_count', 38 'blazeaid_llms_txt_description', 39 'blazeaid_site_token', 40 'blazeaid_visibility_last_run', 41 'blazeaid_onboarding', 42 'blazeaid_installed_at', 43 'blazeaid_scoring_bootstrapped', 44 'blazeaid_needs_first_scoring', 45 ]; 46 47 foreach ( $blazeaid_options as $blazeaid_option ) { 48 delete_option( $blazeaid_option ); 108 if ( is_multisite() ) { 109 $blazeaid_site_ids = get_sites( 110 [ 111 'fields' => 'ids', 112 'number' => 0, 113 'deleted' => 0, 114 ] 115 ); 116 foreach ( (array) $blazeaid_site_ids as $blazeaid_site_id ) { 117 switch_to_blog( (int) $blazeaid_site_id ); 118 blazeaid_uninstall_site(); 119 restore_current_blog(); 120 } 121 } else { 122 blazeaid_uninstall_site(); 49 123 } 50 124 51 // Unschedule Action Scheduler jobs.52 if ( function_exists( 'as_unschedule_all_actions' ) ) {53 as_unschedule_all_actions( 'blazeaid_retention_cleanup' );54 as_unschedule_all_actions( 'blazeaid_batch_score' );55 as_unschedule_all_actions( 'blazeaid_feed_refresh' );56 }57 58 delete_transient( 'blazeaid_scoring_progress' );59 if ( function_exists( 'as_unschedule_all_actions' ) ) {60 as_unschedule_all_actions( 'blazeaid_run_audit' );61 as_unschedule_all_actions( 'blazeaid_batch_score_healthcheck' );62 as_unschedule_all_actions( 'blazeaid_visibility_refresh' );63 as_unschedule_all_actions( 'blazeaid_visibility_monthly' );64 }65 $blazeaid_upload = wp_upload_dir();66 $blazeaid_feed_dir = trailingslashit( $blazeaid_upload['basedir'] ) . 'blazeaid';67 if ( is_dir( $blazeaid_feed_dir ) ) {68 require_once ABSPATH . 'wp-admin/includes/file.php';69 if ( WP_Filesystem() ) {70 global $wp_filesystem;71 if ( $wp_filesystem instanceof WP_Filesystem_Base ) {72 $wp_filesystem->delete( $blazeaid_feed_dir, true );73 }74 }75 }76 // Transient-backed throttles, daily caps and the probe cache: delete them77 // now rather than waiting for expiry (the timeout rows would otherwise78 // linger until the next cron sweep). esc_like() turns every underscore in79 // the prefix into an explicit `\_` so LIKE does not treat it as a wildcard.80 $blazeaid_transient_like = $wpdb->esc_like( '_transient_blazeaid_' ) . '%';81 $blazeaid_timeout_like = $wpdb->esc_like( '_transient_timeout_blazeaid_' ) . '%';82 $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching83 $wpdb->prepare(84 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared85 $blazeaid_transient_like,86 $blazeaid_timeout_like87 )88 );89 125 wp_cache_flush(); -
blaze-ai-discovery-for-woocommerce/trunk/vendor/composer/autoload_classmap.php
r3672021 r3673252 33 33 'BlazeAiDiscovery\\Audit\\Checks\\RobotsTxt' => $baseDir . '/src/Audit/Checks/RobotsTxt.php', 34 34 'BlazeAiDiscovery\\Audit\\Checks\\SslActive' => $baseDir . '/src/Audit/Checks/SslActive.php', 35 'BlazeAiDiscovery\\Audit\\Checks\\StoreVisibility' => $baseDir . '/src/Audit/Checks/StoreVisibility.php', 35 36 'BlazeAiDiscovery\\Audit\\Checks\\WooCommerceVersion' => $baseDir . '/src/Audit/Checks/WooCommerceVersion.php', 36 37 'BlazeAiDiscovery\\Audit\\CrawlerAccess\\CrawlerAccessCheck' => $baseDir . '/src/Audit/CrawlerAccess/CrawlerAccessCheck.php', … … 53 54 'BlazeAiDiscovery\\Container' => $baseDir . '/src/Container.php', 54 55 'BlazeAiDiscovery\\Database\\DatabaseModule' => $baseDir . '/src/Database/DatabaseModule.php', 56 'BlazeAiDiscovery\\Database\\Installer' => $baseDir . '/src/Database/Installer.php', 55 57 'BlazeAiDiscovery\\Database\\Migrator' => $baseDir . '/src/Database/Migrator.php', 56 58 'BlazeAiDiscovery\\Database\\RetentionCleanup' => $baseDir . '/src/Database/RetentionCleanup.php', … … 60 62 'BlazeAiDiscovery\\Feed\\FeedModule' => $baseDir . '/src/Feed/FeedModule.php', 61 63 'BlazeAiDiscovery\\Feed\\FeedScheduler' => $baseDir . '/src/Feed/FeedScheduler.php', 64 'BlazeAiDiscovery\\Feed\\FeedStorage' => $baseDir . '/src/Feed/FeedStorage.php', 62 65 'BlazeAiDiscovery\\Feed\\FeedValidator' => $baseDir . '/src/Feed/FeedValidator.php', 66 'BlazeAiDiscovery\\Feed\\FeedWriter' => $baseDir . '/src/Feed/FeedWriter.php', 63 67 'BlazeAiDiscovery\\Feed\\TargetCountries' => $baseDir . '/src/Feed/TargetCountries.php', 64 68 'BlazeAiDiscovery\\Jobs\\JobsModule' => $baseDir . '/src/Jobs/JobsModule.php', -
blaze-ai-discovery-for-woocommerce/trunk/vendor/composer/autoload_static.php
r3672021 r3673252 48 48 'BlazeAiDiscovery\\Audit\\Checks\\RobotsTxt' => __DIR__ . '/../..' . '/src/Audit/Checks/RobotsTxt.php', 49 49 'BlazeAiDiscovery\\Audit\\Checks\\SslActive' => __DIR__ . '/../..' . '/src/Audit/Checks/SslActive.php', 50 'BlazeAiDiscovery\\Audit\\Checks\\StoreVisibility' => __DIR__ . '/../..' . '/src/Audit/Checks/StoreVisibility.php', 50 51 'BlazeAiDiscovery\\Audit\\Checks\\WooCommerceVersion' => __DIR__ . '/../..' . '/src/Audit/Checks/WooCommerceVersion.php', 51 52 'BlazeAiDiscovery\\Audit\\CrawlerAccess\\CrawlerAccessCheck' => __DIR__ . '/../..' . '/src/Audit/CrawlerAccess/CrawlerAccessCheck.php', … … 68 69 'BlazeAiDiscovery\\Container' => __DIR__ . '/../..' . '/src/Container.php', 69 70 'BlazeAiDiscovery\\Database\\DatabaseModule' => __DIR__ . '/../..' . '/src/Database/DatabaseModule.php', 71 'BlazeAiDiscovery\\Database\\Installer' => __DIR__ . '/../..' . '/src/Database/Installer.php', 70 72 'BlazeAiDiscovery\\Database\\Migrator' => __DIR__ . '/../..' . '/src/Database/Migrator.php', 71 73 'BlazeAiDiscovery\\Database\\RetentionCleanup' => __DIR__ . '/../..' . '/src/Database/RetentionCleanup.php', … … 75 77 'BlazeAiDiscovery\\Feed\\FeedModule' => __DIR__ . '/../..' . '/src/Feed/FeedModule.php', 76 78 'BlazeAiDiscovery\\Feed\\FeedScheduler' => __DIR__ . '/../..' . '/src/Feed/FeedScheduler.php', 79 'BlazeAiDiscovery\\Feed\\FeedStorage' => __DIR__ . '/../..' . '/src/Feed/FeedStorage.php', 77 80 'BlazeAiDiscovery\\Feed\\FeedValidator' => __DIR__ . '/../..' . '/src/Feed/FeedValidator.php', 81 'BlazeAiDiscovery\\Feed\\FeedWriter' => __DIR__ . '/../..' . '/src/Feed/FeedWriter.php', 78 82 'BlazeAiDiscovery\\Feed\\TargetCountries' => __DIR__ . '/../..' . '/src/Feed/TargetCountries.php', 79 83 'BlazeAiDiscovery\\Jobs\\JobsModule' => __DIR__ . '/../..' . '/src/Jobs/JobsModule.php', -
blaze-ai-discovery-for-woocommerce/trunk/vendor/composer/installed.php
r3672021 r3673252 2 2 'root' => array( 3 3 'name' => 'blazecommerce/blaze-ai-discovery-for-woocommerce', 4 'pretty_version' => 'v1.1. 2',5 'version' => '1.1. 2.0',6 'reference' => ' 8d6a69dcebcc9972707017c5f3983098d6499808',4 'pretty_version' => 'v1.1.3', 5 'version' => '1.1.3.0', 6 'reference' => 'da0525d966c4d68fc334b81ad1ccd9c2bd7e259c', 7 7 'type' => 'wordpress-plugin', 8 8 'install_path' => __DIR__ . '/../../', … … 12 12 'versions' => array( 13 13 'blazecommerce/blaze-ai-discovery-for-woocommerce' => array( 14 'pretty_version' => 'v1.1. 2',15 'version' => '1.1. 2.0',16 'reference' => ' 8d6a69dcebcc9972707017c5f3983098d6499808',14 'pretty_version' => 'v1.1.3', 15 'version' => '1.1.3.0', 16 'reference' => 'da0525d966c4d68fc334b81ad1ccd9c2bd7e259c', 17 17 'type' => 'wordpress-plugin', 18 18 'install_path' => __DIR__ . '/../../',
Note:
See TracChangeset
for help on using the changeset viewer.