sftp-zip-deploy 0.0.2 → 0.0.4

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/README.md CHANGED
@@ -1,2 +1,69 @@
1
1
  # sftp-zip-deploy
2
- Fast zip-deployment over SFTP
2
+
3
+ [![Node Version](https://img.shields.io/badge/nodejs-%2026-green.svg?logo=node.js&style=flat)](https://nodejs.org)
4
+
5
+ Simple and efficient way to auto-deploy your project to a server:
6
+
7
+ - It zips your distribution folder and sends the archive to your server via SFTP
8
+ - It optionally runs remote commands, before / after zip deployment, via SHH2
9
+ - It provides detailed data about what is going on all the way
10
+
11
+ **IMPORTANT:**
12
+
13
+ This library relies on Node-native support for SHH2 and ZIP, and therefore requires Node v26 as minimum.
14
+
15
+ ## Install
16
+
17
+ ```
18
+ npm i sftp-zip-deploy
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ In the example below, we deploy a NodeJS project into `/root/web` on our remote server.
24
+
25
+ Once zip file is deployed, we run commands to set that folder as active, then unpack
26
+ the archive and install project's dependencies.
27
+
28
+ ```ts
29
+ import {zipAndDeploy} from 'sftp-zip-deploy';
30
+
31
+ await zipAndDeploy({
32
+ srcDir: './dist', // folder with content to deploy
33
+ destDir: '/root/web/', // remote folder to copy our zip file
34
+ zipFile: {
35
+ name: 'release.zip', // set custom name for the archive
36
+ dir: './' // we can change where zip is created
37
+ },
38
+ cn: {
39
+ host: '1.2.3.4',
40
+ port: 123,
41
+ username: 'root',
42
+ password: '#########'
43
+ },
44
+ cmd: {
45
+ after: 'cd /root/web && unzip -o release.zip && npm i'
46
+ }
47
+ });
48
+ ```
49
+
50
+ Note that we use option `-o` (overwrite) with `unzip`, because otherwise the command may prompt for input,
51
+ if files are already there, and this library does not deal with remote prompts, it will just get stuck.
52
+ So avoid running commands that may trigger an input prompt.
53
+
54
+ ## API
55
+
56
+ The library shares connection options for SFTP / SHH2, and reuses the standard `ConnectOptions` / `ConnectConfig`
57
+ types from the underlying modules.
58
+
59
+ The main interface [ISftpZipDeployConfig] has a number of options, including events for providing progress details:
60
+
61
+ * [onZipReady] - notifies when zip is ready
62
+ * [onFilter] - to let you filter files inside distribution folder
63
+ * [onCmdOutput] - to get all output from remote commands
64
+
65
+ [onZipReady]:https://github.com/vitaly-t/sftp-zip-deploy/blob/main/src/config.ts#L67
66
+ [onFilter]:https://github.com/vitaly-t/sftp-zip-deploy/blob/main/src/config.ts#L61
67
+ [onCmdOutput]:https://github.com/vitaly-t/sftp-zip-deploy/blob/main/src/config.ts#L81
68
+
69
+ [ISftpZipDeployConfig]:https://github.com/vitaly-t/sftp-zip-deploy/blob/main/src/config.ts#L6
package/dist/config.d.ts CHANGED
@@ -1,48 +1,54 @@
1
1
  import { ConnectOptions } from 'ssh2-sftp-client';
2
- export interface IZipDetails {
3
- /**
4
- * All files placed into zip.
5
- */
6
- files: string[];
7
- /**
8
- * Local path to the zip file.
9
- */
10
- zipLocalPath: string;
11
- /**
12
- * Remote path to the zip file.
13
- */
14
- zipRemotePath: string;
15
- /**
16
- * Zip file size, in bytes.
17
- */
18
- zipSize: number;
19
- }
2
+ /**
3
+ * Configuration structure, to be passed into `zipAndDeploy`.
4
+ */
20
5
  export interface ISftpZipDeployConfig {
21
6
  /**
22
7
  * Connection parameters.
23
8
  */
24
9
  cn: ConnectOptions;
25
10
  /**
26
- * Source directory.
11
+ * Source directory (on the local machine).
27
12
  */
28
13
  srcDir: string;
29
14
  /**
30
- * Destination directory.
15
+ * Destination directory (on the remote server).
31
16
  */
32
17
  destDir: string;
33
18
  /**
34
- * Optional path for the zip file.
19
+ * Optional name + location of the local zip file.
20
+ *
21
+ * It defaults to {dir: './', name: 'release.zip'},
22
+ * to create it in the root of your project.
35
23
  */
36
- zipPath?: string;
24
+ zipFile?: {
25
+ /**
26
+ * Local directory where zip file is to be created.
27
+ * Default is './'
28
+ */
29
+ dir?: string;
30
+ /**
31
+ * Name for the local zip file. Default is 'release.zip'
32
+ */
33
+ name?: string;
34
+ };
37
35
  /**
38
- * Optional remote commands to run before or after zip file has been copied over.
36
+ * Optional commands to execute before / after deploying zip file.
39
37
  */
40
- commands?: {
41
- before?: string | string[];
42
- after?: string | string[];
38
+ cmd?: {
39
+ /**
40
+ * Command(s) to be executed before creating zip file.
41
+ */
42
+ before?: string;
43
+ /**
44
+ * Command(s) to be executed after zip has been deployed.
45
+ */
46
+ after?: string;
43
47
  };
44
48
  /**
45
- * Optional filter on file enumeration, returning:
49
+ * Optional filter on file enumeration (found in `srcDir`),
50
+ * returning:
51
+ *
46
52
  * - true for files to be added;
47
53
  * - false for files to be skipped.
48
54
  */
@@ -54,6 +60,36 @@ export interface ISftpZipDeployConfig {
54
60
  onZipReady?: (zd: IZipDetails) => void;
55
61
  /**
56
62
  * Notification of every output produced by a remote command.
63
+ *
64
+ * @param cmd
65
+ * Command that produced an output.
66
+ *
67
+ * @param err
68
+ * Set when the output was sent into StdErr, i.e. an error is reported.
69
+ *
70
+ * @param std
71
+ * Set when normal/standard output is generated (not an error).
57
72
  */
58
73
  onCmdOutput?: (cmd: string, err?: Buffer, std?: Buffer) => void;
59
74
  }
75
+ /**
76
+ * For use with onZipReady event.
77
+ */
78
+ export interface IZipDetails {
79
+ /**
80
+ * All files placed into zip.
81
+ */
82
+ files: string[];
83
+ /**
84
+ * Local path to the zip file.
85
+ */
86
+ zipLocalPath: string;
87
+ /**
88
+ * Remote path to the zip file.
89
+ */
90
+ zipRemotePath: string;
91
+ /**
92
+ * Zip file size, in bytes.
93
+ */
94
+ zipSize: number;
95
+ }
package/dist/config.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,3 +1,15 @@
1
- import { ISftpZipDeployConfig } from './config';
2
- export { default as ConnectOptions } from 'ssh2-sftp-client';
1
+ import { ISftpZipDeployConfig } from './config.js';
2
+ export { IZipDetails, ISftpZipDeployConfig } from './config.js';
3
+ export { ConnectOptions } from 'ssh2-sftp-client';
4
+ /**
5
+ * From the configuration object, it implements the following steps:
6
+ *
7
+ * 1. Executes `cmd.before` commands, if such were specified
8
+ * 2. Enumerates all files inside `srcDir`, plus filters them via `onFilter` (if used)
9
+ * 3. Produces zip file with all the resulting files and triggers `onZipReady` (if used)
10
+ * 4. Uploads zip file to the remote machine
11
+ * 5. Executes `cmd.after` commands, if such were specified
12
+ * 6. Resolves with `true`, if at least one file was found and zip was created,
13
+ * or `false` otherwise (i.e. it does not create an empty zip)
14
+ */
3
15
  export declare function zipAndDeploy(cfg: ISftpZipDeployConfig): Promise<boolean>;
package/dist/index.js CHANGED
@@ -1,63 +1,44 @@
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.ConnectOptions = void 0;
7
- exports.zipAndDeploy = zipAndDeploy;
8
- const ssh2_sftp_client_1 = __importDefault(require("ssh2-sftp-client"));
9
- const ssh2_1 = require("ssh2");
10
- const utils_1 = require("./utils");
11
- const node_zlib_1 = require("node:zlib");
12
- const node_fs_1 = require("node:fs");
13
- const glob_1 = require("glob");
14
- const promises_1 = require("node:fs/promises");
15
- const promises_2 = require("node:stream/promises");
16
- var ssh2_sftp_client_2 = require("ssh2-sftp-client");
17
- Object.defineProperty(exports, "ConnectOptions", { enumerable: true, get: function () { return __importDefault(ssh2_sftp_client_2).default; } });
18
- async function zipAndDeploy(cfg) {
19
- const ac = cfg.commands?.after ?? [];
20
- const afterCommands = (Array.isArray(ac) ? ac : [ac]);
21
- const bc = cfg.commands?.before ?? [];
22
- const beforeCommands = (Array.isArray(bc) ? bc : [bc]);
23
- const ssh2Client = new ssh2_1.Client();
24
- if (ac.length > 0 || bc.length > 0) {
25
- await (0, utils_1.connectSSH2Client)(ssh2Client, cfg.cn);
26
- for (const c of beforeCommands) {
27
- await (0, utils_1.execSHH2Command)(ssh2Client, c, (err, std) => {
28
- if (typeof cfg.onCmdOutput === 'function') {
29
- cfg.onCmdOutput(c, err, std);
30
- }
31
- });
32
- }
1
+ import SftpClient from 'ssh2-sftp-client';
2
+ import { Client as SSH2Client } from 'ssh2';
3
+ import { connectSSH2Client, execSHH2Command, fixWindowsPath, zipFiles } from './utils.js';
4
+ import { globSync } from 'glob';
5
+ import path from 'node:path';
6
+ /**
7
+ * From the configuration object, it implements the following steps:
8
+ *
9
+ * 1. Executes `cmd.before` commands, if such were specified
10
+ * 2. Enumerates all files inside `srcDir`, plus filters them via `onFilter` (if used)
11
+ * 3. Produces zip file with all the resulting files and triggers `onZipReady` (if used)
12
+ * 4. Uploads zip file to the remote machine
13
+ * 5. Executes `cmd.after` commands, if such were specified
14
+ * 6. Resolves with `true`, if at least one file was found and zip was created,
15
+ * or `false` otherwise (i.e. it does not create an empty zip)
16
+ */
17
+ export async function zipAndDeploy(cfg) {
18
+ const ssh2Client = new SSH2Client();
19
+ const { before = '', after = '' } = cfg.cmd ?? {};
20
+ if (before || after) {
21
+ await connectSSH2Client(ssh2Client, cfg.cn);
22
+ await execSHH2Command(ssh2Client, before, (err, std) => cfg.onCmdOutput?.(before, err, std));
33
23
  }
34
- let allFiles = (0, glob_1.globSync)('**/{*.*,.*}', { cwd: cfg.srcDir })
35
- .map(f => f.replace(/\\/g, '/'));
24
+ let files = globSync('**/{*.*,.*}', { cwd: cfg.srcDir })
25
+ .map(f => fixWindowsPath(f));
36
26
  if (typeof cfg.onFilter === 'function') {
37
- allFiles = allFiles.filter(cfg.onFilter);
27
+ files = files.filter(cfg.onFilter);
38
28
  }
39
- if (allFiles.length === 0) {
40
- return false; // nothing to deploy
41
- }
42
- const entries = [];
43
- for (const src of allFiles) {
44
- entries.push(await node_zlib_1.ZipEntry.create(src, await (0, promises_1.readFile)(src)));
45
- }
46
- const archive = (0, node_zlib_1.createZipArchive)(entries);
47
- const ws = (0, node_fs_1.createWriteStream)('release.zip');
48
- await (0, promises_2.pipeline)(archive, ws);
49
- const sftp = new ssh2_sftp_client_1.default();
29
+ const zipFileDir = cfg.zipFile?.dir ?? './';
30
+ const zipFileName = cfg.zipFile?.name ?? 'release.zip';
31
+ const zipLocalPath = fixWindowsPath(path.join(zipFileDir, zipFileName));
32
+ const zipRemotePath = fixWindowsPath(path.join(cfg.destDir, zipFileName));
33
+ const zipSize = await zipFiles(cfg.srcDir, files, zipLocalPath);
34
+ cfg.onZipReady?.({ files, zipLocalPath, zipRemotePath, zipSize });
35
+ const sftp = new SftpClient();
50
36
  await sftp.connect(cfg.cn);
51
- const p = `${cfg.destDir}/release.zip`;
52
- await sftp.put('release.zip', p);
53
- await sftp.end();
54
- for (const c of afterCommands) {
55
- await (0, utils_1.execSHH2Command)(ssh2Client, c, (err, std) => {
56
- if (typeof cfg.onCmdOutput === 'function') {
57
- cfg.onCmdOutput(c, err, std);
58
- }
59
- });
37
+ await sftp.put(zipLocalPath, zipRemotePath);
38
+ if (after) {
39
+ await execSHH2Command(ssh2Client, after, (err, std) => cfg.onCmdOutput?.(after, err, std));
60
40
  }
41
+ await sftp.end();
61
42
  ssh2Client.end();
62
- return true;
43
+ return files.length > 0;
63
44
  }
package/dist/utils.d.ts CHANGED
@@ -1,3 +1,11 @@
1
1
  import { Client as SSH2Client, ConnectConfig } from 'ssh2';
2
2
  export declare function connectSSH2Client(client: SSH2Client, cn: ConnectConfig): Promise<SSH2Client>;
3
3
  export declare function execSHH2Command(client: SSH2Client, cmd: string, output: (err?: Buffer, std?: Buffer) => void): Promise<void>;
4
+ /**
5
+ * Zips list of files, and resolves with the size of the resulting archive (in bytes).
6
+ */
7
+ export declare function zipFiles(dir: string, files: string[], zipPath: string): Promise<number>;
8
+ /**
9
+ * Fixes Windows path-s, by replacing every '\' with '/'
10
+ */
11
+ export declare function fixWindowsPath(path: string): string;
package/dist/utils.js CHANGED
@@ -1,20 +1,20 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.connectSSH2Client = connectSSH2Client;
4
- exports.execSHH2Command = execSHH2Command;
5
- function connectSSH2Client(client, cn) {
1
+ import { createZipArchive, ZipEntry } from 'node:zlib';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createWriteStream } from 'node:fs';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import path from 'node:path';
6
+ export function connectSSH2Client(client, cn) {
6
7
  return new Promise((resolve, reject) => {
7
8
  client.once('ready', () => resolve(client));
8
9
  client.once('error', err => reject(err));
9
10
  client.connect(cn);
10
11
  });
11
12
  }
12
- function execSHH2Command(client, cmd, output) {
13
+ export function execSHH2Command(client, cmd, output) {
13
14
  return new Promise((resolve, reject) => {
14
15
  client.exec(cmd, (err, stream) => {
15
16
  if (err) {
16
- reject(err);
17
- return;
17
+ return reject(err);
18
18
  }
19
19
  stream.once('close', () => resolve());
20
20
  stream.on('data', (chunk) => output(undefined, chunk));
@@ -22,3 +22,23 @@ function execSHH2Command(client, cmd, output) {
22
22
  });
23
23
  });
24
24
  }
25
+ /**
26
+ * Zips list of files, and resolves with the size of the resulting archive (in bytes).
27
+ */
28
+ export async function zipFiles(dir, files, zipPath) {
29
+ const entries = [];
30
+ for (const f of files) {
31
+ const p = path.join(dir, f);
32
+ entries.push(await ZipEntry.create(f, await readFile(p)));
33
+ }
34
+ const archive = createZipArchive(entries);
35
+ const ws = createWriteStream(zipPath);
36
+ await pipeline(archive, ws);
37
+ return ws.bytesWritten;
38
+ }
39
+ /**
40
+ * Fixes Windows path-s, by replacing every '\' with '/'
41
+ */
42
+ export function fixWindowsPath(path) {
43
+ return path.replace(/\\/g, '/');
44
+ }
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "sftp-zip-deploy",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "type": "module",
7
8
  "scripts": {
8
9
  "build": "tsc -p src",
9
- "start": "tsc && node ./src/index.js"
10
+ "start": "tsc -p src && node --no-warnings=ExperimentalWarning=9820 ./dist/index.js"
10
11
  },
11
12
  "files": [
12
13
  "dist"
@@ -30,6 +31,6 @@
30
31
  "devDependencies": {
31
32
  "@types/node": "26.6.6",
32
33
  "@types/ssh2-sftp-client": "9.0.6",
33
- "typescript": "6.0.3"
34
+ "typescript": "7.0.2"
34
35
  }
35
36
  }