@elumixor/devkit 0.12.3 → 0.12.5

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 (43) hide show
  1. package/README.md +87 -0
  2. package/package.json +26 -2
  3. package/src/bin/devkit.ts +32 -1
  4. package/src/blob/index.ts +169 -0
  5. package/src/build-targets/web.ts +66 -20
  6. package/src/cloud/aws.ts +108 -0
  7. package/src/cloud/bootstrap.ts +114 -0
  8. package/src/cloud/cli.ts +56 -0
  9. package/src/cloud/commands/context.ts +42 -0
  10. package/src/cloud/commands/destroy.ts +43 -0
  11. package/src/cloud/commands/domains.ts +68 -0
  12. package/src/cloud/commands/env.ts +59 -0
  13. package/src/cloud/commands/init.ts +74 -0
  14. package/src/cloud/commands/logs.ts +35 -0
  15. package/src/cloud/commands/rollback.ts +54 -0
  16. package/src/cloud/commands/status.ts +50 -0
  17. package/src/cloud/edge/router.js +86 -0
  18. package/src/cloud/env.ts +93 -0
  19. package/src/cloud/github.ts +92 -0
  20. package/src/cloud/index.ts +9 -0
  21. package/src/cloud/log-events.ts +56 -0
  22. package/src/cloud/mcp.ts +150 -0
  23. package/src/cloud/names.ts +98 -0
  24. package/src/cloud/nitro-build.ts +42 -0
  25. package/src/cloud/overview.ts +105 -0
  26. package/src/cloud/project.ts +146 -0
  27. package/src/cloud/reconcile/acm.ts +97 -0
  28. package/src/cloud/reconcile/cloudflare.ts +103 -0
  29. package/src/cloud/reconcile/edge.ts +108 -0
  30. package/src/cloud/reconcile/guardrails.ts +112 -0
  31. package/src/cloud/reconcile/iam.ts +328 -0
  32. package/src/cloud/reconcile/kvs.ts +98 -0
  33. package/src/cloud/reconcile/lambda.ts +305 -0
  34. package/src/cloud/reconcile/logs.ts +24 -0
  35. package/src/cloud/reconcile/platform.ts +281 -0
  36. package/src/cloud/reconcile/s3.ts +155 -0
  37. package/src/cloud/reconcile/scheduler.ts +100 -0
  38. package/src/cloud/records.ts +129 -0
  39. package/src/cloud/release.ts +268 -0
  40. package/src/cloud/runtime-wrapper.ts +84 -0
  41. package/src/deploy-targets/aws.ts +26 -0
  42. package/src/run-target.ts +2 -0
  43. package/src/runtime/index.ts +50 -0
@@ -0,0 +1,114 @@
1
+ import { $ } from "bun";
2
+ import { accountId, CloudError, log } from "./aws.ts";
3
+ import { ensureSecret, readParameter, writeParameter } from "./env.ts";
4
+ import { PLATFORM_ALIASES, platform, STAGE_BRANCHES } from "./names.ts";
5
+ import { ensureCertificate } from "./reconcile/acm.ts";
6
+ import { ensureRecord } from "./reconcile/cloudflare.ts";
7
+ import { findDistribution, reconcileAliases, waitDeployed } from "./reconcile/edge.ts";
8
+ import { ensureAnomalyAlerts, ensureBudgets } from "./reconcile/guardrails.ts";
9
+ import { ensureDeployRole, ensureLocalDeployProfile, ensureSchedulerRole } from "./reconcile/iam.ts";
10
+ import { putEdgeSecret } from "./reconcile/kvs.ts";
11
+ import {
12
+ allowDistribution,
13
+ createDistribution,
14
+ ensureBucket,
15
+ ensureCachePolicy,
16
+ ensureKeyValueStore,
17
+ ensureOriginAccessControl,
18
+ ensureRouterFunction,
19
+ } from "./reconcile/platform.ts";
20
+ import { buckets } from "./reconcile/s3.ts";
21
+ import { ensureScheduleGroup } from "./reconcile/scheduler.ts";
22
+
23
+ export interface BootstrapOptions {
24
+ /** Where budget and anomaly alerts go (default: `git config user.email`). */
25
+ email?: string;
26
+ }
27
+
28
+ /**
29
+ * Everything the account needs once, in the order each piece needs the last: buckets, the edge
30
+ * (OAC, cache policy, route store, router, certificate, distribution), DNS, the roles and the
31
+ * cost guardrails. Every step reads first, so running it again changes nothing that already matches.
32
+ */
33
+ export async function bootstrap(options: BootstrapOptions = {}) {
34
+ const account = await accountId();
35
+ const email = options.email ?? (await $`git config user.email`.quiet().nothrow().text()).trim();
36
+ if (!email) throw new CloudError("No email for alerts: pass --email or set git config user.email");
37
+ log(`Bootstrapping Devkit Cloud in account ${account}\n`);
38
+
39
+ log("secrets");
40
+ const edgeSecret = await ensureSecret(platform.edgeSecretParameter);
41
+ await storeCloudflareToken();
42
+
43
+ log("\nbuckets");
44
+ const { sites, blobs } = await buckets();
45
+ await Promise.all([ensureBucket(sites), ensureBucket(blobs)]);
46
+
47
+ log("\nedge");
48
+ const [oacId, cachePolicyId, kvsArn] = await Promise.all([
49
+ ensureOriginAccessControl(),
50
+ ensureCachePolicy(),
51
+ ensureKeyValueStore(),
52
+ ]);
53
+ await putEdgeSecret(edgeSecret);
54
+ const routerArn = await ensureRouterFunction(kvsArn);
55
+ const certificateArn = await ensureCertificate(PLATFORM_ALIASES);
56
+ const existing = await findDistribution();
57
+ const distribution = existing
58
+ ? await reconcileAliases([])
59
+ : await createDistribution({
60
+ sitesBucket: sites,
61
+ blobsBucket: blobs,
62
+ oacId,
63
+ cachePolicyId,
64
+ routerArn,
65
+ certificateArn,
66
+ });
67
+ await Promise.all([
68
+ allowDistribution(sites, distribution.arn, "*"),
69
+ allowDistribution(blobs, distribution.arn, "*/*/public/*"),
70
+ ]);
71
+
72
+ log("\ndns");
73
+ for (const name of PLATFORM_ALIASES)
74
+ log(` ${name} → ${distribution.domainName} ${await ensureRecord(name, "CNAME", distribution.domainName)}`);
75
+
76
+ log("\naccess");
77
+ await ensureScheduleGroup();
78
+ const scheduler = await ensureSchedulerRole();
79
+ const deploy = await ensureDeployRole(Object.values(STAGE_BRANCHES));
80
+ const local = await ensureLocalDeployProfile();
81
+ log(` role ${platform.schedulerRole} ${scheduler.created ? "created" : "ok"}`);
82
+ log(
83
+ ` role ${platform.deployRole} ${deploy.created ? "created" : "ok"} (GitHub OIDC, elumixor/* on ${Object.values(STAGE_BRANCHES).join(", ")})`,
84
+ );
85
+ log(` profile ${platform.localProfile} ${local.profile} (user ${platform.localDeployUser})`);
86
+
87
+ log("\nguardrails");
88
+ await ensureBudgets(email);
89
+ await ensureAnomalyAlerts(email);
90
+
91
+ if (!existing) {
92
+ log("\nwaiting for the distribution to deploy (10–15 minutes the first time)");
93
+ await waitDeployed(distribution.id);
94
+ }
95
+
96
+ log(
97
+ `\nReady. Distribution ${distribution.id} at ${distribution.domainName}; deploy role arn:aws:iam::${account}:role/${platform.deployRole}`,
98
+ );
99
+ }
100
+
101
+ /** The Cloudflare token comes from the environment on the first run and lives in SSM after that. */
102
+ async function storeCloudflareToken() {
103
+ const fromEnv = process.env.CLOUDFLARE_API_TOKEN;
104
+ const stored = await readParameter(platform.cloudflareTokenParameter);
105
+ if (fromEnv && fromEnv !== stored) {
106
+ await writeParameter(platform.cloudflareTokenParameter, fromEnv);
107
+ log(` stored Cloudflare token at ${platform.cloudflareTokenParameter}`);
108
+ return;
109
+ }
110
+ if (!stored)
111
+ throw new CloudError(
112
+ `No Cloudflare token: run with CLOUDFLARE_API_TOKEN=<token with DNS edit on your zones> once; it is kept at ${platform.cloudflareTokenParameter}`,
113
+ );
114
+ }
@@ -0,0 +1,56 @@
1
+ import { bootstrap } from "./bootstrap.ts";
2
+ import { destroy } from "./commands/destroy.ts";
3
+ import { domains } from "./commands/domains.ts";
4
+ import { env } from "./commands/env.ts";
5
+ import { init } from "./commands/init.ts";
6
+ import { logs } from "./commands/logs.ts";
7
+ import { rollback } from "./commands/rollback.ts";
8
+ import { deploys, status } from "./commands/status.ts";
9
+
10
+ export interface CloudFlags {
11
+ stage?: string;
12
+ since?: string;
13
+ grep?: string;
14
+ follow?: boolean;
15
+ to?: string;
16
+ email?: string;
17
+ }
18
+
19
+ export const CLOUD_USAGE = `usage: devkit cloud bootstrap [--email x] once per account: buckets, edge, roles, budgets
20
+ devkit cloud init once per repo: aws deploy target + GitHub workflow
21
+ devkit cloud status [project] live deploy per stage, calls and errors for 24 h
22
+ devkit cloud deploys <project> [--stage s]
23
+ devkit cloud logs [project] [--stage s] [--since 1h] [--grep x] [--follow]
24
+ devkit cloud rollback <project> [--stage s] [--to <deployId>]
25
+ devkit cloud env ls|pull|push|set|rm [--stage s]
26
+ devkit cloud domains ls|add|rm <project> [host] [--stage s]
27
+ devkit cloud destroy <project> --stage s`;
28
+
29
+ /** `devkit cloud <command> ...` */
30
+ export function runCloud(args: readonly string[], flags: CloudFlags) {
31
+ const [command, ...rest] = args;
32
+ switch (command) {
33
+ case "bootstrap":
34
+ return bootstrap({ email: flags.email });
35
+ case "init":
36
+ return init();
37
+ case "status":
38
+ return status(rest[0]);
39
+ case "deploys":
40
+ if (!rest[0]) throw new Error("usage: devkit cloud deploys <project> [--stage s]");
41
+ return deploys(rest[0], flags.stage);
42
+ case "logs":
43
+ return logs(rest[0], { stage: flags.stage, since: flags.since, grep: flags.grep, follow: flags.follow });
44
+ case "rollback":
45
+ if (!rest[0]) throw new Error("usage: devkit cloud rollback <project> [--stage s] [--to <deployId>]");
46
+ return rollback(rest[0], flags.stage, flags.to);
47
+ case "env":
48
+ return env(rest[0], rest.slice(1), flags.stage);
49
+ case "domains":
50
+ return domains(rest[0], rest[1], rest[2], flags.stage);
51
+ case "destroy":
52
+ return destroy(rest[0], flags.stage);
53
+ default:
54
+ throw new Error(`Unknown cloud command "${command ?? ""}"\n\n${CLOUD_USAGE}`);
55
+ }
56
+ }
@@ -0,0 +1,42 @@
1
+ import { loadConfig } from "../../config.ts";
2
+ import { CloudError } from "../aws.ts";
3
+ import { PRODUCTION, STAGE_BRANCHES } from "../names.ts";
4
+ import { type AwsTargetOptions, projectName, resolveStage, Target } from "../project.ts";
5
+ import { readRegistry } from "../records.ts";
6
+
7
+ /** The `aws` deploy step of the repo we are in, or an error that says what to add. */
8
+ export function awsOptions(root = process.cwd()): AwsTargetOptions {
9
+ const step = loadConfig(root).deploy.find((entry) => entry.type === "aws");
10
+ if (!step)
11
+ throw new CloudError('No "aws" deploy target in package.json — run `devkit cloud init` or pass the project name');
12
+ return (step.options ?? { apiPrefixes: ["api"] }) as AwsTargetOptions;
13
+ }
14
+
15
+ /**
16
+ * A target for a command run inside a project repo: the config gives the options, the branch the
17
+ * stage. Commands that name a project (`status`, `rollback`) work from anywhere instead.
18
+ */
19
+ export async function targetFromRepo(stageFlag: string | undefined, root = process.cwd()) {
20
+ const options = awsOptions(root);
21
+ const stage = await resolveStage(stageFlag, options.stages ?? STAGE_BRANCHES, root);
22
+ return new Target(await projectName(options, root), stage, options);
23
+ }
24
+
25
+ /** A target by name, with whatever the last deploy recorded about it. */
26
+ export async function targetByName(project: string, stageFlag: string | undefined) {
27
+ const registry = await readRegistry(project);
28
+ if (!registry) throw new CloudError(`No project "${project}" has been deployed`);
29
+ const stage = stageFlag ?? PRODUCTION;
30
+ const recorded = registry.stages[stage];
31
+ if (!recorded) {
32
+ const known = Object.keys(registry.stages).join(", ") || "none";
33
+ throw new CloudError(`${project} has no stage "${stage}" (deployed: ${known})`);
34
+ }
35
+ return { target: new Target(project, stage), recorded };
36
+ }
37
+
38
+ /** Which target a command means: the project named, else the repo we're in. */
39
+ export async function resolveTarget(project: string | undefined, stageFlag: string | undefined) {
40
+ if (project) return (await targetByName(project, stageFlag)).target;
41
+ return targetFromRepo(stageFlag);
42
+ }
@@ -0,0 +1,43 @@
1
+ import { CloudError, log } from "../aws.ts";
2
+ import { deleteStageEnv } from "../env.ts";
3
+ import { stage as names } from "../names.ts";
4
+ import { deleteRecord } from "../reconcile/cloudflare.ts";
5
+ import { needsDns, reconcileAliases } from "../reconcile/edge.ts";
6
+ import { deleteRole } from "../reconcile/iam.ts";
7
+ import { updateKeys } from "../reconcile/kvs.ts";
8
+ import { deleteFunction } from "../reconcile/lambda.ts";
9
+ import { deleteLogGroup } from "../reconcile/logs.ts";
10
+ import { buckets, deletePrefix } from "../reconcile/s3.ts";
11
+ import { deleteStageSchedules } from "../reconcile/scheduler.ts";
12
+ import { removeRegistryStage } from "../records.ts";
13
+ import { targetByName } from "./context.ts";
14
+
15
+ /** Removes one stage entirely: routes first so nothing serves, then compute, files, env and records. Blobs stay. */
16
+ export async function destroy(project: string | undefined, stageFlag: string | undefined) {
17
+ if (!project || !stageFlag) throw new CloudError("usage: devkit cloud destroy <project> --stage <stage>");
18
+ const { target, recorded } = await targetByName(project, stageFlag);
19
+ log(`Destroying ${project} ${target.stage}`);
20
+
21
+ await updateKeys({}, recorded.hostnames);
22
+ log(" routes removed");
23
+ const custom = recorded.hostnames.filter(needsDns);
24
+ if (custom.length) {
25
+ await reconcileAliases([], custom);
26
+ for (const host of custom) await deleteRecord(host, "CNAME");
27
+ log(` aliases and DNS removed: ${custom.join(", ")}`);
28
+ }
29
+
30
+ await deleteStageSchedules(target);
31
+ await deleteFunction(target.functionName);
32
+ await deleteRole(target.roleName);
33
+ await deleteLogGroup(target.logGroup);
34
+ log(" function, schedules, role and logs removed");
35
+
36
+ const { sites } = await buckets();
37
+ const files = await deletePrefix(sites, names.stagePrefix(target.project, target.stage));
38
+ await deletePrefix(sites, `_dk/${target.project}/${target.stage}/`);
39
+ await deleteStageEnv(target);
40
+ await removeRegistryStage(target);
41
+ log(` ${files} files, deploy records and env removed`);
42
+ log(`Done. Blobs under ${names.blobPrefix(target.project, target.stage)} were left in place.`);
43
+ }
@@ -0,0 +1,68 @@
1
+ import { bold, dim } from "../../ansi.ts";
2
+ import { CloudError, log } from "../aws.ts";
3
+ import { deleteRecord } from "../reconcile/cloudflare.ts";
4
+ import { needsDns, reconcileAliases } from "../reconcile/edge.ts";
5
+ import { deleteRoute, getRoute, putRoutes } from "../reconcile/kvs.ts";
6
+ import { readRegistry, updateRegistryHostname } from "../records.ts";
7
+ import { targetByName } from "./context.ts";
8
+
9
+ const USAGE = "usage: devkit cloud domains ls|add|rm <project> [host] [--stage s]";
10
+
11
+ /** Every hostname each stage of a project answers on, the primary one first. */
12
+ export async function listDomains(project: string) {
13
+ const registry = await readRegistry(project);
14
+ if (!registry) throw new CloudError(`No project "${project}" has been deployed`);
15
+ return Object.fromEntries(Object.entries(registry.stages).map(([stage, entry]) => [stage, entry.hostnames]));
16
+ }
17
+
18
+ /**
19
+ * Points one more hostname at a stage without a redeploy: certificate, alias, DNS and route. Later
20
+ * deploys keep it. A hostname in a Cloudflare zone the platform token can edit needs nothing else.
21
+ */
22
+ export async function addDomain(project: string, host: string, stageFlag?: string) {
23
+ const { target, recorded } = await targetByName(project, stageFlag);
24
+ const route = await getRoute(recorded.hostnames[0] as string);
25
+ if (!route) throw new CloudError(`No route record for ${recorded.hostnames[0]} — deploy once first`);
26
+ await reconcileAliases([host]);
27
+ await putRoutes({ [host]: route });
28
+ await updateRegistryHostname(target, host, true);
29
+ return `https://${host} now serves ${project} ${target.stage} (new hostnames reach every edge within ~1 min)`;
30
+ }
31
+
32
+ /** Takes a hostname off a stage: route, alias and DNS record. The default hostname stays. */
33
+ export async function removeDomain(project: string, host: string, stageFlag?: string) {
34
+ const { target } = await targetByName(project, stageFlag);
35
+ if (host === target.defaultHost) throw new CloudError(`${host} is the stage's default hostname and stays`);
36
+ await deleteRoute(host);
37
+ if (needsDns(host)) {
38
+ await reconcileAliases([], [host]);
39
+ await deleteRecord(host, "CNAME");
40
+ }
41
+ await updateRegistryHostname(target, host, false);
42
+ return `${host} removed from ${project} ${target.stage} (a host listed in the config's \`domains\` returns on the next deploy)`;
43
+ }
44
+
45
+ export async function domains(
46
+ action: string | undefined,
47
+ project: string | undefined,
48
+ host: string | undefined,
49
+ stageFlag: string | undefined,
50
+ ) {
51
+ if (!project) throw new CloudError(USAGE);
52
+ switch (action) {
53
+ case "ls": {
54
+ log(bold(project));
55
+ for (const [stage, hostnames] of Object.entries(await listDomains(project)))
56
+ log(` ${stage.padEnd(12)} ${hostnames.map((name, i) => (i ? dim(name) : name)).join(" ")}`);
57
+ return;
58
+ }
59
+ case "add":
60
+ if (!host) throw new CloudError(USAGE);
61
+ return log(await addDomain(project, host, stageFlag));
62
+ case "rm":
63
+ if (!host) throw new CloudError(USAGE);
64
+ return log(await removeDomain(project, host, stageFlag));
65
+ default:
66
+ throw new CloudError(USAGE);
67
+ }
68
+ }
@@ -0,0 +1,59 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { bold, dim } from "../../ansi.ts";
4
+ import { CloudError, log } from "../aws.ts";
5
+ import { deleteStageVariable, formatDotenv, parseDotenv, readStageEnv, writeStageEnv } from "../env.ts";
6
+ import { targetFromRepo } from "./context.ts";
7
+
8
+ const DOTENV = ".env";
9
+
10
+ /** `devkit cloud env ls|pull|push|set|rm`: the stage's variables in SSM, as the root `.env` sees them. */
11
+ export async function env(action: string | undefined, args: readonly string[], stageFlag: string | undefined) {
12
+ const target = await targetFromRepo(stageFlag);
13
+ const label = `${target.project} ${target.stage}`;
14
+
15
+ switch (action) {
16
+ case "ls": {
17
+ const current = await readStageEnv(target);
18
+ const keys = Object.keys(current).sort();
19
+ if (!keys.length) return log(`No variables for ${label}`);
20
+ log(bold(label));
21
+ for (const key of keys) log(` ${key.padEnd(32)} ${dim(mask(current[key] as string))}`);
22
+ return;
23
+ }
24
+ case "pull": {
25
+ const file = resolve(args[0] ?? DOTENV);
26
+ await Bun.write(file, formatDotenv(await readStageEnv(target)));
27
+ return log(`Wrote ${label} to ${args[0] ?? DOTENV}`);
28
+ }
29
+ case "push": {
30
+ const file = resolve(args[0] ?? DOTENV);
31
+ if (!existsSync(file)) throw new CloudError(`No ${args[0] ?? DOTENV} to push`);
32
+ const values = parseDotenv(await Bun.file(file).text());
33
+ await writeStageEnv(target, values);
34
+ return log(`Pushed ${Object.keys(values).length} variables to ${label}`);
35
+ }
36
+ case "set": {
37
+ const pairs = args.map((arg) => {
38
+ const at = arg.indexOf("=");
39
+ if (at <= 0) throw new CloudError(`"${arg}" is not KEY=value`);
40
+ return [arg.slice(0, at), arg.slice(at + 1)] as const;
41
+ });
42
+ if (!pairs.length) throw new CloudError("usage: devkit cloud env set KEY=value [KEY=value...]");
43
+ await writeStageEnv(target, Object.fromEntries(pairs));
44
+ return log(`Set ${pairs.map(([key]) => key).join(", ")} on ${label}`);
45
+ }
46
+ case "rm": {
47
+ if (!args.length) throw new CloudError("usage: devkit cloud env rm KEY [KEY...]");
48
+ for (const key of args) await deleteStageVariable(target, key);
49
+ return log(`Removed ${args.join(", ")} from ${label}`);
50
+ }
51
+ default:
52
+ throw new CloudError("usage: devkit cloud env ls|pull [file]|push [file]|set KEY=value...|rm KEY... [--stage s]");
53
+ }
54
+ }
55
+
56
+ function mask(value: string) {
57
+ if (value.length <= 8) return "•".repeat(value.length);
58
+ return `${value.slice(0, 3)}${"•".repeat(Math.min(12, value.length - 5))}${value.slice(-2)}`;
59
+ }
@@ -0,0 +1,74 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { accountId, log } from "../aws.ts";
5
+ import { platform, REGION, STAGE_BRANCHES } from "../names.ts";
6
+
7
+ const WORKFLOW_PATH = ".github/workflows/deploy.yml";
8
+
9
+ /** Once per repo: the `aws` deploy target in package.json and the workflow that runs it. */
10
+ export async function init(root = process.cwd()) {
11
+ const account = await accountId();
12
+ const workflow = resolve(root, WORKFLOW_PATH);
13
+ await mkdir(resolve(root, ".github/workflows"), { recursive: true });
14
+ await Bun.write(workflow, deployWorkflow(account));
15
+ log(`Wrote ${WORKFLOW_PATH}`);
16
+
17
+ const pkgPath = resolve(root, "package.json");
18
+ if (!existsSync(pkgPath)) return log("No package.json here — add the aws deploy target by hand");
19
+ const text = await Bun.file(pkgPath).text();
20
+ const pkg = JSON.parse(text) as {
21
+ devkit?: { deploy?: Record<string, { type?: string; options?: Record<string, unknown> }> };
22
+ };
23
+ const deploy = pkg.devkit?.deploy ?? {};
24
+ const vercel = Object.entries(deploy).find(([, step]) => step.type === "vercel");
25
+ const aws = Object.entries(deploy).find(([, step]) => step.type === "aws");
26
+ if (aws) return log(`package.json already deploys "${aws[0]}" to aws`);
27
+
28
+ const name = vercel?.[0] ?? "web";
29
+ const buildOptions =
30
+ (pkg as { devkit?: { build?: Record<string, { options?: Record<string, unknown> }> } }).devkit?.build?.[name]
31
+ ?.options ?? {};
32
+ const options = { ...buildOptions, ...(vercel?.[1].options ?? {}), apiPrefixes: buildOptions.apiPrefixes ?? ["api"] };
33
+ const next = {
34
+ ...pkg,
35
+ devkit: { ...pkg.devkit, deploy: { ...deploy, [name]: { ...(deploy[name] ?? {}), type: "aws", options } } },
36
+ };
37
+ await Bun.write(pkgPath, `${JSON.stringify(next, null, 2)}\n`);
38
+ log(`package.json: devkit.deploy.${name} now deploys to aws${vercel ? " (was vercel)" : ""}`);
39
+ }
40
+
41
+ function deployWorkflow(account: string) {
42
+ const branches = Object.values(STAGE_BRANCHES);
43
+ return `name: deploy
44
+
45
+ on:
46
+ push:
47
+ branches: [${branches.join(", ")}]
48
+
49
+ # One deploy per stage at a time; a second push waits rather than racing the first.
50
+ concurrency:
51
+ group: deploy-\${{ github.ref_name }}
52
+ cancel-in-progress: false
53
+
54
+ permissions:
55
+ id-token: write
56
+ contents: read
57
+ deployments: write
58
+
59
+ jobs:
60
+ deploy:
61
+ runs-on: ubuntu-latest
62
+ steps:
63
+ - uses: actions/checkout@v4
64
+ - uses: oven-sh/setup-bun@v2
65
+ - uses: aws-actions/configure-aws-credentials@v4
66
+ with:
67
+ role-to-assume: arn:aws:iam::${account}:role/${platform.deployRole}
68
+ aws-region: ${REGION}
69
+ - run: bun install --frozen-lockfile
70
+ - run: bunx devkit deploy
71
+ env:
72
+ GITHUB_TOKEN: \${{ github.token }}
73
+ `;
74
+ }
@@ -0,0 +1,35 @@
1
+ import { dim } from "../../ansi.ts";
2
+ import { fetchLogEvents, parseDuration } from "../log-events.ts";
3
+ import { resolveTarget } from "./context.ts";
4
+
5
+ export interface LogsOptions {
6
+ stage?: string;
7
+ /** How far back to start: `30m`, `2h`, `1d` (default `1h`). */
8
+ since?: string;
9
+ grep?: string;
10
+ follow?: boolean;
11
+ }
12
+
13
+ const FOLLOW_EVERY_MS = 2000;
14
+
15
+ /** Function logs, oldest first; `--follow` keeps polling for new lines. */
16
+ export async function logs(project: string | undefined, options: LogsOptions) {
17
+ const target = await resolveTarget(project, options.stage);
18
+ let startTime = Date.now() - parseDuration(options.since ?? "1h");
19
+ const seen = new Set<string>();
20
+
21
+ const page = async () => {
22
+ for (const event of await fetchLogEvents(target, { startTime, grep: options.grep })) {
23
+ if (seen.has(event.id)) continue;
24
+ seen.add(event.id);
25
+ startTime = Math.max(startTime, event.timestamp);
26
+ console.log(`${dim(new Date(event.timestamp).toISOString())} ${event.message}`);
27
+ }
28
+ };
29
+
30
+ await page();
31
+ while (options.follow) {
32
+ await Bun.sleep(FOLLOW_EVERY_MS);
33
+ await page();
34
+ }
35
+ }
@@ -0,0 +1,54 @@
1
+ import { CloudError, log } from "../aws.ts";
2
+ import { getRoute, putRoutes } from "../reconcile/kvs.ts";
3
+ import { pointLiveAlias } from "../reconcile/lambda.ts";
4
+ import { listDeploys, readCurrent, readDeploy, writeCurrent, writeDeploy } from "../records.ts";
5
+ import { targetByName } from "./context.ts";
6
+
7
+ /**
8
+ * Moves the alias and the route records to an earlier deploy. No build, no upload: the files and
9
+ * the function version are still there, so this is two writes and takes a few seconds.
10
+ */
11
+ export async function rollback(project: string, stageFlag: string | undefined, toDeployId: string | undefined) {
12
+ const { target, recorded } = await targetByName(project, stageFlag);
13
+ const current = await readCurrent(target);
14
+ if (!current) throw new CloudError(`${project} ${target.stage} has never been deployed`);
15
+
16
+ const to = toDeployId
17
+ ? await readDeploy(target, toDeployId)
18
+ : (await listDeploys(target, 50)).find(
19
+ (deploy) => deploy.id !== current.deployId && deploy.version && deploy.status !== "failed",
20
+ );
21
+ if (!to)
22
+ throw new CloudError(
23
+ toDeployId ? `No deploy ${toDeployId} for ${project} ${target.stage}` : "No earlier deploy to roll back to",
24
+ );
25
+ if (!to.version || to.status === "failed")
26
+ throw new CloudError(`Deploy ${to.id} never went live (${to.status}); pick another with \`devkit cloud deploys\``);
27
+
28
+ const started = Date.now();
29
+ log(`Rolling ${project} ${target.stage} back from ${current.deployId} to ${to.id} (${to.message})`);
30
+
31
+ await pointLiveAlias(target.functionName, to.version);
32
+ const route = await getRoute(recorded.hostnames[0] as string);
33
+ if (!route) throw new CloudError(`No route record for ${recorded.hostnames[0]} — deploy once before rolling back`);
34
+ const moved = { ...route, d: `${target.stage}/${to.id}` };
35
+ await putRoutes(Object.fromEntries(recorded.hostnames.map((host) => [host, moved])));
36
+
37
+ const now = new Date().toISOString();
38
+ const was = await readDeploy(target, current.deployId);
39
+ await Promise.all([
40
+ writeCurrent(target, { deployId: to.id, version: to.version, since: now }),
41
+ writeDeploy({ ...to, status: "live" }),
42
+ was ? writeDeploy({ ...was, status: "rolled-back" }) : Promise.resolve(),
43
+ ]);
44
+ const seconds = Math.round((Date.now() - started) / 1000);
45
+ log(`Live again at https://${recorded.hostnames[0]} (${seconds}s)`);
46
+ return {
47
+ project,
48
+ stage: target.stage,
49
+ from: current.deployId,
50
+ to: to.id,
51
+ url: `https://${recorded.hostnames[0]}`,
52
+ seconds,
53
+ };
54
+ }
@@ -0,0 +1,50 @@
1
+ import { bold, dim, paint } from "../../ansi.ts";
2
+ import { log } from "../aws.ts";
3
+ import { age, overview } from "../overview.ts";
4
+ import { type DeployRecord, listDeploys } from "../records.ts";
5
+ import { targetByName } from "./context.ts";
6
+
7
+ /** Live deploy per stage with its age and commit, and the last day's calls, errors and p95 duration. */
8
+ export async function status(project: string | undefined) {
9
+ const projects = await overview(project);
10
+ if (!projects.length) return log(project ? `No project "${project}" has been deployed` : "Nothing deployed yet");
11
+
12
+ for (const { project: name, stages } of projects) {
13
+ log(bold(name));
14
+ for (const stage of stages) {
15
+ const health = stage.metrics.errors
16
+ ? paint(`${stage.metrics.errors} errors`, "red")
17
+ : paint("no errors", "green");
18
+ const current = stage.current
19
+ ? `${stage.current.deployId} ${dim(age(stage.current.since))}`
20
+ : dim("not deployed");
21
+ const live = stage.live ? dim(`${stage.live.commit.slice(0, 7)} ${stage.live.message}`) : "";
22
+ log(` ${stage.stage.padEnd(12)} ${current} ${live}`);
23
+ log(
24
+ ` ${"".padEnd(12)} https://${stage.hostnames[0]} ${stage.metrics.calls} calls · ${health} · p95 ${stage.metrics.p95ms} ms (24 h)`,
25
+ );
26
+ }
27
+ log("");
28
+ }
29
+ }
30
+
31
+ /** The last deploys of one stage, newest first. */
32
+ export async function deploys(project: string, stageFlag: string | undefined) {
33
+ const { target } = await targetByName(project, stageFlag);
34
+ const records = await listDeploys(target, 10);
35
+ if (!records.length) return log(`No deploys for ${project} ${target.stage}`);
36
+ log(bold(`${project} ${target.stage}`));
37
+ for (const record of records) log(` ${line(record)}`);
38
+ }
39
+
40
+ function line(record: DeployRecord) {
41
+ const mark =
42
+ record.status === "live"
43
+ ? paint("● live", "green")
44
+ : record.status === "failed"
45
+ ? paint("✗ failed", "red")
46
+ : dim(record.status === "rolled-back" ? "↩ rolled back" : " superseded");
47
+ const when = dim(age(record.finishedAt ?? record.startedAt));
48
+ const detail = record.status === "failed" ? paint(record.error?.split("\n")[0] ?? "", "red") : dim(record.message);
49
+ return `${record.id} ${mark.padEnd(22)} ${when.padEnd(14)} ${record.commit.slice(0, 7)} ${record.author.padEnd(18)} ${detail}`;
50
+ }