@reativ/wpbox 0.0.0-stage → 1.0.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.
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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Francisco Costa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,289 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://reativ.com">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/reativ-solutions/wpbox/main/.github/assets/reativ-logo-dark.svg">
5
+ <img src="https://raw.githubusercontent.com/reativ-solutions/wpbox/main/.github/assets/reativ-logo-light.svg" alt="Reativ" width="260">
6
+ </picture>
7
+ </a>
8
+ </p>
2
9
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
10
+ <h1 align="center">📦 wpbox</h1>
11
+
12
+ <p align="center">
13
+ <strong>From a live WordPress site to a clean local development environment, in one command.</strong>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@reativ/wpbox"><img src="https://img.shields.io/npm/v/@reativ/wpbox?color=5206fd" alt="npm version"></a>
18
+ <a href="https://github.com/reativ-solutions/wpbox/actions/workflows/ci.yml"><img src="https://github.com/reativ-solutions/wpbox/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
19
+ <img src="https://img.shields.io/node/v/@reativ/wpbox" alt="Node.js version">
20
+ <img src="https://img.shields.io/badge/platform-macOS%20%7C%20Windows%20%7C%20Linux-lightgrey" alt="Platforms">
21
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
22
+ </p>
23
+
24
+ ---
25
+
26
+ ## Why we built it
27
+
28
+ Many projects reach us as nothing more than a website running somewhere on the internet. There is no repository, no staging server and no local copy: just production, and often a habit of editing it directly.
29
+
30
+ We don't work like that. Changes are made in a development environment, tracked in version control, reviewed, and only then shipped. Production is the place where work arrives, not where it happens.
31
+
32
+ **wpbox** is the first step of that workflow. It takes whatever we receive (a backup file, a download link, or FTP access to a live server) and turns it into a local, isolated, reproducible environment. The site's own code goes into `src/`, ready for git. Everything else is rebuilt the same way on every machine, every time.
33
+
34
+ We use it on our own projects, and now it's yours too.
35
+
36
+ ## ✨ What it does
37
+
38
+ ```text
39
+ ┌ wpbox init
40
+ │
41
+ ◇ Where is the backup?
42
+ │ 📁 Files in import/
43
+ │
44
+ ◆ Backup format: UpdraftPlus
45
+ ● Production site https://www.example.com · table prefix wp_
46
+ │
47
+ ◇ Which themes do you want to edit? (mapped to src/themes)
48
+ │ example-theme
49
+ │
50
+ ◇ Your site is ready 🎉 ────────────────────────────────────╮
51
+ │ │
52
+ │ 🌐 Site http://localhost:8090 │
53
+ │ 🔑 Admin http://localhost:8090/wp-admin/ (admin / admin)
54
+ │ 📬 Emails http://localhost:8025 (Mailpit) │
55
+ │ 🎨 Theme src/themes/example-theme │
56
+ │ 🔌 Plugin src/plugins/example-core │
57
+ │ 🖼️ Uploads src/uploads │
58
+ ├─────────────────────────────────────────────────────────────╯
59
+ ```
60
+
61
+ - 🗂️ **Reads the backups you already have.** Plain `wp-content` zip + `.sql`, full-site zips, **UpdraftPlus**, **Duplicator**, **All-in-One WP Migration** (`.wpress`), **cPanel / Plesk** `.tar.gz`, and `.sql.gz`.
62
+ - 🌍 **Or fetches them for you.** From a URL (Dropbox and Google Drive share links included), or straight from a live server over **FTP / FTPS / SFTP**, with incremental sync.
63
+ - 🔁 **Moves the site to a local domain safely.** WP-CLI `search-replace` handles PHP-serialized data, JSON-escaped URLs and every `http` / `https` / `www` variant. A `sed` on the dump would silently corrupt serialized data.
64
+ - 🧑‍💻 **Your code in `src/`, everything else rebuilt.** Custom themes and plugins (the ones not from wordpress.org) are detected and bind-mounted for live editing. WordPress core and third-party plugins live in a Docker volume.
65
+ - 🛡️ **Never overwrites your work.** Running `init` or `pull` again keeps your changes in `src/` and only adds new uploads.
66
+ - 📬 **Nothing leaves your machine.** Every email WordPress sends is caught by [Mailpit](https://mailpit.axllent.org/). Search engine indexing is turned off.
67
+ - 🧹 **Ready to work in.** It creates a local admin and deactivates plugins that get in the way of local work: security, caching, maintenance mode, hidden login URLs, Site Kit, Jetpack…
68
+ - 🖥️ **Same result on every OS.** macOS, Windows and Linux. You only need Node.js and Docker, because extraction, the database and WP-CLI all run in containers.
69
+
70
+ ## 🚀 Quick start
71
+
72
+ **Requirements:** [Node.js](https://nodejs.org/) 20+ and [Docker Desktop](https://www.docker.com/products/docker-desktop/) (or Docker Engine with Compose v2).
73
+
74
+ ```bash
75
+ mkdir my-site && cd my-site
76
+ mkdir import # drop your backup files here
77
+ npx @reativ/wpbox init
78
+ ```
79
+
80
+ Open the site with `npx @reativ/wpbox open`.
81
+
82
+ > 💡 Install it once and use the short command everywhere:
83
+ >
84
+ > ```bash
85
+ > npm install -g @reativ/wpbox
86
+ > wpbox init
87
+ > ```
88
+
89
+ ## 📥 Where the backup comes from
90
+
91
+ `wpbox init` asks where the backup is:
92
+
93
+ | Source | What you need |
94
+ |---|---|
95
+ | 📁 **Files in `import/`** | Put the backup files in `import/`. The format is detected automatically. |
96
+ | 🌍 **URL** | One or more direct download links. Credentials in the URL (`https://user:pass@host/…`) become HTTP basic auth. |
97
+ | 📡 **FTP / FTPS** | Host, user and password. wpbox finds the WordPress folder by itself. |
98
+ | 🔐 **SFTP** | Host, user and a password or SSH key. |
99
+
100
+ ### Supported backup formats
101
+
102
+ | Format | Files to put in `import/` |
103
+ |---|---|
104
+ | Plain | `wp-content.zip` + `database.sql` (or `.sql.gz`) |
105
+ | Full site | a zip with `wp-content/` inside, optionally with the `.sql` |
106
+ | UpdraftPlus | all `backup_…-plugins.zip`, `-themes.zip`, `-uploads.zip`, `-others.zip`, `-db.gz` files |
107
+ | Duplicator | the `…_archive.zip` (the installer isn't needed) |
108
+ | All-in-One WP Migration | the `.wpress` file (unencrypted, without compression) |
109
+ | cPanel / Plesk / generic | the `.tar.gz`, `.tgz` or `.tar` backup |
110
+
111
+ If an archive holds more than one database dump, wpbox asks which one belongs to the site.
112
+
113
+ ### Database from a live server
114
+
115
+ When the files come over FTP/SFTP, the database can come from:
116
+
117
+ 1. **A temporary export script** (works on most hosting). wpbox uploads a one-time PHP file with a random name and token, streams the dump over HTTPS, and deletes the file. Only the tables with the site's prefix are exported.
118
+ 2. **A direct MySQL connection**, with the credentials read from `wp-config.php`. Most shared hosting blocks this from outside.
119
+ 3. **A `.sql` file** you put in `import/` yourself.
120
+
121
+ Files are mirrored to `.wpbox/mirror/`, so `wpbox pull` only downloads what changed since the last run.
122
+
123
+ ## 🗺️ Project layout
124
+
125
+ ```text
126
+ my-site/
127
+ ├── import/ 📥 backup files (yours or downloaded)
128
+ ├── src/
129
+ │ ├── themes/<slug> 🎨 your themes: edit here, changes are live
130
+ │ ├── plugins/<slug> 🔌 your plugins: edit here, changes are live
131
+ │ └── uploads/ 🖼️ wp-content/uploads
132
+ ├── dumps/ 💾 database dumps from `wpbox db:dump`
133
+ └── .wpbox/ ⚙️ generated: compose.yaml, Dockerfile, config.json, mirror/
134
+ ```
135
+
136
+ wpbox adds `.wpbox/`, `import/`, `dumps/` and `src/uploads/` to `.gitignore`, so `git init` gives you a repository with only the code that matters.
137
+
138
+ ## 🧰 Commands
139
+
140
+ | Command | What it does |
141
+ |---|---|
142
+ | `wpbox init` | Create the local site from a backup |
143
+ | `wpbox pull` | Refresh database and files from the same source as last time. Your code in `src/` is kept |
144
+ | `wpbox up` / `wpbox down` | Start / stop the containers (data is kept) |
145
+ | `wpbox open` | Open the site (`--admin` for the dashboard, `--mail` for Mailpit) |
146
+ | `wpbox info` | Show URLs, credentials and folders |
147
+ | `wpbox wp <args>` | Run WP-CLI, e.g. `wpbox wp plugin list` |
148
+ | `wpbox shell` | Open a shell in the WordPress container |
149
+ | `wpbox logs [service]` | Follow the logs (`wordpress`, `database`, `mailpit`) |
150
+ | `wpbox db:dump` | Save the local database to `dumps/` |
151
+ | `wpbox db:reimport` | Restore the database from the backup (discards local database changes) |
152
+ | `wpbox destroy` | Remove containers and volumes. `src/`, `import/` and `dumps/` stay |
153
+
154
+ ### Options
155
+
156
+ ```bash
157
+ wpbox init --yes # no questions: detected values and last answers
158
+ wpbox init --force # overwrite src/ with the backup version (careful!)
159
+ wpbox init --source sftp # skip the "where is the backup?" question
160
+ wpbox init --url https://example.com/backup.zip https://example.com/db.sql.gz
161
+ ```
162
+
163
+ For scripts and CI, passwords can come from `WPBOX_FTP_PASSWORD`, `WPBOX_DB_PASSWORD` and `WPBOX_KEY_PASSPHRASE`.
164
+
165
+ ## ⚙️ Configuration
166
+
167
+ Answers are saved in `.wpbox/config.json`. Edit it and run `wpbox init --yes` to apply:
168
+
169
+ | Key | Default | Description |
170
+ |---|---|---|
171
+ | `local.url` | `http://localhost:8090` | Local URL. If 8090 is taken, the next free port is used |
172
+ | `wordpressImage` | `php8.3-apache` | [WordPress image tag](https://hub.docker.com/_/wordpress), e.g. `php8.1-apache` for older sites |
173
+ | `devCode.themes` / `devCode.plugins` | auto-detected | Themes and plugins mapped to `src/` |
174
+ | `disablePlugins` | security, cache, maintenance… | Plugins deactivated locally, if installed |
175
+ | `admin` | `admin` / `admin` | Local admin user (created, or its password reset) |
176
+
177
+ ### Custom local domain
178
+
179
+ Use a URL such as `http://my-site.localhost:8090`: `*.localhost` domains work in modern browsers without any setup.
180
+
181
+ For other domains (e.g. `http://my-site.test:8090`), add them to your hosts file once:
182
+
183
+ - **macOS / Linux:** `sudo sh -c 'echo "127.0.0.1 my-site.test" >> /etc/hosts'`
184
+ - **Windows:** add `127.0.0.1 my-site.test` to `C:\Windows\System32\drivers\etc\hosts` (Notepad as administrator)
185
+
186
+ ## 🔍 How it works
187
+
188
+ 1. **Collect.** Archives are read (or downloaded or mirrored) into a clean `wp-content` and a `database.sql`. Caches, backups of backups and production-only drop-ins like `object-cache.php` are left out.
189
+ 2. **Analyze.** The dump is streamed to find the table prefix, the production URLs and multisite installs.
190
+ 3. **Run.** `.wpbox/compose.yaml` is generated with WordPress + PHP + WP-CLI, MariaDB and Mailpit.
191
+ 4. **Import.** The dump goes into MariaDB, with MySQL 8 collations mapped so the import doesn't fail.
192
+ 5. **Place.** Your code goes to `src/`, uploads to `src/uploads`, everything else into the Docker volume.
193
+ 6. **Localize.** Production URLs are replaced, the local admin is created, disruptive plugins are deactivated and indexing is turned off.
194
+
195
+ ## ❓ Troubleshooting
196
+
197
+ <details>
198
+ <summary><b>"Docker is not running"</b></summary>
199
+
200
+ Start Docker Desktop, wait until it's running, and try again.
201
+ </details>
202
+
203
+ <details>
204
+ <summary><b>The site needs an older PHP version</b></summary>
205
+
206
+ Set `"wordpressImage": "php8.1-apache"` (or `php7.4-apache`) in `.wpbox/config.json`, then run `wpbox destroy` and `wpbox init --yes`.
207
+ </details>
208
+
209
+ <details>
210
+ <summary><b>I can't log in</b></summary>
211
+
212
+ Use `admin` / `admin`, or the user in `.wpbox/config.json`. If the site uses a custom login URL plugin that isn't deactivated, `wpbox info` shows the right address. `wpbox wp user list` lists every user.
213
+ </details>
214
+
215
+ <details>
216
+ <summary><b>Images are missing</b></summary>
217
+
218
+ If you skipped uploads when pulling over FTP/SFTP, run `wpbox init` and answer yes to uploads, or copy them into `src/uploads/`.
219
+ </details>
220
+
221
+ <details>
222
+ <summary><b>The .wpress file can't be read</b></summary>
223
+
224
+ Encrypted or compressed `.wpress` archives (premium extension options) aren't supported yet. Export again without them.
225
+ </details>
226
+
227
+ ## ⚠️ Limitations
228
+
229
+ - Multisite installs are detected but not supported yet.
230
+ - HTTPS isn't served locally yet.
231
+ - Duplicator Pro `.daf` archives aren't supported.
232
+
233
+ ## 🧭 Roadmap
234
+
235
+ - [ ] HTTPS and port-less local domains (`https://my-site.localhost`) through a shared local proxy
236
+ - [ ] `wpbox pull --db-only` / `--files-only`
237
+ - [ ] Serve missing uploads from production instead of downloading them
238
+ - [ ] Anonymize personal data on import (users, WooCommerce orders) and switch payment gateways to test mode
239
+ - [ ] Database snapshots: `wpbox snapshot save` / `restore`
240
+ - [ ] Optional Xdebug and Adminer
241
+ - [ ] SSH + WP-CLI source (export on the server, faster than FTP)
242
+
243
+ ## 🛠️ Development
244
+
245
+ wpbox is written in TypeScript and compiled to plain ESM with `tsc`, without a bundler.
246
+
247
+ ```bash
248
+ git clone https://github.com/reativ-solutions/wpbox.git && cd wpbox
249
+ npm install
250
+ npm test # builds and runs the test suite
251
+ npm link # makes `wpbox` point to your working copy
252
+ ```
253
+
254
+ ```text
255
+ src/
256
+ ├── cli.ts command-line interface
257
+ ├── commands/ init, pull, site and database commands
258
+ ├── sources/ where backups come from: local files, URL, FTP/SFTP
259
+ ├── backup/ archive readers (zip, tar, wpress), staging and dump analysis
260
+ ├── remote/ FTP/SFTP file systems, mirroring, remote database export
261
+ ├── wordpress/ import, URL replacement, content placement
262
+ ├── docker/ compose file generation and Docker Compose commands
263
+ ├── project/ paths, configuration, secrets
264
+ ├── ui/ prompts and terminal output
265
+ └── utils/ small shared helpers
266
+ ```
267
+
268
+ ### Releasing
269
+
270
+ Releases are published to npm by GitHub Actions when a version tag is pushed:
271
+
272
+ ```bash
273
+ npm version minor # bumps package.json, commits and creates the tag (e.g. v1.1.0)
274
+ git push --follow-tags
275
+ ```
276
+
277
+ The workflow checks that the tag matches `package.json`, runs the tests, publishes to npm with provenance and creates the GitHub release. Pre-release tags such as `v1.1.0-beta.1` are published under the `next` npm tag.
278
+
279
+ Issues and pull requests are welcome.
280
+
281
+ ## 📄 License
282
+
283
+ The code is released under the [MIT License](LICENSE).
284
+
285
+ The Reativ name and logo are trademarks of Reativ and are not covered by the MIT License.
286
+
287
+ <p align="center">
288
+ Made with care by <a href="https://reativ.com">Reativ</a>.
289
+ </p>
package/bin/wpbox.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../dist/cli.js';
3
+ import { log } from '../dist/ui/output.js';
4
+ import { UserError } from '../dist/utils/errors.js';
5
+
6
+ main(process.argv).catch((error) => {
7
+ log.error(error instanceof Error ? error.message : String(error));
8
+ if (!(error instanceof UserError)) {
9
+ console.error(process.env.DEBUG ? error.stack : 'Run with DEBUG=1 for the full stack trace.');
10
+ }
11
+ process.exit(1);
12
+ });
@@ -0,0 +1,44 @@
1
+ import fs from 'node:fs';
2
+ const CHUNK_SIZE = 1024 * 1024;
3
+ const CHUNK_OVERLAP = 64 * 1024;
4
+ const CREATE_TABLE = /CREATE TABLE (?:IF NOT EXISTS )?`([^`]+)`/g;
5
+ const OPTION_ROW = /\(\s*'?\d+'?\s*,\s*'(home|siteurl|whl_page)'\s*,\s*'((?:[^'\\]|\\.)*)'\s*,\s*'[^']*'\s*\)/g;
6
+ const SQL_ESCAPES = { n: '\n', r: '\r', t: '\t', '0': '\0' };
7
+ export async function analyzeDump(file) {
8
+ const tables = new Set();
9
+ const options = {};
10
+ let carry = '';
11
+ for await (const chunk of fs.createReadStream(file, { encoding: 'utf8', highWaterMark: CHUNK_SIZE })) {
12
+ const text = carry + String(chunk);
13
+ for (const [, table] of text.matchAll(CREATE_TABLE))
14
+ tables.add(table);
15
+ for (const [, name, value] of text.matchAll(OPTION_ROW))
16
+ addOption(options, name, unescapeSql(value));
17
+ carry = text.slice(-CHUNK_OVERLAP);
18
+ }
19
+ return { tables: [...tables].sort(), options };
20
+ }
21
+ export function findTablePrefixes(tables) {
22
+ const known = new Set(tables);
23
+ return tables
24
+ .filter((table) => table.endsWith('options'))
25
+ .map((table) => table.slice(0, -'options'.length))
26
+ .filter((prefix) => known.has(`${prefix}posts`) && known.has(`${prefix}users`));
27
+ }
28
+ export function isMultisite(tables, prefix) {
29
+ return tables.includes(`${prefix}blogs`) && tables.includes(`${prefix}site`);
30
+ }
31
+ export function productionUrls(analysis) {
32
+ const urls = [...(analysis.options.home ?? []), ...(analysis.options.siteurl ?? [])]
33
+ .map((url) => url.replace(/\/+$/, ''))
34
+ .filter((url) => /^https?:\/\//.test(url));
35
+ return [...new Set(urls)];
36
+ }
37
+ export function unescapeSql(value) {
38
+ return value.replace(/\\(.)/g, (_, character) => SQL_ESCAPES[character] ?? character);
39
+ }
40
+ function addOption(options, name, value) {
41
+ const values = (options[name] ??= []);
42
+ if (!values.includes(value))
43
+ values.push(value);
44
+ }
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { isDumpName } from './layout.js';
4
+ const UPDRAFT_FILE = /^backup_\d{4}-\d{2}-\d{2}-\d{4}_.+_[0-9a-f]{12}-(plugins|themes|uploads|others|mu-plugins|more|db)\d*\.(zip|gz)$/i;
5
+ const UPDRAFT_CONTENT_PART = /-(others|uploads|mu-plugins|more)\d*\.zip$/i;
6
+ export function isUpdraftFile(name) {
7
+ return UPDRAFT_FILE.test(path.basename(name));
8
+ }
9
+ export function isUpdraftContentPart(name) {
10
+ return isUpdraftFile(name) && UPDRAFT_CONTENT_PART.test(name);
11
+ }
12
+ export function archiveKind(name) {
13
+ const lower = name.toLowerCase();
14
+ if (lower.endsWith('.wpress'))
15
+ return 'wpress';
16
+ if (lower.endsWith('.tar.gz') || lower.endsWith('.tgz') || lower.endsWith('.tar'))
17
+ return 'tar';
18
+ if (lower.endsWith('.zip'))
19
+ return 'zip';
20
+ return null;
21
+ }
22
+ export function isDumpFile(name) {
23
+ return isDumpName(name) || (isUpdraftFile(name) && name.toLowerCase().endsWith('.gz'));
24
+ }
25
+ export function scanImportFolder(dir) {
26
+ const found = { archives: [], dumps: [] };
27
+ if (!fs.existsSync(dir))
28
+ return found;
29
+ for (const name of fs.readdirSync(dir).sort()) {
30
+ const filePath = path.join(dir, name);
31
+ const stat = fs.statSync(filePath);
32
+ if (!stat.isFile() || name.endsWith('.part'))
33
+ continue;
34
+ const kind = archiveKind(name);
35
+ if (kind)
36
+ found.archives.push({ path: filePath, name, size: stat.size, kind });
37
+ else if (isDumpFile(name))
38
+ found.dumps.push({ path: filePath, name, size: stat.size });
39
+ }
40
+ return found;
41
+ }
42
+ export function onlyNamed(files, names) {
43
+ return {
44
+ archives: files.archives.filter((archive) => names.includes(archive.name)),
45
+ dumps: files.dumps.filter((dump) => names.includes(dump.name)),
46
+ };
47
+ }
48
+ export function countFiles(files) {
49
+ return files.archives.length + files.dumps.length;
50
+ }
@@ -0,0 +1,89 @@
1
+ import path from 'node:path';
2
+ const WP_CONTENT_FOLDERS = new Set(['themes', 'plugins', 'uploads', 'mu-plugins', 'languages']);
3
+ export const EXCLUDED_CONTENT = new Set([
4
+ 'cache',
5
+ 'upgrade',
6
+ 'upgrade-temp-backup',
7
+ 'wflogs',
8
+ 'ai1wm-backups',
9
+ 'updraft',
10
+ 'backups-dup-lite',
11
+ 'backups-dup-pro',
12
+ 'backup-guard',
13
+ 'wpvividbackups',
14
+ 'backwpup',
15
+ 'et-cache',
16
+ 'litespeed',
17
+ 'debug.log',
18
+ 'advanced-cache.php',
19
+ 'object-cache.php',
20
+ 'db.php',
21
+ ]);
22
+ export function normalizeEntry(name) {
23
+ return name.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
24
+ }
25
+ export function isOperatingSystemJunk(entry) {
26
+ return entry.startsWith('__MACOSX/') || entry.split('/').some((segment) => segment.startsWith('._') || segment === '.DS_Store');
27
+ }
28
+ export function findContentBase(entries, hint) {
29
+ const files = entries.filter((entry) => !isOperatingSystemJunk(entry));
30
+ return (shortest(files.map(prefixUpToWpContent)) ??
31
+ shortest(files.map(prefixBeforeThemesOrPlugins)) ??
32
+ (hint === 'content-at-root' || files.some(startsWithContentFolder) ? '' : null));
33
+ }
34
+ export function contentPath(entry, base) {
35
+ if (base === null || !entry.startsWith(base) || isOperatingSystemJunk(entry))
36
+ return null;
37
+ const relative = entry.slice(base.length);
38
+ const segments = relative.split('/');
39
+ if (!relative || relative.endsWith('/'))
40
+ return null;
41
+ if (EXCLUDED_CONTENT.has(segments[0]) || segments.includes('..'))
42
+ return null;
43
+ return relative;
44
+ }
45
+ export function isDumpName(name) {
46
+ return /\.sql(\.gz)?$/i.test(name);
47
+ }
48
+ export function findDumpEntries(entries, base) {
49
+ return entries.filter((entry) => isDumpName(entry) &&
50
+ !isOperatingSystemJunk(entry) &&
51
+ !isInsideContent(entry, base) &&
52
+ !/(^|\/)wp-(includes|admin)\//.test(entry));
53
+ }
54
+ export function dumpLikelihood(name, size) {
55
+ const lower = name.toLowerCase();
56
+ let score = 0;
57
+ if (/dup-database|database\.sql|(^|\/)mysql\//.test(lower))
58
+ score += 10;
59
+ if (/-db\d*\.gz$|backup.*db/.test(lower))
60
+ score += 5;
61
+ if (/wordpress|wp/.test(path.basename(lower)))
62
+ score += 2;
63
+ return score * 1e12 + size;
64
+ }
65
+ function isInsideContent(entry, base) {
66
+ if (base === null)
67
+ return false;
68
+ if (base === '')
69
+ return entry.includes('/') && startsWithContentFolder(entry);
70
+ return entry.startsWith(base);
71
+ }
72
+ function prefixUpToWpContent(entry) {
73
+ const segments = entry.split('/');
74
+ const index = segments.indexOf('wp-content');
75
+ return index >= 0 && index < segments.length - 1 ? `${segments.slice(0, index + 1).join('/')}/` : null;
76
+ }
77
+ function prefixBeforeThemesOrPlugins(entry) {
78
+ const segments = entry.split('/');
79
+ const index = segments.findIndex((segment, i) => i < segments.length - 1 && (segment === 'themes' || segment === 'plugins'));
80
+ if (index < 0)
81
+ return null;
82
+ return index === 0 ? '' : `${segments.slice(0, index).join('/')}/`;
83
+ }
84
+ function startsWithContentFolder(entry) {
85
+ return entry.includes('/') && WP_CONTENT_FOLDERS.has(entry.split('/')[0]);
86
+ }
87
+ function shortest(candidates) {
88
+ return candidates.reduce((best, candidate) => (candidate !== null && (best === null || candidate.length < best.length) ? candidate : best), null);
89
+ }
@@ -0,0 +1,16 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Transform } from 'node:stream';
4
+ import { pipeline } from 'node:stream/promises';
5
+ export function countBytes(onBytes) {
6
+ return new Transform({
7
+ transform(chunk, _encoding, callback) {
8
+ onBytes?.(chunk.length);
9
+ callback(null, chunk);
10
+ },
11
+ });
12
+ }
13
+ export async function writeEntry(source, target, onBytes) {
14
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
15
+ await pipeline(source, countBytes(onBytes), fs.createWriteStream(target));
16
+ }
@@ -0,0 +1,14 @@
1
+ import { TarReader } from './tar-reader.js';
2
+ import { WpressReader } from './wpress-reader.js';
3
+ import { ZipReader } from './zip-reader.js';
4
+ export { TarReader, WpressReader, ZipReader };
5
+ export function openArchive(file, kind) {
6
+ switch (kind) {
7
+ case 'zip':
8
+ return new ZipReader(file);
9
+ case 'tar':
10
+ return new TarReader(file);
11
+ case 'wpress':
12
+ return new WpressReader(file);
13
+ }
14
+ }
@@ -0,0 +1,42 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pipeline } from 'node:stream/promises';
4
+ import * as tar from 'tar';
5
+ import { normalizeEntry } from '../layout.js';
6
+ import { countBytes } from './archive-reader.js';
7
+ const FILE_TYPES = new Set(['File', 'OldFile']);
8
+ export class TarReader {
9
+ file;
10
+ constructor(file) {
11
+ this.file = file;
12
+ }
13
+ async list() {
14
+ const entries = [];
15
+ await tar.t({
16
+ file: this.file,
17
+ onReadEntry: (entry) => {
18
+ if (FILE_TYPES.has(entry.type))
19
+ entries.push({ name: normalizeEntry(entry.path), size: entry.size ?? 0 });
20
+ },
21
+ });
22
+ return entries;
23
+ }
24
+ async extract(destination, onBytes) {
25
+ const pendingWrites = [];
26
+ const parser = new tar.Parser({
27
+ onReadEntry: (entry) => {
28
+ const target = FILE_TYPES.has(entry.type) ? destination(normalizeEntry(entry.path)) : null;
29
+ if (!target) {
30
+ entry.resume();
31
+ return;
32
+ }
33
+ fs.mkdirSync(path.dirname(target), { recursive: true });
34
+ const output = fs.createWriteStream(target);
35
+ pendingWrites.push(new Promise((resolve, reject) => output.on('finish', resolve).on('error', reject)));
36
+ entry.pipe(countBytes(onBytes)).pipe(output);
37
+ },
38
+ });
39
+ await pipeline(fs.createReadStream(this.file), parser);
40
+ await Promise.all(pendingWrites);
41
+ }
42
+ }
@@ -0,0 +1,76 @@
1
+ import fs from 'node:fs';
2
+ import { Readable } from 'node:stream';
3
+ import { normalizeEntry } from '../layout.js';
4
+ import { writeEntry } from './archive-reader.js';
5
+ const HEADER_SIZE = 4377;
6
+ const NAME = { offset: 0, length: 255 };
7
+ const SIZE = { offset: 255, length: 14 };
8
+ const PREFIX = { offset: 281, length: 4096 };
9
+ export class WpressReader {
10
+ file;
11
+ constructor(file) {
12
+ this.file = file;
13
+ }
14
+ async list() {
15
+ const entries = [];
16
+ for await (const { name, size } of this.entries())
17
+ entries.push({ name, size });
18
+ return entries;
19
+ }
20
+ async extract(destination, onBytes) {
21
+ for await (const entry of this.entries()) {
22
+ const target = destination(entry.name);
23
+ if (target)
24
+ await writeEntry(this.contentStream(entry), target, onBytes);
25
+ }
26
+ }
27
+ async readText(entryName) {
28
+ for await (const entry of this.entries()) {
29
+ if (entry.name !== entryName)
30
+ continue;
31
+ const buffer = Buffer.alloc(entry.size);
32
+ const handle = await fs.promises.open(this.file, 'r');
33
+ try {
34
+ await handle.read(buffer, 0, entry.size, entry.offset);
35
+ }
36
+ finally {
37
+ await handle.close();
38
+ }
39
+ return buffer.toString('utf8');
40
+ }
41
+ return null;
42
+ }
43
+ contentStream(entry) {
44
+ if (entry.size === 0)
45
+ return Readable.from([]);
46
+ return fs.createReadStream(this.file, { start: entry.offset, end: entry.offset + entry.size - 1 });
47
+ }
48
+ async *entries() {
49
+ const handle = await fs.promises.open(this.file, 'r');
50
+ const header = Buffer.alloc(HEADER_SIZE);
51
+ let position = 0;
52
+ try {
53
+ while ((await handle.read(header, 0, HEADER_SIZE, position)).bytesRead === HEADER_SIZE) {
54
+ const name = readField(header, NAME);
55
+ if (!name)
56
+ break;
57
+ const size = Number.parseInt(readField(header, SIZE), 10);
58
+ if (!Number.isFinite(size) || size < 0)
59
+ throw new Error(`Corrupted .wpress archive near byte ${position}`);
60
+ const prefix = readField(header, PREFIX);
61
+ const fullName = prefix && prefix !== '.' ? `${prefix}/${name}` : name;
62
+ position += HEADER_SIZE;
63
+ yield { name: normalizeEntry(fullName), size, offset: position };
64
+ position += size;
65
+ }
66
+ }
67
+ finally {
68
+ await handle.close();
69
+ }
70
+ }
71
+ }
72
+ function readField(header, field) {
73
+ const bytes = header.subarray(field.offset, field.offset + field.length);
74
+ const end = bytes.indexOf(0);
75
+ return bytes.subarray(0, end === -1 ? field.length : end).toString('utf8');
76
+ }