@coraltravelcenter/b2c-landing-builder 3.0.0 → 3.2.0

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/src/cli/index.mjs CHANGED
@@ -10,9 +10,9 @@ Commands:
10
10
  build Build CMS-ready HTML files
11
11
  deploy Build, sync assets, and deploy CMS widgets
12
12
  deploy --section <key> Deploy one CMS section
13
- deploy --dry-run Build and show the CDN/CMS plan without changing remote or local deploy state
14
- deploy --dry-run --section <key>
15
- Build and show the plan for one CMS section
13
+ deploy status Compare the last @CMS build with CMS
14
+ deploy status --section <key>
15
+ Show changes for one CMS section
16
16
  deploy assets Build and sync assets with the B2C CDN
17
17
  check Validate project configuration
18
18
  block:add <key> Create a block
@@ -24,9 +24,9 @@ dev Start Vite and the userscript
24
24
  build Build CMS files and assets
25
25
  deploy Sync assets and CMS widgets
26
26
  deploy --section <key> Sync one CMS section
27
- deploy --dry-run Show the complete deploy plan
28
- deploy --dry-run --section <key>
29
- Show one section plan
27
+ deploy status Compare the last @CMS build with CMS
28
+ deploy status --section <key>
29
+ Show changes for one CMS section
30
30
  deploy assets Sync CDN assets only
31
31
  block:add <key> Create a block
32
32
  block:rename <old> <new> Rename a block
@@ -34,24 +34,21 @@ update Check for updates`;
34
34
 
35
35
  export function parseDeployArgs(args) {
36
36
  if (args.length === 1 && args[0] === "assets") {
37
- return {assetsOnly: true, dryRun: false, section: null};
37
+ return {assetsOnly: true, status: false, section: null};
38
38
  }
39
- let dryRun = false;
39
+ const status = args[0] === "status";
40
+ if (status) args = args.slice(1);
40
41
  let section = null;
41
42
  for (let index = 0; index < args.length; index += 1) {
42
43
  const argument = args[index];
43
- if (argument === "--dry-run" && !dryRun) {
44
- dryRun = true;
45
- continue;
46
- }
47
44
  if (argument === "--section" && section === null && args[index + 1] && !args[index + 1].startsWith("--")) {
48
45
  section = args[index + 1];
49
46
  index += 1;
50
47
  continue;
51
48
  }
52
- throw new Error("Usage: b2c-landing-vite deploy [assets | --dry-run [--section <key>] | --section <key>]");
49
+ throw new Error("Usage: b2c-landing-vite deploy [assets | status [--section <key>] | --section <key>]");
53
50
  }
54
- return {assetsOnly: false, dryRun, section};
51
+ return {assetsOnly: false, status, section};
55
52
  }
56
53
 
57
54
  async function check({strict = false, ui} = {}) {
@@ -140,20 +137,22 @@ export async function runCli(args, {ui: providedUi, embedded = false} = {}) {
140
137
  return build({ui, embedded});
141
138
  }
142
139
  if (command === "deploy") {
143
- const {assetsOnly, dryRun, section} = parseDeployArgs(rest);
140
+ const {assetsOnly, status, section} = parseDeployArgs(rest);
144
141
  const config = await loadConfig();
145
142
  const project = validateProject(config);
146
143
  const preset = resolvePreset(config.site.preset, {requireAssets: true});
147
- if (dryRun) {
148
- ui.start("Deploy dry-run", config.project.name);
149
- await build({ui, embedded: true});
150
- const {getBackofficeToken} = await import("../deploy/auth.mjs");
151
- const token = await getBackofficeToken({brand: preset.id});
152
- const {BackofficeClient} = await import("../deploy/backoffice-client.mjs");
153
- const client = new BackofficeClient({brand: preset.id, token, log: (message) => ui.warning(message)});
154
- const {planDeployment} = await import("../deploy/deploy.mjs");
155
- const result = await planDeployment({config, preset, client, section, log: (message) => ui.info(message.replace(/^\[dry-run\]\s*/, ""))});
156
- ui.complete(result.blocked ? `Plan blocked · ${result.blocked}` : "Dry-run complete · nothing was changed remotely");
144
+ if (status) {
145
+ ui.start("Deploy status", config.project.name);
146
+ const {deploymentStatus} = await import("../deploy/deploy.mjs");
147
+ const result = await deploymentStatus({
148
+ config, preset, section,
149
+ getToken: async () => {
150
+ const {getBackofficeToken} = await import("../deploy/auth.mjs");
151
+ return getBackofficeToken({brand: preset.id});
152
+ },
153
+ log: (message) => ui.info(message),
154
+ });
155
+ ui.complete("Status complete · no deployment changes were made");
157
156
  return result;
158
157
  }
159
158
  const {withDeploymentLock} = await import("../deploy/lock.mjs");
@@ -0,0 +1,19 @@
1
+ export function resolveDevPath(value = "/monkey/") {
2
+ const invalid = () => new Error(
3
+ "src/order.json devPath must be a path starting with a single /, without backslashes, wildcards or malformed URL characters"
4
+ );
5
+ if (typeof value !== "string" || !/^\/(?!\/)/.test(value) || /[\\\s\u0000-\u001f\u007f]/.test(value)) {
6
+ throw invalid();
7
+ }
8
+ try {
9
+ decodeURI(value);
10
+ encodeURI(value);
11
+ const pathname = value.split(/[?#]/, 1)[0];
12
+ if (pathname.includes("*") || /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i.test(pathname)) throw invalid();
13
+ const url = new URL(value, "https://dev-path.invalid");
14
+ if (url.origin !== "https://dev-path.invalid") throw invalid();
15
+ } catch {
16
+ throw invalid();
17
+ }
18
+ return value;
19
+ }
@@ -0,0 +1,18 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export const MARKUP_FORMATS = ["html", "pug"];
5
+
6
+ export function resolveMarkupFile({directory, key, markup}) {
7
+ const formats = markup === "mix" ? MARKUP_FORMATS : [markup];
8
+ const matches = formats
9
+ .map((format) => ({format, filePath: path.resolve(directory, `${key}.${format}`)}))
10
+ .filter(({filePath}) => fs.existsSync(filePath));
11
+
12
+ if (matches.length > 1) {
13
+ throw new Error(
14
+ `Ambiguous markup for block ${key}: src/markup/${key}.html and src/markup/${key}.pug both exist`
15
+ );
16
+ }
17
+ return matches[0] || null;
18
+ }
@@ -0,0 +1,60 @@
1
+ import {execFileSync} from "node:child_process";
2
+ import {existsSync, readFileSync} from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const packageJson = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
6
+ export const MINIMUM_NODE_VERSION = packageJson.engines.node.slice(2);
7
+ export const MINIMUM_NPM_VERSION = packageJson.engines.npm.slice(2);
8
+
9
+ function requireVersion(name, actual, minimum, update) {
10
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:\+[\w.-]+)?$/.exec(actual || "");
11
+ const expected = minimum.split(".").map(Number);
12
+ const numbers = match?.slice(1, 4).map(Number);
13
+ const difference = numbers?.findIndex((value, index) => value !== expected[index]);
14
+ if (!numbers || (difference !== -1 && numbers[difference] < expected[difference])) {
15
+ throw new Error(`${name} ${actual || "unknown"} is not supported. Required: >=${minimum}. ${update}`);
16
+ }
17
+ }
18
+
19
+ export function resolveNpmCommand({
20
+ platform = process.platform,
21
+ npmExecPath = process.env.npm_execpath,
22
+ nodeExecPath = process.execPath,
23
+ pathEnv = process.env.PATH || "",
24
+ fileExists = existsSync,
25
+ } = {}) {
26
+ if (npmExecPath) return {command: nodeExecPath, args: [npmExecPath], shell: false};
27
+ if (platform !== "win32") return {command: "npm", args: [], shell: false};
28
+
29
+ for (const entry of pathEnv.split(";").filter(Boolean)) {
30
+ const directory = entry.replace(/^"|"$/g, "");
31
+ if (!fileExists(path.win32.join(directory, "npm.cmd"))) continue;
32
+ const cli = path.win32.join(directory, "node_modules", "npm", "bin", "npm-cli.js");
33
+ if (!fileExists(cli)) throw new Error(`Cannot find npm-cli.js for npm on PATH: ${directory}. Reinstall npm.`);
34
+ return {command: nodeExecPath, args: [cli], shell: false};
35
+ }
36
+ throw new Error("Cannot find npm on PATH. Install Node.js and npm, then reopen your terminal.");
37
+ }
38
+
39
+ export function assertRuntime({
40
+ nodeVersion = process.versions.node,
41
+ npmVersion,
42
+ run = execFileSync,
43
+ ...npmOptions
44
+ } = {}) {
45
+ requireVersion("Node.js", nodeVersion, MINIMUM_NODE_VERSION,
46
+ `Update Node.js: https://nodejs.org/en/download (>=${MINIMUM_NODE_VERSION}).`);
47
+ if (npmVersion === undefined) {
48
+ try {
49
+ const npm = resolveNpmCommand(npmOptions);
50
+ npmVersion = String(run(npm.command, [...npm.args, "--version"], {
51
+ encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "pipe"], shell: npm.shell,
52
+ })).trim();
53
+ } catch (cause) {
54
+ throw new Error(`Cannot check npm version. Install npm >=${MINIMUM_NPM_VERSION} and ensure it is on PATH. ${cause.message}`, {cause});
55
+ }
56
+ }
57
+ requireVersion("npm", npmVersion, MINIMUM_NPM_VERSION,
58
+ `Update npm: npm install --global npm@${MINIMUM_NPM_VERSION}`);
59
+ return {nodeVersion, npmVersion};
60
+ }
@@ -6,7 +6,7 @@ const SUPPORTED_SCHEMA_VERSIONS = new Set([1, 2]);
6
6
  const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
7
7
  const STACK_VALUES = {
8
8
  script: SCRIPT_STACK_VALUES,
9
- markup: new Set(["html", "pug"]),
9
+ markup: new Set(["html", "pug", "mix"]),
10
10
  styles: new Set(["css", "scss", "less"]),
11
11
  };
12
12
  const SITE_PRESETS = new Set(["coral", "sunmar"]);
@@ -2,22 +2,24 @@ import fs from "node:fs";
2
2
  import {createRequire} from "node:module";
3
3
  import path from "node:path";
4
4
 
5
+ import {resolveDevPath} from "./dev-path.mjs";
5
6
  import {processMarkup} from "../lib/processMarkup.mjs";
7
+ import {resolveMarkupFile} from "./markup-stack.mjs";
6
8
  import {resolveScriptStack} from "./script-stack.mjs";
7
9
  import {hasDefaultInitializer} from "./validate-script-contract.mjs";
8
10
 
9
11
  const BLOCK_KEY_RE = /^[a-z0-9][a-z0-9-_]*$/i;
10
12
  const DEPLOY_FOLDER_RE = /^[a-z0-9][a-z0-9-]*$/;
11
13
  const STACK_DEPENDENCIES = {
12
- markup: {pug: ["pug"]},
13
14
  styles: {less: ["less"], scss: ["sass"]},
14
15
  };
15
16
  const SCRIPT_EXTENSIONS = ["js", "ts"];
16
17
 
17
- function validateLocalDependencies(config, root) {
18
+ function validateLocalDependencies(config, root, {usesPug = false} = {}) {
18
19
  const projectRequire = createRequire(path.resolve(root, "package.json"));
19
20
  const dependencies = [
20
21
  ...resolveScriptStack(config.stack.script).dependencies,
22
+ ...(usesPug ? ["pug"] : []),
21
23
  ...Object.entries(STACK_DEPENDENCIES)
22
24
  .flatMap(([section, values]) => values[config.stack[section]] || []),
23
25
  ];
@@ -59,9 +61,12 @@ export function validateProject(config, root = process.cwd(), {strict = false} =
59
61
  throw new Error("src/order.json folder must match ^[a-z0-9][a-z0-9-]*$");
60
62
  }
61
63
 
64
+ resolveDevPath(order.devPath);
65
+
62
66
  const seen = new Set();
63
67
  const staticBlocks = new Set(config.blocks?.static || []);
64
68
  const blockDetails = [];
69
+ let usesPug = false;
65
70
  for (const key of order.blocks) {
66
71
  if (typeof key !== "string" || !BLOCK_KEY_RE.test(key)) {
67
72
  throw new Error(`Invalid block key in src/order.json: ${JSON.stringify(key)}`);
@@ -69,12 +74,20 @@ export function validateProject(config, root = process.cwd(), {strict = false} =
69
74
  if (seen.has(key)) throw new Error(`Duplicate block key in src/order.json: ${key}`);
70
75
  seen.add(key);
71
76
 
72
- const markupPath = path.resolve(root, "src/markup", `${key}.${config.stack.markup}`);
73
- if (!fs.existsSync(markupPath)) {
74
- throw new Error(`Missing configured markup for block ${key}: src/markup/${key}.${config.stack.markup}`);
77
+ const markup = resolveMarkupFile({
78
+ directory: path.resolve(root, "src/markup"),
79
+ key,
80
+ markup: config.stack.markup,
81
+ });
82
+ if (!markup) {
83
+ const expected = config.stack.markup === "mix"
84
+ ? `src/markup/${key}.html or src/markup/${key}.pug`
85
+ : `src/markup/${key}.${config.stack.markup}`;
86
+ throw new Error(`Missing configured markup for block ${key}: ${expected}`);
75
87
  }
76
- if (config.stack.markup === "html") {
77
- processMarkup(fs.readFileSync(markupPath, "utf8"), {filePath: markupPath});
88
+ usesPug ||= markup.format === "pug";
89
+ if (markup.format === "html") {
90
+ processMarkup(fs.readFileSync(markup.filePath, "utf8"), {filePath: markup.filePath});
78
91
  }
79
92
 
80
93
  const stylePath = path.resolve(root, "src/styles", `${key}.${config.stack.styles}`);
@@ -120,6 +133,6 @@ export function validateProject(config, root = process.cwd(), {strict = false} =
120
133
  if (!seen.has(key)) throw new Error(`Unknown block in blocks.static: ${key}`);
121
134
  }
122
135
 
123
- validateLocalDependencies(config, root);
136
+ validateLocalDependencies(config, root, {usesPug});
124
137
  return {folder: order.folder, blocks: [...order.blocks], blockDetails};
125
138
  }
@@ -13,10 +13,10 @@ function callableDefaultExport(program) {
13
13
  const exported = program.body.find((node) => node.type === "ExportDefaultDeclaration")?.declaration;
14
14
  const target = exported?.type === "Identifier" ? bindings.get(exported.name) : exported;
15
15
  return target?.type === "FunctionDeclaration" || target?.type === "FunctionExpression" ||
16
- target?.type === "ArrowFunctionExpression";
16
+ target?.type === "ArrowFunctionExpression" ? target : null;
17
17
  }
18
18
 
19
- export function hasDefaultInitializer({source, filePath, extension}) {
19
+ function parseScript({source, filePath, extension}) {
20
20
  let program;
21
21
  try {
22
22
  program = parse(source, {
@@ -27,5 +27,25 @@ export function hasDefaultInitializer({source, filePath, extension}) {
27
27
  const language = extension === "ts" ? "TypeScript" : "JavaScript";
28
28
  throw new Error(`${filePath} contains invalid ${language}: ${error.message}`, {cause: error});
29
29
  }
30
- return callableDefaultExport(program);
30
+ return program;
31
+ }
32
+
33
+ export function hasDefaultInitializer(options) {
34
+ return Boolean(callableDefaultExport(parseScript(options)));
35
+ }
36
+
37
+ export function hasEmptyDefaultInitializer(options) {
38
+ const program = parseScript(options);
39
+ const initializer = callableDefaultExport(program);
40
+ if (!initializer || initializer.params.length || initializer.body.type !== "BlockStatement" ||
41
+ initializer.body.body.some((node) => node.type !== "EmptyStatement")) return false;
42
+
43
+ // Keep the call when module-level code could replace the exported binding.
44
+ return program.body.every((node) =>
45
+ node === initializer || node.type === "ExportDefaultDeclaration" ||
46
+ node.type === "ImportDeclaration" || node.type === "EmptyStatement" ||
47
+ node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration" ||
48
+ (node.type === "VariableDeclaration" && node.kind === "const" &&
49
+ node.declarations.length === 1 && node.declarations[0].init === initializer)
50
+ );
31
51
  }
@@ -1,4 +1,4 @@
1
- import {assertNoAssetConflicts, planAssetChanges, uploadChangedAssets} from "./assets.mjs";
1
+ import {assertNoAssetConflicts, planAssetChanges, uploadChangedAssets, remoteAssetReader} from "./assets.mjs";
2
2
  import {BackofficeClient} from "./backoffice-client.mjs";
3
3
  import {readBuildManifest} from "./manifest.mjs";
4
4
  import {readDeploymentState, writeDeploymentState} from "./state.mjs";
@@ -102,6 +102,7 @@ export async function deployAssetsCommand({
102
102
  state,
103
103
  remoteRoot,
104
104
  listFiles: api.listFiles.bind(api),
105
+ readRemoteAsset: api.readRemoteAsset?.bind(api) || remoteAssetReader(preset.assetsBase, api.fetchImpl),
105
106
  });
106
107
  const upload = plan.upload.map((asset) => asset.path);
107
108
  const skip = plan.skip.map((asset) => asset.path);
@@ -1,4 +1,14 @@
1
1
  import path from "node:path";
2
+ import crypto from "node:crypto";
3
+
4
+ export function remoteAssetReader(assetsBase, fetchImpl = globalThis.fetch) {
5
+ return async (assetPath) => {
6
+ const url = `${assetsBase.replace(/\/$/, "")}/${assetPath.split("/").map(encodeURIComponent).join("/")}`;
7
+ const response = await fetchImpl(url, {signal: AbortSignal.timeout(30000), cache: "no-store"});
8
+ if (!response.ok) throw new Error(`Cannot verify CDN asset ${assetPath}: HTTP ${response.status}`);
9
+ return new Uint8Array(await response.arrayBuffer());
10
+ };
11
+ }
2
12
 
3
13
  export function changedAssets(manifest, state) {
4
14
  return manifest.assets.filter((asset) => state.assets?.[asset.path]?.sha256 !== asset.sha256);
@@ -17,7 +27,7 @@ function filesFromListing(listing) {
17
27
  return new Set(files.map((file) => typeof file === "string" ? path.posix.basename(file) : file.name));
18
28
  }
19
29
 
20
- export async function planAssetChanges({manifest, state, listFiles, remoteRoot = "/content", prune = false}) {
30
+ export async function planAssetChanges({manifest, state, listFiles, readRemoteAsset, remoteRoot = "/content", prune = false}) {
21
31
  const pending = changedAssets(manifest, state);
22
32
  if (!listFiles) {
23
33
  return {
@@ -55,7 +65,13 @@ export async function planAssetChanges({manifest, state, listFiles, remoteRoot =
55
65
  }
56
66
  const deployedAsset = state.assets?.[asset.path];
57
67
  if (deployedAsset?.sha256 && deployedAsset.sha256 !== asset.sha256) conflicts.push(asset);
58
- else skip.push(asset);
68
+ else {
69
+ if (!readRemoteAsset) throw new Error(`Cannot verify unknown CDN asset: ${asset.path}`);
70
+ const bytes = await readRemoteAsset(`${manifest.assetsPrefix}/${asset.path}`);
71
+ const hash = crypto.createHash("sha256").update(bytes).digest("hex");
72
+ if (hash !== asset.sha256) conflicts.push(asset);
73
+ else skip.push(asset);
74
+ }
59
75
  }));
60
76
  const byPath = (left, right) => left.path.localeCompare(right.path);
61
77
  return {
@@ -102,13 +118,14 @@ export async function uploadChangedAssets({
102
118
  root = process.cwd(),
103
119
  uploadFile,
104
120
  listFiles,
121
+ readRemoteAsset,
105
122
  remoteRoot = "/content",
106
123
  concurrency = 5,
107
124
  prune = false,
108
125
  deleteFile,
109
126
  plan: preparedPlan,
110
127
  }) {
111
- const plan = preparedPlan || await planAssetChanges({manifest, state, listFiles, remoteRoot, prune});
128
+ const plan = preparedPlan || await planAssetChanges({manifest, state, listFiles, readRemoteAsset, remoteRoot, prune});
112
129
  assertNoAssetConflicts(plan);
113
130
  const assets = {...state.assets};
114
131
  const uploaded = [];
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  export const RU_LANGUAGE_ID = "1049";
5
5
  export const HTML_WIDGET_ID = "d400b0e7-918d-4d4c-bea3-8522253b6544";
6
6
  export const STATUS = Object.freeze({published: 1, checkout: 2, unpublished: 4});
7
- const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
7
+ const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
8
8
 
9
9
  export class BackofficeRequestError extends Error {
10
10
  constructor(message, {code, status, method, endpoint, retryable = false, cause} = {}) {
@@ -40,6 +40,14 @@ function retryDelay(response, attempt) {
40
40
 
41
41
  const defaultSleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
42
42
 
43
+ const uploadMimeTypes = {
44
+ html: "text/html", htm: "text/html", css: "text/css", js: "text/javascript", mjs: "text/javascript",
45
+ json: "application/json", map: "application/json", xml: "application/xml", svg: "image/svg+xml", jpg: "image/jpeg",
46
+ jpeg: "image/jpeg", png: "image/png", webp: "image/webp", avif: "image/avif", gif: "image/gif",
47
+ ico: "image/vnd.microsoft.icon", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf",
48
+ otf: "font/otf", pdf: "application/pdf", mp4: "video/mp4", webm: "video/webm", ogv: "video/ogg",
49
+ };
50
+
43
51
  export class BackofficeClient {
44
52
  constructor({
45
53
  brand,
@@ -221,7 +229,10 @@ export class BackofficeClient {
221
229
  const form = new FormData();
222
230
  form.append("Body.OverWrite", "false");
223
231
  form.append("Body.Path", parsed.dir.replace(/^\/+/, ""));
224
- form.append("Body.Files", new Blob([fs.readFileSync(localPath)]), parsed.base);
232
+ const extension = parsed.ext.slice(1).toLowerCase();
233
+ const mimeType = Object.hasOwn(uploadMimeTypes, extension) ? uploadMimeTypes[extension] : undefined;
234
+ const file = new Blob([fs.readFileSync(localPath)], mimeType ? {type: mimeType} : undefined);
235
+ form.append("Body.Files", file, parsed.base);
225
236
  const result = await this.request("POST", "/FileManagement/UploadFile", {form});
226
237
  return result?.result;
227
238
  }