@solidactions/cli 3.26.0 → 3.28.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "cli_name": "solidactions",
4
- "cli_version": "3.26.0",
4
+ "cli_version": "3.28.0",
5
5
  "global_options": [
6
6
  {
7
7
  "flags": "-V, --version",
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PLAN_LIMIT_NON_INTERACTIVE_HINT = exports.SKILLS_TIP_LINES = void 0;
7
+ exports.validateProject = validateProject;
7
8
  exports.cacheBusterEntry = cacheBusterEntry;
8
9
  exports.projectStatusUrl = projectStatusUrl;
9
10
  exports.fetchDeploymentConfirmation = fetchDeploymentConfirmation;
@@ -26,6 +27,9 @@ const chalk_1 = __importDefault(require("chalk"));
26
27
  const js_yaml_1 = __importDefault(require("js-yaml"));
27
28
  const prompts_1 = __importDefault(require("prompts"));
28
29
  const env_1 = require("../utils/env");
30
+ const validate_items_1 = require("../utils/validate-items");
31
+ const pages_sync_1 = require("../utils/pages-sync");
32
+ const functions_sync_1 = require("../utils/functions-sync");
29
33
  const api_1 = require("../utils/api");
30
34
  const host_display_1 = require("../utils/host-display");
31
35
  const deploy_ignore_1 = require("../utils/deploy-ignore");
@@ -33,6 +37,7 @@ const slug_1 = require("../utils/slug");
33
37
  const project_ref_1 = require("../utils/project-ref");
34
38
  const skills_1 = require("../utils/skills");
35
39
  const tar_archive_1 = require("../utils/tar-archive");
40
+ const deploy_status_poll_1 = require("../utils/deploy-status-poll");
36
41
  const source_provenance_1 = require("../utils/source-provenance");
37
42
  const project_view_1 = require("./project-view");
38
43
  /** Printed when a deploy target has no SolidActions skill files installed. */
@@ -54,62 +59,81 @@ function validateProject(sourceDir) {
54
59
  errors.push('solidactions.yaml not found. This file defines your workflows.');
55
60
  return { valid: false, errors, warnings };
56
61
  }
57
- // Check for package.json
58
- const packageJsonPath = path_1.default.join(sourceDir, 'package.json');
59
- if (!fs_1.default.existsSync(packageJsonPath)) {
60
- errors.push('package.json not found. Initialize with: npm init');
62
+ // Parse solidactions.yaml
63
+ let config;
64
+ try {
65
+ const configContent = fs_1.default.readFileSync(solidactionsPath, 'utf8');
66
+ config = js_yaml_1.default.load(configContent);
67
+ }
68
+ catch (err) {
69
+ errors.push(`Failed to parse solidactions.yaml: ${err.message}`);
61
70
  return { valid: false, errors, warnings };
62
71
  }
63
- // Read and validate package.json
64
- const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
65
- const allDeps = { ...packageJson.dependencies, ...packageJson.devDependencies };
66
- // Check for SDK - either @solidactions/sdk or bundled sdk folder
67
- const hasSdkPackage = '@solidactions/sdk' in allDeps;
68
- const hasBundledSdk = fs_1.default.existsSync(path_1.default.join(sourceDir, 'sdk'));
69
- if (!hasSdkPackage && !hasBundledSdk) {
70
- errors.push('Missing SDK in package.json dependencies. Run: npm install @solidactions/sdk');
71
- }
72
- // Check for TypeScript config if .ts files are used
73
- const srcDir = path_1.default.join(sourceDir, 'src');
74
- const hasTypeScriptFiles = fs_1.default.existsSync(srcDir) &&
75
- fs_1.default.readdirSync(srcDir).some(f => f.endsWith('.ts') || f.endsWith('.tsx'));
76
- if (hasTypeScriptFiles) {
77
- const tsconfigPath = path_1.default.join(sourceDir, 'tsconfig.json');
78
- if (!fs_1.default.existsSync(tsconfigPath)) {
79
- warnings.push('TypeScript files detected but tsconfig.json not found. Build may fail.');
80
- }
72
+ const raw = (config ?? {});
73
+ // Presence selects the retained workflow checks: an explicit `workflows: []`
74
+ // still requires package.json and the SDK.
75
+ const hasWorkflows = Array.isArray(raw.workflows);
76
+ const hasPages = Array.isArray(raw.pages) && raw.pages.length > 0;
77
+ const hasFunctions = Array.isArray(raw.functions) && raw.functions.length > 0;
78
+ if (config?.workflows !== undefined && !Array.isArray(config.workflows)) {
79
+ errors.push('Invalid solidactions.yaml: workflows section is required.');
80
+ }
81
+ else if (!hasWorkflows && !hasPages && !hasFunctions) {
82
+ errors.push('solidactions.yaml must declare at least one of workflows, pages, functions.');
83
+ return { valid: false, errors, warnings };
81
84
  }
82
- // Parse and validate solidactions.yaml
83
- try {
84
- const configContent = fs_1.default.readFileSync(solidactionsPath, 'utf8');
85
- const config = js_yaml_1.default.load(configContent);
86
- if (!config || !config.workflows || !Array.isArray(config.workflows)) {
87
- errors.push('Invalid solidactions.yaml: workflows section is required.');
85
+ if (hasWorkflows) {
86
+ // Check for package.json
87
+ const packageJsonPath = path_1.default.join(sourceDir, 'package.json');
88
+ if (!fs_1.default.existsSync(packageJsonPath)) {
89
+ errors.push('package.json not found. Initialize with: npm init');
90
+ return { valid: false, errors, warnings };
88
91
  }
89
- else {
90
- // Validate each workflow
91
- for (const wf of config.workflows) {
92
- if (!wf.name) {
93
- errors.push(`Workflow missing required 'name' field.`);
94
- continue;
95
- }
96
- // Must have either command: or file:
97
- if (!wf.command && !wf.file) {
98
- errors.push(`Workflow "${wf.name}": must specify either 'command:' or 'file:'.`);
99
- continue;
100
- }
101
- // If file: is specified, verify the file exists
102
- if (wf.file) {
103
- const filePath = path_1.default.join(sourceDir, wf.file);
104
- if (!fs_1.default.existsSync(filePath)) {
105
- errors.push(`Workflow "${wf.name}": file "${wf.file}" not found.`);
106
- }
92
+ // Read and validate package.json
93
+ const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
94
+ const allDeps = { ...packageJson.dependencies, ...packageJson.devDependencies };
95
+ // Check for SDK - either @solidactions/sdk or bundled sdk folder
96
+ const hasSdkPackage = '@solidactions/sdk' in allDeps;
97
+ const hasBundledSdk = fs_1.default.existsSync(path_1.default.join(sourceDir, 'sdk'));
98
+ if (!hasSdkPackage && !hasBundledSdk) {
99
+ errors.push('Missing SDK in package.json dependencies. Run: npm install @solidactions/sdk');
100
+ }
101
+ // Check for TypeScript config if .ts files are used
102
+ const srcDir = path_1.default.join(sourceDir, 'src');
103
+ const hasTypeScriptFiles = fs_1.default.existsSync(srcDir) &&
104
+ fs_1.default.readdirSync(srcDir).some(f => f.endsWith('.ts') || f.endsWith('.tsx'));
105
+ if (hasTypeScriptFiles) {
106
+ const tsconfigPath = path_1.default.join(sourceDir, 'tsconfig.json');
107
+ if (!fs_1.default.existsSync(tsconfigPath)) {
108
+ warnings.push('TypeScript files detected but tsconfig.json not found. Build may fail.');
109
+ }
110
+ }
111
+ // Validate each workflow
112
+ for (const wf of config.workflows ?? []) {
113
+ if (typeof wf !== 'object' || wf === null) {
114
+ errors.push(`Workflow entry must be an object with a 'name' field.`);
115
+ continue;
116
+ }
117
+ if (!wf.name) {
118
+ errors.push(`Workflow missing required 'name' field.`);
119
+ continue;
120
+ }
121
+ // Must have either command: or file:
122
+ if (!wf.command && !wf.file) {
123
+ errors.push(`Workflow "${wf.name}": must specify either 'command:' or 'file:'.`);
124
+ continue;
125
+ }
126
+ // If file: is specified, verify the file exists
127
+ if (wf.file) {
128
+ const filePath = path_1.default.join(sourceDir, wf.file);
129
+ if (!fs_1.default.existsSync(filePath)) {
130
+ errors.push(`Workflow "${wf.name}": file "${wf.file}" not found.`);
107
131
  }
108
132
  }
109
133
  }
110
134
  }
111
- catch (err) {
112
- errors.push(`Failed to parse solidactions.yaml: ${err.message}`);
135
+ for (const itemError of (0, validate_items_1.validateItems)(config, sourceDir)) {
136
+ errors.push(`${itemError.entry}.${itemError.field}: ${itemError.message}`);
113
137
  }
114
138
  return { valid: errors.length === 0, errors, warnings };
115
139
  }
@@ -581,9 +605,82 @@ async function deploy(projectName, sourcePath, options = {}) {
581
605
  const sourceMetadata = safeCollectSourceMetadata(sourceDir, options, (directory) => (0, source_provenance_1.collectSourceMetadata)(directory, process.env, (hint) => {
582
606
  console.log(chalk_1.default.yellow(`Git provenance hint: ${hint}`));
583
607
  }));
584
- if (sourceMetadata) {
608
+ if (sourceMetadata && yamlConfig?.workflows) {
585
609
  console.log(chalk_1.default.gray(`Revision to upload (client-reported): ${(0, source_provenance_1.formatRevisionSummary)(sourceMetadata)}`));
586
610
  }
611
+ const pageFiles = (0, pages_sync_1.listCodePages)(yamlConfig ?? {});
612
+ let pageBodies;
613
+ try {
614
+ pageBodies = (0, pages_sync_1.readPageBodies)(sourceDir, pageFiles);
615
+ }
616
+ catch (error) {
617
+ console.error(chalk_1.default.red(`Failed to read page: ${error.message}`));
618
+ process.exit(1);
619
+ }
620
+ const codeRef = sourceMetadata ? {
621
+ branch: sourceMetadata.branch,
622
+ short_sha: sourceMetadata.short_sha,
623
+ commit_sha: sourceMetadata.commit_sha,
624
+ dirty: sourceMetadata.dirty,
625
+ } : null;
626
+ // Functions sync runs before the workflow archive build (spec 3.1): the
627
+ // server compiles and uploads each code function on its own. Editor
628
+ // pointers are never sent (listCodeFunctions skips them).
629
+ const functionFiles = (0, functions_sync_1.listCodeFunctions)(yamlConfig ?? {});
630
+ let functionSources;
631
+ try {
632
+ functionSources = (0, functions_sync_1.readFunctionSources)(sourceDir, functionFiles);
633
+ }
634
+ catch (error) {
635
+ console.error(chalk_1.default.red(`Failed to read function: ${error.message}`));
636
+ process.exit(1);
637
+ }
638
+ const functionsPayload = (0, functions_sync_1.buildFunctionsSyncPayload)(functionFiles, functionSources, codeRef);
639
+ const functionsResult = await (0, functions_sync_1.syncFunctions)(config, projectSlug, functionsPayload);
640
+ const functionRows = functionsResult.body?.functions ?? [];
641
+ const retiredFunctions = functionsResult.body?.retired ?? [];
642
+ const retireErrors = functionsResult.body?.retire_errors ?? [];
643
+ const functionsInput = { httpStatus: functionsResult.httpStatus, transportError: functionsResult.transportError, sentFunctionCount: functionFiles.length };
644
+ const functionsFailure = (0, functions_sync_1.formatFunctionsSyncFailure)({ ...functionsInput, body: functionsResult.body });
645
+ for (const line of (0, functions_sync_1.formatFunctionsSummary)(functionRows, retiredFunctions, retireErrors))
646
+ console.log(line);
647
+ if (functionsFailure)
648
+ console.error(chalk_1.default.red(functionsFailure));
649
+ const functionsOutcome = (0, functions_sync_1.functionsSyncOutcome)({ ...functionsInput, body: functionsResult.body, rows: functionRows, retireErrors });
650
+ const finishDeploy = async ({ deploymentId, buildFailed }) => {
651
+ let yamlSyncFailed = false;
652
+ if (yamlConfig) {
653
+ try {
654
+ await pushYamlDeclarations(config, projectSlug, yamlConfig);
655
+ }
656
+ catch (error) {
657
+ yamlSyncFailed = true;
658
+ if (error.response?.status === 401) {
659
+ console.error(chalk_1.default.red((0, api_1.authFailedLine)(config.host)));
660
+ }
661
+ else {
662
+ console.error(chalk_1.default.red(`Config sync FAILED: ${error.response?.data?.message || error.message}`));
663
+ }
664
+ }
665
+ }
666
+ const payload = (0, pages_sync_1.buildPagesSyncPayload)(pageFiles, pageBodies, deploymentId, codeRef);
667
+ const result = await (0, pages_sync_1.syncPages)(config, projectSlug, payload);
668
+ const rows = result.body?.pages ?? [];
669
+ const trashed = result.body?.trashed ?? [];
670
+ const trashErrors = result.body?.trash_errors ?? [];
671
+ const input = { httpStatus: result.httpStatus, transportError: result.transportError, sentPageCount: pageFiles.length };
672
+ const failure = (0, pages_sync_1.formatPagesSyncFailure)({ ...input, body: result.body });
673
+ for (const line of (0, pages_sync_1.formatPagesSummary)(rows, trashed, trashErrors))
674
+ console.log(line);
675
+ if (failure)
676
+ console.error(chalk_1.default.red(failure));
677
+ const pagesOutcome = (0, pages_sync_1.pagesSyncOutcome)({ ...input, rows, trashErrors, stamp: result.body?.stamp });
678
+ const outcome = (0, functions_sync_1.joinSyncOutcomes)(functionsOutcome, pagesOutcome);
679
+ process.exit((0, pages_sync_1.terminalExitCode)({ buildFailed, yamlSyncFailed, outcome }));
680
+ };
681
+ if (!yamlConfig?.workflows) {
682
+ return finishDeploy({ deploymentId: null, buildFailed: false });
683
+ }
587
684
  // Plan the file list BEFORE creating the archive write stream so a walk error
588
685
  // (permission error, unreadable dir) aborts cleanly with no orphan tarball.
589
686
  let plan;
@@ -650,99 +747,67 @@ async function deploy(projectName, sourcePath, options = {}) {
650
747
  process.stderr.write(`[deploy-debug] poll URL = ${(0, host_display_1.displayHost)(config.host)}/api/v1/projects/${projectSlug} (workspace=${config.workspaceId ?? '(none)'})\n`);
651
748
  }
652
749
  // Poll for completion
653
- let attempts = 0;
654
- const maxAttempts = 600; // 10 minutes of inactivity timeout
655
- let lastLogLength = 0;
656
- const poll = setInterval(async () => {
657
- try {
658
- attempts++;
659
- const statusRes = await axios_1.default.get(projectStatusUrl(config.host, projectSlug), {
750
+ (0, deploy_status_poll_1.startDeployStatusPoll)({
751
+ read: async () => {
752
+ const response = await axios_1.default.get(projectStatusUrl(config.host, projectSlug), {
660
753
  headers: (0, api_1.getApiHeaders)(config),
661
754
  });
662
- const { status, build_log } = statusRes.data;
663
- // Stream new log content
664
- if (build_log && build_log.length > lastLogLength) {
665
- const newContent = build_log.substring(lastLogLength);
666
- process.stdout.write(chalk_1.default.gray(newContent));
667
- if (!newContent.endsWith('\n')) {
668
- process.stdout.write('\n');
755
+ return response.data;
756
+ },
757
+ schedule: (tick) => {
758
+ const poll = setInterval(tick, 1000);
759
+ return () => clearInterval(poll);
760
+ },
761
+ maxAttempts: 600, // 10 minutes of inactivity timeout
762
+ onLog: (newContent) => {
763
+ process.stdout.write(chalk_1.default.gray(newContent));
764
+ if (!newContent.endsWith('\n')) {
765
+ process.stdout.write('\n');
766
+ }
767
+ },
768
+ onWaiting: () => console.log(chalk_1.default.gray('Still waiting for build to start...')),
769
+ onDeployed: async () => {
770
+ console.log(chalk_1.default.green(`\n✓ Deployed to ${projectSlug}${envLabel}!`));
771
+ try {
772
+ const confirmedProject = await confirmDeploymentWithRetry(acceptedDeployment.deploymentId, () => fetchDeploymentConfirmation(config, projectSlug));
773
+ for (const line of formatDeploymentConfirmation(confirmedProject, acceptedDeployment.deploymentId, acceptedDeployment.sourceMetadataRejected)) {
774
+ console.log(line);
669
775
  }
670
- lastLogLength = build_log.length;
671
- attempts = 0; // Reset timeout — build is still progressing
672
776
  }
673
- // Periodic waiting indicator when no logs yet
674
- if (attempts > 0 && attempts % 15 === 0 && lastLogLength === 0) {
675
- console.log(chalk_1.default.gray('Still waiting for build to start...'));
777
+ catch {
778
+ console.log(chalk_1.default.yellow('Build finished; server revision confirmation was unavailable.'));
676
779
  }
677
- if (status === 'deployed') {
678
- clearInterval(poll);
679
- console.log(chalk_1.default.green(`\n✓ Deployed to ${projectSlug}${envLabel}!`));
680
- try {
681
- const confirmedProject = await confirmDeploymentWithRetry(acceptedDeployment.deploymentId, () => fetchDeploymentConfirmation(config, projectSlug));
682
- for (const line of formatDeploymentConfirmation(confirmedProject, acceptedDeployment.deploymentId, acceptedDeployment.sourceMetadataRejected)) {
683
- console.log(line);
684
- }
685
- }
686
- catch {
687
- console.log(chalk_1.default.yellow('Build finished; server revision confirmation was unavailable.'));
688
- }
689
- // Always sync YAML declarations (registers variables and their mappings)
690
- if (yamlConfig) {
691
- try {
692
- await pushYamlDeclarations(config, projectSlug, yamlConfig);
693
- }
694
- catch (error) {
695
- if (error.response?.status === 401) {
696
- console.error(chalk_1.default.red((0, api_1.authFailedLine)(config.host)));
697
- }
698
- else {
699
- console.error(chalk_1.default.red(`Config sync FAILED: ${error.response?.data?.message || error.message}`));
700
- }
701
- cleanupArchive();
702
- process.exit(1);
703
- }
704
- }
705
- if (yamlConfig && shouldPrintWebhookSecretNotice(yamlConfig.workflows ?? [])) {
706
- const envFlag = environment !== 'dev' ? ` -e ${environment}` : '';
707
- console.log('');
708
- console.log(chalk_1.default.blue(`ℹ Webhook secret: run \`solidactions webhook secret ${(0, slug_1.slugifyName)(projectName) || projectName}${envFlag}\` to retrieve the generated secret.`));
709
- console.log(chalk_1.default.gray(` Set the same value in your sender (e.g. Telegram setWebhook secret_token).`));
710
- }
711
- if (options.paused) {
712
- console.log('');
713
- if (acceptedDeployment.schedulesPaused === true) {
714
- console.log(chalk_1.default.green('Schedules deployed paused.'));
715
- console.log(chalk_1.default.gray(`Enable one when ready with: solidactions schedule enable ${projectSlug} <schedule-id>`));
716
- }
717
- else {
718
- console.log(chalk_1.default.yellow('Warning: server did not acknowledge paused schedules; verify schedules before relying on them being paused.'));
719
- }
720
- }
721
- cleanupArchive();
722
- process.exit(0);
780
+ if (yamlConfig && shouldPrintWebhookSecretNotice(yamlConfig.workflows ?? [])) {
781
+ const envFlag = environment !== 'dev' ? ` -e ${environment}` : '';
782
+ console.log('');
783
+ console.log(chalk_1.default.blue(`ℹ Webhook secret: run \`solidactions webhook secret ${(0, slug_1.slugifyName)(projectName) || projectName}${envFlag}\` to retrieve the generated secret.`));
784
+ console.log(chalk_1.default.gray(` Set the same value in your sender (e.g. Telegram setWebhook secret_token).`));
723
785
  }
724
- else if (status === 'error') {
725
- clearInterval(poll);
726
- console.error(chalk_1.default.red('\n✗ Build Failed!'));
727
- if (build_log) {
728
- console.log(chalk_1.default.yellow('\n--- Full Build Log ---'));
729
- console.log(chalk_1.default.gray(build_log));
730
- console.log(chalk_1.default.yellow('--- End Build Log ---\n'));
786
+ if (options.paused) {
787
+ console.log('');
788
+ if (acceptedDeployment.schedulesPaused === true) {
789
+ console.log(chalk_1.default.green('Schedules deployed paused.'));
790
+ console.log(chalk_1.default.gray(`Enable one when ready with: solidactions schedule enable ${projectSlug} <schedule-id>`));
791
+ }
792
+ else {
793
+ console.log(chalk_1.default.yellow('Warning: server did not acknowledge paused schedules; verify schedules before relying on them being paused.'));
731
794
  }
732
- cleanupArchive();
733
- process.exit(1);
734
795
  }
735
- else if (attempts >= maxAttempts) {
736
- clearInterval(poll);
737
- console.error(chalk_1.default.red('\nTimeout waiting for build. It might still finish.'));
738
- cleanupArchive();
739
- process.exit(1);
796
+ },
797
+ onFailed: (build_log) => {
798
+ console.error(chalk_1.default.red('\n✗ Build Failed!'));
799
+ if (build_log) {
800
+ console.log(chalk_1.default.yellow('\n--- Full Build Log ---'));
801
+ console.log(chalk_1.default.gray(build_log));
802
+ console.log(chalk_1.default.yellow('--- End Build Log ---\n'));
740
803
  }
741
- }
742
- catch {
743
- // Ignore transient errors
744
- }
745
- }, 1000);
804
+ },
805
+ onTimeout: () => console.error(chalk_1.default.red('\nTimeout waiting for build. It might still finish.')),
806
+ finalize: async (buildFailed) => {
807
+ cleanupArchive();
808
+ await finishDeploy({ deploymentId: acceptedDeployment.deploymentId, buildFailed });
809
+ },
810
+ });
746
811
  }
747
812
  catch (error) {
748
813
  console.error(chalk_1.default.red('Deployment failed:'));
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startDeployStatusPoll = startDeployStatusPoll;
4
+ const terminal_gate_1 = require("./terminal-gate");
5
+ function startDeployStatusPoll(options) {
6
+ let attempts = 0;
7
+ let lastLogLength = 0;
8
+ let pollInFlight = false;
9
+ const terminalGate = (0, terminal_gate_1.createTerminalGate)();
10
+ const stop = options.schedule(async () => {
11
+ if (pollInFlight)
12
+ return;
13
+ pollInFlight = true;
14
+ try {
15
+ attempts++;
16
+ const { status, build_log } = await options.read();
17
+ if (build_log && build_log.length > lastLogLength) {
18
+ options.onLog(build_log.substring(lastLogLength));
19
+ lastLogLength = build_log.length;
20
+ attempts = 0;
21
+ }
22
+ if (attempts > 0 && attempts % 15 === 0 && lastLogLength === 0) {
23
+ options.onWaiting();
24
+ }
25
+ if (status === 'deployed') {
26
+ if (!terminalGate.claim())
27
+ return;
28
+ stop();
29
+ await options.onDeployed();
30
+ await options.finalize(false);
31
+ }
32
+ else if (status === 'error') {
33
+ if (!terminalGate.claim())
34
+ return;
35
+ stop();
36
+ options.onFailed(build_log);
37
+ await options.finalize(true);
38
+ }
39
+ else if (attempts >= options.maxAttempts) {
40
+ if (!terminalGate.claim())
41
+ return;
42
+ stop();
43
+ options.onTimeout();
44
+ await options.finalize(true);
45
+ }
46
+ }
47
+ catch {
48
+ // Ignore transient errors
49
+ }
50
+ finally {
51
+ pollInFlight = false;
52
+ }
53
+ });
54
+ }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FUNCTIONS_SYNC_TIMEOUT_MS = void 0;
7
+ exports.listCodeFunctions = listCodeFunctions;
8
+ exports.readFunctionSources = readFunctionSources;
9
+ exports.buildFunctionsSyncPayload = buildFunctionsSyncPayload;
10
+ exports.formatFunctionsSummary = formatFunctionsSummary;
11
+ exports.functionsSyncOutcome = functionsSyncOutcome;
12
+ exports.joinSyncOutcomes = joinSyncOutcomes;
13
+ exports.formatFunctionsSyncFailure = formatFunctionsSyncFailure;
14
+ exports.syncFunctions = syncFunctions;
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const axios_1 = __importDefault(require("axios"));
18
+ const api_1 = require("./api");
19
+ function listCodeFunctions(config) {
20
+ return (config.functions ?? []).filter(entry => typeof entry === 'object' && entry !== null && entry.owner !== 'editor').map(entry => {
21
+ const fn = entry;
22
+ return {
23
+ id: fn.id,
24
+ name: fn.name,
25
+ file: fn.file,
26
+ ...(fn.description === undefined ? {} : { description: fn.description }),
27
+ ...(fn.webhook === undefined ? {} : { webhook: fn.webhook }),
28
+ ...(fn.webhook_auth === undefined ? {} : { webhook_auth: fn.webhook_auth }),
29
+ ...(fn.mcp === undefined ? {} : { mcp: fn.mcp }),
30
+ ...(fn.mcp_tool_name === undefined ? {} : { mcp_tool_name: fn.mcp_tool_name }),
31
+ ...(fn.timeout === undefined ? {} : { timeout: fn.timeout }),
32
+ ...(fn.confirm === undefined ? {} : { confirm: fn.confirm }),
33
+ ...(fn.input_schema === undefined ? {} : { input_schema: fn.input_schema }),
34
+ };
35
+ });
36
+ }
37
+ function readFunctionSources(sourceDir, functions) {
38
+ return new Map(functions.map(fn => [fn.id, fs_1.default.readFileSync(path_1.default.join(sourceDir, fn.file), 'utf8')]));
39
+ }
40
+ function buildFunctionsSyncPayload(functions, sources, codeRef) {
41
+ return { code_ref: codeRef, functions: functions.map(fn => ({ ...fn, source: sources.get(fn.id) })) };
42
+ }
43
+ function formatFunctionsSummary(rows, retired, retireErrors) {
44
+ return [
45
+ ...rows.map(row => row.status === 'error'
46
+ ? `function ${row.id}: error ${row.error.code}: ${row.error.message}`
47
+ : `function ${row.id}: ${row.status}${row.webhook_url === null ? '' : ` ${row.webhook_url}`}`),
48
+ ...retired.map(row => `function ${row.id}: retired`),
49
+ ...retireErrors.map(row => `function ${row.id}: retired, its script delete failed and will retry: ${row.error.message}`),
50
+ ];
51
+ }
52
+ function responseBodyCode(body) {
53
+ if (body !== null && typeof body === 'object' && 'code' in body && typeof body.code === 'string')
54
+ return body.code;
55
+ return null;
56
+ }
57
+ function functionsSyncOutcome(input) {
58
+ if (input.transportError)
59
+ return 'failed';
60
+ if (input.httpStatus === 404 && input.sentFunctionCount === 0)
61
+ return 'skipped-old-server';
62
+ if (input.httpStatus === 503 && input.sentFunctionCount === 0 && responseBodyCode(input.body) === 'functions_disabled')
63
+ return 'skipped-old-server';
64
+ if (input.httpStatus === null || input.httpStatus < 200 || input.httpStatus >= 300)
65
+ return 'failed';
66
+ return input.rows.some(row => row.status === 'error') ? 'failed' : 'ok';
67
+ }
68
+ /** Joins the functions and pages outcomes for the deploy exit code. */
69
+ function joinSyncOutcomes(functionsOutcome, pagesOutcome) {
70
+ if (functionsOutcome === 'failed' || pagesOutcome === 'failed')
71
+ return 'failed';
72
+ if (functionsOutcome === 'ok' || pagesOutcome === 'ok')
73
+ return 'ok';
74
+ return 'skipped-old-server';
75
+ }
76
+ function formatFunctionsSyncFailure(input) {
77
+ if (input.transportError)
78
+ return 'functions sync failed: could not reach the server';
79
+ if (input.httpStatus !== null && input.httpStatus >= 200 && input.httpStatus < 300)
80
+ return null;
81
+ if (input.httpStatus === 404)
82
+ return input.sentFunctionCount === 0 ? null : 'This server does not support functions yet; upgrade the platform';
83
+ if (input.httpStatus === 503 && input.sentFunctionCount === 0 && responseBodyCode(input.body) === 'functions_disabled')
84
+ return null;
85
+ if (input.body !== null && typeof input.body === 'object' && 'code' in input.body && 'message' in input.body && typeof input.body.code === 'string' && typeof input.body.message === 'string') {
86
+ return `functions sync failed (${input.httpStatus} ${input.body.code}): ${input.body.message}`;
87
+ }
88
+ // Laravel's own validation 422 carries `message` and `errors` but no `code`.
89
+ if (input.body !== null && typeof input.body === 'object' && 'message' in input.body && typeof input.body.message === 'string') {
90
+ return `functions sync failed (HTTP ${input.httpStatus}): ${input.body.message}`;
91
+ }
92
+ return `functions sync failed (HTTP ${input.httpStatus})`;
93
+ }
94
+ /** HTTP client timeout for the functions/sync call (P7: the server holds the request up to 180 s). */
95
+ exports.FUNCTIONS_SYNC_TIMEOUT_MS = 210_000;
96
+ async function syncFunctions(config, projectSlug, payload) {
97
+ try {
98
+ const response = await axios_1.default.put(`${config.host}/api/v1/projects/${encodeURIComponent(projectSlug)}/functions/sync`, payload, { headers: (0, api_1.getApiHeaders)(config, 'application/json'), timeout: exports.FUNCTIONS_SYNC_TIMEOUT_MS });
99
+ return { httpStatus: response.status, transportError: false, body: response.data };
100
+ }
101
+ catch (error) {
102
+ return { httpStatus: error.response?.status ?? null, transportError: !error.response, body: error.response?.data ?? null };
103
+ }
104
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.listCodePages = listCodePages;
7
+ exports.readPageBodies = readPageBodies;
8
+ exports.buildPagesSyncPayload = buildPagesSyncPayload;
9
+ exports.formatPagesSummary = formatPagesSummary;
10
+ exports.pagesSyncOutcome = pagesSyncOutcome;
11
+ exports.formatPagesSyncFailure = formatPagesSyncFailure;
12
+ exports.terminalExitCode = terminalExitCode;
13
+ exports.syncPages = syncPages;
14
+ const fs_1 = __importDefault(require("fs"));
15
+ const path_1 = __importDefault(require("path"));
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const api_1 = require("./api");
18
+ const validate_items_1 = require("./validate-items");
19
+ function listCodePages(config) {
20
+ return (config.pages ?? []).filter(page => !(0, validate_items_1.isPagePointer)(page)).map(page => ({
21
+ slug: page.id,
22
+ name: page.name,
23
+ path: page.file,
24
+ kind: page.file.endsWith('.html') ? 'visual' : 'dashboard',
25
+ home: page.home ?? false,
26
+ ...(page.sources === undefined ? {} : { sources: page.sources }),
27
+ }));
28
+ }
29
+ function readPageBodies(sourceDir, pages) {
30
+ return new Map(pages.map(page => [page.slug, fs_1.default.readFileSync(path_1.default.join(sourceDir, page.path), 'utf8')]));
31
+ }
32
+ function buildPagesSyncPayload(pages, bodies, deploymentId, codeRef) {
33
+ return { deployment_id: deploymentId, code_ref: codeRef, pages: pages.map(page => ({ ...page, body: bodies.get(page.slug) })) };
34
+ }
35
+ function formatPagesSummary(rows, trashed, trashErrors) {
36
+ return [
37
+ ...rows.map(row => row.status === 'live'
38
+ ? `page ${row.slug}: live${row.url === null ? '' : ` ${row.url}`}`
39
+ : `page ${row.slug}: error ${row.error.code}: ${row.error.message}`),
40
+ ...trashed.map(row => `page ${row.slug}: moved to trash (id ${row.id})`),
41
+ ...trashErrors.map(row => `page ${row.slug}: could not move to trash: ${row.error.code}: ${row.error.message}`),
42
+ ];
43
+ }
44
+ function pagesSyncOutcome(input) {
45
+ if (input.transportError)
46
+ return 'failed';
47
+ if (input.httpStatus === 404 && input.sentPageCount === 0)
48
+ return 'skipped-old-server';
49
+ if (input.httpStatus === null || input.httpStatus < 200 || input.httpStatus >= 300)
50
+ return 'failed';
51
+ return input.stamp === 'superseded' || input.stamp === 'failed' || input.rows.some(row => row.status === 'error') || input.trashErrors.length > 0 ? 'failed' : 'ok';
52
+ }
53
+ function formatPagesSyncFailure(input) {
54
+ if (input.transportError)
55
+ return 'pages sync failed: could not reach the server';
56
+ if (input.httpStatus !== null && input.httpStatus >= 200 && input.httpStatus < 300) {
57
+ if (input.body !== null && typeof input.body === 'object' && 'stamp' in input.body) {
58
+ if (input.body.stamp === 'superseded')
59
+ return 'pages sync superseded: a newer deploy of this project took over';
60
+ if (input.body.stamp === 'failed')
61
+ return 'pages sync failed: pages finished but completion could not be recorded; cleanup may be incomplete: deploy again';
62
+ }
63
+ return null;
64
+ }
65
+ if (input.httpStatus === 404)
66
+ return input.sentPageCount === 0 ? null : 'This server does not support pages: yet; upgrade the platform';
67
+ if (input.body !== null && typeof input.body === 'object' && 'code' in input.body && 'message' in input.body && typeof input.body.code === 'string' && typeof input.body.message === 'string') {
68
+ return `pages sync failed (${input.httpStatus} ${input.body.code}): ${input.body.message}`;
69
+ }
70
+ return `pages sync failed (HTTP ${input.httpStatus})`;
71
+ }
72
+ function terminalExitCode(input) {
73
+ return input.buildFailed || input.yamlSyncFailed || input.outcome === 'failed' ? 1 : 0;
74
+ }
75
+ async function syncPages(config, projectSlug, payload) {
76
+ try {
77
+ const response = await axios_1.default.put(`${config.host}/api/v1/projects/${encodeURIComponent(projectSlug)}/pages/sync`, payload, { headers: (0, api_1.getApiHeaders)(config, 'application/json') });
78
+ return { httpStatus: response.status, transportError: false, body: response.data };
79
+ }
80
+ catch (error) {
81
+ return { httpStatus: error.response?.status ?? null, transportError: !error.response, body: error.response?.data ?? null };
82
+ }
83
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTerminalGate = createTerminalGate;
4
+ function createTerminalGate() {
5
+ let claimed = false;
6
+ return {
7
+ claim: () => {
8
+ if (claimed)
9
+ return false;
10
+ claimed = true;
11
+ return true;
12
+ },
13
+ };
14
+ }
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isPagePointer = isPagePointer;
7
+ exports.validateItems = validateItems;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const slug_1 = require("./slug");
11
+ function isPagePointer(e) {
12
+ return e.owner === 'editor';
13
+ }
14
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
15
+ const MAX_PAGES = 50;
16
+ const MAX_FUNCTIONS = 50;
17
+ const MAX_PAGE_FILE_BYTES = 1024 * 1024;
18
+ const MAX_FUNCTION_FILE_BYTES = 256 * 1024;
19
+ const PAGE_EXTENSIONS = ['.html', '.tsx'];
20
+ const WEBHOOK_AUTHS = ['hmac', 'basic', 'header', 'none'];
21
+ function label(kind, id, index) {
22
+ return `${kind}[${String(id ?? index)}]`;
23
+ }
24
+ function describeReceived(value) {
25
+ return JSON.stringify(value) ?? typeof value;
26
+ }
27
+ function isEditorOwned(entry) {
28
+ return entry.owner === 'editor';
29
+ }
30
+ function checkFile(sourceDir, kind, entryLabel, file, allowedExtensions, maxBytes, limitName) {
31
+ const noun = kind === 'pages' ? 'page file' : 'function file';
32
+ if (typeof file !== 'string' || file === '') {
33
+ return [{ entry: entryLabel, field: 'file', message: `${entryLabel}.file: ${noun} is required.` }];
34
+ }
35
+ if (!allowedExtensions.includes(path_1.default.extname(file))) {
36
+ return [{ entry: entryLabel, field: 'file', message: `${entryLabel}.file: ${noun} "${file}" must end in ${allowedExtensions.join(' or ')}.` }];
37
+ }
38
+ let stat;
39
+ try {
40
+ stat = fs_1.default.statSync(path_1.default.join(sourceDir, file));
41
+ }
42
+ catch {
43
+ return [{ entry: entryLabel, field: 'file', message: `${entryLabel}.file: ${noun} "${file}" not found.` }];
44
+ }
45
+ if (!stat.isFile()) {
46
+ return [{ entry: entryLabel, field: 'file', message: `${entryLabel}.file: ${noun} "${file}" is not a file.` }];
47
+ }
48
+ if (stat.size > maxBytes) {
49
+ return [{ entry: entryLabel, field: 'file', message: `${entryLabel}.file: ${noun} "${file}" is ${stat.size} bytes, over the ${limitName} limit.` }];
50
+ }
51
+ return [];
52
+ }
53
+ function validateItems(config, sourceDir) {
54
+ const errors = [];
55
+ if (config.pages !== undefined && !Array.isArray(config.pages)) {
56
+ errors.push({ entry: 'pages', field: 'pages', message: 'pages: pages must be a list.' });
57
+ }
58
+ if (config.functions !== undefined && !Array.isArray(config.functions)) {
59
+ errors.push({ entry: 'functions', field: 'functions', message: 'functions: functions must be a list.' });
60
+ }
61
+ const pages = Array.isArray(config.pages) ? config.pages : [];
62
+ const functions = Array.isArray(config.functions) ? config.functions : [];
63
+ if (pages.length > MAX_PAGES) {
64
+ errors.push({ entry: 'pages', field: 'pages', message: `pages: at most 50 pages per project (got ${pages.length}).` });
65
+ }
66
+ if (functions.length > MAX_FUNCTIONS) {
67
+ errors.push({ entry: 'functions', field: 'functions', message: `functions: at most 50 functions per project (got ${functions.length}).` });
68
+ }
69
+ const seenPageSlugs = new Map();
70
+ let firstHomeLabel = null;
71
+ pages.forEach((entry, index) => {
72
+ if (typeof entry !== 'object' || entry === null) {
73
+ const entryLabel = label('pages', undefined, index);
74
+ errors.push({ entry: entryLabel, field: 'pages', message: `${entryLabel}.pages: page entry must be an object (got ${describeReceived(entry)}).` });
75
+ return;
76
+ }
77
+ const rawId = entry.id;
78
+ const entryLabel = label('pages', rawId, index);
79
+ if (isEditorOwned(entry)) {
80
+ const file = entry.file;
81
+ if (file !== undefined) {
82
+ errors.push({ entry: entryLabel, field: 'file', message: `${entryLabel}.file: a page made in the app (owner: editor) can't have a file: "${String(file)}".` });
83
+ }
84
+ return;
85
+ }
86
+ if (typeof rawId !== 'string' || !SLUG_RE.test(rawId)) {
87
+ errors.push({ entry: entryLabel, field: 'id', message: `${entryLabel}.id: invalid slug "${String(rawId)}" — slugs must match [a-z0-9][a-z0-9-]{0,62}.` });
88
+ }
89
+ else if (seenPageSlugs.has(rawId)) {
90
+ errors.push({ entry: entryLabel, field: 'id', message: `${entryLabel}.id: duplicate page slug "${rawId}" (already used by ${seenPageSlugs.get(rawId)}).` });
91
+ }
92
+ else {
93
+ seenPageSlugs.set(rawId, entryLabel);
94
+ }
95
+ if (entry.home === true) {
96
+ if (firstHomeLabel === null) {
97
+ firstHomeLabel = entryLabel;
98
+ }
99
+ else {
100
+ errors.push({ entry: entryLabel, field: 'home', message: `${entryLabel}.home: at most one page may have home: true (already set on ${firstHomeLabel}).` });
101
+ }
102
+ }
103
+ errors.push(...checkFile(sourceDir, 'pages', entryLabel, entry.file, PAGE_EXTENSIONS, MAX_PAGE_FILE_BYTES, '1 MB'));
104
+ });
105
+ const workflows = Array.isArray(config.workflows) ? config.workflows : [];
106
+ const workflowSlugs = new Set();
107
+ for (const [index, wf] of workflows.entries()) {
108
+ if (typeof wf !== 'object' || wf === null) {
109
+ const entryLabel = label('workflows', undefined, index);
110
+ errors.push({ entry: entryLabel, field: 'workflows', message: `${entryLabel}.workflows: workflow entry must be an object (got ${describeReceived(wf)}).` });
111
+ continue;
112
+ }
113
+ if (typeof wf.id === 'string' && wf.id !== '') {
114
+ workflowSlugs.add(wf.id);
115
+ }
116
+ if (typeof wf.name === 'string' && wf.name !== '') {
117
+ const slug = (0, slug_1.slugifyName)(wf.name);
118
+ if (slug !== '') {
119
+ workflowSlugs.add(slug);
120
+ }
121
+ }
122
+ }
123
+ const seenFunctionSlugs = new Map();
124
+ functions.forEach((entry, index) => {
125
+ if (typeof entry !== 'object' || entry === null) {
126
+ const entryLabel = label('functions', undefined, index);
127
+ errors.push({ entry: entryLabel, field: 'functions', message: `${entryLabel}.functions: function entry must be an object (got ${describeReceived(entry)}).` });
128
+ return;
129
+ }
130
+ const rawId = entry.id;
131
+ const entryLabel = label('functions', rawId, index);
132
+ if (isEditorOwned(entry)) {
133
+ const file = entry.file;
134
+ if (file !== undefined) {
135
+ errors.push({ entry: entryLabel, field: 'file', message: `${entryLabel}.file: a function made in the app (owner: editor) can't have a file: "${String(file)}".` });
136
+ }
137
+ return;
138
+ }
139
+ if (typeof rawId !== 'string' || !SLUG_RE.test(rawId)) {
140
+ errors.push({ entry: entryLabel, field: 'id', message: `${entryLabel}.id: invalid slug "${String(rawId)}" — slugs must match [a-z0-9][a-z0-9-]{0,62}.` });
141
+ }
142
+ else {
143
+ if (seenFunctionSlugs.has(rawId)) {
144
+ errors.push({ entry: entryLabel, field: 'id', message: `${entryLabel}.id: duplicate function slug "${rawId}" (already used by ${seenFunctionSlugs.get(rawId)}).` });
145
+ }
146
+ else {
147
+ seenFunctionSlugs.set(rawId, entryLabel);
148
+ }
149
+ if (workflowSlugs.has(rawId)) {
150
+ errors.push({ entry: entryLabel, field: 'id', message: `${entryLabel}.id: function slug "${rawId}" is already used by a workflow.` });
151
+ }
152
+ }
153
+ errors.push(...checkFile(sourceDir, 'functions', entryLabel, entry.file, ['.ts'], MAX_FUNCTION_FILE_BYTES, '256 KB'));
154
+ const timeout = entry.timeout;
155
+ if (timeout !== undefined && (typeof timeout !== 'number' || Number.isNaN(timeout) || timeout < 1 || timeout > 30)) {
156
+ errors.push({ entry: entryLabel, field: 'timeout', message: `${entryLabel}.timeout: timeout must be between 1 and 30 seconds (got ${JSON.stringify(timeout)}).` });
157
+ }
158
+ const webhookAuth = entry.webhook_auth;
159
+ if (webhookAuth !== undefined && (typeof webhookAuth !== 'string' || !WEBHOOK_AUTHS.includes(webhookAuth))) {
160
+ errors.push({ entry: entryLabel, field: 'webhook_auth', message: `${entryLabel}.webhook_auth: webhook_auth must be one of hmac, basic, header, none (got ${JSON.stringify(webhookAuth)}).` });
161
+ }
162
+ });
163
+ return errors;
164
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidactions/cli",
3
- "version": "3.26.0",
3
+ "version": "3.28.0",
4
4
  "description": "SolidActions CLI - Deploy and manage workflow automation",
5
5
  "main": "dist/index.js",
6
6
  "bin": {