@jay-framework/wix-deploy 0.24.0 → 0.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1278 @@
1
+ import { WixDataArtifactStore } from "./artifact-store.js";
2
+ import { makeCliCommand, CONSOLE_CONTEXT } from "@jay-framework/fullstack-component";
3
+ import { WIX_CLIENT_SERVICE } from "@jay-framework/wix-server-client";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import crypto from "node:crypto";
7
+ import yaml from "js-yaml";
8
+ import { getService } from "@jay-framework/stack-server-runtime";
9
+ import { collections, items } from "@wix/data";
10
+ import { walkElements } from "@jay-framework/compiler-shared";
11
+ import { parseTemplateParts } from "@jay-framework/compiler-jay-html";
12
+ const DEFAULT_COLLECTION_ID = "jay-backend-files";
13
+ const DEFAULT_CACHE_DIR = "/tmp/jay-backend";
14
+ function getDeployVersion(metadata) {
15
+ const version = metadata.version || "0.0.0";
16
+ const hash = metadata.sourceHash || "";
17
+ if (!hash) return version;
18
+ return `${version}-${hash}`;
19
+ }
20
+ const DEFAULT_EXCLUDE_PLUGINS = [
21
+ "aiditor",
22
+ "wix-deploy",
23
+ // Build-time validators — use compiler APIs stubbed out of the BaaS bundle
24
+ "wix-media",
25
+ "seo-validator",
26
+ "a11y-validator"
27
+ ];
28
+ function scanPagePartsFiles(dir, fs2, path2) {
29
+ const results = [];
30
+ for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
31
+ const fullPath = path2.join(dir, entry.name);
32
+ if (entry.isDirectory()) {
33
+ results.push(...scanPagePartsFiles(fullPath, fs2, path2));
34
+ } else if (entry.name === "page-parts.json") {
35
+ results.push(fullPath);
36
+ }
37
+ }
38
+ return results;
39
+ }
40
+ function copyPluginConfigsToDist(projectRoot, distConfigDir, fs2, path2, log) {
41
+ const configSrcDir = path2.join(projectRoot, "config");
42
+ if (!fs2.existsSync(configSrcDir)) {
43
+ return [];
44
+ }
45
+ fs2.mkdirSync(distConfigDir, { recursive: true });
46
+ const copied = [];
47
+ for (const entry of fs2.readdirSync(configSrcDir)) {
48
+ if (!entry.endsWith(".yaml") && !entry.endsWith(".yml")) {
49
+ continue;
50
+ }
51
+ const srcPath = path2.join(configSrcDir, entry);
52
+ if (!fs2.statSync(srcPath).isFile()) {
53
+ continue;
54
+ }
55
+ fs2.copyFileSync(srcPath, path2.join(distConfigDir, entry));
56
+ copied.push(entry);
57
+ if (entry.startsWith(".")) {
58
+ const plainName = entry.slice(1);
59
+ fs2.copyFileSync(srcPath, path2.join(distConfigDir, plainName));
60
+ copied.push(plainName);
61
+ } else if (!fs2.existsSync(path2.join(configSrcDir, `.${entry}`))) {
62
+ fs2.copyFileSync(srcPath, path2.join(distConfigDir, `.${entry}`));
63
+ copied.push(`.${entry}`);
64
+ }
65
+ }
66
+ if (copied.length > 0) {
67
+ log(`Copied plugin config files to dist/config/: ${[...new Set(copied)].join(", ")}`);
68
+ } else {
69
+ log("No config/*.yaml files found to copy");
70
+ }
71
+ return copied;
72
+ }
73
+ function sortPluginsByDeps(plugins) {
74
+ const priorityPackages = ["@jay-framework/wix-server-client"];
75
+ const sorted = [];
76
+ for (const pkg of priorityPackages) {
77
+ const p = plugins.find((p2) => p2.packageName === pkg);
78
+ if (p) sorted.push(p);
79
+ }
80
+ for (const p of plugins) {
81
+ if (!sorted.includes(p)) sorted.push(p);
82
+ }
83
+ return sorted;
84
+ }
85
+ function generateStubContents(modulePath) {
86
+ const throwStub = '() => { throw new Error("build-time only"); }';
87
+ const stubs = {
88
+ "@jay-framework/compiler-jay-html": [
89
+ "export default {};",
90
+ `export const parseJayFile = ${throwStub};`,
91
+ `export const JAY_IMPORT_RESOLVER = {};`,
92
+ `export const generateServerElementFile = ${throwStub};`,
93
+ `export const injectHeadfullFSTemplates = ${throwStub};`,
94
+ `export const discoverHeadlessInstances = ${throwStub};`,
95
+ `export const assignCoordinatesToJayHtml = ${throwStub};`,
96
+ `export const parseAction = ${throwStub};`,
97
+ `export const parseContract = ${throwStub};`
98
+ ].join("\n"),
99
+ "@jay-framework/compiler-shared": [
100
+ "export default {};",
101
+ `export const checkValidationErrors = (x) => x;`,
102
+ `export const formatCode = (code) => code;`
103
+ ].join("\n"),
104
+ "@jay-framework/compiler-jay-stack": [
105
+ "export default {};",
106
+ `export const jayStackCompiler = ${throwStub};`
107
+ ].join("\n"),
108
+ "@jay-framework/compiler-analyze-exported-types": [
109
+ "export default {};",
110
+ `export const extractActionsFromSource = ${throwStub};`
111
+ ].join("\n"),
112
+ "@jay-framework/compiler": [
113
+ "export default {};",
114
+ `export const jayRuntime = ${throwStub};`
115
+ ].join("\n")
116
+ };
117
+ return stubs[modulePath] || "export default {};";
118
+ }
119
+ function generateEntrySource(plugins, actionPackages, serverElements, collectionId, staticBaseUrl, version) {
120
+ const moduleImports = plugins.map(
121
+ (p, i) => `import * as pluginModule_${i} from '${p.packageName}';`
122
+ );
123
+ const seImports = serverElements.map(
124
+ (se, i) => `import * as serverElement_${i} from '${se.absolutePath}';`
125
+ );
126
+ const pluginsArray = plugins.map(
127
+ (p, i) => ` { name: '${p.name}', init: pluginModule_${i}.init },`
128
+ );
129
+ const registryEntries = [
130
+ ...plugins.map((p, i) => ` '${p.packageName}': pluginModule_${i},`),
131
+ ...serverElements.map((se, i) => ` '${se.relativePath}': serverElement_${i},`)
132
+ ];
133
+ const actionsArray = actionPackages.map((pkg) => {
134
+ const idx = plugins.findIndex((p) => p.packageName === pkg);
135
+ return ` { module: pluginModule_${idx}, name: '${pkg}' },`;
136
+ });
137
+ return `// Auto-generated BaaS entry — do not edit
138
+ // Generated by @jay-framework/wix-deploy build-entry
139
+
140
+ // Plugin imports (full modules for init + page-parts resolution)
141
+ ${moduleImports.join("\n")}
142
+
143
+ // Server element imports (bundled with ssr-runtime)
144
+ ${seImports.join("\n")}
145
+
146
+ // Framework imports
147
+ import {
148
+ matchRequest,
149
+ fetchPageRequest,
150
+ fetchActionRequest,
151
+ isActionRequest,
152
+ initializeServicesFromModules,
153
+ registerActionsFromModules,
154
+ FilesystemArtifactStore,
155
+ } from '@jay-framework/production-server/serve';
156
+ import { parseCookies, getService } from '@jay-framework/stack-server-runtime';
157
+ import { WIX_CLIENT_SERVICE } from '@jay-framework/wix-server-client';
158
+ import { WixDataArtifactStore } from '@jay-framework/wix-deploy/artifact-store';
159
+
160
+ // Module registry — npm packages + server elements (all bundled by esbuild)
161
+ const MODULE_REGISTRY = {
162
+ ${registryEntries.join("\n")}
163
+ };
164
+
165
+ // Configuration
166
+ const COLLECTION_ID = process.env.JAY_COLLECTION_ID || '${collectionId}';
167
+ const STATIC_BASE_URL = process.env.STATIC_BASE_URL || '${staticBaseUrl}';
168
+ const VERSION = process.env.JAY_BUILD_VERSION || '${version}';
169
+ const LOCAL_BACKEND_DIR = process.env.JAY_BACKEND_DIR || '';
170
+
171
+ let artifacts;
172
+ let initialized = false;
173
+ let initError = null;
174
+
175
+ async function initialize() {
176
+ if (initialized) return;
177
+
178
+ // Set CWD to entry.mjs dir so config/.wix.yaml is found by wix-server-client
179
+ const entryDir = new URL('.', import.meta.url).pathname;
180
+ if (entryDir && process.cwd() !== entryDir) {
181
+ try { process.chdir(entryDir); } catch {}
182
+ }
183
+ console.log('[BaaS] CWD:', process.cwd());
184
+
185
+ // BaaS may skip dotfiles during upload — restore dot-prefixed config from plain aliases
186
+ const fs = await import('node:fs');
187
+ const configDir = process.cwd() + '/config';
188
+ if (fs.existsSync(configDir)) {
189
+ for (const name of fs.readdirSync(configDir)) {
190
+ if (name.startsWith('.') || (!name.endsWith('.yaml') && !name.endsWith('.yml'))) {
191
+ continue;
192
+ }
193
+ const plainPath = configDir + '/' + name;
194
+ const dotPath = configDir + '/.' + name;
195
+ if (!fs.existsSync(dotPath)) {
196
+ fs.copyFileSync(plainPath, dotPath);
197
+ console.log('[BaaS] Copied config/' + name + ' to config/.' + name);
198
+ }
199
+ }
200
+ }
201
+
202
+ // Initialize plugins first — wix-server-client reads config/.wix.yaml and creates WixClient
203
+ console.log('[BaaS] Initializing plugins...');
204
+ await initializeServicesFromModules([
205
+ ${pluginsArray.join("\n")}
206
+ ], 'BaaS');
207
+
208
+ // Register actions
209
+ console.log('[BaaS] Registering actions...');
210
+ await registerActionsFromModules([
211
+ ${actionsArray.join("\n")}
212
+ ]);
213
+
214
+ // Create artifact store — uses the WixClient that wix-server-client just initialized
215
+ if (LOCAL_BACKEND_DIR) {
216
+ console.log('[BaaS] Using filesystem artifact store:', LOCAL_BACKEND_DIR);
217
+ artifacts = new FilesystemArtifactStore(LOCAL_BACKEND_DIR);
218
+ } else {
219
+ console.log('[BaaS] Creating WixDataArtifactStore...');
220
+ const wixClientService = getService(WIX_CLIENT_SERVICE);
221
+ console.log('[BaaS] WixClientService:', wixClientService ? 'found' : 'MISSING');
222
+ artifacts = new WixDataArtifactStore({
223
+ wixClient: wixClientService,
224
+ collectionId: COLLECTION_ID,
225
+ version: VERSION,
226
+ distDir: entryDir,
227
+ cacheDir: '${DEFAULT_CACHE_DIR}',
228
+ moduleRegistry: MODULE_REGISTRY,
229
+ });
230
+ console.log('[BaaS] Artifact store ready (eager files from dist/, lazy from collection)');
231
+ }
232
+
233
+ initialized = true;
234
+ console.log('[BaaS] Initialization complete');
235
+ }
236
+
237
+ function errorPage(title, err, path) {
238
+ const html = '<!doctype html><html><head><meta charset="UTF-8"><title>' + title + '</title>'
239
+ + '<style>body{font-family:monospace;max-width:800px;margin:40px auto;padding:0 20px}'
240
+ + 'h1{color:#c00}pre{background:#f5f5f5;padding:16px;overflow-x:auto;border-radius:4px}'
241
+ + '.path{color:#666}</style></head><body>'
242
+ + '<h1>' + title + '</h1>'
243
+ + '<p class="path">' + path + '</p>'
244
+ + '<p><strong>' + (err.message || '') + '</strong></p>'
245
+ + '<pre>' + (err.stack || '') + '</pre>'
246
+ + '</body></html>';
247
+ return new Response(html, { status: 500, headers: { 'Content-Type': 'text/html' } });
248
+ }
249
+
250
+ // Build a concrete URL from a route pattern + instance params (mirrors framework generate-sitemap.ts)
251
+ function buildUrl(pattern, params) {
252
+ return (
253
+ pattern
254
+ .replace(/\\[\\[(\\w+)\\]\\]/g, (_, n) => params[n] || '')
255
+ .replace(/\\[\\.\\.\\.(\\w+)\\]/g, (_, n) => params[n] || '')
256
+ .replace(/\\[(\\w+)\\]/g, (_, n) => params[n] || '')
257
+ .replace(/\\/\\/+/g, '/')
258
+ .replace(/\\/$/, '') || '/'
259
+ );
260
+ }
261
+
262
+ // Serve the Wix page inventory (/_wix/pages.json) — Wix reads this to build /sitemap.xml.
263
+ // Streamed to handle large page counts. All pages are static (Jay resolves params itself).
264
+ function streamPagesJson(manifest) {
265
+ const enc = new TextEncoder();
266
+ const stream = new ReadableStream({
267
+ start(controller) {
268
+ controller.enqueue(enc.encode('['));
269
+ let first = true;
270
+ const emit = (path) => {
271
+ const entry = { path, srcFilePath: path, static: true };
272
+ controller.enqueue(enc.encode((first ? '' : ',') + JSON.stringify(entry)));
273
+ first = false;
274
+ };
275
+ for (const route of manifest.routes) {
276
+ if (route.devOnly || route.noIndex) continue;
277
+ if (!route.instances || route.instances.length === 0) {
278
+ const hasDynamic = route.segments.some((s) => s.type !== 'static');
279
+ if (!hasDynamic) emit(route.pattern === '/' ? '/' : route.pattern);
280
+ continue;
281
+ }
282
+ for (const instance of route.instances) {
283
+ emit(buildUrl(route.pattern, instance.params));
284
+ }
285
+ }
286
+ controller.enqueue(enc.encode(']'));
287
+ controller.close();
288
+ },
289
+ });
290
+ return new Response(stream, { headers: { 'Content-Type': 'application/json' } });
291
+ }
292
+
293
+ async function handler(request) {
294
+ const url = new URL(request.url);
295
+
296
+ // Diagnostic endpoint — runs before init
297
+ if (url.pathname === '/_jay/debug') {
298
+ const fs = await import('node:fs');
299
+ const entryDir = new URL('.', import.meta.url).pathname;
300
+ const info = {
301
+ cwd: process.cwd(),
302
+ entryUrl: import.meta.url,
303
+ entryDir,
304
+ initialized,
305
+ hasArtifacts: !!artifacts,
306
+ initError: initError?.message || null,
307
+ };
308
+ try { info.cwdFiles = fs.readdirSync(process.cwd()); } catch (e) { info.cwdFiles = e.message; }
309
+ try { info.configDirFiles = fs.readdirSync(process.cwd() + '/config'); } catch (e) { info.configDirFiles = e.message; }
310
+ try { info.entryDirFiles = fs.readdirSync(entryDir); } catch (e) { info.entryDirFiles = e.message; }
311
+ try { info.entryConfigFiles = fs.readdirSync(entryDir + '/config'); } catch (e) { info.entryConfigFiles = e.message; }
312
+ try { info.userCodeFiles = fs.readdirSync('/user-code'); } catch (e) { info.userCodeFiles = e.message; }
313
+ try { info.userCodeConfigFiles = fs.readdirSync('/user-code/config'); } catch (e) { info.userCodeConfigFiles = e.message; }
314
+ return new Response(JSON.stringify(info, null, 2), { headers: { 'Content-Type': 'application/json' } });
315
+ }
316
+
317
+ try {
318
+ await initialize();
319
+ } catch (e) {
320
+ if (!initError) {
321
+ initError = e;
322
+ console.error('[BaaS] INIT FAILED:', e.message, e.stack);
323
+ }
324
+ return errorPage('Initialization Failed', e, url.pathname);
325
+ }
326
+
327
+ try {
328
+ if (isActionRequest(url.pathname)) return fetchActionRequest(request);
329
+
330
+ const manifest = await artifacts.readManifest();
331
+
332
+ // Wix reads this page inventory to build /sitemap.xml
333
+ if (url.pathname === '/_wix/pages.json') return streamPagesJson(manifest);
334
+
335
+ const match = matchRequest(manifest, url.pathname);
336
+ if (!match) return new Response('Not Found', { status: 404 });
337
+
338
+ const cookies = parseCookies(request.headers.get('cookie') || '');
339
+ return fetchPageRequest(match, manifest, url, artifacts, STATIC_BASE_URL, cookies);
340
+ } catch (e) {
341
+ console.error('[BaaS] REQUEST FAILED:', url.pathname, e.message, e.stack);
342
+ return errorPage('Request Failed', e, url.pathname);
343
+ }
344
+ }
345
+
346
+ export default { fetch: handler };
347
+ export { handler as fetch };
348
+ `;
349
+ }
350
+ function generateServeSource(frontendDir, backendDir) {
351
+ const lines = [
352
+ "#!/usr/bin/env node",
353
+ "// Local test server for the BaaS entry — run with: node dist/serve.mjs",
354
+ 'import http from "node:http";',
355
+ 'import fs from "node:fs";',
356
+ 'import path from "node:path";',
357
+ 'import { Readable } from "node:stream";',
358
+ "",
359
+ 'process.env.STATIC_BASE_URL = process.env.STATIC_BASE_URL || "/";',
360
+ `process.env.JAY_BACKEND_DIR = process.env.JAY_BACKEND_DIR || "";`,
361
+ 'const entry = await import("./dist/entry.mjs");',
362
+ "const handler = entry.default?.fetch || entry.fetch;",
363
+ 'const PORT = parseInt(process.env.PORT || "4000", 10);',
364
+ `const FRONTEND_DIR = "${frontendDir}";`,
365
+ "",
366
+ "const MIME = {",
367
+ ' ".js": "application/javascript", ".mjs": "application/javascript",',
368
+ ' ".css": "text/css", ".html": "text/html", ".json": "application/json",',
369
+ ' ".png": "image/png", ".jpg": "image/jpeg", ".svg": "image/svg+xml",',
370
+ ' ".woff2": "font/woff2", ".woff": "font/woff",',
371
+ ' ".xml": "application/xml", ".txt": "text/plain",',
372
+ "};",
373
+ "",
374
+ "function serveStatic(pathname, res) {",
375
+ " let fp = path.join(FRONTEND_DIR, pathname);",
376
+ " if (!fs.existsSync(fp) || !fs.statSync(fp).isFile()) {",
377
+ ' fp = path.join(FRONTEND_DIR, "public", pathname);',
378
+ " if (!fs.existsSync(fp) || !fs.statSync(fp).isFile()) return false;",
379
+ " }",
380
+ ' res.writeHead(200, { "Content-Type": MIME[path.extname(fp)] || "application/octet-stream" });',
381
+ " fs.createReadStream(fp).pipe(res);",
382
+ " return true;",
383
+ "}",
384
+ "",
385
+ "http.createServer(async (req, res) => {",
386
+ ' const url = new URL(req.url, "http://" + req.headers.host);',
387
+ " if (serveStatic(url.pathname, res)) return;",
388
+ " const headers = new Headers();",
389
+ " for (const [k, v] of Object.entries(req.headers)) {",
390
+ ' if (v) headers.set(k, Array.isArray(v) ? v.join(", ") : v);',
391
+ " }",
392
+ " const init = { method: req.method, headers };",
393
+ ' if (req.method !== "GET" && req.method !== "HEAD") {',
394
+ ' init.body = Readable.toWeb(req); init.duplex = "half";',
395
+ " }",
396
+ " try {",
397
+ " const response = await handler(new Request(url, init));",
398
+ " const rh = {}; response.headers.forEach((v, k) => { rh[k] = v; });",
399
+ " res.writeHead(response.status, rh);",
400
+ " if (response.body) {",
401
+ " const reader = response.body.getReader();",
402
+ " while (true) { const { done, value } = await reader.read(); if (done) break; res.write(value); }",
403
+ " }",
404
+ " res.end();",
405
+ ' } catch (err) { console.error("Handler error:", err); res.writeHead(500); res.end("Internal Server Error"); }',
406
+ "}).listen(PORT, () => {",
407
+ ' console.log("Local test server at http://localhost:" + PORT);',
408
+ ' console.log("Frontend: " + FRONTEND_DIR);',
409
+ "});"
410
+ ];
411
+ return lines.join("\n") + "\n";
412
+ }
413
+ const buildEntry = makeCliCommand("build-entry").withServices(CONSOLE_CONTEXT).withHandler(async (input, ctx) => {
414
+ const fs2 = await import("node:fs");
415
+ const path2 = await import("node:path");
416
+ const { createRequire } = await import("node:module");
417
+ const buildDir = ctx.build.backend;
418
+ const outFile = path2.resolve(ctx.projectRoot, "dist/entry.mjs");
419
+ const collectionId = input.collectionId || DEFAULT_COLLECTION_ID;
420
+ const staticBaseUrl = input.staticBaseUrl || "/";
421
+ const userExcludes = input.excludePlugins?.split(",") || [];
422
+ const excludePlugins = [...DEFAULT_EXCLUDE_PLUGINS, ...userExcludes];
423
+ ctx.log(`Build dir: ${buildDir}`);
424
+ ctx.log(`Output: ${outFile}`);
425
+ const manifestPath = path2.join(buildDir, "route-manifest.json");
426
+ if (!fs2.existsSync(manifestPath)) {
427
+ ctx.error(`route-manifest.json not found at ${manifestPath}`);
428
+ ctx.error("Run jay-stack build first.");
429
+ return { success: false };
430
+ }
431
+ const manifest = JSON.parse(fs2.readFileSync(manifestPath, "utf8"));
432
+ const metadataPath = path2.join(buildDir, "build-metadata.json");
433
+ let version = "0.0.0";
434
+ if (fs2.existsSync(metadataPath)) {
435
+ const metadata = JSON.parse(fs2.readFileSync(metadataPath, "utf8"));
436
+ version = getDeployVersion(metadata);
437
+ }
438
+ const filteredPlugins = manifest.plugins.filter(
439
+ (p) => !excludePlugins.includes(p.name) && !excludePlugins.includes(p.packageName)
440
+ );
441
+ const plugins = sortPluginsByDeps(filteredPlugins);
442
+ const pluginPackages = new Set(plugins.map((p) => p.packageName));
443
+ const actionPackages = manifest.actions.filter((a) => a.isPlugin && a.packageName && pluginPackages.has(a.packageName)).map((a) => a.packageName).filter((v, i, arr) => arr.indexOf(v) === i);
444
+ const localModuleSet = /* @__PURE__ */ new Set();
445
+ for (const route of manifest.routes) {
446
+ if (route.serverElementPath) localModuleSet.add(route.serverElementPath);
447
+ if (route.serverModule) localModuleSet.add(route.serverModule);
448
+ }
449
+ const pagePartsFiles = scanPagePartsFiles(buildDir, fs2, path2);
450
+ for (const ppFile of pagePartsFiles) {
451
+ try {
452
+ const config = JSON.parse(fs2.readFileSync(ppFile, "utf8"));
453
+ const collectLocal = (entries) => {
454
+ for (const entry of entries) {
455
+ if (entry.source === "local" && entry.modulePath) {
456
+ localModuleSet.add(entry.modulePath);
457
+ }
458
+ }
459
+ };
460
+ if (config.parts) collectLocal(config.parts);
461
+ if (config.instanceComponents) collectLocal(config.instanceComponents);
462
+ } catch {
463
+ }
464
+ }
465
+ const serverElements = [...localModuleSet].map((rel) => ({
466
+ relativePath: rel,
467
+ absolutePath: path2.join(buildDir, rel)
468
+ }));
469
+ ctx.log(`Version: ${version}`);
470
+ ctx.log(`Plugins: ${plugins.map((p) => p.name).join(", ")}`);
471
+ ctx.log(`Action packages: ${actionPackages.join(", ")}`);
472
+ ctx.log(`Local modules: ${serverElements.length} (${[...localModuleSet].join(", ")})`);
473
+ const entrySource = generateEntrySource(
474
+ plugins,
475
+ actionPackages,
476
+ serverElements,
477
+ collectionId,
478
+ staticBaseUrl,
479
+ version
480
+ );
481
+ const entryDir = path2.dirname(outFile);
482
+ fs2.mkdirSync(entryDir, { recursive: true });
483
+ const tempEntryPath = path2.join(entryDir, ".entry.generated.mjs");
484
+ fs2.writeFileSync(tempEntryPath, entrySource, "utf8");
485
+ const stubs = [
486
+ "@jay-framework/compiler-jay-html",
487
+ "@jay-framework/compiler-shared",
488
+ "@jay-framework/compiler-analyze-exported-types",
489
+ "@jay-framework/compiler-jay-stack",
490
+ "@jay-framework/compiler",
491
+ "@jay-framework/rollup-plugin",
492
+ "@jay-framework/vite-plugin",
493
+ "typescript",
494
+ "prettier",
495
+ "vite",
496
+ "lightningcss",
497
+ "fsevents",
498
+ "@types/js-yaml",
499
+ "@wix/sdk-runtime",
500
+ "yaml",
501
+ "js-beautify"
502
+ ];
503
+ const stubFilter = new RegExp(
504
+ "^(" + stubs.map((s) => s.replace(/[/.]/g, "\\$&")).join("|") + ")$"
505
+ );
506
+ const stubBuildDepsPlugin = {
507
+ name: "stub-build-deps",
508
+ setup(build) {
509
+ build.onResolve({ filter: stubFilter }, (args) => ({
510
+ path: args.path,
511
+ namespace: "stub"
512
+ }));
513
+ build.onLoad({ filter: /.*/, namespace: "stub" }, (args) => ({
514
+ contents: generateStubContents(args.path),
515
+ loader: "js"
516
+ }));
517
+ }
518
+ };
519
+ const require2 = createRequire(import.meta.url);
520
+ const resolveAliasPlugin = {
521
+ name: "resolve-aliases",
522
+ setup(build) {
523
+ build.onResolve({ filter: /^@jay-framework\/production-server\/serve$/ }, () => {
524
+ return { path: require2.resolve("@jay-framework/production-server/serve") };
525
+ });
526
+ build.onResolve({ filter: /^@jay-framework\/wix-deploy\/artifact-store$/ }, () => {
527
+ return { path: require2.resolve("@jay-framework/wix-deploy/artifact-store") };
528
+ });
529
+ }
530
+ };
531
+ const esbuild = await import("esbuild");
532
+ const result = await esbuild.build({
533
+ entryPoints: [tempEntryPath],
534
+ bundle: true,
535
+ format: "esm",
536
+ platform: "node",
537
+ target: "node20",
538
+ outfile: outFile,
539
+ external: ["node:*"],
540
+ banner: {
541
+ js: 'import { createRequire as __bundleCreateRequire } from "node:module";const require = __bundleCreateRequire(import.meta.url);'
542
+ },
543
+ plugins: [resolveAliasPlugin, stubBuildDepsPlugin],
544
+ minify: false,
545
+ treeShaking: true,
546
+ logLevel: "warning",
547
+ logOverride: { "import-is-undefined": "silent" },
548
+ metafile: true
549
+ });
550
+ fs2.rmSync(tempEntryPath, { force: true });
551
+ const runtimeStubs = ["typescript", "prettier", "lightningcss"];
552
+ let patched = fs2.readFileSync(outFile, "utf8");
553
+ let patchCount = 0;
554
+ for (const mod of runtimeStubs) {
555
+ const pattern = new RegExp(`[\\w$]+\\("${mod}"\\)`, "g");
556
+ const before = patched;
557
+ patched = patched.replace(pattern, "({})");
558
+ if (patched !== before) patchCount++;
559
+ }
560
+ if (patchCount > 0) {
561
+ fs2.writeFileSync(outFile, patched);
562
+ ctx.log(`Patched ${patchCount} runtime require() calls for build-time modules`);
563
+ }
564
+ const stat = fs2.statSync(outFile);
565
+ const sizeMB = (stat.size / 1024 / 1024).toFixed(1);
566
+ ctx.log(`Done: ${outFile} (${sizeMB} MB)`);
567
+ if (result.metafile) {
568
+ ctx.log(`Bundled ${Object.keys(result.metafile.inputs).length} input files`);
569
+ fs2.writeFileSync(
570
+ outFile.replace(/\.mjs$/, ".meta.json"),
571
+ JSON.stringify(result.metafile)
572
+ );
573
+ }
574
+ for (const name of ["route-manifest.json", "build-metadata.json"]) {
575
+ const src = path2.join(buildDir, name);
576
+ if (fs2.existsSync(src)) {
577
+ fs2.copyFileSync(src, path2.join(entryDir, name));
578
+ }
579
+ }
580
+ ctx.log("Copied route-manifest.json + build-metadata.json to dist/");
581
+ const distConfigDir = path2.join(entryDir, "config");
582
+ copyPluginConfigsToDist(
583
+ ctx.projectRoot,
584
+ distConfigDir,
585
+ fs2,
586
+ path2,
587
+ (message) => ctx.log(message)
588
+ );
589
+ const wixConfigSrc = path2.join(ctx.projectRoot, "config", ".wix.yaml");
590
+ if (!fs2.existsSync(wixConfigSrc)) {
591
+ ctx.warn(
592
+ `config/.wix.yaml not found — wix-server-client init will fail on BaaS unless WIX_API_KEY env vars are set`
593
+ );
594
+ }
595
+ const serveFile = path2.join(ctx.projectRoot, "serve.mjs");
596
+ fs2.writeFileSync(serveFile, generateServeSource(ctx.build.frontend));
597
+ ctx.log(`Generated ${serveFile} — run with: node serve.mjs`);
598
+ return { success: true, outFile, sizeMB };
599
+ });
600
+ const SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
601
+ ".js",
602
+ ".png",
603
+ ".jpg",
604
+ ".jpeg",
605
+ ".gif",
606
+ ".svg",
607
+ ".webp",
608
+ ".jay-html"
609
+ ]);
610
+ const MAX_BATCH_BYTES = 4e5;
611
+ function categorize(relativePath) {
612
+ if (relativePath === "route-manifest.json") return "eager";
613
+ if (relativePath === "build-metadata.json") return "eager";
614
+ return "lazy";
615
+ }
616
+ function scanFileEntries(dir, base, fs2, path2) {
617
+ const entries = [];
618
+ for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
619
+ const fullPath = path2.join(dir, entry.name);
620
+ const relativePath = base ? `${base}/${entry.name}` : entry.name;
621
+ if (entry.isDirectory()) {
622
+ entries.push(...scanFileEntries(fullPath, relativePath, fs2, path2));
623
+ } else {
624
+ const ext = path2.extname(entry.name).toLowerCase();
625
+ if (SKIP_EXTENSIONS.has(ext)) continue;
626
+ const stat = fs2.statSync(fullPath);
627
+ entries.push({
628
+ relativePath,
629
+ fullPath,
630
+ sizeBytes: stat.size,
631
+ category: categorize(relativePath)
632
+ });
633
+ }
634
+ }
635
+ return entries;
636
+ }
637
+ function buildBatches(entries) {
638
+ const batches = [];
639
+ let currentBatch = [];
640
+ let currentSize = 0;
641
+ for (const entry of entries) {
642
+ if (currentBatch.length > 0 && currentSize + entry.sizeBytes > MAX_BATCH_BYTES) {
643
+ batches.push(currentBatch);
644
+ currentBatch = [];
645
+ currentSize = 0;
646
+ }
647
+ currentBatch.push(entry);
648
+ currentSize += entry.sizeBytes;
649
+ }
650
+ if (currentBatch.length > 0) batches.push(currentBatch);
651
+ return batches;
652
+ }
653
+ const uploadBackend = makeCliCommand("upload-backend").withServices(WIX_CLIENT_SERVICE, CONSOLE_CONTEXT).withHandler(
654
+ async (input, wixClient, ctx) => {
655
+ const fs2 = await import("node:fs");
656
+ const path2 = await import("node:path");
657
+ const buildDir = ctx.build.backend;
658
+ const collectionId = input.collectionId || DEFAULT_COLLECTION_ID;
659
+ const dryRun = input.dryRun || false;
660
+ const metadataPath = path2.join(buildDir, "build-metadata.json");
661
+ let version = "0.0.0";
662
+ if (fs2.existsSync(metadataPath)) {
663
+ const metadata = JSON.parse(fs2.readFileSync(metadataPath, "utf8"));
664
+ version = getDeployVersion(metadata);
665
+ }
666
+ if (dryRun) ctx.log("DRY RUN — no uploads");
667
+ if (!fs2.existsSync(buildDir)) {
668
+ ctx.error(`Backend dir not found: ${buildDir}`);
669
+ return { success: false };
670
+ }
671
+ const entries = scanFileEntries(buildDir, "", fs2, path2);
672
+ const totalSize = entries.reduce((sum, f) => sum + f.sizeBytes, 0);
673
+ ctx.log(`${entries.length} files (${(totalSize / 1024 / 1024).toFixed(1)} MB)`);
674
+ if (dryRun) {
675
+ for (const f of entries.slice(0, 20)) {
676
+ ctx.log(
677
+ ` [${f.category}] ${f.relativePath} (${(f.sizeBytes / 1024).toFixed(0)} KB)`
678
+ );
679
+ }
680
+ if (entries.length > 20) ctx.log(` ... and ${entries.length - 20} more`);
681
+ return { success: true, fileCount: entries.length, totalSize };
682
+ }
683
+ const store = new WixDataArtifactStore({
684
+ wixClient,
685
+ collectionId,
686
+ version,
687
+ cacheDir: "/tmp/upload-staging"
688
+ });
689
+ const batches = buildBatches(entries);
690
+ let uploaded = 0;
691
+ let errors = 0;
692
+ let lastReported = 0;
693
+ for (let i = 0; i < batches.length; i++) {
694
+ const batch = batches[i];
695
+ const files = batch.map((f) => ({
696
+ path: f.relativePath,
697
+ content: fs2.readFileSync(f.fullPath, "utf8"),
698
+ category: f.category
699
+ }));
700
+ const count = await store.writeFiles(files);
701
+ uploaded += count;
702
+ errors += batch.length - count;
703
+ if (uploaded - lastReported >= 100 || i === batches.length - 1) {
704
+ ctx.log(`${uploaded}/${entries.length} files uploaded`);
705
+ lastReported = uploaded;
706
+ }
707
+ }
708
+ if (errors > 0) ctx.log(`${errors} errors`);
709
+ return { success: errors === 0, uploaded, errors, version };
710
+ }
711
+ );
712
+ const MANAGE_BASE = "https://manage.wix.com";
713
+ function createWixManageClient(accessToken) {
714
+ const headers = {
715
+ Authorization: accessToken,
716
+ "Content-Type": "application/json",
717
+ "X-XSRF-TOKEN": "nocheck",
718
+ Cookie: "XSRF-TOKEN=nocheck"
719
+ };
720
+ return {
721
+ async fetch(path2, options = {}) {
722
+ const { method = "GET", body, params } = options;
723
+ const url = new URL(path2, MANAGE_BASE);
724
+ if (params) {
725
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
726
+ }
727
+ const response = await fetch(url.toString(), {
728
+ method,
729
+ headers,
730
+ body: body ? JSON.stringify(body) : void 0
731
+ });
732
+ if (!response.ok) {
733
+ const text2 = await response.text();
734
+ throw new Error(`Wix API ${response.status} ${path2}: ${text2}`);
735
+ }
736
+ const text = await response.text();
737
+ return text ? JSON.parse(text) : {};
738
+ }
739
+ };
740
+ }
741
+ async function createAppDeployment(client, appId, staticFilesMetadata) {
742
+ return client.fetch(
743
+ `/_api/wix-code-app-deployments/v1/app-projects/${appId}/app-deployments`,
744
+ {
745
+ method: "POST",
746
+ body: { appDeployment: { appProjectId: appId, staticFilesMetadata } }
747
+ }
748
+ );
749
+ }
750
+ async function completeAppDeployment(client, appId, deployment, backendFiles, staticsCompletionToken) {
751
+ return client.fetch(
752
+ `/_api/wix-code-app-deployments/v1/app-projects/${appId}/app-deployments/${deployment.id}/complete`,
753
+ {
754
+ method: "POST",
755
+ body: {
756
+ appDeployment: { ...deployment, files: backendFiles },
757
+ staticsCompletionToken
758
+ }
759
+ }
760
+ );
761
+ }
762
+ async function getLatestProductionVersion(client, appId) {
763
+ const data = await client.fetch(
764
+ "/_api/app-versions/v1/app-versions/get-latest-production",
765
+ { params: { appId } }
766
+ );
767
+ return data.appVersion?.version || 0;
768
+ }
769
+ async function createComponentsOverride(client, override) {
770
+ await client.fetch("/_api/components-overrides/v1/components-override", {
771
+ method: "POST",
772
+ body: { componentsOverride: override }
773
+ });
774
+ }
775
+ async function releaseBaas(client, appId, componentOverrideId) {
776
+ return client.fetch(
777
+ `/apps-release-manager-service-web/apps/release/${appId}/${componentOverrideId}`,
778
+ {
779
+ method: "POST",
780
+ body: { appId, componentOverrideId, createMinorVersion: true }
781
+ }
782
+ );
783
+ }
784
+ const BACKEND_WORKER_COMPONENT_ID = "ed5f3d0e-7b79-4717-9c00-c4cd7bbbe906";
785
+ function md5(buffer) {
786
+ return crypto.createHash("md5").update(buffer).digest("hex");
787
+ }
788
+ function getMimeType(filePath) {
789
+ const ext = path.extname(filePath).toLowerCase();
790
+ const types = {
791
+ ".mjs": "application/javascript",
792
+ ".js": "application/javascript",
793
+ ".json": "application/json",
794
+ ".html": "text/html",
795
+ ".css": "text/css",
796
+ ".yaml": "text/yaml",
797
+ ".yml": "text/yaml"
798
+ };
799
+ return types[ext] || "application/octet-stream";
800
+ }
801
+ function collectFiles(dir, base = "") {
802
+ const files = [];
803
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
804
+ const fullPath = path.join(dir, entry.name);
805
+ const relativePath = base ? `${base}/${entry.name}` : entry.name;
806
+ if (entry.isDirectory()) {
807
+ files.push(...collectFiles(fullPath, relativePath));
808
+ } else {
809
+ const content = fs.readFileSync(fullPath);
810
+ files.push({
811
+ path: `/${relativePath}`,
812
+ content,
813
+ hash: md5(content),
814
+ contentType: getMimeType(entry.name),
815
+ size: content.length
816
+ });
817
+ }
818
+ }
819
+ return files;
820
+ }
821
+ const deployBaas = makeCliCommand("deploy-baas").withServices(CONSOLE_CONTEXT).withHandler(async (input, ctx) => {
822
+ const distDir = path.resolve(ctx.projectRoot, "dist");
823
+ const dryRun = input.dryRun || false;
824
+ if (!fs.existsSync(distDir)) {
825
+ ctx.error("dist/ not found. Run wix-deploy/build-entry first.");
826
+ return { success: false };
827
+ }
828
+ const wixConfigPath = path.join(ctx.projectRoot, "wix.config.json");
829
+ if (!fs.existsSync(wixConfigPath)) {
830
+ ctx.error("wix.config.json not found.");
831
+ return { success: false };
832
+ }
833
+ const wixConfig = JSON.parse(fs.readFileSync(wixConfigPath, "utf8"));
834
+ const appId = wixConfig.appId;
835
+ wixConfig.siteId;
836
+ const os = await import("node:os");
837
+ const accountPath = path.join(os.homedir(), ".wix", "auth", "account.json");
838
+ if (!fs.existsSync(accountPath)) {
839
+ ctx.error("No auth found. Run `wix login` first.");
840
+ return { success: false };
841
+ }
842
+ const authData = JSON.parse(fs.readFileSync(accountPath, "utf8"));
843
+ let accessToken = authData.accessToken;
844
+ const issuedAt = authData.issuedAt * 1e3;
845
+ const expiresAt = issuedAt + authData.expiresIn * 1e3;
846
+ if (Date.now() > expiresAt - 6e4) {
847
+ ctx.log("Access token expired, refreshing...");
848
+ const refreshResponse = await fetch("https://manage.wix.com/oauth2/token", {
849
+ method: "POST",
850
+ headers: {
851
+ "Content-Type": "application/json",
852
+ "X-XSRF-TOKEN": "nocheck",
853
+ Cookie: "XSRF-TOKEN=nocheck"
854
+ },
855
+ body: JSON.stringify({
856
+ clientId: "6f95cec8-3e98-48b9-b4e5-1fb92fcd9973",
857
+ grantType: "refresh_token",
858
+ refreshToken: authData.refreshToken
859
+ })
860
+ });
861
+ if (!refreshResponse.ok) {
862
+ ctx.error(
863
+ `Token refresh failed: ${refreshResponse.status}. Run \`wix login\` again.`
864
+ );
865
+ return { success: false };
866
+ }
867
+ const tokenData = await refreshResponse.json();
868
+ accessToken = tokenData.access_token;
869
+ authData.accessToken = accessToken;
870
+ authData.issuedAt = Math.floor(Date.now() / 1e3);
871
+ authData.expiresIn = tokenData.expires_in;
872
+ fs.writeFileSync(accountPath, JSON.stringify(authData, null, 2));
873
+ ctx.log("Token refreshed");
874
+ }
875
+ const manageClient = createWixManageClient(accessToken);
876
+ const frontendDir = ctx.build.frontend;
877
+ const serverDir = distDir;
878
+ const clientFiles = fs.existsSync(frontendDir) ? collectFiles(frontendDir) : [];
879
+ const serverFiles = collectFiles(serverDir);
880
+ const files = [...clientFiles, ...serverFiles];
881
+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);
882
+ ctx.log(
883
+ `${clientFiles.length} client + ${serverFiles.length} server files (${(totalSize / 1024 / 1024).toFixed(1)} MB)`
884
+ );
885
+ if (dryRun) {
886
+ for (const f of files) {
887
+ ctx.log(` ${f.path} (${(f.size / 1024).toFixed(1)} KB)`);
888
+ }
889
+ return { success: true, fileCount: files.length, totalSize };
890
+ }
891
+ ctx.log("Creating deployment...");
892
+ const staticFilesMetadata = clientFiles.map((f) => ({
893
+ path: f.path,
894
+ hash: f.hash,
895
+ contentType: f.contentType,
896
+ size: f.size
897
+ }));
898
+ const deployData = await createAppDeployment(manageClient, appId, staticFilesMetadata);
899
+ const appDeployment = deployData.appDeployment;
900
+ const uploadUrls = deployData.staticFilesUploadUrls || [];
901
+ const uploadToken = deployData.uploadAuthToken;
902
+ const uploadBuckets = deployData.uploadBuckets || [];
903
+ if (uploadUrls.length > 0) {
904
+ const isKubernetes = appDeployment?.cloudProviderOverride === "KUBERNETES";
905
+ if (isKubernetes) {
906
+ let uploaded = 0;
907
+ for (const uploadInfo of uploadUrls) {
908
+ const file = clientFiles.find(
909
+ (f) => f.path === uploadInfo.staticFileMetadata?.path
910
+ );
911
+ if (!file || !uploadInfo.uploadUrl) continue;
912
+ const response = await fetch(uploadInfo.uploadUrl, {
913
+ method: "PUT",
914
+ headers: { "Content-Type": file.contentType },
915
+ body: file.content
916
+ });
917
+ if (!response.ok) {
918
+ ctx.error(` FAILED ${file.path}: ${response.status}`);
919
+ } else {
920
+ uploaded++;
921
+ }
922
+ }
923
+ ctx.log(`Uploaded ${uploaded} CDN files`);
924
+ } else {
925
+ const uploadUrl = uploadUrls[0].uploadUrl;
926
+ const buckets = uploadBuckets.length > 0 ? uploadBuckets : [{ hashes: clientFiles.map((f) => f.hash) }];
927
+ for (let i = 0; i < buckets.length; i++) {
928
+ const bucket = buckets[i];
929
+ const formData = new FormData();
930
+ for (const hash of bucket.hashes || []) {
931
+ const file = clientFiles.find((f) => f.hash === hash);
932
+ if (!file) continue;
933
+ formData.append(
934
+ hash,
935
+ new Blob([file.content], { type: file.contentType }),
936
+ hash
937
+ );
938
+ }
939
+ const response = await fetch(uploadUrl, {
940
+ method: "POST",
941
+ headers: { Authorization: `Bearer ${uploadToken}` },
942
+ body: formData
943
+ });
944
+ if (!response.ok) {
945
+ ctx.error(` Bucket ${i + 1} FAILED: ${response.status}`);
946
+ } else {
947
+ ctx.log(
948
+ ` Bucket ${i + 1}/${buckets.length}: ${bucket.hashes?.length} files`
949
+ );
950
+ }
951
+ }
952
+ }
953
+ }
954
+ ctx.log("Uploading server files...");
955
+ const backendFiles = serverFiles.map((f) => ({
956
+ path: f.path.startsWith("/") ? f.path.slice(1) : f.path,
957
+ content: f.content.toString("base64")
958
+ }));
959
+ const completeData = await completeAppDeployment(
960
+ manageClient,
961
+ appId,
962
+ appDeployment,
963
+ backendFiles,
964
+ uploadToken
965
+ );
966
+ const completedDeployment = completeData.appDeployment || {};
967
+ const deploymentId = appDeployment?.id;
968
+ const deploymentBaseUrl = completedDeployment.deploymentBaseUrl || appDeployment?.deploymentBaseUrl || "";
969
+ ctx.log(`Deployment uploaded. Base URL: ${deploymentBaseUrl}`);
970
+ let appVersion = 0;
971
+ try {
972
+ appVersion = await getLatestProductionVersion(manageClient, appId);
973
+ } catch {
974
+ }
975
+ ctx.log("Registering + releasing...");
976
+ const overrideId = crypto.randomUUID();
977
+ await createComponentsOverride(manageClient, {
978
+ appId,
979
+ appVersion,
980
+ externalId: appId,
981
+ id: overrideId,
982
+ modifiedComponents: [
983
+ {
984
+ componentId: BACKEND_WORKER_COMPONENT_ID,
985
+ type: "BACKEND_WORKER",
986
+ data: {
987
+ backendWorker: {
988
+ deploymentId,
989
+ deploymentUrl: deploymentBaseUrl
990
+ }
991
+ }
992
+ }
993
+ ]
994
+ });
995
+ const releaseData = await releaseBaas(manageClient, appId, overrideId);
996
+ const releaseUrl = releaseData.releaseBaseUrl || deploymentBaseUrl;
997
+ ctx.log(`Released → ${releaseUrl}`);
998
+ return { success: true, deploymentId, baseUrl: releaseUrl };
999
+ });
1000
+ const TXT_FILES = [
1001
+ {
1002
+ fileName: "robots.txt",
1003
+ url: "https://www.wixapis.com/promote-seo-txt-file-server/v2/robots",
1004
+ bodyKey: "robotsTxt"
1005
+ },
1006
+ {
1007
+ fileName: "ads.txt",
1008
+ url: "https://www.wixapis.com/promote-seo-txt-file-server/v2/ads",
1009
+ bodyKey: "adsTxt"
1010
+ },
1011
+ {
1012
+ fileName: "llms.txt",
1013
+ url: "https://www.wixapis.com/promote-seo-txt-file-server/v2/llms",
1014
+ bodyKey: "llmsTxt"
1015
+ }
1016
+ ];
1017
+ const syncTxtFiles = makeCliCommand("sync-txt-files").withServices(WIX_CLIENT_SERVICE, CONSOLE_CONTEXT).withHandler(
1018
+ async (input, wixClientService, ctx) => {
1019
+ const fs2 = await import("node:fs");
1020
+ const path2 = await import("node:path");
1021
+ const subdomain = input.subdomain || "www";
1022
+ const publicDir = path2.join(ctx.projectRoot, "public");
1023
+ const synced = [];
1024
+ const skipped = [];
1025
+ const errors = [];
1026
+ for (const file of TXT_FILES) {
1027
+ const filePath = path2.join(publicDir, file.fileName);
1028
+ if (!fs2.existsSync(filePath)) {
1029
+ skipped.push(file.fileName);
1030
+ continue;
1031
+ }
1032
+ const content = fs2.readFileSync(filePath, "utf8");
1033
+ const body = { [file.bodyKey]: { content, default: false, subdomain } };
1034
+ try {
1035
+ const response = await wixClientService.wixClient.fetchWithAuth(file.url, {
1036
+ method: "PUT",
1037
+ headers: { "Content-Type": "application/json" },
1038
+ body: JSON.stringify(body)
1039
+ });
1040
+ if (!response.ok) {
1041
+ const text = await response.text();
1042
+ errors.push(`${file.fileName}: HTTP ${response.status} ${text}`);
1043
+ continue;
1044
+ }
1045
+ synced.push(file.fileName);
1046
+ } catch (err) {
1047
+ errors.push(`${file.fileName}: ${err instanceof Error ? err.message : err}`);
1048
+ }
1049
+ }
1050
+ const parts = [];
1051
+ if (synced.length) parts.push(`Synced ${synced.join(", ")}`);
1052
+ if (skipped.length) parts.push(`skipped ${skipped.join(", ")} (not in public/)`);
1053
+ ctx.log(parts.join("; ") || "No txt files to sync");
1054
+ for (const error of errors) ctx.warn(error);
1055
+ return { success: errors.length === 0, synced, skipped, errors };
1056
+ }
1057
+ );
1058
+ function silentCtx(ctx) {
1059
+ return { ...ctx, log: () => {
1060
+ }, warn: () => {
1061
+ } };
1062
+ }
1063
+ function prefixCtx(ctx, prefix) {
1064
+ return { ...ctx, log: (msg) => ctx.log(`[deploy] ${prefix} ${msg}`), warn: () => {
1065
+ } };
1066
+ }
1067
+ const deploy = makeCliCommand("deploy").withServices(WIX_CLIENT_SERVICE, CONSOLE_CONTEXT).withHandler(async (input, wixClient, ctx) => {
1068
+ const fs2 = await import("node:fs");
1069
+ const path2 = await import("node:path");
1070
+ const dryRun = input.dryRun || false;
1071
+ const t0 = Date.now();
1072
+ const metadataPath = path2.join(ctx.build.backend, "build-metadata.json");
1073
+ if (!fs2.existsSync(metadataPath)) {
1074
+ ctx.error(`[deploy] build-metadata.json not found. Run build:production first.`);
1075
+ return { success: false };
1076
+ }
1077
+ const metadata = JSON.parse(fs2.readFileSync(metadataPath, "utf8"));
1078
+ const deployVersion = getDeployVersion(metadata);
1079
+ ctx.log(`[deploy] Version: ${deployVersion}`);
1080
+ ctx.log("[deploy] Bundling entry.mjs...");
1081
+ const buildResult = await buildEntry.handler(
1082
+ {
1083
+ collectionId: input.collectionId,
1084
+ staticBaseUrl: input.staticBaseUrl,
1085
+ excludePlugins: input.excludePlugins
1086
+ },
1087
+ silentCtx(ctx)
1088
+ );
1089
+ if (!buildResult?.success) {
1090
+ ctx.error("[deploy] Bundle failed");
1091
+ return { success: false };
1092
+ }
1093
+ const bundleTime = ((Date.now() - t0) / 1e3).toFixed(1);
1094
+ ctx.log(`[deploy] Bundled entry.mjs (${buildResult.sizeMB} MB) in ${bundleTime}s`);
1095
+ ctx.log("[deploy] Uploading...");
1096
+ const t1 = Date.now();
1097
+ const [uploadResult, deployResult, txtResult] = await Promise.all([
1098
+ uploadBackend.handler(
1099
+ { collectionId: input.collectionId, dryRun },
1100
+ wixClient,
1101
+ prefixCtx(ctx, "data |")
1102
+ ),
1103
+ dryRun ? { success: true, baseUrl: "(dry run)" } : deployBaas.handler({ dryRun }, prefixCtx(ctx, "baas |")),
1104
+ dryRun ? { success: true } : syncTxtFiles.handler({}, wixClient, prefixCtx(ctx, "txt |"))
1105
+ ]);
1106
+ if (!uploadResult?.success) ctx.error("[deploy] Backend data upload failed");
1107
+ if (!deployResult?.success) ctx.error("[deploy] BaaS deployment failed");
1108
+ if (!txtResult?.success) {
1109
+ ctx.warn("[deploy] Some txt files failed to sync (non-fatal):");
1110
+ for (const error of txtResult?.errors ?? []) ctx.warn(`[deploy] txt | ${error}`);
1111
+ }
1112
+ const success = !!(uploadResult?.success && deployResult?.success);
1113
+ const elapsed = ((Date.now() - t0) / 1e3).toFixed(1);
1114
+ const deployTime = ((Date.now() - t1) / 1e3).toFixed(1);
1115
+ ctx.log("");
1116
+ if (success) {
1117
+ ctx.log(`[deploy] Done in ${elapsed}s (bundle ${bundleTime}s + deploy ${deployTime}s)`);
1118
+ ctx.log(
1119
+ `[deploy] Version: ${deployVersion} | Entry: ${buildResult.sizeMB} MB | Backend files: ${uploadResult.uploaded}`
1120
+ );
1121
+ if (deployResult.baseUrl) {
1122
+ ctx.log(`[deploy] URL: ${deployResult.baseUrl}`);
1123
+ }
1124
+ } else {
1125
+ ctx.log(`[deploy] Failed after ${elapsed}s`);
1126
+ }
1127
+ return { success, ...deployResult };
1128
+ });
1129
+ async function setupWixDeploy(ctx) {
1130
+ if (ctx.initError) {
1131
+ return {
1132
+ status: "error",
1133
+ message: `Service init failed: ${ctx.initError.message}`
1134
+ };
1135
+ }
1136
+ const wixConfigPath = path.join(ctx.projectRoot, "wix.config.json");
1137
+ const wixYamlPath = path.join(ctx.configDir, ".wix.yaml");
1138
+ if (!fs.existsSync(wixConfigPath)) {
1139
+ return {
1140
+ status: "needs-config",
1141
+ message: "wix.config.json not found. Run: npm create @wix/new@latest init"
1142
+ };
1143
+ }
1144
+ const wixConfig = JSON.parse(fs.readFileSync(wixConfigPath, "utf8"));
1145
+ const appId = wixConfig.appId;
1146
+ const siteId = wixConfig.siteId;
1147
+ if (!appId) {
1148
+ return {
1149
+ status: "error",
1150
+ message: "wix.config.json missing appId"
1151
+ };
1152
+ }
1153
+ const configCreated = [];
1154
+ if (fs.existsSync(wixYamlPath)) {
1155
+ const content = fs.readFileSync(wixYamlPath, "utf8");
1156
+ const config = yaml.load(content);
1157
+ if (config) {
1158
+ let changed = false;
1159
+ const currentClientId = config.oauthStrategy?.clientId || "";
1160
+ if (!currentClientId || currentClientId.startsWith("<")) {
1161
+ if (!config.oauthStrategy) config.oauthStrategy = {};
1162
+ config.oauthStrategy.clientId = appId;
1163
+ changed = true;
1164
+ configCreated.push("clientId");
1165
+ }
1166
+ const currentSiteId = config.apiKeyStrategy?.siteId || "";
1167
+ if (siteId && (!currentSiteId || currentSiteId.startsWith("<"))) {
1168
+ if (!config.apiKeyStrategy) config.apiKeyStrategy = {};
1169
+ config.apiKeyStrategy.siteId = siteId;
1170
+ changed = true;
1171
+ configCreated.push("siteId");
1172
+ }
1173
+ if (changed) {
1174
+ fs.writeFileSync(wixYamlPath, yaml.dump(config, { lineWidth: -1 }), "utf8");
1175
+ }
1176
+ }
1177
+ }
1178
+ if (fs.existsSync(wixYamlPath)) {
1179
+ const config = yaml.load(fs.readFileSync(wixYamlPath, "utf8"));
1180
+ const apiKey = config?.apiKeyStrategy?.apiKey || "";
1181
+ if (!apiKey || apiKey.startsWith("<")) {
1182
+ return {
1183
+ status: "needs-config",
1184
+ configCreated,
1185
+ message: "API key required — create one at https://manage.wix.com/ and add to config/.wix.yaml"
1186
+ };
1187
+ }
1188
+ }
1189
+ let collectionOk = false;
1190
+ const wixClient = getService(WIX_CLIENT_SERVICE);
1191
+ if (wixClient) {
1192
+ const dataClient = wixClient.use({ items, collections });
1193
+ try {
1194
+ await dataClient.items.query(DEFAULT_COLLECTION_ID).limit(1).find();
1195
+ collectionOk = true;
1196
+ } catch {
1197
+ try {
1198
+ await dataClient.collections.createDataCollection({
1199
+ _id: DEFAULT_COLLECTION_ID,
1200
+ displayName: "Jay Backend Files",
1201
+ fields: [
1202
+ { key: "path", type: "TEXT" },
1203
+ { key: "content", type: "TEXT" },
1204
+ { key: "fileType", type: "TEXT" },
1205
+ { key: "sizeBytes", type: "NUMBER" },
1206
+ { key: "category", type: "TEXT" },
1207
+ { key: "version", type: "TEXT" }
1208
+ ],
1209
+ permissions: {
1210
+ insert: "ADMIN",
1211
+ update: "ADMIN",
1212
+ remove: "ADMIN",
1213
+ read: "ADMIN"
1214
+ }
1215
+ });
1216
+ collectionOk = true;
1217
+ configCreated.push("collection");
1218
+ } catch (createErr) {
1219
+ return {
1220
+ status: "error",
1221
+ configCreated,
1222
+ message: `Failed to create data collection "${DEFAULT_COLLECTION_ID}": ${createErr instanceof Error ? createErr.message : createErr}`
1223
+ };
1224
+ }
1225
+ }
1226
+ }
1227
+ return {
1228
+ status: "configured",
1229
+ configCreated,
1230
+ message: `Deploy target: wix.config.json (appId: ${appId.slice(0, 8)}...). Collection: ${DEFAULT_COLLECTION_ID} ${collectionOk ? "✓" : ""}`
1231
+ };
1232
+ }
1233
+ const STATIC_ELEMENTS = /* @__PURE__ */ new Set(["img", "video", "source", "link"]);
1234
+ const SRC_ATTRS = ["src", "poster"];
1235
+ const HREF_ATTRS = ["href"];
1236
+ const ASSET_EXTENSIONS_RE = /\.(jpe?g|png|gif|webp|svg|bmp|ico|woff2?|ttf|css|js)$/i;
1237
+ function isLocalPath(value) {
1238
+ if (value.startsWith("http://") || value.startsWith("https://") || value.startsWith("data:"))
1239
+ return false;
1240
+ return true;
1241
+ }
1242
+ function suggestRenamed(filePath) {
1243
+ return filePath.replace(/ /g, "-");
1244
+ }
1245
+ const validate = (ctx) => {
1246
+ const findings = [];
1247
+ walkElements(ctx.body, ctx, (el, _scope) => {
1248
+ const tagName = el.rawTagName?.toLowerCase();
1249
+ if (!tagName || !STATIC_ELEMENTS.has(tagName)) return;
1250
+ const attrsToCheck = tagName === "link" ? HREF_ATTRS : SRC_ATTRS;
1251
+ for (const attr of attrsToCheck) {
1252
+ const value = el.getAttribute(attr);
1253
+ if (!value) continue;
1254
+ const parts = parseTemplateParts(value);
1255
+ if (!parts.every((p) => p.kind === "static")) continue;
1256
+ const staticValue = parts.map((p) => p.value).join("");
1257
+ if (!isLocalPath(staticValue)) continue;
1258
+ if (!ASSET_EXTENSIONS_RE.test(staticValue)) continue;
1259
+ if (!staticValue.includes(" ")) continue;
1260
+ findings.push({
1261
+ severity: "error",
1262
+ message: `Static file path '${staticValue}' contains spaces — Wix CDN replaces spaces with hyphens, breaking the reference. Rename the file to '${suggestRenamed(staticValue)}' and update all references.`,
1263
+ element: `<${tagName}>`,
1264
+ attribute: attr
1265
+ });
1266
+ }
1267
+ });
1268
+ return findings;
1269
+ };
1270
+ export {
1271
+ WixDataArtifactStore,
1272
+ buildEntry,
1273
+ deploy,
1274
+ deployBaas,
1275
+ setupWixDeploy,
1276
+ uploadBackend,
1277
+ validate
1278
+ };