@i2bskn/workers-deploy 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +106 -2
- package/bin/workers-deploy.js +36 -0
- package/package.json +27 -3
- package/src/deploy.js +320 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 i2bskn
|
|
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,107 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @i2bskn/workers-deploy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The deploy command for Cloudflare Workers with D1. It creates the missing D1 databases and R2 buckets in the location
|
|
4
|
+
given by `LOCATION_HINT`, applies the D1 migrations, then runs `wrangler deploy`.
|
|
5
|
+
|
|
6
|
+
It is meant to be the deploy command of Workers Builds and of the Deploy to Cloudflare button, so it also works on the
|
|
7
|
+
very first deploy, when the D1 database does not exist yet.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pnpm add -D @i2bskn/workers-deploy wrangler
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`wrangler` is a peer dependency. The version tested with this package is 4.154.0.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"scripts": {
|
|
22
|
+
"deploy": "workers-deploy"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pnpm run deploy
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Run it from the root of the project. The bindings are read from the Wrangler configuration with wrangler's
|
|
32
|
+
`unstable_readConfig` (top level only; `env.*` is not read), and `wrangler` is run from the `PATH`, which `pnpm run`
|
|
33
|
+
extends with `node_modules/.bin`.
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
Usage: workers-deploy [--require-existing-databases]
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Environment variables
|
|
40
|
+
|
|
41
|
+
| name | contents |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| `LOCATION_HINT` | Optional. `weur`, `eeur`, `apac`, `oc`, `wnam` or `enam` (case-insensitive). The missing D1 databases and R2 buckets are created there. Empty means not set. |
|
|
44
|
+
| `CUSTOM_DOMAINS` | Optional. Hostnames separated by commas or spaces, such as `app.example.com, www.example.com`. They are passed to `wrangler deploy --domains`. Duplicates are removed. Schemes, paths, ports, wildcards and single-label names are rejected. |
|
|
45
|
+
| `CUSTOM_DOMAIN` | The former name. Setting it to a non-empty value is an error: rename it to `CUSTOM_DOMAINS`. |
|
|
46
|
+
|
|
47
|
+
In Workers Builds, set them as build variables.
|
|
48
|
+
|
|
49
|
+
## Flags
|
|
50
|
+
|
|
51
|
+
| flag | effect |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `--require-existing-databases` | Stops with an error, before creating or deploying anything, when a D1 database of the configuration does not exist. Without it, `wrangler deploy` would create a new, empty database. A D1 binding without both `database_name` and `database_id` counts as missing. R2 buckets are still created as usual. |
|
|
54
|
+
| `--help`, `-h` | Prints the usage. |
|
|
55
|
+
|
|
56
|
+
Any other argument is an error.
|
|
57
|
+
|
|
58
|
+
## What it does
|
|
59
|
+
|
|
60
|
+
1. Validates the arguments, `LOCATION_HINT` and `CUSTOM_DOMAINS`. On an error, nothing is called.
|
|
61
|
+
2. Reads the Wrangler configuration.
|
|
62
|
+
3. Checks whether each D1 database in `d1_databases` exists, with `wrangler d1 info <binding>`. A binding without
|
|
63
|
+
`database_name` and `database_id` is treated as missing without the lookup.
|
|
64
|
+
4. With `--require-existing-databases`, stops with exit code 1 if any D1 database is missing.
|
|
65
|
+
5. When `LOCATION_HINT` is set:
|
|
66
|
+
- creates each missing D1 database that has a `database_name` and no `database_id` with
|
|
67
|
+
`wrangler d1 create <name> --location <location> --no-update-config`. The others are left to `wrangler deploy`.
|
|
68
|
+
- creates each missing R2 bucket in `r2_buckets` that has a `bucket_name` and no `jurisdiction` with
|
|
69
|
+
`wrangler r2 bucket create <name> --location <location> --no-update-config`, then checks where it ended up and
|
|
70
|
+
warns if the location differs. The location hint only applies to the first bucket ever created with a name.
|
|
71
|
+
6. Collects the D1 databases whose migrations directory (`migrations_dir`, default `./migrations`, relative to the
|
|
72
|
+
Wrangler configuration) exists. The others are skipped.
|
|
73
|
+
7. If all of those databases exist, applies the migrations (`wrangler d1 migrations apply <binding> --remote`) and then
|
|
74
|
+
deploys, so that new code never runs against missing tables. If any of them is missing, deploys first so that
|
|
75
|
+
`wrangler deploy` creates it, and then applies the migrations. In that case the new Worker runs without tables for a
|
|
76
|
+
few seconds, which is harmless on a first deploy.
|
|
77
|
+
8. Deploys with `wrangler deploy`, adding `--domains <hostname>` for each hostname of `CUSTOM_DOMAINS`.
|
|
78
|
+
|
|
79
|
+
Existing databases and buckets are never moved: their location cannot be changed.
|
|
80
|
+
|
|
81
|
+
## Exit codes
|
|
82
|
+
|
|
83
|
+
- `0` on success.
|
|
84
|
+
- `1` on an invalid argument, `LOCATION_HINT`, `CUSTOM_DOMAINS` or `CUSTOM_DOMAIN`, and on a missing database with
|
|
85
|
+
`--require-existing-databases`. The message goes to stderr.
|
|
86
|
+
- When `wrangler d1 info` or `wrangler r2 bucket info` fails for another reason (e.g. authentication), its captured
|
|
87
|
+
output is printed and its exit status is returned.
|
|
88
|
+
- When any other wrangler command fails, its exit status (1 if it has none) is returned and nothing after it runs.
|
|
89
|
+
A failed `d1 create` or `r2 bucket create` stops the deploy: `LOCATION_HINT` is an explicit request, so creating the
|
|
90
|
+
resource elsewhere would be worse.
|
|
91
|
+
|
|
92
|
+
## Notes
|
|
93
|
+
|
|
94
|
+
- **Custom Domains are replaced.** `wrangler deploy` replaces the Worker's Custom Domains with the ones in the
|
|
95
|
+
configuration's `routes` together with `--domains`. A Custom Domain added only in the dashboard is removed on the
|
|
96
|
+
next deploy, so list every Custom Domain either in `routes` or in `CUSTOM_DOMAINS`.
|
|
97
|
+
- **`routes` and `--domains` are combined.** The hostnames of `CUSTOM_DOMAINS` are added to the `routes` of the
|
|
98
|
+
configuration; they do not override them.
|
|
99
|
+
- **`CUSTOM_DOMAIN` is an error.** The former name is rejected rather than ignored, so that a stale build variable does
|
|
100
|
+
not silently stop passing the domains. Rename it to `CUSTOM_DOMAINS`.
|
|
101
|
+
- **workers.dev.** When neither `workers_dev` nor `routes` are in the Wrangler configuration, `wrangler deploy` without
|
|
102
|
+
`CUSTOM_DOMAINS` enables the workers.dev subdomain on every deploy, even after it was disabled in the dashboard.
|
|
103
|
+
- **Tested wrangler version.** This package was tested with wrangler 4.154.0.
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { main } from "../src/deploy.js";
|
|
5
|
+
|
|
6
|
+
// wrangler is resolved from the PATH, which `pnpm run` extends with node_modules/.bin.
|
|
7
|
+
function wrangler(args, { capture }) {
|
|
8
|
+
const result = spawnSync("wrangler", args, {
|
|
9
|
+
stdio: capture ? ["inherit", "pipe", "pipe"] : "inherit",
|
|
10
|
+
encoding: "utf8",
|
|
11
|
+
});
|
|
12
|
+
if (result.error) {
|
|
13
|
+
throw result.error;
|
|
14
|
+
}
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// exitCode instead of process.exit(), so that the output written to a pipe is flushed before Node exits. Nothing
|
|
19
|
+
// else keeps the event loop alive: every wrangler call is synchronous.
|
|
20
|
+
process.exitCode = await main({
|
|
21
|
+
argv: process.argv.slice(2),
|
|
22
|
+
env: process.env,
|
|
23
|
+
// Imported lazily, so that --help and argument errors do not load wrangler.
|
|
24
|
+
readConfig: async () => {
|
|
25
|
+
const { unstable_readConfig } = await import("wrangler");
|
|
26
|
+
return unstable_readConfig({});
|
|
27
|
+
},
|
|
28
|
+
wrangler,
|
|
29
|
+
exists: existsSync,
|
|
30
|
+
cwd: process.cwd(),
|
|
31
|
+
log: (message) => console.log(message),
|
|
32
|
+
warn: (message) => console.warn(message),
|
|
33
|
+
error: (message) => console.error(message),
|
|
34
|
+
writeStdout: (text) => process.stdout.write(text),
|
|
35
|
+
writeStderr: (text) => process.stderr.write(text),
|
|
36
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@i2bskn/workers-deploy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Deploy command for Cloudflare Workers with D1: creates resources in LOCATION_HINT, applies migrations, then deploys.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/i2bskn/workers-deploy.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=22"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"workers-deploy": "./bin/workers-deploy.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin",
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"wrangler": ">=4.154.0 <5"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"wrangler": "4.154.0"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "node --test"
|
|
29
|
+
}
|
|
6
30
|
}
|
package/src/deploy.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// `workers-deploy`: creates the missing D1 databases and R2 buckets in the requested location, applies the D1
|
|
2
|
+
// migrations, then deploys the Worker.
|
|
3
|
+
//
|
|
4
|
+
// The Deploy to Cloudflare button and Workers Builds run this command as the deploy command (`pnpm run deploy`), so it
|
|
5
|
+
// must also work on the very first deploy. `wrangler d1 migrations apply` only looks up an existing database, while
|
|
6
|
+
// `wrangler deploy` creates the missing D1 databases, KV namespaces, R2 buckets and queues. So when a database does not
|
|
7
|
+
// exist yet, this command deploys first and applies the migrations right after. In that case the new Worker runs
|
|
8
|
+
// without tables for a few seconds, which is harmless because nobody uses it yet. With --require-existing-databases,
|
|
9
|
+
// a missing database is an error instead, so that `wrangler deploy` never creates a new, empty one.
|
|
10
|
+
//
|
|
11
|
+
// On later deploys the migrations are applied before `wrangler deploy`, so that new code never runs against missing
|
|
12
|
+
// tables.
|
|
13
|
+
//
|
|
14
|
+
// `wrangler deploy` creates D1 databases and R2 buckets without a location, so they end up near the build
|
|
15
|
+
// environment. When the LOCATION_HINT environment variable is set (a Workers Builds build variable), this command
|
|
16
|
+
// creates the missing ones in that location first, and `wrangler deploy` then connects to them by name. The location
|
|
17
|
+
// of an existing database or bucket cannot be changed, so existing ones are left as they are.
|
|
18
|
+
//
|
|
19
|
+
// When the CUSTOM_DOMAINS environment variable is set (a Workers Builds build variable; hostnames separated by commas
|
|
20
|
+
// or spaces), the hostnames are passed to `wrangler deploy --domains`, which attaches them as Custom Domains. Wrangler
|
|
21
|
+
// replaces the Worker's Custom Domains with the ones in the configuration's routes and --domains together, so every
|
|
22
|
+
// Custom Domain of the Worker must be listed in one of them.
|
|
23
|
+
//
|
|
24
|
+
// The bindings are read from the Wrangler configuration (top level only, not `env.*`), so this command does not
|
|
25
|
+
// depend on the names used by a project.
|
|
26
|
+
//
|
|
27
|
+
// Every side effect is injected, so that this module can be imported and tested without wrangler.
|
|
28
|
+
import path from "node:path";
|
|
29
|
+
|
|
30
|
+
export const USAGE = "Usage: workers-deploy [--require-existing-databases]";
|
|
31
|
+
|
|
32
|
+
const HELP = `${USAGE}
|
|
33
|
+
|
|
34
|
+
Environment variables:
|
|
35
|
+
LOCATION_HINT Location of the D1 databases and R2 buckets to create: weur, eeur, apac, oc, wnam or enam.
|
|
36
|
+
CUSTOM_DOMAINS Hostnames passed to wrangler deploy --domains, separated by commas or spaces.
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
const REQUIRE_EXISTING_DATABASES = "--require-existing-databases";
|
|
40
|
+
const LOCATIONS = ["weur", "eeur", "apac", "oc", "wnam", "enam"];
|
|
41
|
+
const MISSING_DATABASE = /Couldn't find (a|an auto-provisioned) D1 DB/;
|
|
42
|
+
const MISSING_BUCKET = "[code: 10006]";
|
|
43
|
+
// The default of `migrations_dir` in wrangler.
|
|
44
|
+
const DEFAULT_MIGRATIONS_DIR = "./migrations";
|
|
45
|
+
// Hostnames only: Custom Domains take no scheme, path, port or wildcard.
|
|
46
|
+
const HOSTNAME = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
47
|
+
|
|
48
|
+
// Stops the deploy with an exit code. Thrown from deep inside and caught by `main`.
|
|
49
|
+
class Exit extends Error {
|
|
50
|
+
constructor(code) {
|
|
51
|
+
super(`exit ${code}`);
|
|
52
|
+
this.code = code;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function output(result) {
|
|
57
|
+
return `${result.stdout ?? ""}${result.stderr ?? ""}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parses the command line arguments.
|
|
62
|
+
* @param {string[]} argv
|
|
63
|
+
* @returns {{ help: true } | { help: false, requireExistingDatabases: boolean } | { error: string }}
|
|
64
|
+
*/
|
|
65
|
+
export function parseArgs(argv) {
|
|
66
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
67
|
+
return { help: true };
|
|
68
|
+
}
|
|
69
|
+
let requireExistingDatabases = false;
|
|
70
|
+
for (const arg of argv) {
|
|
71
|
+
if (arg === REQUIRE_EXISTING_DATABASES) {
|
|
72
|
+
requireExistingDatabases = true;
|
|
73
|
+
} else {
|
|
74
|
+
return { error: `Unknown argument "${arg}". ${USAGE}` };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { help: false, requireExistingDatabases };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Reads LOCATION_HINT.
|
|
82
|
+
* @returns {{ location: string | undefined } | { error: string }}
|
|
83
|
+
*/
|
|
84
|
+
export function parseLocation(value) {
|
|
85
|
+
const location = (value ?? "").trim().toLowerCase() || undefined;
|
|
86
|
+
if (location !== undefined && !LOCATIONS.includes(location)) {
|
|
87
|
+
return { error: `Invalid LOCATION_HINT "${value}": expected one of ${LOCATIONS.join(", ")}.` };
|
|
88
|
+
}
|
|
89
|
+
return { location };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Reads CUSTOM_DOMAINS, rejecting the former name CUSTOM_DOMAIN.
|
|
94
|
+
* @returns {{ domains: string[] } | { error: string }}
|
|
95
|
+
*/
|
|
96
|
+
export function parseDomains(env) {
|
|
97
|
+
if ((env.CUSTOM_DOMAIN ?? "").trim() !== "") {
|
|
98
|
+
return {
|
|
99
|
+
error:
|
|
100
|
+
"CUSTOM_DOMAIN is no longer read: rename the variable to CUSTOM_DOMAINS (hostnames separated by commas or spaces).",
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const domains = [];
|
|
104
|
+
for (const entry of (env.CUSTOM_DOMAINS ?? "").split(/[\s,]+/)) {
|
|
105
|
+
const domain = entry.trim().toLowerCase();
|
|
106
|
+
if (domain === "" || domains.includes(domain)) {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (!HOSTNAME.test(domain)) {
|
|
110
|
+
return {
|
|
111
|
+
error: `Invalid CUSTOM_DOMAINS entry "${domain}": expected hostnames such as app.example.com, separated by commas or spaces.`,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
domains.push(domain);
|
|
115
|
+
}
|
|
116
|
+
return { domains };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Runs the deploy and resolves to the exit code. Never calls `process.exit`.
|
|
121
|
+
* @param {object} deps
|
|
122
|
+
* @param {string[]} deps.argv
|
|
123
|
+
* @param {Record<string, string | undefined>} deps.env
|
|
124
|
+
* @param {() => any} deps.readConfig Returns (or resolves to) the Wrangler configuration.
|
|
125
|
+
* @param {(args: string[], options: { capture: boolean }) => { status: number | null, stdout?: string, stderr?: string }} deps.wrangler
|
|
126
|
+
* @param {(absPath: string) => boolean} deps.exists
|
|
127
|
+
* @param {string} deps.cwd
|
|
128
|
+
* @param {(message: string) => void} deps.log
|
|
129
|
+
* @param {(message: string) => void} deps.warn
|
|
130
|
+
* @param {(message: string) => void} deps.error
|
|
131
|
+
* @param {(text: string) => void} deps.writeStdout
|
|
132
|
+
* @param {(text: string) => void} deps.writeStderr
|
|
133
|
+
* @returns {Promise<number>}
|
|
134
|
+
*/
|
|
135
|
+
export async function main(deps) {
|
|
136
|
+
try {
|
|
137
|
+
return await deploy(deps);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
if (e instanceof Exit) {
|
|
140
|
+
return e.code;
|
|
141
|
+
}
|
|
142
|
+
throw e;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function deploy({ argv, env, readConfig, wrangler, exists, cwd, log, warn, error, writeStdout, writeStderr }) {
|
|
147
|
+
const args = parseArgs(argv);
|
|
148
|
+
if ("error" in args) {
|
|
149
|
+
error(args.error);
|
|
150
|
+
return 1;
|
|
151
|
+
}
|
|
152
|
+
if (args.help) {
|
|
153
|
+
writeStdout(HELP);
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const parsedLocation = parseLocation(env.LOCATION_HINT);
|
|
158
|
+
if ("error" in parsedLocation) {
|
|
159
|
+
error(parsedLocation.error);
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
const { location } = parsedLocation;
|
|
163
|
+
|
|
164
|
+
const parsedDomains = parseDomains(env);
|
|
165
|
+
if ("error" in parsedDomains) {
|
|
166
|
+
error(parsedDomains.error);
|
|
167
|
+
return 1;
|
|
168
|
+
}
|
|
169
|
+
const { domains } = parsedDomains;
|
|
170
|
+
|
|
171
|
+
// Runs wrangler with inherited stdio, and stops on failure.
|
|
172
|
+
function run(wranglerArgs) {
|
|
173
|
+
const { status } = wrangler(wranglerArgs, { capture: false });
|
|
174
|
+
if (status !== 0) {
|
|
175
|
+
throw new Exit(status ?? 1);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Prints the captured output of a failed wrangler command and stops with its status.
|
|
180
|
+
function fail(result) {
|
|
181
|
+
writeStdout(result.stdout ?? "");
|
|
182
|
+
writeStderr(result.stderr ?? "");
|
|
183
|
+
throw new Exit(result.status ?? 1);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const config = await readConfig();
|
|
187
|
+
const configDir = config.configPath ? path.dirname(config.configPath) : cwd;
|
|
188
|
+
const databases = config.d1_databases ?? [];
|
|
189
|
+
const buckets = config.r2_buckets ?? [];
|
|
190
|
+
|
|
191
|
+
// Whether each D1 database exists, by binding.
|
|
192
|
+
const databaseExists = new Map();
|
|
193
|
+
for (const db of databases) {
|
|
194
|
+
if (!db.database_name && !db.database_id) {
|
|
195
|
+
// `d1 info` fails with a different error for a binding without a name or an ID, and such a database
|
|
196
|
+
// can only be created by `wrangler deploy`.
|
|
197
|
+
databaseExists.set(db.binding, false);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
// `d1 info` fails with the same lookup error as `d1 migrations apply` but never prompts, so its output
|
|
201
|
+
// can be captured safely.
|
|
202
|
+
const info = wrangler(["d1", "info", db.binding], { capture: true });
|
|
203
|
+
if (info.status === 0) {
|
|
204
|
+
databaseExists.set(db.binding, true);
|
|
205
|
+
} else if (MISSING_DATABASE.test(output(info))) {
|
|
206
|
+
databaseExists.set(db.binding, false);
|
|
207
|
+
} else {
|
|
208
|
+
fail(info);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (args.requireExistingDatabases) {
|
|
213
|
+
const absent = databases.filter((db) => !databaseExists.get(db.binding));
|
|
214
|
+
if (absent.length > 0) {
|
|
215
|
+
for (const db of absent) {
|
|
216
|
+
error(
|
|
217
|
+
`The D1 database for "${db.binding}" does not exist. Nothing was deployed: with ${REQUIRE_EXISTING_DATABASES}, ` +
|
|
218
|
+
"a missing database is an error so that wrangler deploy does not create a new, empty one.",
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return 1;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (location === undefined) {
|
|
226
|
+
log("LOCATION_HINT is not set: wrangler deploy creates the missing resources near the build environment.");
|
|
227
|
+
} else {
|
|
228
|
+
// Failures stop the deploy: LOCATION_HINT is an explicit request, so creating the resources elsewhere
|
|
229
|
+
// without notice would be worse than failing.
|
|
230
|
+
// --no-update-config keeps wrangler from offering to add another binding to the configuration when run locally.
|
|
231
|
+
for (const db of databases) {
|
|
232
|
+
if (databaseExists.get(db.binding)) {
|
|
233
|
+
log(`The D1 database for "${db.binding}" already exists: leaving it as is.`);
|
|
234
|
+
} else if (!db.database_name) {
|
|
235
|
+
log(
|
|
236
|
+
`The D1 database for "${db.binding}" has no database_name, so its location cannot be specified: leaving it to wrangler deploy.`,
|
|
237
|
+
);
|
|
238
|
+
} else if (db.database_id) {
|
|
239
|
+
log(
|
|
240
|
+
`The D1 database for "${db.binding}" has a database_id, so it is not created here: leaving it to wrangler deploy.`,
|
|
241
|
+
);
|
|
242
|
+
} else {
|
|
243
|
+
log(`Creating D1 database "${db.database_name}" in ${location}.`);
|
|
244
|
+
run(["d1", "create", db.database_name, "--location", location, "--no-update-config"]);
|
|
245
|
+
databaseExists.set(db.binding, true);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
for (const bucket of buckets) {
|
|
250
|
+
if (!bucket.bucket_name || bucket.jurisdiction) {
|
|
251
|
+
const reason = bucket.jurisdiction ? "has a jurisdiction" : "has no bucket_name";
|
|
252
|
+
log(
|
|
253
|
+
`The R2 bucket for "${bucket.binding}" ${reason}, so its location cannot be specified: leaving it to wrangler deploy.`,
|
|
254
|
+
);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
const info = wrangler(["r2", "bucket", "info", bucket.bucket_name], { capture: true });
|
|
258
|
+
if (info.status === 0) {
|
|
259
|
+
log(`The R2 bucket "${bucket.bucket_name}" already exists: leaving it as is.`);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (!output(info).includes(MISSING_BUCKET)) {
|
|
263
|
+
fail(info);
|
|
264
|
+
}
|
|
265
|
+
log(`Creating R2 bucket "${bucket.bucket_name}" in ${location}.`);
|
|
266
|
+
run(["r2", "bucket", "create", bucket.bucket_name, "--location", location, "--no-update-config"]);
|
|
267
|
+
|
|
268
|
+
// The location hint only applies to the first bucket ever created with a name, so check where it ended up.
|
|
269
|
+
const created = wrangler(["r2", "bucket", "info", bucket.bucket_name], { capture: true });
|
|
270
|
+
const actual = created.status === 0 ? /^\s*location:\s*(\S+)/m.exec(output(created))?.[1] : undefined;
|
|
271
|
+
log(`The R2 bucket "${bucket.bucket_name}" is located in ${actual ?? "(unknown)"}.`);
|
|
272
|
+
if (actual?.toLowerCase() !== location) {
|
|
273
|
+
warn(
|
|
274
|
+
`Warning: the R2 bucket "${bucket.bucket_name}" was requested in ${location} but is located in ${actual ?? "(unknown)"}. ` +
|
|
275
|
+
"The location hint may have been ignored because a bucket with the same name existed before.",
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// `d1 migrations apply` fails when the migrations directory does not exist.
|
|
282
|
+
const migrated = databases.filter((db) => {
|
|
283
|
+
const dir = path.resolve(configDir, db.migrations_dir ?? DEFAULT_MIGRATIONS_DIR);
|
|
284
|
+
if (exists(dir)) {
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
log(`The D1 database for "${db.binding}" has no migrations directory: skipping its migrations.`);
|
|
288
|
+
return false;
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
function migrate() {
|
|
292
|
+
for (const db of migrated) {
|
|
293
|
+
log(`Applying the migrations of the D1 database for "${db.binding}".`);
|
|
294
|
+
run(["d1", "migrations", "apply", db.binding, "--remote"]);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function deployWorker() {
|
|
299
|
+
if (domains.length === 0) {
|
|
300
|
+
log("Deploying the Worker. CUSTOM_DOMAINS is not set: no Custom Domains are passed to wrangler deploy.");
|
|
301
|
+
run(["deploy"]);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
log(`Deploying the Worker with the Custom Domains ${domains.join(", ")}.`);
|
|
305
|
+
run(["deploy", ...domains.flatMap((domain) => ["--domains", domain])]);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const missing = migrated.filter((db) => !databaseExists.get(db.binding));
|
|
309
|
+
if (missing.length === 0) {
|
|
310
|
+
migrate();
|
|
311
|
+
deployWorker();
|
|
312
|
+
} else {
|
|
313
|
+
for (const db of missing) {
|
|
314
|
+
log(`The D1 database for "${db.binding}" does not exist yet: deploying first to create it.`);
|
|
315
|
+
}
|
|
316
|
+
deployWorker();
|
|
317
|
+
migrate();
|
|
318
|
+
}
|
|
319
|
+
return 0;
|
|
320
|
+
}
|