@reativ/wpbox 0.0.0-stage → 1.0.1

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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +288 -2
  3. package/bin/wpbox.js +12 -0
  4. package/dist/backup/dump-analysis.js +44 -0
  5. package/dist/backup/import-files.js +50 -0
  6. package/dist/backup/layout.js +89 -0
  7. package/dist/backup/readers/archive-reader.js +16 -0
  8. package/dist/backup/readers/index.js +14 -0
  9. package/dist/backup/readers/tar-reader.js +42 -0
  10. package/dist/backup/readers/wpress-reader.js +76 -0
  11. package/dist/backup/readers/zip-reader.js +51 -0
  12. package/dist/backup/stage.js +128 -0
  13. package/dist/cli.js +61 -0
  14. package/dist/commands/database.js +22 -0
  15. package/dist/commands/init/analyze.js +24 -0
  16. package/dist/commands/init/index.js +73 -0
  17. package/dist/commands/init/questions.js +42 -0
  18. package/dist/commands/project.js +12 -0
  19. package/dist/commands/site.js +58 -0
  20. package/dist/docker/compose-file.js +110 -0
  21. package/dist/docker/compose.js +41 -0
  22. package/dist/docker/environment.js +35 -0
  23. package/dist/project/config.js +60 -0
  24. package/dist/project/gitignore.js +15 -0
  25. package/dist/project/paths.js +22 -0
  26. package/dist/project/secrets.js +29 -0
  27. package/dist/project/site-url.js +27 -0
  28. package/dist/remote/connect.js +17 -0
  29. package/dist/remote/download.js +70 -0
  30. package/dist/remote/ftp-fs.js +56 -0
  31. package/dist/remote/mirror.js +72 -0
  32. package/dist/remote/remote-database.js +103 -0
  33. package/dist/remote/remote-fs.js +1 -0
  34. package/dist/remote/sftp-fs.js +54 -0
  35. package/dist/remote/wordpress-locator.js +58 -0
  36. package/dist/sources/backup-source.js +1 -0
  37. package/dist/sources/index.js +36 -0
  38. package/dist/sources/local-source.js +32 -0
  39. package/dist/sources/remote-questions.js +71 -0
  40. package/dist/sources/remote-source.js +119 -0
  41. package/dist/sources/url-source.js +32 -0
  42. package/dist/ui/output.js +24 -0
  43. package/dist/ui/prompts.js +80 -0
  44. package/dist/utils/errors.js +6 -0
  45. package/dist/utils/exec.js +45 -0
  46. package/dist/utils/format.js +22 -0
  47. package/dist/utils/fs.js +88 -0
  48. package/dist/utils/result.js +2 -0
  49. package/dist/utils/work-queue.js +30 -0
  50. package/dist/wordpress/content.js +74 -0
  51. package/dist/wordpress/database.js +78 -0
  52. package/dist/wordpress/summary.js +30 -0
  53. package/dist/wordpress/url-replacements.js +23 -0
  54. package/package.json +62 -4
  55. package/templates/Dockerfile +26 -0
  56. package/templates/exporter.php +129 -0
  57. package/templates/local-entrypoint.sh +9 -0
  58. package/templates/mailpit.php +17 -0
@@ -0,0 +1,51 @@
1
+ import yauzl from 'yauzl';
2
+ import { normalizeEntry } from '../layout.js';
3
+ import { writeEntry } from './archive-reader.js';
4
+ export class ZipReader {
5
+ file;
6
+ constructor(file) {
7
+ this.file = file;
8
+ }
9
+ async list() {
10
+ const entries = [];
11
+ await this.forEachFile(async (entry) => {
12
+ entries.push({ name: normalizeEntry(entry.fileName), size: entry.uncompressedSize });
13
+ });
14
+ return entries;
15
+ }
16
+ async extract(destination, onBytes) {
17
+ await this.forEachFile(async (entry, zip) => {
18
+ const target = destination(normalizeEntry(entry.fileName));
19
+ if (target)
20
+ await writeEntry(await openEntry(zip, entry), target, onBytes);
21
+ });
22
+ }
23
+ async forEachFile(visit) {
24
+ const zip = await openZip(this.file);
25
+ try {
26
+ await new Promise((resolve, reject) => {
27
+ zip.on('error', reject);
28
+ zip.on('end', resolve);
29
+ zip.on('entry', (entry) => {
30
+ const isDirectory = entry.fileName.endsWith('/');
31
+ const visited = isDirectory ? Promise.resolve() : visit(entry, zip);
32
+ visited.then(() => zip.readEntry(), reject);
33
+ });
34
+ zip.readEntry();
35
+ });
36
+ }
37
+ finally {
38
+ zip.close();
39
+ }
40
+ }
41
+ }
42
+ function openZip(file) {
43
+ return new Promise((resolve, reject) => {
44
+ yauzl.open(file, { lazyEntries: true, autoClose: false }, (error, zip) => (error ? reject(error) : resolve(zip)));
45
+ });
46
+ }
47
+ function openEntry(zip, entry) {
48
+ return new Promise((resolve, reject) => {
49
+ zip.openReadStream(entry, (error, stream) => (error ? reject(error) : resolve(stream)));
50
+ });
51
+ }
@@ -0,0 +1,128 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import zlib from 'node:zlib';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { log, task } from '../ui/output.js';
6
+ import { select } from '../ui/prompts.js';
7
+ import { UserError } from '../utils/errors.js';
8
+ import { formatBytes, formatProgress } from '../utils/format.js';
9
+ import { safeJoin } from '../utils/fs.js';
10
+ import { isUpdraftContentPart, isUpdraftFile } from './import-files.js';
11
+ import { contentPath, dumpLikelihood, findContentBase, findDumpEntries } from './layout.js';
12
+ import { openArchive, WpressReader } from './readers/index.js';
13
+ const WPRESS_METADATA = /^(package|multisite|blogs)\.json$|^database\.sql$/;
14
+ export async function stageBackup(files, paths, { includeContent = true } = {}) {
15
+ resetStage(paths);
16
+ const candidatesDir = path.join(paths.stage, 'dump-candidates');
17
+ const candidates = files.dumps.map((dump) => ({ ...dump, label: dump.name }));
18
+ const staged = [];
19
+ for (const archive of files.archives) {
20
+ const result = await stageArchive(archive, { paths, candidatesDir, includeContent });
21
+ staged.push(result);
22
+ candidates.push(...result.dumps);
23
+ }
24
+ if (includeContent && files.archives.length > 0 && !staged.some((archive) => archive.hasContent)) {
25
+ throw new UserError('None of the archives contains a wp-content folder (themes/, plugins/ or uploads/).');
26
+ }
27
+ const dumpPath = candidates.length ? await stageDump(candidates, paths.stagedDump) : null;
28
+ fs.rmSync(candidatesDir, { recursive: true, force: true });
29
+ return {
30
+ contentDir: includeContent ? paths.stagedContent : null,
31
+ dumpPath,
32
+ format: describeFormat(files.archives, staged),
33
+ };
34
+ }
35
+ function resetStage(paths) {
36
+ fs.rmSync(paths.stage, { recursive: true, force: true });
37
+ fs.mkdirSync(paths.stagedContent, { recursive: true });
38
+ }
39
+ async function stageArchive(archive, context) {
40
+ const reader = openArchive(archive.path, archive.kind);
41
+ const entries = await task(`Reading ${archive.name}`, () => reader.list());
42
+ if (reader instanceof WpressReader)
43
+ await assertReadableWpress(reader, archive.name);
44
+ const names = entries.map((entry) => entry.name);
45
+ const sizes = new Map(entries.map((entry) => [entry.name, entry.size]));
46
+ const contentAtRoot = archive.kind === 'wpress' || isUpdraftContentPart(archive.name);
47
+ const base = findContentBase(names, contentAtRoot ? 'content-at-root' : undefined);
48
+ const dumpTargets = new Map(findDumpEntries(names, base)
49
+ .filter((name) => archive.kind !== 'wpress' || name === 'database.sql')
50
+ .map((name, index) => [name, path.join(context.candidatesDir, `${archive.name}-${index}-${path.basename(name)}`)]));
51
+ const destination = (name) => {
52
+ const dumpTarget = dumpTargets.get(name);
53
+ if (dumpTarget)
54
+ return dumpTarget;
55
+ if (!context.includeContent)
56
+ return null;
57
+ const relative = contentPath(name, base);
58
+ if (!relative || (archive.kind === 'wpress' && WPRESS_METADATA.test(relative)))
59
+ return null;
60
+ return safeJoin(context.paths.stagedContent, relative);
61
+ };
62
+ const totalBytes = names.reduce((sum, name) => sum + (destination(name) ? (sizes.get(name) ?? 0) : 0), 0);
63
+ const dumps = [...dumpTargets].map(([name, target]) => ({
64
+ label: `${archive.name} → ${name}`,
65
+ path: target,
66
+ name,
67
+ size: sizes.get(name) ?? 0,
68
+ }));
69
+ const result = {
70
+ hasContent: context.includeContent && base !== null,
71
+ isDuplicator: names.some((name) => name.startsWith('dup-installer/')),
72
+ dumps,
73
+ };
74
+ if (totalBytes === 0 && dumps.length === 0) {
75
+ log.warn(`${archive.name}: nothing usable inside (no wp-content files or database dump).`);
76
+ return { ...result, hasContent: false };
77
+ }
78
+ let extractedBytes = 0;
79
+ await task(`Extracting ${archive.name}`, (report) => reader.extract(destination, (bytes) => {
80
+ extractedBytes += bytes;
81
+ report(`Extracting ${archive.name} ${formatProgress(extractedBytes, totalBytes)}`);
82
+ }));
83
+ return result;
84
+ }
85
+ async function stageDump(candidates, target) {
86
+ const ranked = [...candidates].sort((a, b) => dumpLikelihood(b.name, b.size) - dumpLikelihood(a.name, a.size));
87
+ const chosen = ranked.length === 1
88
+ ? ranked[0]
89
+ : await select('More than one database dump found. Which one is the WordPress database?', ranked.map((candidate) => ({ value: candidate, label: candidate.label, hint: formatBytes(candidate.size) })), ranked[0]);
90
+ await task('Preparing database dump', async () => {
91
+ if (/\.gz$/i.test(chosen.name)) {
92
+ await pipeline(fs.createReadStream(chosen.path), zlib.createGunzip(), fs.createWriteStream(target));
93
+ }
94
+ else {
95
+ await fs.promises.copyFile(chosen.path, target);
96
+ }
97
+ });
98
+ return target;
99
+ }
100
+ async function assertReadableWpress(reader, name) {
101
+ const raw = await reader.readText('package.json');
102
+ if (!raw)
103
+ return;
104
+ let metadata;
105
+ try {
106
+ metadata = JSON.parse(raw);
107
+ }
108
+ catch {
109
+ return;
110
+ }
111
+ if (metadata.Encrypted || metadata.Encryption?.Enabled) {
112
+ throw new UserError(`${name} is encrypted. Export it again from All-in-One WP Migration without a password.`);
113
+ }
114
+ if (metadata.Compression?.Enabled) {
115
+ throw new UserError(`${name} is compressed, which wpbox can't read yet. Export it again with compression disabled.`);
116
+ }
117
+ }
118
+ function describeFormat(archives, staged) {
119
+ if (archives.some((archive) => archive.kind === 'wpress'))
120
+ return 'All-in-One WP Migration (.wpress)';
121
+ if (archives.some((archive) => isUpdraftFile(archive.name)))
122
+ return 'UpdraftPlus';
123
+ if (staged.some((archive) => archive.isDuplicator))
124
+ return 'Duplicator';
125
+ if (archives.some((archive) => archive.kind === 'tar'))
126
+ return 'tar archive (cPanel / Plesk / generic)';
127
+ return archives.length ? 'zip' : 'database dump only';
128
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,61 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Command } from 'commander';
3
+ import * as database from './commands/database.js';
4
+ import { init } from './commands/init/index.js';
5
+ import * as site from './commands/site.js';
6
+ const { version } = createRequire(import.meta.url)('../package.json');
7
+ export async function main(argv) {
8
+ const program = new Command()
9
+ .name('wpbox')
10
+ .description('Turn any WordPress backup into a local Docker development environment.')
11
+ .version(version)
12
+ .enablePositionalOptions()
13
+ .showHelpAfterError();
14
+ program
15
+ .command('init')
16
+ .description('create the local site from a backup (files in import/, a URL, or a live site over FTP/SFTP)')
17
+ .option('-y, --yes', "don't ask: use detected values and the ones saved in .wpbox/config.json")
18
+ .option('-f, --force', 'overwrite your themes/plugins in src/ and existing uploads with the backup version')
19
+ .option('-s, --source <type>', 'backup source: local, url, ftp or sftp')
20
+ .option('-u, --url <urls...>', 'download the backup from these URLs')
21
+ .action((options) => init({ ...options, urls: options.url }));
22
+ program
23
+ .command('pull')
24
+ .description('refresh from the same source as last time (your code in src/ is kept)')
25
+ .option('-f, --force', 'overwrite your themes/plugins in src/ with the backup version')
26
+ .action((options) => init({ ...options, repeatLastRun: true }));
27
+ program.command('up').description('start the containers').action(site.up);
28
+ program.command('down').description('stop the containers (data is kept)').action(site.down);
29
+ program.command('info').description('show URLs, credentials and folders').action(site.info);
30
+ program
31
+ .command('open')
32
+ .description('open the site in your browser')
33
+ .option('-a, --admin', 'open the admin dashboard')
34
+ .option('-m, --mail', 'open Mailpit (caught emails)')
35
+ .action(site.open);
36
+ program
37
+ .command('logs')
38
+ .description('follow container logs')
39
+ .argument('[service]', 'wordpress, database or mailpit')
40
+ .action(site.logs);
41
+ program
42
+ .command('wp')
43
+ .description('run WP-CLI in the container (e.g. wpbox wp plugin list)')
44
+ .argument('[args...]')
45
+ .allowUnknownOption()
46
+ .passThroughOptions()
47
+ .helpOption(false)
48
+ .action(site.wpCli);
49
+ program.command('shell').description('open a shell in the WordPress container').action(site.shell);
50
+ program.command('db:dump').description('dump the local database to dumps/').action(database.dump);
51
+ program
52
+ .command('db:reimport')
53
+ .description('restore the database from the backup (discards database changes)')
54
+ .action(database.reimport);
55
+ program
56
+ .command('destroy')
57
+ .description('remove containers and volumes (src/, import/ and dumps/ are kept)')
58
+ .option('-y, --yes', "don't ask for confirmation")
59
+ .action(site.destroy);
60
+ await program.parseAsync(argv);
61
+ }
@@ -0,0 +1,22 @@
1
+ import fs from 'node:fs';
2
+ import { log, pc, task } from '../ui/output.js';
3
+ import { UserError } from '../utils/errors.js';
4
+ import { dumpDatabase, importDump, localizeSite } from '../wordpress/database.js';
5
+ import { openProject } from './project.js';
6
+ export async function dump() {
7
+ const { compose } = openProject();
8
+ const fileName = `local-${timestamp()}.sql`;
9
+ await task('Dumping database', () => dumpDatabase(compose, fileName));
10
+ log.success(`Saved dumps/${fileName} ${pc.dim('(with local URLs)')}`);
11
+ }
12
+ export async function reimport() {
13
+ const { paths, config, compose } = openProject();
14
+ if (!fs.existsSync(paths.stagedDump))
15
+ throw new UserError('The original dump is gone. Run `wpbox init` again.');
16
+ await task('Importing database', () => importDump(compose));
17
+ await task('Preparing WordPress for local use', () => localizeSite(compose, config, [config.production.url]));
18
+ log.success('Database restored from the backup.');
19
+ }
20
+ function timestamp() {
21
+ return new Date().toISOString().replace(/[:T]/g, '-').slice(0, 19);
22
+ }
@@ -0,0 +1,24 @@
1
+ import { analyzeDump, findTablePrefixes, isMultisite, productionUrls } from '../../backup/dump-analysis.js';
2
+ import { log, pc, task } from '../../ui/output.js';
3
+ import { select } from '../../ui/prompts.js';
4
+ import { UserError } from '../../utils/errors.js';
5
+ export async function analyzeSite(dumpPath, previousPrefix) {
6
+ const dump = await task('Analyzing database dump', () => analyzeDump(dumpPath));
7
+ const tablePrefix = await chooseTablePrefix(findTablePrefixes(dump.tables), previousPrefix);
8
+ if (isMultisite(dump.tables, tablePrefix)) {
9
+ log.warn('This is a multisite install. Multisite is not supported yet: expect rough edges.');
10
+ }
11
+ const urls = productionUrls(dump);
12
+ if (urls.length === 0)
13
+ throw new UserError("Couldn't find the site URL (home / siteurl) in the database dump.");
14
+ log.info(`Production site ${pc.cyan(urls[0])} · table prefix ${pc.cyan(tablePrefix)}`);
15
+ return { production: { url: urls[0], tablePrefix }, productionUrls: urls };
16
+ }
17
+ async function chooseTablePrefix(prefixes, previous) {
18
+ if (prefixes.length === 0) {
19
+ throw new UserError("The database dump doesn't contain WordPress tables (no *options, *posts and *users).");
20
+ }
21
+ if (prefixes.length === 1)
22
+ return prefixes[0];
23
+ return select('The dump has more than one WordPress install. Which table prefix is this site?', prefixes.map((prefix) => ({ value: prefix, label: prefix })), previous && prefixes.includes(previous) ? previous : prefixes[0]);
24
+ }
@@ -0,0 +1,73 @@
1
+ import fs from 'node:fs';
2
+ import { Compose } from '../../docker/compose.js';
3
+ import { writeComposeProject } from '../../docker/compose-file.js';
4
+ import { ensureDocker } from '../../docker/environment.js';
5
+ import { loadConfig, saveConfig } from '../../project/config.js';
6
+ import { ensureGitignore } from '../../project/gitignore.js';
7
+ import { projectPaths } from '../../project/paths.js';
8
+ import { SecretStore } from '../../project/secrets.js';
9
+ import { chooseSourceType, createSource } from '../../sources/index.js';
10
+ import { intro, log, note, outro, pc, task } from '../../ui/output.js';
11
+ import { useDefaultAnswers } from '../../ui/prompts.js';
12
+ import { UserError } from '../../utils/errors.js';
13
+ import { placeContent } from '../../wordpress/content.js';
14
+ import { importDump, localizeSite } from '../../wordpress/database.js';
15
+ import { loginUrl, renderSummary } from '../../wordpress/summary.js';
16
+ import { analyzeSite } from './analyze.js';
17
+ import { askDevCode, askLocalSite } from './questions.js';
18
+ export async function init(options = {}) {
19
+ const paths = projectPaths();
20
+ const repeatLastRun = Boolean(options.repeatLastRun);
21
+ useDefaultAnswers(Boolean(options.yes) || repeatLastRun);
22
+ intro(`${pc.bgCyan(pc.black(' wpbox '))} ${repeatLastRun ? 'pull' : 'init'}`);
23
+ await ensureDocker();
24
+ const config = loadConfig(paths);
25
+ if (repeatLastRun && !config.source)
26
+ throw new UserError('Nothing to pull from yet. Run `wpbox init` first.');
27
+ fs.mkdirSync(paths.import, { recursive: true });
28
+ const backup = await acquireBackup(paths, config, options);
29
+ const site = await analyzeSite(backup.dumpPath, config.production?.tablePrefix);
30
+ const ready = {
31
+ ...config,
32
+ local: await askLocalSite(config.local),
33
+ devCode: await askDevCode(backup.contentDir, config.devCode),
34
+ production: site.production,
35
+ source: backup.source,
36
+ };
37
+ saveConfig(paths, ready);
38
+ ensureGitignore(paths);
39
+ writeComposeProject(paths, ready);
40
+ const compose = new Compose(paths);
41
+ await buildSite(compose, paths, ready, backup, site.productionUrls, Boolean(options.force));
42
+ note(renderSummary(ready, await loginUrl(compose, ready)), 'Your site is ready 🎉');
43
+ outro(`Run ${pc.cyan('wpbox open')} to open it in the browser.`);
44
+ }
45
+ async function acquireBackup(paths, config, options) {
46
+ const requestedSource = options.urls?.length ? 'url' : options.source;
47
+ const type = options.repeatLastRun && config.source ? config.source.type : await chooseSourceType(paths, config, requestedSource);
48
+ return createSource(type).acquire({
49
+ paths,
50
+ config,
51
+ secrets: new SecretStore(paths.secrets),
52
+ repeatLastRun: Boolean(options.repeatLastRun),
53
+ urls: options.urls,
54
+ });
55
+ }
56
+ async function buildSite(compose, paths, config, backup, productionUrls, overwrite) {
57
+ await task('Starting containers (the first run builds the image)', () => compose.up());
58
+ await task('Importing database', () => importDump(compose));
59
+ log.step('Copying files');
60
+ await placeContent({
61
+ paths,
62
+ compose,
63
+ devCode: config.devCode,
64
+ contentDir: backup.contentDir,
65
+ disposable: backup.disposable,
66
+ overwrite,
67
+ });
68
+ const { deactivatedPlugins } = await task('Preparing WordPress for local use', () => localizeSite(compose, config, productionUrls));
69
+ if (deactivatedPlugins.length)
70
+ log.info(`Deactivated locally: ${deactivatedPlugins.join(', ')}`);
71
+ if (backup.disposable)
72
+ fs.rmSync(paths.stagedContent, { recursive: true, force: true });
73
+ }
@@ -0,0 +1,42 @@
1
+ import { findFreePort, isPortFree } from '../../docker/environment.js';
2
+ import { parseSiteUrl } from '../../project/site-url.js';
3
+ import { log, pc } from '../../ui/output.js';
4
+ import { multiselect, text } from '../../ui/prompts.js';
5
+ import { detectCustomCode, listCode } from '../../wordpress/content.js';
6
+ const FIRST_SITE_PORT = 8090;
7
+ const FIRST_MAILPIT_PORT = 8025;
8
+ export async function askLocalSite(previous) {
9
+ const suggestedPort = previous?.port ?? (await findFreePort(FIRST_SITE_PORT));
10
+ const answer = await text('Local site URL', {
11
+ initial: previous?.url ?? `http://localhost:${suggestedPort}`,
12
+ validate: (value) => {
13
+ const parsed = parseSiteUrl(value);
14
+ return parsed.ok ? undefined : parsed.error;
15
+ },
16
+ });
17
+ const parsed = parseSiteUrl(answer);
18
+ if (!parsed.ok)
19
+ throw new Error(parsed.error);
20
+ const site = parsed.value;
21
+ if (site.https)
22
+ log.warn("wpbox doesn't serve HTTPS yet. Use http:// unless you put a proxy in front.");
23
+ if (site.port !== previous?.port && !(await isPortFree(site.port))) {
24
+ log.warn(`Port ${site.port} is already in use. Starting the site will fail unless you free it or choose another URL.`);
25
+ }
26
+ const mailpitPort = previous?.mailpitPort && previous.mailpitPort !== site.port
27
+ ? previous.mailpitPort
28
+ : await findFreePort(FIRST_MAILPIT_PORT, [site.port]);
29
+ return { url: site.url, port: site.port, mailpitPort };
30
+ }
31
+ export async function askDevCode(contentDir, previous) {
32
+ return {
33
+ themes: await askCodeFolders(contentDir, 'themes', previous.themes),
34
+ plugins: await askCodeFolders(contentDir, 'plugins', previous.plugins),
35
+ };
36
+ }
37
+ async function askCodeFolders(contentDir, kind, previous) {
38
+ const available = listCode(contentDir, kind);
39
+ const custom = detectCustomCode(contentDir, kind);
40
+ const preselected = previous.length ? previous.filter((name) => available.includes(name)) : custom;
41
+ return multiselect(`Which ${kind} do you want to edit? ${pc.dim(`(mapped to src/${kind})`)}`, available.map((name) => ({ value: name, label: name, hint: custom.includes(name) ? 'custom code' : undefined })), preselected);
42
+ }
@@ -0,0 +1,12 @@
1
+ import { Compose } from '../docker/compose.js';
2
+ import { hasConfig, isInitialized, loadConfig } from '../project/config.js';
3
+ import { projectPaths } from '../project/paths.js';
4
+ import { UserError } from '../utils/errors.js';
5
+ export function openProject() {
6
+ const paths = projectPaths();
7
+ const config = loadConfig(paths);
8
+ if (!hasConfig(paths) || !isInitialized(config)) {
9
+ throw new UserError('No wpbox project in this folder. Run `wpbox init` first.');
10
+ }
11
+ return { paths, config, compose: new Compose(paths) };
12
+ }
@@ -0,0 +1,58 @@
1
+ import { ensureDocker } from '../docker/environment.js';
2
+ import { log, note, task } from '../ui/output.js';
3
+ import { confirm } from '../ui/prompts.js';
4
+ import { run } from '../utils/exec.js';
5
+ import { loginUrl, renderSummary } from '../wordpress/summary.js';
6
+ import { openProject } from './project.js';
7
+ export async function up() {
8
+ const { config, compose } = openProject();
9
+ await ensureDocker();
10
+ await task('Starting containers', () => compose.up());
11
+ note(renderSummary(config, await loginUrl(compose, config)), 'Running');
12
+ }
13
+ export async function down() {
14
+ const { compose } = openProject();
15
+ await task('Stopping containers', () => compose.down());
16
+ }
17
+ export async function info() {
18
+ const { config, compose } = openProject();
19
+ const login = await loginUrl(compose, config).catch(() => `${config.local.url}/wp-admin/`);
20
+ note(renderSummary(config, login), 'wpbox');
21
+ }
22
+ export async function open(options) {
23
+ const { config, compose } = openProject();
24
+ if (options.mail)
25
+ return openInBrowser(`http://localhost:${config.local.mailpitPort}`);
26
+ return openInBrowser(options.admin ? await loginUrl(compose, config) : config.local.url);
27
+ }
28
+ export async function logs(service) {
29
+ const { compose } = openProject();
30
+ process.exitCode = await compose.attach(['logs', '-f', '--tail=100', ...(service ? [service] : [])]);
31
+ }
32
+ export async function wpCli(args) {
33
+ const { compose } = openProject();
34
+ const tty = process.stdin.isTTY && process.stdout.isTTY ? [] : ['-T'];
35
+ process.exitCode = await compose.attach(['exec', ...tty, '--user', 'www-data', 'wordpress', 'wp', ...args]);
36
+ }
37
+ export async function shell() {
38
+ const { compose } = openProject();
39
+ process.exitCode = await compose.attach(['exec', 'wordpress', 'bash']);
40
+ }
41
+ export async function destroy(options) {
42
+ const { compose } = openProject();
43
+ const confirmed = options.yes || (await confirm('Remove the containers, the database and the WordPress core volume?', false));
44
+ if (!confirmed) {
45
+ log.info('Cancelled.');
46
+ return;
47
+ }
48
+ await task('Removing containers and volumes', () => compose.down({ removeVolumes: true }));
49
+ log.success('Done. Your files in src/, import/ and dumps/ are untouched. `wpbox init` starts over.');
50
+ }
51
+ async function openInBrowser(url) {
52
+ if (process.platform === 'darwin')
53
+ await run('open', [url]);
54
+ else if (process.platform === 'win32')
55
+ await run('cmd', ['/c', 'start', '""', url]);
56
+ else
57
+ await run('xdg-open', [url]);
58
+ }
@@ -0,0 +1,110 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import YAML from 'yaml';
5
+ import { hostOf, isLoopbackHost } from '../project/site-url.js';
6
+ const TEMPLATES_DIR = fileURLToPath(new URL('../../templates/', import.meta.url));
7
+ const DOCKER_TEMPLATES = ['Dockerfile', 'local-entrypoint.sh', 'mailpit.php'];
8
+ const WP_ROOT = '/var/www/html';
9
+ const WP_CONTENT = `${WP_ROOT}/wp-content`;
10
+ export function buildComposeFile(config) {
11
+ return {
12
+ name: `wpbox-${config.project}`,
13
+ services: {
14
+ wordpress: wordpressService(config),
15
+ database: databaseService(config),
16
+ mailpit: mailpitService(config),
17
+ },
18
+ volumes: { wordpress_data: {}, database_data: {} },
19
+ };
20
+ }
21
+ export function writeComposeProject(paths, config) {
22
+ copyDockerTemplates(paths.dockerContext);
23
+ createMountedFolders(paths, config);
24
+ const header = '# Generated by wpbox from .wpbox/config.json. Run `wpbox init` to change it.\n';
25
+ fs.writeFileSync(paths.compose, header + YAML.stringify(buildComposeFile(config)));
26
+ }
27
+ function wordpressService(config) {
28
+ const host = hostOf(config.local.url);
29
+ return {
30
+ build: { context: './docker', args: { WORDPRESS_TAG: config.wordpressImage } },
31
+ image: `wpbox-wordpress:${config.wordpressImage}`,
32
+ ports: [`127.0.0.1:${config.local.port}:80`],
33
+ environment: {
34
+ WORDPRESS_DB_HOST: 'database:3306',
35
+ WORDPRESS_DB_NAME: config.database.name,
36
+ WORDPRESS_DB_USER: config.database.user,
37
+ WORDPRESS_DB_PASSWORD: config.database.password,
38
+ WORDPRESS_TABLE_PREFIX: config.production.tablePrefix,
39
+ WORDPRESS_DEBUG: '1',
40
+ WORDPRESS_CONFIG_EXTRA: wordpressConstants(),
41
+ SITE_URL: config.local.url,
42
+ LOCAL_PORT: String(config.local.port),
43
+ WP_CLI_CACHE_DIR: '/tmp/wp-cli-cache',
44
+ },
45
+ volumes: [
46
+ `wordpress_data:${WP_ROOT}`,
47
+ `../src/uploads:${WP_CONTENT}/uploads`,
48
+ ...config.devCode.themes.map((theme) => `../src/themes/${theme}:${WP_CONTENT}/themes/${theme}`),
49
+ ...config.devCode.plugins.map((plugin) => `../src/plugins/${plugin}:${WP_CONTENT}/plugins/${plugin}`),
50
+ `./docker/mailpit.php:${WP_CONTENT}/mu-plugins/wpbox-mailpit.php:ro`,
51
+ './:/wpbox:ro',
52
+ ],
53
+ extra_hosts: isLoopbackHost(host) ? undefined : [`${host}:127.0.0.1`],
54
+ depends_on: { database: { condition: 'service_healthy' } },
55
+ };
56
+ }
57
+ function wordpressConstants() {
58
+ return [
59
+ "define('WP_ENVIRONMENT_TYPE', 'local');",
60
+ "define('WP_DEVELOPMENT_MODE', 'all');",
61
+ "define('WP_HOME', getenv_docker('SITE_URL', ''));",
62
+ "define('WP_SITEURL', getenv_docker('SITE_URL', ''));",
63
+ "define('WP_DEBUG_LOG', true);",
64
+ "define('WP_DEBUG_DISPLAY', true);",
65
+ ].join('\n');
66
+ }
67
+ function databaseService(config) {
68
+ return {
69
+ image: 'mariadb:11.4',
70
+ command: ['--max-allowed-packet=1G'],
71
+ environment: {
72
+ MARIADB_DATABASE: config.database.name,
73
+ MARIADB_USER: config.database.user,
74
+ MARIADB_PASSWORD: config.database.password,
75
+ MARIADB_ROOT_PASSWORD: config.database.rootPassword,
76
+ },
77
+ volumes: ['database_data:/var/lib/mysql', './:/wpbox', '../dumps:/dumps'],
78
+ healthcheck: {
79
+ test: ['CMD', 'healthcheck.sh', '--connect', '--innodb_initialized'],
80
+ interval: '5s',
81
+ timeout: '5s',
82
+ retries: 30,
83
+ start_period: '30s',
84
+ },
85
+ };
86
+ }
87
+ function mailpitService(config) {
88
+ return {
89
+ image: 'axllent/mailpit:v1.21',
90
+ ports: [`127.0.0.1:${config.local.mailpitPort}:8025`],
91
+ };
92
+ }
93
+ function copyDockerTemplates(target) {
94
+ fs.mkdirSync(target, { recursive: true });
95
+ for (const file of DOCKER_TEMPLATES) {
96
+ const content = fs.readFileSync(path.join(TEMPLATES_DIR, file), 'utf8').replace(/\r\n/g, '\n');
97
+ fs.writeFileSync(path.join(target, file), content);
98
+ }
99
+ }
100
+ function createMountedFolders(paths, config) {
101
+ const folders = [
102
+ paths.srcUploads,
103
+ paths.dumps,
104
+ paths.stage,
105
+ ...config.devCode.themes.map((theme) => path.join(paths.srcThemes, theme)),
106
+ ...config.devCode.plugins.map((plugin) => path.join(paths.srcPlugins, plugin)),
107
+ ];
108
+ for (const folder of folders)
109
+ fs.mkdirSync(folder, { recursive: true });
110
+ }
@@ -0,0 +1,41 @@
1
+ import fs from 'node:fs';
2
+ import { UserError } from '../utils/errors.js';
3
+ import { run } from '../utils/exec.js';
4
+ export class Compose {
5
+ paths;
6
+ constructor(paths) {
7
+ this.paths = paths;
8
+ }
9
+ up() {
10
+ return this.run(['up', '-d', '--build', '--wait', '--remove-orphans']);
11
+ }
12
+ down({ removeVolumes = false } = {}) {
13
+ return this.run(removeVolumes ? ['down', '-v', '--remove-orphans'] : ['down']);
14
+ }
15
+ async attach(args) {
16
+ const result = await this.run(args, { inherit: true, allowFail: true });
17
+ return result.code;
18
+ }
19
+ exec(service, command, options = {}) {
20
+ const { env = {}, user, ...runOptions } = options;
21
+ const userFlags = user ? ['--user', user] : [];
22
+ const envFlags = Object.keys(env).flatMap((name) => ['-e', name]);
23
+ return this.run(['exec', '-T', ...userFlags, ...envFlags, service, ...command], { ...runOptions, env });
24
+ }
25
+ shell(service, script, args = [], options = {}) {
26
+ return this.exec(service, ['sh', '-c', script, 'sh', ...args], options);
27
+ }
28
+ wp(args, options = {}) {
29
+ return this.exec('wordpress', ['wp', '--allow-root', '--skip-plugins', '--skip-themes', ...args], options);
30
+ }
31
+ async wpSucceeds(args) {
32
+ const result = await this.wp(args, { allowFail: true });
33
+ return result.code === 0;
34
+ }
35
+ run(args, options = {}) {
36
+ if (!fs.existsSync(this.paths.compose)) {
37
+ throw new UserError('No wpbox project here. Run `wpbox init` first.');
38
+ }
39
+ return run('docker', ['compose', '-f', this.paths.compose, ...args], { cwd: this.paths.root, ...options });
40
+ }
41
+ }
@@ -0,0 +1,35 @@
1
+ import net from 'node:net';
2
+ import { UserError } from '../utils/errors.js';
3
+ import { run } from '../utils/exec.js';
4
+ const DOCKER_DOWNLOAD_URL = 'https://www.docker.com/products/docker-desktop/';
5
+ export async function ensureDocker() {
6
+ try {
7
+ await run('docker', ['version', '--format', '{{.Server.Version}}']);
8
+ }
9
+ catch (error) {
10
+ if (error instanceof UserError)
11
+ throw new UserError(`Docker is not installed. Get Docker Desktop: ${DOCKER_DOWNLOAD_URL}`);
12
+ throw new UserError('Docker is not running. Start Docker Desktop and try again.');
13
+ }
14
+ try {
15
+ await run('docker', ['compose', 'version']);
16
+ }
17
+ catch {
18
+ throw new UserError('Docker Compose v2 is required (`docker compose`). Update Docker Desktop.');
19
+ }
20
+ }
21
+ export async function findFreePort(start, exclude = []) {
22
+ for (let port = start; port < start + 200; port++) {
23
+ if (!exclude.includes(port) && (await isPortFree(port)))
24
+ return port;
25
+ }
26
+ throw new UserError(`No free port found near ${start}.`);
27
+ }
28
+ export function isPortFree(port) {
29
+ return new Promise((resolve) => {
30
+ const server = net.createServer();
31
+ server.once('error', () => resolve(false));
32
+ server.once('listening', () => server.close(() => resolve(true)));
33
+ server.listen(port, '127.0.0.1');
34
+ });
35
+ }