Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6,681 changes: 6,681 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"raisely": "./bin/raisely.js"
},
"scripts": {
"test": "node --test"
"test": "vitest run --config vitest.config.js"
},
"engines": {
"node": ">=18"
Expand Down Expand Up @@ -40,7 +40,8 @@
"p-limit": "^4.0.0"
},
"devDependencies": {
"prettier": "^2.6.2"
"prettier": "^2.6.2",
"vitest": "^1.6.1"
},
"repository": {
"type": "git",
Expand Down
4 changes: 4 additions & 0 deletions src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export async function cli() {
.description(
'Synchronise (push) a remote Raisely campaign with the files on this machine'
)
.option(
'--no-validate',
'Skip pre-flight SCSS/component validation before upload'
)
.option(
'-f, --force',
'Deploy without asking for confirmation (non-interactive)'
Expand Down
255 changes: 202 additions & 53 deletions src/deploy.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,35 +21,169 @@ import {
import { uploadPage } from './actions/pages.js';
import { loadConfig } from './config.js';
import { getToken } from './actions/auth.js';
import {
validateCampaignSass,
validateComponent,
} from './actions/validate.js';

function createDeployDependencies(overrides = {}) {
return {
loadConfigFn: overrides.loadConfigFn || loadConfig,
getTokenFn: overrides.getTokenFn || getToken,
getCampaignFn: overrides.getCampaignFn || getCampaign,
uploadStylesFn: overrides.uploadStylesFn || uploadStyles,
updateComponentConfigFn:
overrides.updateComponentConfigFn || updateComponentConfig,
updateComponentFileFn: overrides.updateComponentFileFn || updateComponentFile,
uploadPageFn: overrides.uploadPageFn || uploadPage,
validateCampaignSassFn:
overrides.validateCampaignSassFn || validateCampaignSass,
validateComponentFn: overrides.validateComponentFn || validateComponent,
globFn: overrides.globFn || glob,
fsModule: overrides.fsModule || fs,
pathModule: overrides.pathModule || path,
logFn: overrides.logFn || log,
brFn: overrides.brFn || br,
welcomeFn: overrides.welcomeFn || welcome,
informUpdateFn: overrides.informUpdateFn || informUpdate,
loaderFactory: overrides.loaderFactory || ora,
consoleRef: overrides.consoleRef || console,
cwd: overrides.cwd || process.cwd,
setExitCode:
overrides.setExitCode ||
((code) => {
process.exitCode = code;
}),
};
}

function formatValidationErrors(errors) {
return errors.map(({ context, error }) => `${context}: ${error}`);
}

function normalizeValidationResult(result, fallbackError) {
if (result && typeof result === 'object' && typeof result.ok === 'boolean') {
return {
ok: result.ok,
error:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing error normalization for empty strings

Low Severity

The normalizeValidationResult function checks if result.error is a non-empty string with result.error.trim(), but doesn't handle the case where result.error is an empty string after trimming. This results in the fallback error being used even when an empty string error was explicitly provided.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4b95fa8. Configure here.

typeof result.error === 'string' && result.error.trim()
? result.error
: fallbackError,
};
}

return {
ok: false,
error: fallbackError,
};
}

function getComponentNames({ fsModule, pathModule, cwd }) {
const componentsDir = pathModule.join(cwd(), 'components');
if (!fsModule.existsSync(componentsDir)) {
return [];
}

return fsModule
.readdirSync(componentsDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
}

async function runPreflightValidation({ config }, dependencies) {
const deps = createDeployDependencies(dependencies);
const validationLimit = pLimit(4);
const loader = deps.loaderFactory('Validating campaigns and components').start();
const campaigns = await Promise.all(
config.campaigns.map(async (campaignUuid) => {
const campaign = await deps.getCampaignFn({ uuid: campaignUuid });
return {
uuid: campaign.data.uuid,
path: campaign.data.path,
};
})
);
const componentNames = getComponentNames(deps);

const validationTasks = [
...campaigns.map((campaign) =>
validationLimit(async () => {
const rawResult = await deps.validateCampaignSassFn({
campaign,
token: config.token,
});
const result = normalizeValidationResult(
rawResult,
'SASS validator returned an invalid response.'
);
return {
ok: result.ok,
context: `Campaign ${campaign.path}`,
error: result.error,
};
})
),
...componentNames.map((name) =>
validationLimit(async () => {
const rawResult = await deps.validateComponentFn({ name });
const result = normalizeValidationResult(
rawResult,
'Component validator returned an invalid response.'
);
return {
ok: result.ok,
context: `Component ${name}`,
error: result.error,
};
})
),
];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race condition in validation error handling

Medium Severity

The validation runs in parallel with a concurrency limit of 4, but the loader is started before all tasks begin. If validation fails very quickly (e.g., first batch fails), the loader shows "Validation passed" or "Deploy validation failed" before all validations complete, potentially missing errors from later batches.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4b95fa8. Configure here.


Comment thread
cursor[bot] marked this conversation as resolved.
const results = await Promise.all(validationTasks);
const failed = results.filter((result) => !result.ok);

if (failed.length > 0) {
loader.fail('Deploy validation failed');
formatValidationErrors(failed).forEach((message) => {
deps.logFn(message, 'red');
});
return false;
}

loader.succeed('Validation passed');
return true;
}

export default async function deploy(options = {}) {
const layout = detectLayout(process.cwd());
export default async function deploy(options = {}, dependencies = {}) {
const deps = createDeployDependencies(dependencies);
const cwd = deps.cwd();
const layout = detectLayout(cwd);
if (shouldRefuseLayoutForCommand('deploy', layout)) {
br();
log(getLegacyLayoutRefusalMessage('deploy', layout), 'red');
process.exitCode = 1;
deps.brFn();
deps.logFn(getLegacyLayoutRefusalMessage('deploy', layout), 'red');
deps.setExitCode(1);
return;
}

// load config
let config = await loadConfig();
await getToken(program, config);

welcome();
log(`You are about to deploy your local directly to Raisely`, 'white');
br();
console.log(` ${chalk.inverse(`${process.cwd()}`)}`);
br();
let config = await deps.loadConfigFn();
config.token = await deps.getTokenFn(program, config);

Comment thread
KeinerM marked this conversation as resolved.
deps.welcomeFn();
deps.logFn(`You are about to deploy your local directly to Raisely`, 'white');
deps.brFn();
deps.consoleRef.log(` ${chalk.inverse(`${cwd}`)}`);
deps.brFn();
if (config.apiUrl) {
br();
console.log(`Using custom API: ${chalk.inverse(config.apiUrl)}`);
br();
deps.brFn();
deps.consoleRef.log(`Using custom API: ${chalk.inverse(config.apiUrl)}`);
deps.brFn();
}
log(
deps.logFn(
`You will overwrite the styles, components, and pages in your campaign.`,
'white'
);
br();
deps.brFn();

if (!config.cli && !options.force) {
const response = await inquirer.prompt([
Expand All @@ -61,23 +195,36 @@ export default async function deploy(options = {}) {
]);

if (!response.confirm) {
br();
return log('Deploy aborted', 'red');
deps.brFn();
return deps.logFn('Deploy aborted', 'red');
}
}

if (options.validate !== false) {
const validationPassed = await runPreflightValidation({ config }, deps);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Token retrieval happens before validation option check

Low Severity

Authentication token is retrieved even when using --no-validate flag and validation might not require it. This causes unnecessary API calls and potential authentication prompts when skipping validation.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4b95fa8. Configure here.

if (!validationPassed) {
deps.brFn();
deps.setExitCode(1);
return;
}
} else {
deps.logFn('Skipping validation due to --no-validate flag.', 'yellow');
}

// upload campaign stylesheets
for (const campaignUuid of config.campaigns) {
const loader = ora(`Uploading styles for ${campaignUuid}`).start();
const loader = deps.loaderFactory(`Uploading styles for ${campaignUuid}`).start();

const campaign = await getCampaign({ uuid: campaignUuid });
const campaign = await deps.getCampaignFn({ uuid: campaignUuid });

try {
await uploadStyles(campaign.data.path);
await deps.uploadStylesFn(campaign.data.path);
} catch (e) {
br();
console.error(e);
process.exit(1);
loader.fail(`Failed to upload styles for ${campaignUuid}`);
deps.brFn();
deps.consoleRef.error(e);
deps.setExitCode(1);
return;
Comment thread
cursor[bot] marked this conversation as resolved.
}

loader.succeed();
Expand All @@ -87,27 +234,29 @@ export default async function deploy(options = {}) {
const limit = pLimit(5);
const components = [];

const componentsDir = path.join(process.cwd(), 'components');
for (const file of fs.readdirSync(componentsDir)) {
const data = {
file: fs.readFileSync(
path.join(componentsDir, file, `${file}.js`),
'utf8'
),
config: JSON.parse(
fs.readFileSync(
path.join(componentsDir, file, `${file}.json`),
const componentsDir = deps.pathModule.join(cwd, 'components');
if (deps.fsModule.existsSync(componentsDir)) {
for (const file of deps.fsModule.readdirSync(componentsDir)) {
const data = {
file: deps.fsModule.readFileSync(
deps.pathModule.join(componentsDir, file, `${file}.js`),
'utf8'
)
),
};
),
config: JSON.parse(
deps.fsModule.readFileSync(
deps.pathModule.join(componentsDir, file, `${file}.json`),
'utf8'
)
),
};

components.push(limit(() => updateComponentConfig(data)));
components.push(limit(() => updateComponentFile(data)));
components.push(limit(() => deps.updateComponentConfigFn(data)));
components.push(limit(() => deps.updateComponentFileFn(data)));
}
}

// Start loading all the components
const loader = ora(`Uploading components`).start();
const loader = deps.loaderFactory(`Uploading components`).start();
const deployResult = await Promise.allSettled(components);

const rejected = deployResult
Expand All @@ -117,21 +266,21 @@ export default async function deploy(options = {}) {
if (rejected.length > 0) {
loader.warn('The following errors occured while uploading components:');
rejected.forEach((error) => {
log(error, 'red');
deps.logFn(error, 'red');
});
} else {
loader.succeed();
}

// upload pages
const pageFiles = await glob('campaigns/*/pages/**/*.json', {
cwd: process.cwd(),
const pageFiles = await deps.globFn('campaigns/*/pages/**/*.json', {
cwd,
});

const pageTasks = [];
for (const file of pageFiles) {
const fullPath = path.join(process.cwd(), file);
const pageData = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
const fullPath = deps.pathModule.join(cwd, file);
const pageData = JSON.parse(deps.fsModule.readFileSync(fullPath, 'utf8'));
if (!pageData.uuid) {
continue;
}
Expand All @@ -141,12 +290,12 @@ export default async function deploy(options = {}) {
) {
continue;
}
pageTasks.push(limit(() => uploadPage(pageData)));
pageTasks.push(limit(() => deps.uploadPageFn(pageData)));
}

let pageRejected = [];
if (pageTasks.length > 0) {
const pageLoader = ora(`Uploading pages`).start();
const pageLoader = deps.loaderFactory(`Uploading pages`).start();
const pageResults = await Promise.allSettled(pageTasks);

pageRejected = pageResults
Expand All @@ -158,16 +307,16 @@ export default async function deploy(options = {}) {
'The following errors occured while uploading pages:'
);
pageRejected.forEach((err) => {
log(err, 'red');
deps.logFn(err, 'red');
});
} else {
pageLoader.succeed();
}
}

if (rejected.length === 0 && pageRejected.length === 0) {
await informUpdate();
await deps.informUpdateFn();
}
br();
log(`All done!`, 'green');
deps.brFn();
deps.logFn(`All done!`, 'green');
}
2 changes: 1 addition & 1 deletion tests/campaigns.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { test, describe } from 'node:test';
import { describe, test } from 'vitest';
import assert from 'node:assert/strict';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
Expand Down
2 changes: 1 addition & 1 deletion tests/command-layout-guard.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { test } from 'node:test';
import { test } from 'vitest';
import assert from 'node:assert/strict';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
Expand Down
Loading