Files
eventLabs/assets/migration.js
josh db4747d85f
All checks were successful
WordPress release / release (push) Successful in 7s
Choose an Elementor event template during or after migration
2026-11-12 15:34:43 -05:00

126 lines
5.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
const form = document.querySelector('[data-be-migrate]');
if (!form) return;
// The hidden WordPress action input shadows the form.action property.
const endpoint = form.getAttribute('action');
const {__, sprintf} = wp.i18n;
const buttons = Array.from(form.querySelectorAll('[data-be-operation]'));
const template = form.querySelector('[name="template_id"]');
const status = form.querySelector('[data-be-migrate-status]');
const errors = form.querySelector('[data-be-migrate-errors]');
const retryableStatuses = new Set([408, 429, 502, 503, 504]);
const messages = {
copy: {
count: 'copied',
starting: __('Copying events…', 'burn-events'),
progress: __('Copying events. %1$d copied, %2$d already copied, %3$d need review.', 'burn-events'),
finished: __('Migration finished. %1$d copied, %2$d already copied, %3$d need review.', 'burn-events'),
paused: __('Migration paused. %1$d copied, %2$d already copied. %3$s', 'burn-events'),
},
apply: {
count: 'applied',
starting: __('Applying the template…', 'burn-events'),
progress: __('Applying the template. %1$d applied, %2$d already assigned, %3$d need review.', 'burn-events'),
finished: __('Template assignment finished. %1$d applied, %2$d already assigned, %3$d need review.', 'burn-events'),
paused: __('Template assignment paused. %1$d applied, %2$d already assigned. %3$s', 'burn-events'),
},
};
let operation = '';
let templateId = '0';
let hasCopies = form.dataset.hasCopies === '1';
let processed = 0;
let skipped = 0;
let after = 0;
function updateControls(busy) {
if (template) template.disabled = busy;
for (const button of buttons) {
const canApply = hasCopies && template && template.value !== '0';
button.disabled = busy || (button.value === 'apply' && !canApply);
}
}
template?.addEventListener('change', () => updateControls(false));
updateControls(false);
async function requestBatch(body) {
for (let attempt = 0; ; attempt++) {
const response = await fetch(endpoint, {
method: 'POST', body, credentials: 'same-origin', headers: {Accept: 'application/json'},
}).catch(() => null);
if (response && (attempt === 2 || !retryableStatuses.has(response.status))) return response;
if (attempt === 2) throw new Error(__('Could not reach WordPress. Try the migration again when the connection is available.', 'burn-events'));
const retryAfter = response?.headers.get('Retry-After');
let delay = (attempt + 1) * 1500;
if (retryAfter) {
const requestedDelay = /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();
if (requestedDelay > 10000) return response;
if (requestedDelay > delay) delay = requestedDelay;
}
status.textContent = __('Waiting to retry the last batch…', 'burn-events');
await new Promise(resolve => setTimeout(resolve, delay));
}
}
async function readBatch(response, count) {
const result = await response.json().catch(() => null);
if (response.ok && result?.success === true) {
const batch = result.data;
const counts = [batch?.[count], batch?.skipped, batch?.next];
if (counts.every(value => Number.isSafeInteger(value) && value >= 0)
&& (batch.next === 0 || batch.next > after) && Array.isArray(batch.errors)) return batch;
}
if (result?.success === false && typeof result.data === 'string' && result.data) throw new Error(result.data);
if (response.status === 401 || (response.redirected && new URL(response.url).pathname.endsWith('/wp-login.php'))) {
throw new Error(__('Your WordPress session has ended. Sign in again and reopen the migration page.', 'burn-events'));
}
throw new Error(sprintf(
response.ok ? __('WordPress returned an unexpected response (HTTP %d). Try the migration again.', 'burn-events')
: __('The migration request failed (HTTP %d). Try the migration again or check the host’s request log for this status.', 'burn-events'),
response.status
));
}
form.addEventListener('submit', async event => {
event.preventDefault();
const button = event.submitter ?? buttons.find(control => !control.disabled);
if (!button || button.disabled) return;
const selectedTemplate = template?.value ?? '0';
if (after === 0 || operation !== button.value || templateId !== selectedTemplate) {
after = 0;
processed = 0;
skipped = 0;
errors.replaceChildren();
}
operation = button.value;
templateId = selectedTemplate;
const labels = messages[operation];
const body = new URLSearchParams(new FormData(form));
body.set('operation', operation);
updateControls(true);
status.textContent = labels.starting;
try {
do {
body.set('after', String(after));
const batch = await readBatch(await requestBatch(body), labels.count);
processed += batch[labels.count];
skipped += batch.skipped;
if (operation === 'copy' && (processed || skipped)) hasCopies = true;
for (const error of batch.errors) {
const item = document.createElement('li');
item.textContent = error;
errors.append(item);
}
after = batch.next;
status.textContent = sprintf(after ? labels.progress : labels.finished, processed, skipped, errors.childElementCount);
} while (after);
} catch (error) {
status.textContent = sprintf(labels.paused, processed, skipped, error.message);
} finally {
updateControls(false);
}
});
})();