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