@ductape/cli 0.4.6 → 0.5.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.
@@ -0,0 +1,90 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { spawn } from 'node:child_process';
6
+ export const MAX_SOURCE_BYTES = 200 * 1024 * 1024;
7
+ /** Left out of every upload. `.env` files are the usual place for secrets, and they must not travel with the source. */
8
+ export const DEFAULT_EXCLUDES = ['.git', 'node_modules', '.env', '.env.*', '.DS_Store'];
9
+ function guardDirectory(dir) {
10
+ const resolved = path.resolve(dir);
11
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory())
12
+ throw new Error(`${resolved} is not a directory`);
13
+ if (resolved === path.parse(resolved).root || resolved === os.homedir()) {
14
+ throw new Error(`${resolved} is your ${resolved === os.homedir() ? 'home directory' : 'filesystem root'}, not a project. Run this from the project's folder or pass --dir.`);
15
+ }
16
+ }
17
+ /** Reads `.dockerignore` into tar exclude patterns. Negations ("!keep") cannot be expressed and are reported, not guessed at. */
18
+ export function readDockerignore(dir) {
19
+ const file = path.join(dir, '.dockerignore');
20
+ if (!fs.existsSync(file))
21
+ return { patterns: [], warnings: [] };
22
+ const patterns = [];
23
+ const warnings = [];
24
+ for (const raw of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
25
+ const line = raw.trim();
26
+ if (!line || line.startsWith('#'))
27
+ continue;
28
+ if (line.startsWith('!')) {
29
+ warnings.push(`.dockerignore line "${line}" is a negation, which is not supported here; the files it names are still left out if another line excludes them`);
30
+ continue;
31
+ }
32
+ patterns.push(line.replace(/^\/+/, '').replace(/\/+$/, ''));
33
+ }
34
+ return { patterns, warnings };
35
+ }
36
+ /** Packs a directory into a compressed archive, hashes it, and refuses anything over the size limit. */
37
+ export async function packSource(dir, options = {}) {
38
+ guardDirectory(dir);
39
+ const root = path.resolve(dir);
40
+ if (options.dockerfile && !fs.existsSync(path.join(root, options.dockerfile))) {
41
+ throw new Error(`${options.dockerfile} was not found in ${root}. Add it, or choose --builder buildpacks to build without a Dockerfile.`);
42
+ }
43
+ const ignore = readDockerignore(root);
44
+ const excluded = [...new Set([...DEFAULT_EXCLUDES, ...ignore.patterns, ...(options.exclude ?? [])])];
45
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'ductape-source-'));
46
+ const file = path.join(work, 'source.tar.gz');
47
+ const cleanup = () => fs.rmSync(work, { recursive: true, force: true });
48
+ try {
49
+ await new Promise((resolve, reject) => {
50
+ const args = ['-czf', file, ...excluded.flatMap((pattern) => ['--exclude', pattern]), '-C', root, '.'];
51
+ const child = spawn('tar', args, { env: { ...process.env, COPYFILE_DISABLE: '1' }, stdio: ['ignore', 'ignore', 'pipe'] });
52
+ let stderr = '';
53
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
54
+ child.on('error', (error) => reject(new Error(`Could not run tar to pack the source: ${error.message}`)));
55
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`tar failed (${code}): ${stderr.trim().slice(0, 300)}`))));
56
+ });
57
+ const bytes = fs.statSync(file).size;
58
+ if (bytes > MAX_SOURCE_BYTES)
59
+ throw new Error(`The packed source is ${(bytes / 1048576).toFixed(1)} MB; the limit is ${MAX_SOURCE_BYTES / 1048576} MB. Add large folders to .dockerignore.`);
60
+ const sha256 = await new Promise((resolve, reject) => {
61
+ const hash = createHash('sha256');
62
+ fs.createReadStream(file).on('data', (chunk) => hash.update(chunk)).on('error', reject).on('end', () => resolve(hash.digest('hex')));
63
+ });
64
+ return { file, sha256, bytes, excluded, warnings: ignore.warnings, cleanup };
65
+ }
66
+ catch (error) {
67
+ cleanup();
68
+ throw error;
69
+ }
70
+ }
71
+ /** Sends the archive straight to the bucket in the customer's cloud account. Ductape's servers never see it. */
72
+ export async function uploadSource(ticket, file) {
73
+ if (ticket.method !== 'PUT')
74
+ throw new Error(`Unexpected upload method ${ticket.method}`);
75
+ const body = fs.readFileSync(file);
76
+ let response;
77
+ try {
78
+ response = await fetch(ticket.url, { method: 'PUT', headers: ticket.headers, body });
79
+ }
80
+ catch (error) {
81
+ throw new Error(`The upload could not reach the bucket: ${error instanceof Error ? error.message : String(error)}`);
82
+ }
83
+ if (response.ok)
84
+ return;
85
+ const detail = (await response.text().catch(() => '')).replace(/\s+/g, ' ').slice(0, 300);
86
+ const hint = response.status === 403
87
+ ? ' The upload link may have expired (they last 15 minutes) or the headers changed. Run the command again.'
88
+ : response.status === 400 ? ' The upload was rejected; this often means the file or its headers do not match what was declared.' : '';
89
+ throw new Error(`The bucket refused the upload (HTTP ${response.status}).${hint} ${detail}`.trim());
90
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ductape/cli",
3
- "version": "0.4.6",
3
+ "version": "0.5.0",
4
4
  "description": "Ductape CLI — local platform, login, link projects, and manage resources via the proxy (Workbench-compatible)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",