@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,78 @@
1
+ import { UserError } from '../utils/errors.js';
2
+ import { buildUrlReplacements } from './url-replacements.js';
3
+ const WP_ROOT = '/var/www/html';
4
+ const CORE_READY_TIMEOUT_SECONDS = 120;
5
+ const IMPORT_SCRIPT = `
6
+ set -e
7
+ mariadb -uroot -p"$MARIADB_ROOT_PASSWORD" -e "DROP DATABASE IF EXISTS \\\`$MARIADB_DATABASE\\\`;
8
+ CREATE DATABASE \\\`$MARIADB_DATABASE\\\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
9
+ GRANT ALL PRIVILEGES ON \\\`$MARIADB_DATABASE\\\`.* TO '$MARIADB_USER'@'%';"
10
+ sed -E \\
11
+ -e '/^(CREATE DATABASE|USE) /d' \\
12
+ -e 's/utf8mb4_0900_[a-z_]+/utf8mb4_unicode_520_ci/g' \\
13
+ /wpbox/stage/database.sql \\
14
+ | mariadb -uroot -p"$MARIADB_ROOT_PASSWORD" --max-allowed-packet=1G "$MARIADB_DATABASE"
15
+ `;
16
+ const DUMP_SCRIPT = 'mariadb-dump -uroot -p"$MARIADB_ROOT_PASSWORD" --single-transaction --default-character-set=utf8mb4 "$MARIADB_DATABASE" > "/dumps/$1"';
17
+ export async function importDump(compose) {
18
+ await compose.shell('database', IMPORT_SCRIPT);
19
+ }
20
+ export async function dumpDatabase(compose, fileName) {
21
+ await compose.shell('database', DUMP_SCRIPT, [fileName]);
22
+ }
23
+ export async function localizeSite(compose, config, productionUrls) {
24
+ await waitForWordPress(compose);
25
+ await assertWordPressDatabase(compose, config.production.tablePrefix);
26
+ await replaceUrls(compose, [config.production.url, ...productionUrls], config.local.url);
27
+ await ensureAdmin(compose, config.admin);
28
+ const deactivatedPlugins = await deactivatePlugins(compose, config.disablePlugins);
29
+ await applyLocalSettings(compose);
30
+ return { deactivatedPlugins };
31
+ }
32
+ export async function waitForWordPress(compose) {
33
+ const coreFiles = `test -f ${WP_ROOT}/wp-includes/version.php && test -f ${WP_ROOT}/wp-config.php`;
34
+ for (let attempt = 0; attempt < CORE_READY_TIMEOUT_SECONDS; attempt++) {
35
+ const result = await compose.shell('wordpress', coreFiles, [], { allowFail: true });
36
+ if (result.code === 0)
37
+ return;
38
+ await new Promise((resolve) => setTimeout(resolve, 1000));
39
+ }
40
+ throw new UserError('WordPress core did not show up in the container. Check `wpbox logs wordpress`.');
41
+ }
42
+ async function assertWordPressDatabase(compose, tablePrefix) {
43
+ if (!(await compose.wpSucceeds(['core', 'is-installed']))) {
44
+ throw new UserError(`The imported database doesn't look like WordPress (table prefix "${tablePrefix}"?).`);
45
+ }
46
+ }
47
+ async function replaceUrls(compose, productionUrls, localUrl) {
48
+ for (const [from, to] of buildUrlReplacements(productionUrls, localUrl)) {
49
+ await compose.wp(['search-replace', from, to, '--all-tables-with-prefix', '--report-changed-only', '--quiet']);
50
+ }
51
+ await compose.wp(['option', 'update', 'home', localUrl, '--quiet']);
52
+ await compose.wp(['option', 'update', 'siteurl', localUrl, '--quiet']);
53
+ }
54
+ async function ensureAdmin(compose, admin) {
55
+ const credentials = [`--user_pass=${admin.password}`, '--role=administrator', '--quiet'];
56
+ if (await compose.wpSucceeds(['user', 'get', admin.user, '--field=ID'])) {
57
+ await compose.wp(['user', 'update', admin.user, ...credentials, '--skip-email']);
58
+ return;
59
+ }
60
+ const created = await compose.wpSucceeds(['user', 'create', admin.user, admin.email, ...credentials]);
61
+ if (!created)
62
+ await compose.wp(['user', 'create', admin.user, `wpbox-${Date.now()}@local.test`, ...credentials]);
63
+ }
64
+ async function deactivatePlugins(compose, plugins) {
65
+ const deactivated = [];
66
+ for (const plugin of plugins) {
67
+ if (!(await compose.wpSucceeds(['plugin', 'is-active', plugin])))
68
+ continue;
69
+ await compose.wp(['plugin', 'deactivate', plugin, '--quiet']);
70
+ deactivated.push(plugin);
71
+ }
72
+ return deactivated;
73
+ }
74
+ async function applyLocalSettings(compose) {
75
+ await compose.wp(['option', 'update', 'blog_public', '0', '--quiet']);
76
+ await compose.wp(['option', 'delete', 'rewrite_rules', '--quiet'], { allowFail: true });
77
+ await compose.wp(['transient', 'delete', '--all', '--quiet'], { allowFail: true });
78
+ }
@@ -0,0 +1,30 @@
1
+ import { hostOf, isLoopbackHost } from '../project/site-url.js';
2
+ import { pc } from '../ui/output.js';
3
+ export async function loginUrl(compose, config) {
4
+ const defaultLogin = `${config.local.url}/wp-admin/`;
5
+ if (!(await compose.wpSucceeds(['plugin', 'is-active', 'wps-hide-login'])))
6
+ return defaultLogin;
7
+ const customSlug = await compose.wp(['option', 'get', 'whl_page'], { allowFail: true });
8
+ const slug = customSlug.stdout.trim();
9
+ return customSlug.code === 0 && slug ? `${config.local.url}/${slug}/` : defaultLogin;
10
+ }
11
+ export function renderSummary(config, login) {
12
+ const { local, admin, devCode } = config;
13
+ const lines = [
14
+ `🌐 Site ${pc.cyan(local.url)}`,
15
+ `🔑 Admin ${pc.cyan(login)} ${pc.dim(`(${admin.user} / ${admin.password})`)}`,
16
+ `📬 Emails ${pc.cyan(`http://localhost:${local.mailpitPort}`)} ${pc.dim('(Mailpit)')}`,
17
+ ...devCode.themes.map((theme) => `🎨 Theme src/themes/${theme}`),
18
+ ...devCode.plugins.map((plugin) => `🔌 Plugin src/plugins/${plugin}`),
19
+ '🖼️ Uploads src/uploads',
20
+ ];
21
+ const host = hostOf(local.url);
22
+ return isLoopbackHost(host) ? lines.join('\n') : [...lines, '', ...hostsFileInstructions(host)].join('\n');
23
+ }
24
+ function hostsFileInstructions(host) {
25
+ return [
26
+ `Add ${pc.bold(`127.0.0.1 ${host}`)} to your hosts file (once):`,
27
+ ` macOS/Linux: sudo sh -c 'echo "127.0.0.1 ${host}" >> /etc/hosts'`,
28
+ ' Windows: C:\\Windows\\System32\\drivers\\etc\\hosts (Notepad as administrator)',
29
+ ];
30
+ }
@@ -0,0 +1,23 @@
1
+ const SCHEMES = ['https', 'http'];
2
+ const SUBDOMAINS = ['www.', ''];
3
+ export function buildUrlReplacements(productionUrls, localUrl) {
4
+ const localHost = new URL(localUrl).host;
5
+ const productionHosts = new Set(productionUrls.map((url) => new URL(url).host.replace(/^www\./, '')));
6
+ const replacements = [...productionHosts].flatMap((host) => [
7
+ ...absoluteUrlReplacements(host, localUrl),
8
+ ...SUBDOMAINS.map((subdomain) => [`//${subdomain}${host}`, `//${localHost}`]),
9
+ ]);
10
+ return replacements.filter(([from, to]) => from !== to);
11
+ }
12
+ function absoluteUrlReplacements(host, localUrl) {
13
+ return SCHEMES.flatMap((scheme) => SUBDOMAINS.flatMap((subdomain) => {
14
+ const productionUrl = `${scheme}://${subdomain}${host}`;
15
+ return [
16
+ [productionUrl, localUrl],
17
+ [escapeSlashes(productionUrl), escapeSlashes(localUrl)],
18
+ ];
19
+ }));
20
+ }
21
+ function escapeSlashes(url) {
22
+ return url.replace(/\//g, '\\/');
23
+ }
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@reativ/wpbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Turn any WordPress backup (zip, sql, UpdraftPlus, Duplicator, All-in-One WP Migration, cPanel, FTP/SFTP) into a local Docker dev environment in one command.",
5
+ "keywords": [
6
+ "wordpress",
7
+ "docker",
8
+ "backup",
9
+ "local-development",
10
+ "migration",
11
+ "updraftplus",
12
+ "duplicator",
13
+ "all-in-one-wp-migration",
14
+ "wp-cli",
15
+ "cli"
16
+ ],
17
+ "homepage": "https://github.com/reativ-solutions/wpbox#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/reativ-solutions/wpbox/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/reativ-solutions/wpbox.git"
24
+ },
25
+ "license": "MIT",
26
+ "author": "Francisco Costa",
27
+ "type": "module",
28
+ "bin": {
29
+ "wpbox": "bin/wpbox.js"
30
+ },
31
+ "files": [
32
+ "bin",
33
+ "dist",
34
+ "templates"
35
+ ],
36
+ "engines": {
37
+ "node": ">=20"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p .",
41
+ "typecheck": "tsc -p . --noEmit",
42
+ "test": "npm run build && node --test",
43
+ "prepublishOnly": "npm test"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@clack/prompts": "^1.9.0",
50
+ "basic-ftp": "^6.2.6",
51
+ "commander": "^15.1.0",
52
+ "picocolors": "^1.1.1",
53
+ "ssh2-sftp-client": "^12.1.1",
54
+ "tar": "^7.5.23",
55
+ "yaml": "^2.9.1",
56
+ "yauzl": "^3.4.0"
57
+ },
58
+ "devDependencies": {
59
+ "@types/node": "^20.19.43",
60
+ "@types/ssh2-sftp-client": "^9.0.6",
61
+ "@types/yauzl": "^3.4.0",
62
+ "typescript": "^7.0.2"
63
+ }
64
+ }
@@ -0,0 +1,26 @@
1
+ # Generated by wpbox. The WordPress image tag (WordPress + PHP version) comes from
2
+ # "wordpressImage" in .wpbox/config.json, e.g. "php8.2-apache" or "6.8-php8.1-apache".
3
+ # See https://hub.docker.com/_/wordpress for the available tags.
4
+ ARG WORDPRESS_TAG=php8.3-apache
5
+
6
+ FROM wordpress:cli-2.12.0-php8.3 AS wpcli
7
+
8
+ FROM wordpress:${WORDPRESS_TAG}
9
+
10
+ # WP-CLI inside the container (`wpbox wp ...`)
11
+ COPY --from=wpcli /usr/local/bin/wp /usr/local/bin/wp
12
+
13
+ RUN apt-get update \
14
+ && apt-get install -y --no-install-recommends less \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ # Generous limits for local development
18
+ RUN { echo 'upload_max_filesize=256M'; echo 'post_max_size=256M'; echo 'memory_limit=512M'; echo 'max_execution_time=300'; } \
19
+ > /usr/local/etc/php/conf.d/wpbox.ini
20
+
21
+ # Answer on any port, so Apache can also listen on the public port (see local-entrypoint.sh).
22
+ RUN sed -i 's/<VirtualHost \*:80>/<VirtualHost *:*>/' /etc/apache2/sites-available/000-default.conf
23
+
24
+ COPY local-entrypoint.sh /usr/local/bin/local-entrypoint.sh
25
+ ENTRYPOINT ["bash", "/usr/local/bin/local-entrypoint.sh"]
26
+ CMD ["apache2-foreground"]
@@ -0,0 +1,129 @@
1
+ <?php
2
+ /**
3
+ * wpbox temporary database exporter.
4
+ *
5
+ * Uploaded by `wpbox init` over FTP/SFTP, called once over HTTP(S) with a random one-time
6
+ * token, and deleted right after (it also deletes itself when done). It streams a SQL dump
7
+ * of the WordPress tables (only the ones using this site's table prefix).
8
+ */
9
+ $token = '__WPBOX_TOKEN__';
10
+ if (!isset($_GET['token']) || !is_string($_GET['token']) || !hash_equals($token, $_GET['token'])) {
11
+ http_response_code(404);
12
+ exit;
13
+ }
14
+
15
+ @set_time_limit(0);
16
+ @ini_set('memory_limit', '512M');
17
+ while (ob_get_level()) {
18
+ ob_end_clean();
19
+ }
20
+
21
+ define('SHORTINIT', true);
22
+ if (!file_exists(__DIR__ . '/wp-load.php')) {
23
+ http_response_code(500);
24
+ exit('wpbox: wp-load.php not found next to the exporter');
25
+ }
26
+ require __DIR__ . '/wp-load.php';
27
+ global $table_prefix;
28
+
29
+ $host = DB_HOST;
30
+ $port = null;
31
+ $socket = null;
32
+ if (preg_match('/^(.*):(\d+)$/', $host, $m)) {
33
+ $host = $m[1];
34
+ $port = (int) $m[2];
35
+ } elseif (preg_match('/^(.*):(\/.*)$/', $host, $m)) {
36
+ $host = $m[1];
37
+ $socket = $m[2];
38
+ }
39
+ if ($host === '') {
40
+ $host = 'localhost';
41
+ }
42
+
43
+ mysqli_report(MYSQLI_REPORT_OFF);
44
+ $db = mysqli_init();
45
+ if (!$db || !@$db->real_connect($host, DB_USER, DB_PASSWORD, DB_NAME, $port, $socket)) {
46
+ http_response_code(500);
47
+ exit('wpbox: could not connect to the database');
48
+ }
49
+ $db->set_charset('utf8mb4');
50
+
51
+ header('Content-Type: text/plain; charset=utf-8');
52
+ header('Cache-Control: no-store');
53
+ header('X-Accel-Buffering: no');
54
+
55
+ $q = function ($name) {
56
+ return '`' . str_replace('`', '``', $name) . '`';
57
+ };
58
+
59
+ echo "-- wpbox export\n";
60
+ echo "SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\nSET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';\n\n";
61
+
62
+ $tables = array();
63
+ $res = $db->query("SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'");
64
+ while ($row = $res->fetch_row()) {
65
+ if (strpos($row[0], $table_prefix) === 0) {
66
+ $tables[] = $row[0];
67
+ }
68
+ }
69
+ $res->free();
70
+
71
+ $binaryTypes = array(
72
+ MYSQLI_TYPE_TINY_BLOB, MYSQLI_TYPE_MEDIUM_BLOB, MYSQLI_TYPE_LONG_BLOB, MYSQLI_TYPE_BLOB,
73
+ MYSQLI_TYPE_STRING, MYSQLI_TYPE_VAR_STRING,
74
+ );
75
+ $numericTypes = array(
76
+ MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG, MYSQLI_TYPE_INT24,
77
+ MYSQLI_TYPE_DECIMAL, MYSQLI_TYPE_NEWDECIMAL, MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE, MYSQLI_TYPE_YEAR,
78
+ );
79
+
80
+ foreach ($tables as $table) {
81
+ $create = $db->query('SHOW CREATE TABLE ' . $q($table))->fetch_row();
82
+ echo 'DROP TABLE IF EXISTS ' . $q($table) . ";\n" . $create[1] . ";\n\n";
83
+
84
+ $result = $db->query('SELECT * FROM ' . $q($table), MYSQLI_USE_RESULT);
85
+ if (!$result) {
86
+ continue;
87
+ }
88
+ $binary = array();
89
+ $numeric = array();
90
+ foreach ($result->fetch_fields() as $i => $field) {
91
+ $binary[$i] = $field->charsetnr === 63 && in_array($field->type, $binaryTypes, true);
92
+ $numeric[$i] = in_array($field->type, $numericTypes, true);
93
+ }
94
+
95
+ $rows = array();
96
+ $size = 0;
97
+ while ($row = $result->fetch_row()) {
98
+ $values = array();
99
+ foreach ($row as $i => $value) {
100
+ if ($value === null) {
101
+ $values[] = 'NULL';
102
+ } elseif ($numeric[$i] && is_numeric($value)) {
103
+ $values[] = $value;
104
+ } elseif ($binary[$i]) {
105
+ $values[] = $value === '' ? "''" : '0x' . bin2hex($value);
106
+ } else {
107
+ $values[] = "'" . $db->real_escape_string($value) . "'";
108
+ }
109
+ }
110
+ $line = '(' . implode(',', $values) . ')';
111
+ $rows[] = $line;
112
+ $size += strlen($line);
113
+ if ($size > 1000000 || count($rows) >= 500) {
114
+ echo 'INSERT INTO ' . $q($table) . " VALUES\n" . implode(",\n", $rows) . ";\n";
115
+ flush();
116
+ $rows = array();
117
+ $size = 0;
118
+ }
119
+ }
120
+ if ($rows) {
121
+ echo 'INSERT INTO ' . $q($table) . " VALUES\n" . implode(",\n", $rows) . ";\n";
122
+ }
123
+ $result->free();
124
+ echo "\n";
125
+ flush();
126
+ }
127
+
128
+ echo "SET FOREIGN_KEY_CHECKS=1;\n-- wpbox export complete\n";
129
+ @unlink(__FILE__);
@@ -0,0 +1,9 @@
1
+ #!/bin/bash
2
+ # Make Apache also listen on the public port (e.g. 8090), so WordPress requests to
3
+ # itself (http://localhost:8090/wp-cron.php, Site Health) work inside the container.
4
+ set -e
5
+ if [ -n "${LOCAL_PORT:-}" ] && [ "$LOCAL_PORT" != "80" ] \
6
+ && ! grep -qx "Listen $LOCAL_PORT" /etc/apache2/ports.conf; then
7
+ echo "Listen $LOCAL_PORT" >> /etc/apache2/ports.conf
8
+ fi
9
+ exec docker-entrypoint.sh "$@"
@@ -0,0 +1,17 @@
1
+ <?php
2
+ /**
3
+ * Plugin Name: wpbox – Mailpit
4
+ * Description: Local environment only. Every email sent by WordPress is caught by Mailpit,
5
+ * so nothing ever reaches real inboxes. Added by wpbox.
6
+ */
7
+ add_action('phpmailer_init', function ($phpmailer) {
8
+ $phpmailer->isSMTP();
9
+ $phpmailer->Host = 'mailpit';
10
+ $phpmailer->Port = 1025;
11
+ $phpmailer->SMTPAuth = false;
12
+ $phpmailer->SMTPSecure = '';
13
+ $phpmailer->SMTPAutoTLS = false;
14
+ }, PHP_INT_MAX);
15
+
16
+ add_filter('wp_mail_from', function () { return 'wordpress@local.test'; });
17
+ add_filter('wp_mail_from_name', function () { return 'WordPress (local)'; });