Wix Replatform
WixOfficialPublished by Wix
- Skill
- Workflow
- Automation and integrations
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
wix-replatform acts as a central supervisor for migrating data and content to Wix. It does not perform migration tasks directly but instead inspects migration artifacts to determine the next required stage in the pipeline. By maintaining a deterministic state, it ensures that migrations can be started, resumed, or recovered reliably without duplicating work or creating redundant destination sites. It manages the flow through various phases including discovery, mapping, setup, and import, while enforcing strict validation and approval gates.
What it does
- Routes migration tasks to appropriate sub-modules based on current project state.
- Ensures resumability by tracking migration progress through authoritative artifacts.
- Enforces mandatory approval gates before performing write operations.
- Dispatches specialized subagents for specific tasks to maintain context boundaries.
- Validates artifacts at each stage to prevent proceeding with corrupted or stale data.
- Handles reruns for incremental data updates without re-scaffolding the entire project.
When to use it
- When initiating a new migration from an external source to a Wix site.
- When resuming a migration that was interrupted or stopped.
- When recovering from a failed migration stage by addressing specific errors.
- When performing incremental imports to sync new or modified records after an initial migration.
Advantages
- Prevents data duplication by enforcing idempotent write operations.
- Maintains a clear audit trail through structured telemetry and completion reports.
- Reduces risk by requiring explicit approvals before critical setup or import steps.
- Supports both standard interactive flows and automated 1-click execution modes.
Usage examples
- “Start a new migration for my project in ./migrations/my-store.”
- The agent resolves the project directory, initializes orchestration artifacts, and routes to the project intake module.
- “Resume the migration in ./migrations/my-store.”
- The agent inspects the existing artifacts, determines the last completed stage, and dispatches the next required module.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/wix/wix-replatform-fya3/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip wix-replatform.zip -d .agents/skills
Documentation by Wix
wix-replatform
wix-replatform is the compact supervisor for a resumable source-to-Wix migration. It
selects one internal module for the active stage; it does not carry every stage procedure
in its own context.
Always-active contract
Resolve the active project under
migrations/<project>/(orREPLATFORM_MIGRATIONS_DIR) before inspecting or creating anything. Only that project's artifacts are authoritative.Preserve
EXPECTATIONS.mdat that project root. It is the user's free-form record of how they expected the run to behave; initialization creates it once and never overwrites it.Start/resume
resources/rp-telemetry/at the beginning of every run and finalize it at a terminal state. Never hand-write telemetry events.Use orchestration JSON plus validated stage artifacts as resume authority. Logs and chat history are diagnostic context only.
Preserve user data: write idempotently, dedupe by source identity, resume rather than restart, and never create a second destination site for a migration.
Never print secrets, secret-bearing config contents, tokens, or credentials. Report only key names and present/blank/missing status.
Do not declare a migration complete from prose or a single artifact. The deterministic router and aggregate completion artifact own terminal completion.
Preserve the owner's cutover handoff: unresolved data, applicable manual setup, missing apps and changed plugin behavior. Reconcile discovery, mapping decisions, setup receipts and final outcomes; imported records alone do not establish working functionality. The producing resources own this guidance and durable completion/handoff artifacts. Use a supported cutover publisher when available; report missing publication integration explicitly rather than claiming the application received local artifacts.
CLI-launched runs and human actions
When a migration is started through replatform, the terminal is deliberately
non-interactive: do not use an agent question UI, ask for stdin, or wait for a person in the
current agent turn. The runner owns process lifecycle and emits only observed events; it does
not replace this skill's router or completion receipts.
When a human choice, review, approval, or manual prerequisite is needed, create a durable
request with node skills/wix-replatform/scripts/user-action.js create --project <projectDir> --request-file <request.json>, then end the turn. Put only reviewed artifact paths in the
request. The person can later use replatform requests, replatform show, and
replatform answer; a resumed agent reads the answered request from
orchestration/user-actions/, never from reconstructed chat context.
Cancellation is not completion. If the runner has recorded cancel_requested, canceled, interrupted or an explicit stop (blocked,
transition --status blocked --resume-from '<json>'; routes run_blocked until explicit resume or --status running, never answer --continue), preserve partial/recovery
artifacts and let a later explicit replatform resume route recovery. Never create aggregate migration completion from an aborted execution report.
Pipeline
intake → destination → source inputs → preflight → (standard: discovery → mapping → codegen;
quick: adapter preflight → quick plan) → setup discovery → website handoff
→ safety review/approval → setup → import
→ storefront continuation (website only) → aggregate finalization → Migration reviewDelivery modes are management (backend only), website (frontend only), and
management_and_website (the integrated flow above). Accept user input both as
management_and_website and persist the canonical value.
For deliveryMode=management, aggregate finalization requires valid backend import
accounting. For deliveryMode=management_and_website, it additionally requires a current
website/completion.json with completed screenshot review, no unresolved critical/high
gaps, and release evidence. execution/completion-report.json is backend accounting,
never website-migration completion by itself.
Route before acting
On every new or resumed turn:
Resolve the project and initialize/load its orchestration artifacts.
Run
node skills/wix-replatform/scripts/orchestration-route.js <projectDir>.Dispatch the
nextResourceto a Developer subagent instead of loading and following it yourself. Give it the project directory and the resource to run; it follows that resource's contract exactly as written, unchanged. Read back only its result — never its transcript, tool output, or logs.Every dispatch (Developer or QA) is a fresh subagent, never a resumed one; pass only a handoff file and stay within a context budget — follow
resources/rp-subagent-dispatch/. Never readstate/attempts/write-attempts.ndjsonraw; usescripts/write-log-summary.js.A Developer may fan out to sub-subagents only for harmless read-only work with no shared state, and only if the host supports it; writes stay one at a time, as each resource says.
Dispatch a QA subagent to check the Developer's result against that resource's own stated required outputs (its own "artifacts to create or update" or "## Output" section, and any review/gap documents it defines). QA is read-only — it never writes or calls Wix. If something's missing, dispatch a new Developer for the same resource with QA's findings; otherwise the stage is done.
At the end of each pipeline phase (discovery, mapping, setup discovery, import, and so on — see the pipeline above; a phase spans several resource-level stages), dispatch a QA subagent to review that phase's documents as a whole (for example
mapping/review/mapping-summary.mdandmapping-gaps.json, orexecution/completion-report.json) before routing to the next phase. This catches anything a single per-task check could miss. For the import phase specifically, this review must be entity-by-entity against the accepted mapping plan, not a skim of the top-level status string — seerp-execute-import's "Entity-by-entity QA" section. Any run-fixing dispatch mid-phase (a crash fix, a slowness fix, a resumed pass) does not itself satisfy this; run the phase-level QA again once the fix lands, since fixing one entity's defect certifies nothing about its neighbors. Mapping QA also checks exact source coverage, decided operation/path semantics and canonical projections. Codegen QA reads the Developer's independently expected synthetic request evidence and its freshness; it does not execute examples. Semantic defects return to mapper, implementation defects to codegen. One-click tests defer unresolved scope and finish independent work with a typed incomplete result, without questions or repeated redispatch; customer runs retain their existing checkpoints.Route again after every stage boundary. Stale requests use
resources/rp-user-action-recovery/; unreadable request artifacts block until repaired. Never discard pending requests or decide the next stage from memory.
The router (lib/orchestration-router.js) is the only routing and resume authority. It
recomputes the route from decisions, approvals, preflight, run.json status and the phase
outputs on every call; run.json.currentState is diagnostic only, never a routing input.
A recorded rejection stops the route in every mode, one-click included:
execution_approval_rejectedisblockedbefore any setup or import write, andmapping_approval_rejectedreturns torp-mapperfor a new plan.A gated output that exists but is unusable (
source_schema_invalid,mapping_plan_invalid,setup_plan_invalid,setup_requirements_invalid,execution_manifest_invalid) isblockedwitherrorsand the producer asnextResource. Do not re-run the producer automatically; report the errors to the Import Operator and stop.The import routes (
missing_completion_report,import_interrupted= a stopped run's aborted report,quick_mode_import_required) carryimportProgress.interruptedlistsrecoveryArtifacts: resume it, never a second import.interruptedReport: "missing": first runscripts/interrupted-completion-report.js.
If an artifact is malformed, partial, stale, or fails its validator, treat its producing stage as incomplete and route to the producer. Do not make parallel replacement artifacts.
A user action whose reviewed artifacts changed after it was created is refused with
user_action_stale and stays pending. Create a new request from the current artifacts.
Catching up a finished migration is a rerun, not a new project. When the user asks to pull
in records that arrived or changed since the import — "the source kept selling", "these orders
are missing", "re-run it" — reuse the same project, destination, mapping, generated importer
and crosswalk, and route to rp-execute-import → "Rerunning an import for new and modified
records". Do not scaffold a second project or re-approve an unchanged mapping; a
mapping or scope change does go back through the existing gates. A rerun's revision conflicts
are user decisions even in 1-click mode.
Demand-loaded module map
| Router situation | Dispatch |
|---|---|
| project, delivery mode, source mode, or grouped intake is unresolved | resources/rp-project-intake/ |
| destination is absent, conflicting, or needs creation/adoption | resources/rp-destination/ |
| source URL/files/config/acquisition mode/credentials are required, including source credentials said to exist already on another site | resources/rp-source-inputs/ |
| deterministic preflight is missing, repaired, or blocked on CLI checks | resources/rp-preflight/ |
| quick mode needs platform resolution, endpoint preflight, plan, extraction, or import | selected resources/rp-quick-<platform>/ |
| source schema is missing | resources/rp-discovery/ and its selected source adapter |
| mapping is missing or needs review | resources/rp-mapper/ |
| Wix requirements are missing | resources/rp-setup-discovery/ |
| import code/review is missing or stale | resources/rp-import-codegen/ |
| setup verification is missing | resources/rp-execute-setup/ |
| backend completion report is missing | resources/rp-execute-import/ |
| frontend-only work, or integrated website handoff/build/gap loop/release receipt is incomplete | resources/rp-website-continuation/ |
| aggregate completion is missing | resources/rp-execution-policy/ |
| aggregate completion exists but the local review publication or current recap is missing | resources/rp-migration-review/ |
The resource named by the route is the complete stage contract, dispatched as described in "Route before acting" — the main session itself never loads it directly. Only the dispatched Developer loads source-file, secret, scaffolding, or storefront procedures, and only for the stage that actually needs them; nothing about a stage where they're irrelevant is loaded, by the main session or the Developer.
Interaction policy
Normal mode asks only for a missing required input, a genuinely ambiguous active project, or a mandatory write approval. Ask one question at a time unless a module says otherwise.
When the user says add to expectations: <note> (or an unambiguous natural-language
equivalent), append the note to the active project's EXPECTATIONS.md before continuing.
Use scripts/expectations-ledger.js so the entry retains the supplied statement plus safe
current context (stage/state, relevant project-relative artifacts, and known entity/field
labels). Do not treat this as approval or silently change a mapping. Never record secrets,
tokens, raw customer data, or raw source records; redact them if supplied and say so.
Before writes, preserve the mandatory execution-plan approval gate. Read-only discovery, mapping, setup verification, code generation, and review happen before it.
Quick management import mode
When managementImportMode=quick, select the platform adapter only after the deterministic
source probe identifies a compatible platform. Quick mode is a bounded public-data import:
the adapter's versioned quick-mode.json owns its source routes, entity graph, field matrix,
and exclusions. Do not run agentic discovery, mapping, or project-specific code generation for
the quick backend branch. Still run destination setup, application installation, Catalog-V3 and
notification safety checks, execution approval, shared write runtime, crosswalks, and completion
accounting. If no adapter qualifies, persist the unsupported-mode result and ask the user to
select standard mode; never silently fall back.
Halt only for missing/invalid required input, a manual action with no API, or a systemic failure/data-loss risk. A halt must persist the code, evidence, owner, and exact unblock action; never silently stop.
1-click mode
When explicitly requested by the user, record automationMode=one_click with
source=user and apply the following. A missing mode or a one_click value recorded as
deterministic_inference/prior_artifact is normal interactive mode and must not skip a
checkpoint:
collect all still-missing intake values in one grouped request; then do not pause for routine approvals;
record mapping and execution approvals as
approved,decidedBy=agent; skipping a pause without state is invalid;for CSV/file-only runs, validate and accept the required sample preview as the agent; without explicit user-authored one-click, pause for the normal mapping review, sample preview validation, and execution approval;
default to a new isolated site unless an existing destination is explicitly supplied or already pinned, but never default the new site's type (Headless, Studio or Harmony): ask it in the grouped intake; choose website scope deterministically from discovered route families;
retry PATH/tool-resolution failures under the operator's compatible interactive login shell; request required browser/network sandbox escalation and retry before calling it blocked;
retry the obvious recovery before stopping: aligned shell first for PATH/tool failures, then the required escalation retry for sandboxed browser or network/API failures;
continue through the complete selected deliverable. In
management_and_websitemode that includes frontend build, post-build gap analysis, bounded fix loop, and release receipt; when the user selected facelift at intake, it also includes the separate post-clone facelift review;before yielding, re-route. A 1-click run is only
completedwithcompletion/migration-completion.json, orblockedwith a typed durable blocker.
Use the operator's compatible local Node/Yarn shell when recovering from a PATH or tool resolution failure. Machine-specific shell paths belong only in local, git-excluded agent instructions.
Repo-local interactive shell contract: a PATH/tool-resolution failure on first attempt may
mean the command ran under a plain, non-interactive shell that never sourced the operator's
Node/Yarn profile. Resolve the operator's compatible login shell from the local environment or
git-excluded agent instructions, verify that it is executable, and retry the exact same command
through that shell in interactive login mode so the profile that resolves node/yarn/npx
loads. Do not hardcode a machine-specific shell path in this public skill. Only escalate to a
durable blocker if the compatible-shell retry itself fails.
Guardrails
Never bypass a validator, approval-state update, verified notification mute, or Catalog-V3 gate to make a stage appear finished.
websitemeans frontend only;management_and_websitemeans the integrated backend and frontend migration. Never hand the integrated migration destination to the frontend skill or create a second frontend site in that mode.A Studio or Harmony destination (
targetSiteType) is created and verified byrp-destination's coordinator and is never published, unpublished or handed towix-headless-replatform; its website and publication remain operator handoff items.Do not implement a storefront manually when
wix-headless-replatformis unavailable; persist a blocker with the exact required runtime capability.In management mode, still generate
website/handoff.*after setup discovery so a later storefront can start without repeating backend discovery.
Files
- .publish-manifest.json210 B
- ATTRIBUTION.mdAdded by AutoGineer815 B
- CLI.md9.8 KiB
- LICENSELicence file added by AutoGineer1.0 KiB
- README.md11.9 KiB
- SKILL.md16.4 KiB
- VERSION6 B
- console/account.css633 B
- console/app.css5.2 KiB
- console/app.jsScript22.9 KiB
- console/index.html837 B
- console/json.css639 B
- lib/agent-adapters/index.jsScript2.9 KiB
- lib/app-page-routing.jsScript4.3 KiB
- lib/app-requirements.jsScript1.5 KiB
- lib/artifact-freshness.jsScript12.7 KiB
- lib/blocked-data-requests.jsScript21.4 KiB
- lib/cached-json.jsScript1.3 KiB
- lib/catalog-baseline.jsScript23.3 KiB
- lib/census-reconciliation.jsScript22.8 KiB
- lib/cms-collection-compatibility.jsScript2.0 KiB
- lib/completion-report.jsScript124.6 KiB
- lib/config-env.jsScript6.1 KiB
- lib/confirmed-pictures.jsScript6.9 KiB
- lib/crosswalk-adoption.jsScript6.3 KiB
- lib/dependency-proofs.jsScript46.7 KiB
- lib/dependency-readiness.jsScript112.3 KiB
- lib/dependency-recovery.jsScript1.5 KiB
- lib/dependency-waves.jsScript2.1 KiB
- lib/destination-choice.jsScript9.7 KiB
- lib/destination-handoff.jsScript12.5 KiB
- lib/destination-http.jsScript2.7 KiB
- lib/destination-route.jsScript5.1 KiB
- lib/destination.jsScript57.1 KiB
- lib/discovered-census.jsScript11.0 KiB
- lib/discovered-set-status.jsScript15.2 KiB
- lib/document-url-guard.jsScript12.7 KiB
- lib/editor-type.jsScript748 B
- lib/egress-proxy.jsScript20.8 KiB
- lib/entity-qa-attestation.jsScript19.4 KiB
- lib/entity-verification.jsScript1.3 KiB
- lib/execution-capability.jsScript7.3 KiB
- lib/execution-log.jsScript6.4 KiB
- lib/execution-manifest.jsScript10.2 KiB
- lib/execution-state.jsScript5.9 KiB
- lib/expectations-ledger.jsScript3.4 KiB
- lib/extract-ledger.jsScript21.4 KiB
- lib/field-mapping-examples.jsScript7.3 KiB
- lib/generated-plugin-handoff.jsScript8.7 KiB
- lib/import-interruption.jsScript13.6 KiB
- lib/import-readiness-contract.jsScript4.3 KiB
- lib/import-recovery.jsScript54.0 KiB
- lib/import-task-runner.jsScript18.1 KiB
- lib/imported-redirect-targets.jsScript32.5 KiB
- lib/internal-link-reconciliation.jsScript10.7 KiB
- lib/link-audit.jsScript11.1 KiB
- lib/link-census.jsScript11.0 KiB
- lib/link-plan.jsScript9.4 KiB
- lib/link-verification.jsScript18.7 KiB
- lib/link-waivers.jsScript5.8 KiB
- lib/link-write-journal.jsScript1.8 KiB
- lib/local-state.js66.8 KiB
- lib/mapping-field-contract.js54.1 KiB
- lib/mapping-omission-approval.js7.6 KiB
- lib/mapping-recovery.js22.4 KiB
- lib/mapping-resolution.js6.1 KiB
- lib/mapping-target-rules.js7.4 KiB
- lib/member-completion.js31.6 KiB
- lib/member-crosswalk.js2.9 KiB
- lib/member-outcome-registry.js13.6 KiB
- lib/migration-completion.js18.3 KiB
- lib/migration-review-mapping.js21.4 KiB
- lib/migration-review.js73.7 KiB
- lib/multi-step-attempt.js4.4 KiB
- lib/multilingual-public-report.js14.5 KiB
- lib/multilingual-public.js26.3 KiB
- lib/notification-mute.js9.9 KiB
- lib/operation-assessments.js9.8 KiB
- lib/operator-identity.js1.2 KiB
- lib/orchestration-decisions.js8.7 KiB
- lib/orchestration-preflight.js25.1 KiB
- lib/orchestration-router.js50.8 KiB
- lib/orchestration-state.js30.9 KiB
- lib/order-reference-readiness.js2.8 KiB
- lib/output-applicability.js5.0 KiB
- lib/payments-outcome-registry.js9.8 KiB
- lib/plan-order-outcome-registry.js13.1 KiB
- lib/plugin-cms-fallback.js35.1 KiB
- lib/preservation-approval-stamp.js2.8 KiB
- lib/product-media-deferral.js3.8 KiB
- lib/product-videos.js7.1 KiB
- lib/progress-log.js6.6 KiB
- lib/progress-log.sh4.1 KiB
- lib/raw-request-guard.js18.5 KiB
- lib/read-back-approval.js16.1 KiB
- lib/read-back-comparison.js10.5 KiB
- lib/read-back-contract.js37.4 KiB
- lib/read-back-extract.js4.0 KiB
- lib/read-back-gate.js46.6 KiB
- lib/read-back-reads.js2.9 KiB
- lib/read-back-state.js3.4 KiB
- lib/read-back-summary.js6.5 KiB
- lib/rerun-conflicts.js14.5 KiB
- lib/run-controller.js26.3 KiB
- lib/seo-outcome-registry.js3.2 KiB
- lib/setup-producers.js1.3 KiB
- lib/setup-verification.js11.6 KiB
- lib/site-regional-gate.js3.3 KiB
- lib/site-regional-report.js10.3 KiB
- lib/site-regional.js37.0 KiB
- lib/source-access.js11.2 KiB
- lib/source-coverage.js54.0 KiB
- lib/source-location.js10.6 KiB
- lib/source-redirect-capture.js2.6 KiB
- lib/source-regional.js15.5 KiB
- lib/source-secrets.js8.1 KiB
- lib/structured-link-patch.js3.1 KiB
- lib/subagent-handoff.js8.9 KiB
- lib/target-import-support.js18.4 KiB
- lib/task-state.js6.2 KiB
- lib/toolkit-dependencies.js947 B
- lib/url-preservation-report.js20.4 KiB
- lib/url-preservation-state.js27.0 KiB
- lib/url-redirect-plan.js36.3 KiB
- lib/url-verification.js15.5 KiB
- lib/user-action-effects.js2.9 KiB
- lib/user-actions.js18.4 KiB
- lib/vendor-closure.js5.6 KiB
- lib/website-handoff.js60.6 KiB
- lib/wix-auth.js11.0 KiB
- lib/wix-client-callers.js6.7 KiB
- lib/wix-dashboard-url.js1.0 KiB
- lib/write-log-summary.js9.4 KiB
- lib/write-verification-state.js7.9 KiB
- lib/write-verification.js30.0 KiB
- scripts/artifact-freshness.js2.3 KiB
- scripts/census-reconciliation.js781 B
- scripts/cms-fallback.js3.2 KiB
- scripts/cms-item-quota.js3.9 KiB
- scripts/crosswalk-adopt.js3.0 KiB
- scripts/dependency-preflight.js2.2 KiB
- scripts/discovered-census.js867 B
- scripts/discovered-set-status.js1.1 KiB
- scripts/entity-qa-attestation.js4.8 KiB
- scripts/execution-health-check.js19.9 KiB
- scripts/execution-manifest-validate.js1.7 KiB
- scripts/execution-state-prepare.js3.9 KiB
- scripts/expectations-ledger.js1.5 KiB
- scripts/extract-ledger.js1.9 KiB
- scripts/import-contract-verify.js20.4 KiB
- scripts/import-supervise.js16.1 KiB
- scripts/internal-link-audit.js6.5 KiB
- scripts/interrupted-completion-report.js2.7 KiB
- scripts/item-seo-tags-verify.js8.2 KiB
- scripts/link-waiver.js3.8 KiB
- scripts/migration-completion.js3.8 KiB
- scripts/migration-review.js3.7 KiB
- scripts/orchestration-preflight.js3.5 KiB
- scripts/orchestration-route.js3.7 KiB
- scripts/orchestration-state.js18.9 KiB
- scripts/read-back-gate.js11.3 KiB
- scripts/replatform-console.js12.9 KiB
- scripts/replatform.js35.4 KiB
- scripts/site-regional.js2.4 KiB
- scripts/source-secrets.js2.9 KiB
- scripts/subagent-handoff.js2.5 KiB
- scripts/url-redirects.js13.0 KiB
- scripts/user-action.js2.9 KiB
- scripts/vendor-closure.js1.0 KiB
- scripts/website-handoff-generate.js2.3 KiB
- scripts/wix-dashboard-url.js1.6 KiB
- scripts/wix-destination.js6.4 KiB
- scripts/wix-env.js1.5 KiB
- scripts/wix-headless-scaffold.js34.8 KiB
- scripts/write-log-summary.js2.2 KiB
- vendor/README.md604 B
- vendor/commander/LICENSE1.1 KiB
- vendor/commander/index.js711 B
- vendor/commander/lib/argument.js3.1 KiB
- vendor/commander/lib/command.js85.6 KiB
- vendor/commander/lib/error.js1.1 KiB
- vendor/commander/lib/help.js20.3 KiB
- vendor/commander/lib/option.js10.0 KiB
- vendor/commander/lib/suggestSimilar.js2.7 KiB
- vendor/commander/package.json1.6 KiB
scripts/wix-headless-scaffold.js
#!/usr/bin/env node
'use strict';
const { spawn } = require('node:child_process');
const fs = require('node:fs/promises');
const path = require('node:path');
const { readEnvFile, upsertEnvFile, statEnvKeys } = require('../lib/config-env.js');
function usage() {
return [
'Usage:',
' node scripts/wix-headless-scaffold.js --business-name <name> [--folder-name frontend] [--site-template commerce] [--project-dir <dir>]',
'',
'Runs the Wix headless scaffold non-interactively through npm create.',
'The new site is left unpublished (--no-publish); publishing is a cutover step.',
'Idempotent: safe to re-invoke against the same project — adopts an',
'existing destination receipt instead of re-scaffolding, and never spawns a second',
'site when config/wix.env or frontend/wix.config.json already name one.',
].join('\n');
}
function parseArgs(argv) {
const args = {
folderName: 'frontend',
siteTemplate: 'blank',
projectDir: process.cwd(),
};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
switch (token) {
case '--business-name':
args.businessName = argv[i + 1];
i += 1;
break;
case '--folder-name':
args.folderName = argv[i + 1];
i += 1;
break;
case '--site-template':
args.siteTemplate = argv[i + 1];
i += 1;
break;
case '--project-dir':
args.projectDir = argv[i + 1];
i += 1;
break;
case '--help':
case '-h':
args.help = true;
break;
default:
throw new Error(`Unknown argument: ${token}`);
}
}
return args;
}
async function readWixConfig(frontendDir) {
try {
const raw = await fs.readFile(path.join(frontendDir, 'wix.config.json'), 'utf8');
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.siteId === 'string' && parsed.siteId.trim() !== '') {
return parsed;
}
return null;
} catch (error) {
if (error && (error.code === 'ENOENT' || error instanceof SyntaxError)) {
return null;
}
throw error;
}
}
async function readWixEnvValues(wixEnvPath) {
try {
return await readEnvFile(wixEnvPath);
} catch (error) {
if (error && error.code === 'ENOENT') {
return {};
}
throw error;
}
}
async function isNonEmptyDir(dir) {
try {
const entries = await fs.readdir(dir);
return entries.length > 0;
} catch (error) {
if (error && error.code === 'ENOENT') {
return false;
}
throw error;
}
}
function scaffoldCommandArgs(args) {
return [
'--yes',
'create',
'@wix/new@latest',
'--',
'headless',
'--business-name',
args.businessName,
'--folder-name',
args.folderName,
'--site-template',
args.siteTemplate,
// New sites stay unpublished until cutover; RePlatform never publishes.
'--no-publish',
'--skip-install',
];
}
async function defaultSpawnScaffold(args) {
return new Promise((resolve, reject) => {
const child = spawn('npm', scaffoldCommandArgs(args), {
cwd: path.resolve(args.projectDir),
stdio: 'inherit',
});
child.on('error', reject);
child.on('exit', (code, signal) => {
resolve({ code: signal ? 1 : (code == null ? 1 : code) });
});
});
}
// Removes WIX_SCAFFOLD_STATUS entirely (not just blanking its value, which config-env.js's
// upsertEnvFile cannot do and which would itself read back as a present-but-unrecognized
// value) — used only when a spawn-launch failure proves nothing could have been created,
// so the next invocation sees a genuinely untouched config/wix.env, not a lingering marker.
async function clearWixScaffoldStatus(wixEnvPath) {
let raw;
try {
raw = await fs.readFile(wixEnvPath, 'utf8');
} catch (error) {
if (error && error.code === 'ENOENT') {
return;
}
throw error;
}
const hadTrailingNewline = /\r?\n$/.test(raw);
const lines = raw.split(/\r?\n/);
if (hadTrailingNewline && lines[lines.length - 1] === '') {
lines.pop();
}
const kept = lines.filter((line) => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) {
return true;
}
const idx = line.indexOf('=');
return idx === -1 || line.slice(0, idx).trim() !== 'WIX_SCAFFOLD_STATUS';
});
const out = kept.join('\n');
await fs.writeFile(wixEnvPath, out === '' ? '' : `${out}\n`, 'utf8');
}
// Persists WIX_SITE_ID from a confirmed receipt, re-checking for a conflict immediately
// before the write (config/wix.env can change between the top-of-invocation read and now).
// Uses statEnvKeys' placeholder-aware classification for the conflict check —
// comparing the raw value directly treated a template placeholder
// (e.g. WIX_SITE_ID=REPLACE_WITH_REAL_VALUE) as a real, conflicting destination, which
// made this throw instead of persisting on the very first scaffold of a freshly
// templated project, silently discarding the receipt this function exists to confirm.
async function persistSiteId(wixEnvPath, siteId, scaffoldStatus) {
const currentStatus = (await statEnvKeys(wixEnvPath, ['WIX_SITE_ID'])).keys.WIX_SITE_ID;
if (currentStatus === 'present') {
const current = await readWixEnvValues(wixEnvPath);
if (current.WIX_SITE_ID !== siteId) {
throw new Error(
`config/wix.env's WIX_SITE_ID (${current.WIX_SITE_ID}) no longer matches the scaffold's own wix.config.json (${siteId}); refusing to overwrite a different destination.`,
);
}
}
await upsertEnvFile(wixEnvPath, { WIX_SITE_ID: siteId, WIX_SCAFFOLD_STATUS: scaffoldStatus });
}
// A locally-run `npm run dev` (or equivalent) against a scaffolded
// `website`-mode project, driven from a Wix Remote Machine by any
// LLM-based coding client (Claude Code or otherwise), hits two problems
// that are properties of the PROJECT, not of any one client or run:
//
// 1. `@wix/astro`'s auto-injected middleware validates an env schema
// (WIX_CLIENT_INSTANCE_ID etc.) that only lives in gitignored
// `.env.local` — wiped whenever the remote machine environment
// restarts, so the next `npm run dev` throws "MiddlewareCantBeLoaded"
// until `.env.local` is manually regenerated via `wix env pull`. Fixed
// durably by making the project re-pull it itself before every
// dev/build/release, rather than assuming it survives a restart.
// 2. The dev server's own Vite config needs `server.allowedHosts` (a
// LEADING-DOT suffix, e.g. ".remote-machine.wix-code.com" — never a
// literal full hostname, which changes on every fresh remote-machine
// instance and would go stale the moment it's committed) and
// `server.host: true` (bind all interfaces) — without the latter, a
// reverse proxy in front of the dev server can't reach it, surfacing as
// an unexplained 504.
//
// Both are properties of the scaffolded PROJECT (checkpointed, reused
// across every future local run), not of any one invocation — so they're
// applied once, right after a destination is confirmed (see main()), not
// re-derived by hand every time this happens.
const REMOTE_MACHINE_HOST_SUFFIX = '.remote-machine.wix-code.com';
const ENV_PULL_HOOK_SCRIPTS = {
predev: 'wix env pull',
prebuild: 'wix env pull',
prerelease: 'wix env pull',
};
// Same-length "search text" with every comment and string/template literal
// blanked out (non-newline characters replaced with spaces) — so none of
// the structural scanning below can mistake a `{`/`}` or a `vite`/`server`-
// shaped substring living inside a comment or string for real object
// structure. A REAL failure this caught before shipping: `// vite: {}`
// (a commented-out key, sitting elsewhere in the same object) was matched
// as if it were live, and injecting a multiline block right after its `{`
// terminated the `//` comment at the injected text's own leading newline,
// turning a perfectly valid file into one with a syntax error. Positions
// in the returned text line up EXACTLY with the input (only content is
// replaced, never length), so any offset found via the masked text is
// valid for slicing the ORIGINAL text — every call site below uses the
// masked text purely to decide WHERE things are, never to read what they
// actually say. The filler is a non-whitespace character (not a space):
// a value-span scan's trailing `\s*` must stop at the real edge of a
// masked string/comment rather than reading straight through it as if it
// were legitimate padding.
function maskCommentsAndStrings(text) {
let out = '';
let i = 0;
const n = text.length;
while (i < n) {
const ch = text[i];
const next = text[i + 1];
if (ch === '/' && next === '/') {
const start = i;
while (i < n && text[i] !== '\n') i += 1;
out += text.slice(start, i).replace(/[^\n]/g, 'x');
continue;
}
if (ch === '/' && next === '*') {
const start = i;
i += 2;
while (i < n && !(text[i] === '*' && text[i + 1] === '/')) i += 1;
i = Math.min(i + 2, n);
out += text.slice(start, i).replace(/[^\n]/g, 'x');
continue;
}
if (ch === "'" || ch === '"' || ch === '`') {
// Template literals are blanked out WHOLESALE, `${...}` interpolation
// included — this script has no reason to understand one, only to
// never mistake its contents for real object structure elsewhere.
// EXCEPTION: a quoted OBJECT KEY (`"vite": {...}`) must survive
// masking untouched — it's the very thing keyName lookups need to
// find — so anything immediately followed by `:` (the only shape a
// quoted key ever takes here) is left as-is instead of blanked.
const quote = ch;
const start = i;
i += 1;
while (i < n && text[i] !== quote) {
if (text[i] === '\\') i += 1; // skip an escaped character, e.g. \' or \\
i += 1;
}
i = Math.min(i + 1, n);
let j = i;
while (j < n && /\s/.test(text[j])) j += 1;
if (text[j] === ':') {
out += text.slice(start, i);
} else {
out += text.slice(start, i).replace(/[^\n]/g, 'x');
}
continue;
}
out += ch;
i += 1;
}
return out;
}
// Finds the index of the `}` that closes the `{` at openBraceIndex, by
// brace-depth counting rather than a full parse. Callers pass the MASKED
// text (see maskCommentsAndStrings) so a `{`/`}` inside a comment or
// string is never miscounted as real structure; every call site below
// only acts when it found a real, load-bearing structural brace via a
// preceding regex match, and returns -1 (skip, never guess) on anything
// unbalanced.
function findMatchingBrace(text, openBraceIndex) {
let depth = 0;
for (let i = openBraceIndex; i < text.length; i += 1) {
if (text[i] === '{') depth += 1;
else if (text[i] === '}') {
depth -= 1;
if (depth === 0) return i;
}
}
return -1;
}
// Matches keyName EXACTLY — as a bare identifier with no adjoining
// identifier/hyphen characters on either side, or as a fully quoted
// key whose entire quoted content is keyName (same quote character on
// both ends, via the backreference). A plain `["']?\bkeyName["']?` (what
// this replaced) only checks for a quote immediately around keyName, so
// it isn't anchored to the KEY'S own boundaries: "legacy-vite": {...} has
// a real word boundary right before "vite" (a hyphen is a non-word
// character) and no quote is required there since it's optional, so it
// matched as though the key were "vite". Requiring an EXACT bare match or
// an exact quoted match rules that out.
function exactKeyPattern(keyName) {
return `(?:(['"])${keyName}\\1|(?<![\\w$-])${keyName}(?![\\w$-]))`;
}
// Finds `keyName: {` (or the quoted form, `"keyName": {`/`'keyName': {'})
// as a DIRECT child of the object spanning parentOpen..parentClose
// (brace-DEPTH 1 relative to parentOpen) — never a same-named key nested
// deeper (e.g. inside a plugin call's own options object), which a plain
// "search anywhere in this span" regex would wrongly match and then
// corrupt. `text` must be the MASKED text (maskCommentsAndStrings), not
// the original source — this only ever returns POSITIONS, valid against
// either text since masking preserves length.
function findDirectChildBrace(text, parentOpen, parentClose, keyName) {
const pattern = new RegExp(`${exactKeyPattern(keyName)}\\s*:\\s*\\{`, 'g');
pattern.lastIndex = parentOpen + 1;
let match;
while ((match = pattern.exec(text)) !== null) {
if (match.index >= parentClose) return -1;
let depth = 0;
for (let i = parentOpen; i < match.index; i += 1) {
if (text[i] === '{') depth += 1;
else if (text[i] === '}') depth -= 1;
}
if (depth === 1) return match.index + match[0].length - 1;
}
return -1;
}
// Finds `keyName: <value>` (or the quoted key form) as a DIRECT child of
// the object spanning parentOpen..parentClose and returns { start, end }
// bounding <value>'s own source text, or 'ambiguous' if a value was found
// but its extent can't be safely bounded (an odd bracket run), or null if
// the key isn't a direct child at all. A bracketed value ([...]/{...}/
// (...)) is bounded by matching brackets; anything else runs to the next
// same-depth comma or the parent's own closing brace. `text` must be the
// MASKED text — this only ever returns POSITIONS; callers read the actual
// value text back out of the ORIGINAL source at those same positions.
function findDirectChildValueSpan(text, parentOpen, parentClose, keyName) {
const pattern = new RegExp(`${exactKeyPattern(keyName)}\\s*:\\s*`, 'g');
pattern.lastIndex = parentOpen + 1;
let match;
while ((match = pattern.exec(text)) !== null) {
if (match.index >= parentClose) return null;
let depth = 0;
for (let i = parentOpen; i < match.index; i += 1) {
if (text[i] === '{') depth += 1;
else if (text[i] === '}') depth -= 1;
}
if (depth !== 1) continue; // a same-named key nested deeper — keep looking
const valueStart = match.index + match[0].length;
const openChar = text[valueStart];
if (openChar === '[' || openChar === '{' || openChar === '(') {
const closeChar = openChar === '[' ? ']' : openChar === '{' ? '}' : ')';
let bracketDepth = 0;
for (let i = valueStart; i < parentClose; i += 1) {
if (text[i] === openChar) bracketDepth += 1;
else if (text[i] === closeChar) {
bracketDepth -= 1;
if (bracketDepth === 0) return { start: valueStart, end: i + 1 };
}
}
return 'ambiguous';
}
let bracketDepth = 0;
// INCLUSIVE of parentClose itself: a value with no trailing comma
// right before the parent's own closing brace (the common single-line
// case, e.g. `{ host: false }`) must have that `}` actually examined,
// not stop one character short of it.
for (let i = valueStart; i <= parentClose; i += 1) {
const ch = text[i];
if (ch === '[' || ch === '{' || ch === '(') bracketDepth += 1;
else if (ch === ']' || ch === '}' || ch === ')') {
if (bracketDepth === 0) return { start: valueStart, end: i }; // hit the parent's own close
bracketDepth -= 1;
} else if (ch === ',' && bracketDepth === 0) {
return { start: valueStart, end: i };
}
}
return 'ambiguous';
}
return null;
}
function quotedStringInner(valueText) {
const match = valueText.match(/^'([^']*)'$|^"([^"]*)"$/);
return match ? (match[1] ?? match[2]) : null;
}
// Best-effort, conservative: never touches a file it can't recognize the
// shape of. Merges into an EXISTING `vite`/`vite.server` block rather than
// skipping outright just because some unrelated vite config (e.g. plugins,
// or an unrelated nested `server:` inside a plugin's OWN options — never
// matched, since lookups here are depth-scoped to direct children only) is
// already present — a project with any of that must not be left
// permanently unpatched. Same treatment for the two settings themselves:
// presence alone isn't "already handled" — `host: false` and an
// `allowedHosts` array missing our own entry both still reproduce the
// original failure, so an already-effective VALUE is what's left alone,
// not just an already-present key. Only a value this can't safely
// interpret (some other expression — not a literal true/false/string or a
// bracketed array) is warned and left untouched rather than guessed at.
async function patchAstroConfigForRemoteMachinePreview(frontendDir) {
const configPath = path.join(frontendDir, 'astro.config.mjs');
let original;
try {
original = await fs.readFile(configPath, 'utf8');
} catch (error) {
if (error && error.code === 'ENOENT') {
console.warn(`[wix-headless-scaffold] no astro.config.mjs at ${configPath} — skipping preview-host patch.`);
return;
}
throw error;
}
// Used for ALL structural navigation below (finding keys, matching
// braces) — never for reading actual content, which always comes from
// `original` at the same positions (masking preserves length exactly).
const masked = maskCommentsAndStrings(original);
const allowedHostsComment =
`// Any remote machine's dynamic preview hostname (the hash/port prefix\n` +
` // changes per session) — a literal full hostname here would go\n` +
` // stale the moment a remote machine restarts.\n` +
` `;
const hostComment =
`// Bind all interfaces — Vite defaults to 127.0.0.1 only, which the\n` +
` // platform's reverse proxy cannot reach (surfaces as a 504).\n` +
` `;
const allowedHostsProp = `${allowedHostsComment}allowedHosts: ['${REMOTE_MACHINE_HOST_SUFFIX}'],`;
const hostProp = `${hostComment}host: true,`;
const defineMatch = masked.match(/defineConfig\(\s*\{/);
if (!defineMatch) {
console.warn('[wix-headless-scaffold] astro.config.mjs is not a recognizable `defineConfig({...})` — leaving it alone.');
return;
}
const defineOpenBrace = defineMatch.index + defineMatch[0].length - 1;
const defineCloseBrace = findMatchingBrace(masked, defineOpenBrace);
if (defineCloseBrace === -1) {
console.warn('[wix-headless-scaffold] astro.config.mjs has an unbalanced defineConfig({...}) call — leaving it alone.');
return;
}
// Depth-scoped to defineConfig's OWN direct children — never a `vite:`
// key nested inside some other option's value at any deeper level.
const viteOpenBrace = findDirectChildBrace(masked, defineOpenBrace, defineCloseBrace, 'vite');
let patched;
if (viteOpenBrace === -1) {
const insertAt = defineOpenBrace + 1;
const injected = `\n vite: {\n server: {\n ${allowedHostsProp}\n ${hostProp}\n },\n },`;
patched = original.slice(0, insertAt) + injected + original.slice(insertAt);
} else {
const viteCloseBrace = findMatchingBrace(masked, viteOpenBrace);
if (viteCloseBrace === -1) {
console.warn('[wix-headless-scaffold] astro.config.mjs has an unbalanced vite: {...} block — leaving it alone.');
return;
}
// Depth-scoped to vite's OWN direct children — never a `server:` key
// nested inside a plugin's own options within the same vite block.
const serverOpenBrace = findDirectChildBrace(masked, viteOpenBrace, viteCloseBrace, 'server');
if (serverOpenBrace === -1) {
const insertAt = viteOpenBrace + 1;
const injected = `\n server: {\n ${allowedHostsProp}\n ${hostProp}\n },`;
patched = original.slice(0, insertAt) + injected + original.slice(insertAt);
} else {
const serverCloseBrace = findMatchingBrace(masked, serverOpenBrace);
if (serverCloseBrace === -1) {
console.warn('[wix-headless-scaffold] astro.config.mjs has an unbalanced vite.server: {...} block — leaving it alone.');
return;
}
// Collected as {start, end, replacement} spans against the ORIGINAL
// text and applied in one pass, highest offset first, so neither
// edit invalidates the other's already-computed positions.
const edits = [];
let touchedSomething = false;
const allowedHostsValue = findDirectChildValueSpan(masked, serverOpenBrace, serverCloseBrace, 'allowedHosts');
if (allowedHostsValue === null) {
edits.push({ start: serverOpenBrace + 1, end: serverOpenBrace + 1, replacement: `\n ${allowedHostsProp}` });
touchedSomething = true;
} else if (allowedHostsValue === 'ambiguous') {
console.warn('[wix-headless-scaffold] vite.server.allowedHosts is set to something this script cannot safely interpret — leaving it alone.');
} else {
const valueText = original.slice(allowedHostsValue.start, allowedHostsValue.end);
const trimmed = valueText.trim();
if (trimmed === 'true') {
// Vite treats `allowedHosts: true` as "disable the check
// entirely" — already strictly more permissive than what this
// needs, nothing to do.
} else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
if (trimmed.includes(REMOTE_MACHINE_HOST_SUFFIX)) {
// Already covers it.
} else {
const closeBracketAt = allowedHostsValue.start + trimmed.lastIndexOf(']');
const beforeClose = original.slice(allowedHostsValue.start, closeBracketAt).replace(/\s+$/, '');
const isEmpty = /\[\s*$/.test(beforeClose);
const hasTrailingComma = /,\s*$/.test(beforeClose);
const sep = isEmpty ? '' : hasTrailingComma ? ' ' : ', ';
edits.push({
start: closeBracketAt,
end: closeBracketAt,
replacement: `${sep}'${REMOTE_MACHINE_HOST_SUFFIX}'`,
});
touchedSomething = true;
}
} else {
console.warn('[wix-headless-scaffold] vite.server.allowedHosts is set to something this script cannot safely interpret — leaving it alone.');
}
}
const hostValue = findDirectChildValueSpan(masked, serverOpenBrace, serverCloseBrace, 'host');
if (hostValue === null) {
edits.push({ start: serverOpenBrace + 1, end: serverOpenBrace + 1, replacement: `\n ${hostProp}` });
touchedSomething = true;
} else if (hostValue === 'ambiguous') {
console.warn('[wix-headless-scaffold] vite.server.host is set to something this script cannot safely interpret — leaving it alone.');
} else {
const trimmed = original.slice(hostValue.start, hostValue.end).trim();
const quotedInner = quotedStringInner(trimmed);
const isIneffective = trimmed === 'false' || (quotedInner !== null && ['localhost', '127.0.0.1'].includes(quotedInner));
const isKnownEffective = trimmed === 'true' || quotedInner !== null;
if (isIneffective) {
edits.push({ start: hostValue.start, end: hostValue.end, replacement: 'true' });
touchedSomething = true;
} else if (!isKnownEffective) {
console.warn('[wix-headless-scaffold] vite.server.host is set to something this script cannot safely interpret — leaving it alone.');
}
// else: true, or a real, non-localhost bind address — already effective.
}
if (!touchedSomething) {
console.log('[wix-headless-scaffold] vite.server.allowedHosts and host are already effective — nothing to patch.');
return;
}
edits.sort((a, b) => b.start - a.start);
patched = original;
for (const edit of edits) {
patched = patched.slice(0, edit.start) + edit.replacement + patched.slice(edit.end);
}
}
}
await fs.writeFile(configPath, patched);
console.log('[wix-headless-scaffold] patched astro.config.mjs for remote-machine preview (allowedHosts + host).');
}
async function patchPackageJsonEnvPullHooks(frontendDir) {
const pkgPath = path.join(frontendDir, 'package.json');
let pkg;
try {
pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
} catch (error) {
if (error && error.code === 'ENOENT') {
console.warn(`[wix-headless-scaffold] no package.json at ${pkgPath} — skipping env-pull hooks.`);
return;
}
throw error;
}
pkg.scripts = pkg.scripts || {};
let changed = false;
for (const [hook, command] of Object.entries(ENV_PULL_HOOK_SCRIPTS)) {
const existing = pkg.scripts[hook];
if (existing === undefined) {
pkg.scripts[hook] = command;
changed = true;
} else if (!existing.includes(command)) {
// A template's own hook (e.g. a codegen step) does something unrelated
// to env-pulling — compose rather than skip, or it silently never runs
// at all, defeating the whole point of this patch. Idempotent: a hook
// that already contains the command is left alone, never re-composed.
pkg.scripts[hook] = `${command} && ${existing}`;
changed = true;
}
}
if (!changed) {
console.warn('[wix-headless-scaffold] package.json already defines all env-pull hooks — leaving it alone.');
return;
}
await fs.writeFile(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
console.log('[wix-headless-scaffold] added predev/prebuild/prerelease "wix env pull" hooks to package.json.');
}
// Safe to call more than once against the same project directory, including
// after its own prior partial failure. Every branch below either confirms a destination
// receipt before returning success, or fails closed without touching config/wix.env.
async function ensureDestinationReceipt(args, { spawnScaffold = defaultSpawnScaffold } = {}) {
const projectDir = path.resolve(args.projectDir);
const frontendDir = path.join(projectDir, args.folderName);
const wixEnvPath = path.join(projectDir, 'config', 'wix.env');
const siteIdStatus = (await statEnvKeys(wixEnvPath, ['WIX_SITE_ID'])).keys.WIX_SITE_ID;
const envValues = await readWixEnvValues(wixEnvPath);
const wixConfig = await readWixConfig(frontendDir);
if (siteIdStatus === 'present') {
// Case 1: config/wix.env already names a destination — checked first, independent of
// wix.config.json, so an env-only receipt (adopted/existing destination, or a lost
// frontend folder) can never fall through to spawning a second site.
if (wixConfig && wixConfig.siteId !== envValues.WIX_SITE_ID) {
// 1b — conflicting.
throw new Error(
`config/wix.env already has WIX_SITE_ID=${envValues.WIX_SITE_ID}, but ${frontendDir}/wix.config.json names a different siteId=${wixConfig.siteId}. Refusing to create or adopt a second destination — resolve the conflict manually.`,
);
}
// 1a — consistent (wix.config.json is absent, has no siteId, or matches).
const status = envValues.WIX_SCAFFOLD_STATUS;
if (status === undefined || status === 'complete') {
return { siteId: envValues.WIX_SITE_ID };
}
if (status === 'incomplete') {
throw new Error(
`Destination ${envValues.WIX_SITE_ID} already exists, but a prior scaffold attempt did not complete (WIX_SCAFFOLD_STATUS=incomplete). Refusing to spawn again — that would risk a duplicate site. Resolve manually before retrying.`,
);
}
throw new Error(
`config/wix.env has an unrecognized WIX_SCAFFOLD_STATUS value (${JSON.stringify(status)}); expected "complete", "incomplete", or the key to be absent. Refusing to proceed.`,
);
}
// Case 2: no confirmed real WIX_SITE_ID (missing, blank, or a placeholder — all treated
// alike here, matching case 1's classification). This branch
// must also inspect WIX_SCAFFOLD_STATUS, not just wix.config.json's existence — a bare
// "wix.config.json exists" check cannot tell a genuinely legacy/host-adopted receipt
// apart from one left behind by a scaffold attempt this script itself started but never
// finished recording (the wrapper crashed, or was killed, after the CLI created the site
// but before persistSiteId ran). Silently adopting the latter as "complete" is the same
// laundering bug as case 1 exists to prevent, just reached from the opposite direction.
const status = envValues.WIX_SCAFFOLD_STATUS;
if (status === 'in_progress') {
if (wixConfig) {
// A prior invocation marked in_progress before spawning (see 2c below) and never
// got to record a final outcome. The CLI may well have finished — never infer
// "complete" from an orphaned receipt like this. Persist it as incomplete (the same
// durable, fail-closed record a known non-zero exit produces) so the *next*
// invocation adopts and blocks via case 1's existing, tested handling instead of
// this ambiguity recurring indefinitely.
await persistSiteId(wixEnvPath, wixConfig.siteId, 'incomplete');
throw new Error(
`A prior scaffold attempt was interrupted before it could record its outcome (WIX_SCAFFOLD_STATUS=in_progress), but a destination was found (WIX_SITE_ID=${wixConfig.siteId}). Persisted as incomplete — resolve manually before retrying.`,
);
}
// No local receipt either does NOT mean nothing
// was created remotely — a crash could have happened after a remote site was created
// but before wix.config.json was written locally (or even before the frontend folder
// existed at all), which isNonEmptyDir below cannot detect. Fail closed
// unconditionally rather than falling through to 2b/2c; the one case that clears this
// marker for a safe automatic retry is a genuine spawn-launch failure (see 2c) — that
// is handled before this marker is ever left behind, not by re-reading it here.
throw new Error(
'A prior scaffold attempt was interrupted before it could record any outcome (WIX_SCAFFOLD_STATUS=in_progress) and no local destination receipt (wix.config.json) exists either. This cannot be safely distinguished from a remote site having been created before a local receipt was written. Refusing to retry automatically — confirm whether a destination already exists, then either record its WIX_SITE_ID manually or clear WIX_SCAFFOLD_STATUS from config/wix.env if nothing was actually created.',
);
}
if (status !== undefined) {
// WIX_SCAFFOLD_STATUS is set to something else (a known-ambiguous marker from this
// script, or corrupted state) while no real WIX_SITE_ID exists. Fail closed rather
// than silently proceeding as though nothing were recorded.
throw new Error(
`config/wix.env has WIX_SCAFFOLD_STATUS=${JSON.stringify(status)} but no valid WIX_SITE_ID; this cannot be automatically resolved. Refusing to proceed automatically — resolve manually.`,
);
}
if (wixConfig) {
// 2a — adopt a receipt with no status marker at all: a genuinely legacy/host-adopted
// destination, or one scaffolded before this script wrote WIX_SCAFFOLD_STATUS.
await upsertEnvFile(wixEnvPath, { WIX_SITE_ID: wixConfig.siteId, WIX_SCAFFOLD_STATUS: 'complete' });
return { siteId: wixConfig.siteId };
}
if (await isNonEmptyDir(frontendDir)) {
// 2b — genuinely ambiguous state this script cannot resolve on its own.
throw new Error(
`${frontendDir} already exists and is not empty, but no valid wix.config.json was found there and config/wix.env has no WIX_SITE_ID. Refusing to scaffold into this folder automatically — resolve manually before retrying.`,
);
}
// 2c — nothing exists yet; mark in_progress before spawning so a crash between now and
// persisting a final outcome always leaves a distinguishable trace instead of silently
// looking like "nothing was ever attempted."
await upsertEnvFile(wixEnvPath, { WIX_SCAFFOLD_STATUS: 'in_progress' });
let code;
try {
({ code } = await spawnScaffold(args));
} catch (spawnError) {
// A rejection alone isn't proof nothing was created — spawnScaffold could fail for
// reasons other than a launch failure after the child already did real work. Check for
// a receipt regardless of why this rejected: if one exists, leave the in_progress
// marker in place so the next invocation's self-heal branch above handles it (never
// clear a marker out from under a receipt that might exist). Only when there is
// genuinely no receipt is it safe to clear — for the real spawnScaffold, which only
// rejects via child_process's 'error' event (emitted specifically when the OS-level
// process itself could never be launched, before any exit code exists), that absence
// is deterministic: nothing could have been created remotely.
const orphanedConfig = await readWixConfig(frontendDir);
if (!orphanedConfig) {
await clearWixScaffoldStatus(wixEnvPath);
}
throw spawnError;
}
const postConfig = await readWixConfig(frontendDir);
if (postConfig) {
// Persisted even on a non-zero exit: site creation and later template/release work are
// separate phases of the CLI's run, so discarding the id here is exactly how a retry
// would spawn a second site.
await persistSiteId(wixEnvPath, postConfig.siteId, code === 0 ? 'complete' : 'incomplete');
if (code === 0) {
return { siteId: postConfig.siteId };
}
throw new Error(
`Scaffold process exited with code ${code}, but a destination was created (WIX_SITE_ID=${postConfig.siteId}); persisted as incomplete. Do not retry automatically — resolve the underlying failure first.`,
);
}
// The child process definitely ran to completion (it returned an exit code), but no
// valid local receipt was found. This must NOT be left as a retryable in_progress
// marker: a remote site could still have been created before a local write failed.
// Convert it to a durable, always-blocked marker instead.
await upsertEnvFile(wixEnvPath, { WIX_SCAFFOLD_STATUS: 'ambiguous' });
if (code === 0) {
throw new Error('Scaffold process exited 0, but no wix.config.json with a siteId was found afterward — cannot confirm whether a destination was created. Marked ambiguous; resolve manually before retrying.');
}
throw new Error(`Scaffold process exited with code ${code} and no destination receipt was found — cannot confirm whether a destination was created. Marked ambiguous; resolve manually before retrying.`);
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
console.log(usage());
return;
}
if (!args.businessName) {
console.error(usage());
process.exit(1);
return;
}
const result = await ensureDestinationReceipt(args);
// Applied after ANY successful resolution (a fresh scaffold, or an
// idempotent adopt of an existing receipt) — both patch functions are
// themselves idempotent and cheap, so an already-patched or pre-existing
// destination is a safe, fast no-op, not just the first-scaffold path.
const frontendDir = path.join(path.resolve(args.projectDir), args.folderName);
await patchAstroConfigForRemoteMachinePreview(frontendDir);
await patchPackageJsonEnvPullHooks(frontendDir);
console.log(JSON.stringify({ ok: true, siteId: result.siteId }));
}
if (require.main === module) {
main().catch((error) => {
console.error(error && error.message ? error.message : error);
process.exit(1);
});
}
module.exports = {
ensureDestinationReceipt,
parseArgs,
scaffoldCommandArgs,
usage,
patchAstroConfigForRemoteMachinePreview,
patchPackageJsonEnvPullHooks,
};
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Wix
- Publisher
- Wix (Official)
- Source
- wix/skills · skills/wix-replatform · commit d168bc2
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Wix or Wix.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download wix-replatform.zip