@hakopod/cloud 0.0.0-bootstrap → 0.1.0-alpha.3
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 +202 -0
- package/README.md +67 -0
- package/package.json +26 -3
- package/src/core.mjs +297 -0
- package/src/main.mjs +490 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Hakopod Cloud CLI
|
|
2
|
+
|
|
3
|
+
Deploy a committed Git repository to Hakopod Cloud or your own Hakopod installation.
|
|
4
|
+
Requires Node.js 22.12+ and Git. This package uses the shared engine API; it does not
|
|
5
|
+
download or execute another binary during npm installation.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx @hakopod/cloud deploy
|
|
9
|
+
# Or point it at your own dashboard:
|
|
10
|
+
npx @hakopod/cloud deploy --url https://hakopod.example.com
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The first run opens browser sign-in. Create an account if needed, compare the
|
|
14
|
+
terminal code, and choose one project/environment or ready Cloud workspace.
|
|
15
|
+
If no destination is ready, open dashboard setup from the consent page, finish
|
|
16
|
+
setup, return, and refresh destinations. Codes expire after ten minutes; repeat
|
|
17
|
+
login if setup takes longer. Cloud admission, email verification, membership and
|
|
18
|
+
MFA requirements still apply. A project administrator or Cloud workspace owner
|
|
19
|
+
must connect Git and authorize a new application source.
|
|
20
|
+
|
|
21
|
+
The deploy command checks that your working tree is clean and the current branch
|
|
22
|
+
is pushed to `origin`, detects the framework remotely, and lets you review or edit
|
|
23
|
+
its commands, service port and public access. GitHub.com and GitLab.com are supported.
|
|
24
|
+
It shows the exact generated workflow and requirements before writing it, then
|
|
25
|
+
writes to the repository default branch. When deploying that branch, it also
|
|
26
|
+
fast-forwards your local checkout to the reviewed workflow commit. Concurrent remote
|
|
27
|
+
or local edits stop this step for review. Builds run in your Git provider's CI.
|
|
28
|
+
|
|
29
|
+
You review the deployment plan before its digest-pinned image is deployed. The CLI
|
|
30
|
+
waits for the deployment's terminal status. Failed builds, failed deployments and
|
|
31
|
+
Cloud Team approvals do not report success. Approval must be completed in Cloud.
|
|
32
|
+
Run the same command after interruption to resume an accepted build/deployment.
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
npx @hakopod/cloud login --url https://cloud.hakopod.com
|
|
36
|
+
npx @hakopod/cloud deploy --name my-app --context apps/web
|
|
37
|
+
npx @hakopod/cloud deploy --build BUILD_ID # link an existing build for this exact source/scope
|
|
38
|
+
npx @hakopod/cloud status
|
|
39
|
+
npx @hakopod/cloud logout
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`--no-browser` prints the sign-in URL without opening it. `--yes` accepts the
|
|
43
|
+
printed configuration, workflow and deployment reviews; it does not bypass browser
|
|
44
|
+
consent or server policy. Noninteractive defaults use Cloud, a small private web
|
|
45
|
+
service and the detected commands. Advanced runtime variables, secret bindings,
|
|
46
|
+
multiple services, architecture and resource settings remain editable in the
|
|
47
|
+
shared dashboard; linked builds preserve those settings.
|
|
48
|
+
|
|
49
|
+
Credentials and resumable deployment state live outside the source repository in
|
|
50
|
+
`~/.config/hakopod/npm`, separately for each exact installation origin. Set
|
|
51
|
+
`HAKOPOD_CLI_HOME` to use another protected directory. Files are written atomically
|
|
52
|
+
with owner-only permissions; Windows uses the account profile's directory ACLs.
|
|
53
|
+
Sessions expire after twelve hours and can be revoked in account security. Logout
|
|
54
|
+
attempts server revocation and always removes local credentials. Account login happens in the browser. Before deployment, missing application
|
|
55
|
+
secrets can be entered with hidden terminal input or explicitly generated.
|
|
56
|
+
Generation creates a random password, not a provider-issued API credential.
|
|
57
|
+
Noninteractive runs stop with the missing names, including when using `--yes`.
|
|
58
|
+
Secret values are sent directly to scoped storage and never saved in CLI state.
|
|
59
|
+
Never commit CLI state to Git.
|
|
60
|
+
|
|
61
|
+
Use an engine/Cloud server release containing npm CLI device-scope support. Older
|
|
62
|
+
servers may expose only the image-based Go CLI API. That CLI remains available for
|
|
63
|
+
TOML, machine API keys, logs and infrastructure administration.
|
|
64
|
+
|
|
65
|
+
For local development: `npm test`, `npm pack`, then `npx --package ./hakopod-cloud-*.tgz hakopod-cloud --help`.
|
|
66
|
+
The package archive contains only public JavaScript, this documentation and the
|
|
67
|
+
Apache-2.0 license. CI tests it and inspects its package contents.
|
package/package.json
CHANGED
|
@@ -1,7 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hakopod/cloud",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0-alpha.3",
|
|
4
|
+
"description": "Guided Git deployments to Hakopod Cloud and self-hosted Hakopod",
|
|
5
|
+
"type": "module",
|
|
5
6
|
"license": "Apache-2.0",
|
|
6
|
-
"
|
|
7
|
+
"bin": {
|
|
8
|
+
"hakopod-cloud": "src/main.mjs"
|
|
9
|
+
},
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=22.12.0"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test",
|
|
20
|
+
"prepublishOnly": "npm test"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/hakopod/hakopod.git",
|
|
25
|
+
"directory": "packages/cli"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
}
|
|
7
30
|
}
|
package/src/core.mjs
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
export const execute = promisify(execFile);
|
|
9
|
+
export const cloud = "https://cloud.hakopod.com";
|
|
10
|
+
export const clean = (value) =>
|
|
11
|
+
String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
12
|
+
export function origin(value) {
|
|
13
|
+
const url = new URL(value);
|
|
14
|
+
if (
|
|
15
|
+
url.username ||
|
|
16
|
+
url.password ||
|
|
17
|
+
url.search ||
|
|
18
|
+
url.hash ||
|
|
19
|
+
!["", "/"].includes(url.pathname) ||
|
|
20
|
+
!(
|
|
21
|
+
url.protocol === "https:" ||
|
|
22
|
+
(url.protocol === "http:" &&
|
|
23
|
+
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
24
|
+
)
|
|
25
|
+
)
|
|
26
|
+
throw new Error(
|
|
27
|
+
"Use an exact HTTPS dashboard origin, or HTTP on localhost.",
|
|
28
|
+
);
|
|
29
|
+
return url.origin;
|
|
30
|
+
}
|
|
31
|
+
export function remote(value) {
|
|
32
|
+
const match =
|
|
33
|
+
/^(?:git@(github\.com|gitlab\.com):|https:\/\/(github\.com|gitlab\.com)\/|ssh:\/\/git@(github\.com|gitlab\.com)\/)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+?)(?:\.git)?$/.exec(
|
|
34
|
+
value,
|
|
35
|
+
);
|
|
36
|
+
if (!match)
|
|
37
|
+
throw new Error(
|
|
38
|
+
"Use a GitHub.com or GitLab.com origin without credentials in its URL.",
|
|
39
|
+
);
|
|
40
|
+
const host = match[1] || match[2] || match[3];
|
|
41
|
+
const repository = match[4].replace(/\.git$/, "");
|
|
42
|
+
if (
|
|
43
|
+
repository.split("/").some((part) => part === "." || part === "..") ||
|
|
44
|
+
(host === "github.com" && repository.split("/").length !== 2)
|
|
45
|
+
)
|
|
46
|
+
throw new Error("Invalid Git repository path.");
|
|
47
|
+
return { provider: host === "github.com" ? "github" : "gitlab", repository };
|
|
48
|
+
}
|
|
49
|
+
export async function git(args, cwd = process.cwd()) {
|
|
50
|
+
try {
|
|
51
|
+
return (
|
|
52
|
+
await execute("git", args, {
|
|
53
|
+
cwd,
|
|
54
|
+
timeout: 30000,
|
|
55
|
+
maxBuffer: 1024 * 1024,
|
|
56
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
57
|
+
})
|
|
58
|
+
).stdout.trim();
|
|
59
|
+
} catch {
|
|
60
|
+
throw new Error(
|
|
61
|
+
"Git could not complete the check. Verify repository access and your local Git credentials.",
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export async function repository(cwd = process.cwd(), requirePushed = true) {
|
|
66
|
+
const root = await git(["rev-parse", "--show-toplevel"], cwd);
|
|
67
|
+
const source = remote(await git(["remote", "get-url", "origin"], root));
|
|
68
|
+
const branch = await git(["symbolic-ref", "--short", "HEAD"], root);
|
|
69
|
+
const commit = await git(["rev-parse", "HEAD"], root);
|
|
70
|
+
if (requirePushed) {
|
|
71
|
+
if (await git(["status", "--porcelain"], root))
|
|
72
|
+
throw new Error(
|
|
73
|
+
"Commit or stash local changes first. This command deploys only committed, pushed Git files.",
|
|
74
|
+
);
|
|
75
|
+
const published = await git(
|
|
76
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
77
|
+
root,
|
|
78
|
+
);
|
|
79
|
+
if (published.split(/\s/)[0] !== commit)
|
|
80
|
+
throw new Error(
|
|
81
|
+
"Push this branch before deploying. Its remote HEAD must match your local commit.",
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return { root, branch, commit, ...source };
|
|
85
|
+
}
|
|
86
|
+
export const configRoot = () =>
|
|
87
|
+
process.env.HAKOPOD_CLI_HOME || join(homedir(), ".config", "hakopod", "npm");
|
|
88
|
+
export const key = (value) => createHash("sha256").update(value).digest("hex");
|
|
89
|
+
export async function readPrivate(file) {
|
|
90
|
+
let handle;
|
|
91
|
+
try {
|
|
92
|
+
handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
93
|
+
const info = await handle.stat();
|
|
94
|
+
if (
|
|
95
|
+
(process.getuid && info.uid !== process.getuid()) ||
|
|
96
|
+
!info.isFile() ||
|
|
97
|
+
info.size > 1024 * 1024 ||
|
|
98
|
+
(process.platform !== "win32" && info.mode & 0o077)
|
|
99
|
+
)
|
|
100
|
+
throw new Error("CLI state must be a private file (chmod 600).");
|
|
101
|
+
return JSON.parse(await handle.readFile("utf8"));
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (error.code === "ENOENT") return null;
|
|
104
|
+
throw error;
|
|
105
|
+
} finally {
|
|
106
|
+
await handle?.close();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export async function writePrivate(file, data) {
|
|
110
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
111
|
+
const temporary = `${file}.${randomUUID()}`;
|
|
112
|
+
const handle = await open(temporary, "wx", 0o600);
|
|
113
|
+
try {
|
|
114
|
+
await handle.writeFile(JSON.stringify(data, null, 2) + "\n");
|
|
115
|
+
await handle.sync();
|
|
116
|
+
} finally {
|
|
117
|
+
await handle.close();
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
await rename(temporary, file);
|
|
121
|
+
} finally {
|
|
122
|
+
await unlink(temporary).catch(() => {});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export const profilePath = (target) =>
|
|
126
|
+
join(configRoot(), `profile-${key(origin(target))}.json`);
|
|
127
|
+
export const statePath = (target, scope, root) =>
|
|
128
|
+
join(
|
|
129
|
+
configRoot(),
|
|
130
|
+
`deploy-${key(JSON.stringify([origin(target), scope, root]))}.json`,
|
|
131
|
+
);
|
|
132
|
+
export class APIError extends Error {
|
|
133
|
+
constructor(status, body) {
|
|
134
|
+
super(
|
|
135
|
+
clean(
|
|
136
|
+
body?.error?.message ||
|
|
137
|
+
body?.error ||
|
|
138
|
+
`API request failed (${status}).`,
|
|
139
|
+
),
|
|
140
|
+
);
|
|
141
|
+
this.status = status;
|
|
142
|
+
this.code = body?.error?.code || body?.error;
|
|
143
|
+
this.details = body?.error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
export class API {
|
|
147
|
+
constructor(target, profile, transport = fetch) {
|
|
148
|
+
this.origin = origin(target);
|
|
149
|
+
this.profile = profile;
|
|
150
|
+
this.transport = transport;
|
|
151
|
+
}
|
|
152
|
+
async call(
|
|
153
|
+
path,
|
|
154
|
+
body,
|
|
155
|
+
{ method = body === undefined ? "GET" : "POST", idempotency } = {},
|
|
156
|
+
) {
|
|
157
|
+
if (
|
|
158
|
+
!/^\/[A-Za-z0-9/?=&%_.:-]+$/.test(path) ||
|
|
159
|
+
path.startsWith("//") ||
|
|
160
|
+
path.split("/").includes("..")
|
|
161
|
+
)
|
|
162
|
+
throw new Error("Invalid API path.");
|
|
163
|
+
if (this.profile && this.profile.origin !== this.origin)
|
|
164
|
+
throw new Error(
|
|
165
|
+
"Credentials belong to a different installation. Sign in again.",
|
|
166
|
+
);
|
|
167
|
+
const headers = { Accept: "application/json" };
|
|
168
|
+
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
169
|
+
if (this.profile) {
|
|
170
|
+
headers.Authorization = `Bearer ${this.profile.token}`;
|
|
171
|
+
if (this.profile.scope_id)
|
|
172
|
+
headers["X-Hakopod-Workspace"] = this.profile.scope_id;
|
|
173
|
+
}
|
|
174
|
+
if (idempotency) headers["Idempotency-Key"] = idempotency;
|
|
175
|
+
let response;
|
|
176
|
+
try {
|
|
177
|
+
response = await this.transport(`${this.origin}/api/v1${path}`, {
|
|
178
|
+
method,
|
|
179
|
+
headers,
|
|
180
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
181
|
+
redirect: "error",
|
|
182
|
+
signal: AbortSignal.timeout(35000),
|
|
183
|
+
});
|
|
184
|
+
} catch {
|
|
185
|
+
throw new Error(
|
|
186
|
+
"Cannot reach this installation. Any accepted work continues; run the command again to resume.",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
const reader = response.body?.getReader();
|
|
190
|
+
const chunks = [];
|
|
191
|
+
let length = 0;
|
|
192
|
+
if (reader)
|
|
193
|
+
for (;;) {
|
|
194
|
+
const { done, value } = await reader.read();
|
|
195
|
+
if (done) break;
|
|
196
|
+
length += value.length;
|
|
197
|
+
if (length > 2 * 1024 * 1024) {
|
|
198
|
+
await reader.cancel();
|
|
199
|
+
throw new Error("API response exceeds the CLI limit.");
|
|
200
|
+
}
|
|
201
|
+
chunks.push(Buffer.from(value));
|
|
202
|
+
}
|
|
203
|
+
let result;
|
|
204
|
+
try {
|
|
205
|
+
result = JSON.parse(Buffer.concat(chunks).toString());
|
|
206
|
+
} catch {
|
|
207
|
+
throw new Error(
|
|
208
|
+
"This installation did not return JSON. Check the dashboard URL and server version.",
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
if (!response.ok) throw new APIError(response.status, result);
|
|
212
|
+
return result;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
export async function openBrowser(url) {
|
|
216
|
+
const command =
|
|
217
|
+
process.platform === "darwin"
|
|
218
|
+
? "open"
|
|
219
|
+
: process.platform === "win32"
|
|
220
|
+
? "rundll32"
|
|
221
|
+
: "xdg-open";
|
|
222
|
+
const args =
|
|
223
|
+
process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
|
|
224
|
+
await execute(command, args, { timeout: 5000 }).catch(() => {});
|
|
225
|
+
}
|
|
226
|
+
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
227
|
+
export async function deviceLogin(
|
|
228
|
+
api,
|
|
229
|
+
{ show, launch = openBrowser, wait = sleep, now = Date.now } = {},
|
|
230
|
+
) {
|
|
231
|
+
const challenge = await api.call("/auth/device/start", {});
|
|
232
|
+
const link = new URL(challenge.verification_uri_complete);
|
|
233
|
+
if (
|
|
234
|
+
link.origin !== api.origin ||
|
|
235
|
+
link.pathname !== "/login/device" ||
|
|
236
|
+
link.username ||
|
|
237
|
+
link.password ||
|
|
238
|
+
link.hash ||
|
|
239
|
+
link.searchParams.get("user_code") !== challenge.user_code ||
|
|
240
|
+
!/^[A-Z2-7]{4}-[A-Z2-7]{4}$/.test(challenge.user_code) ||
|
|
241
|
+
!/^[a-f0-9]{64}$/.test(challenge.device_code)
|
|
242
|
+
)
|
|
243
|
+
throw new Error(
|
|
244
|
+
"The server returned an invalid browser authorization link.",
|
|
245
|
+
);
|
|
246
|
+
if (
|
|
247
|
+
!Number.isInteger(challenge.expires_in) ||
|
|
248
|
+
challenge.expires_in < 1 ||
|
|
249
|
+
challenge.expires_in > 900 ||
|
|
250
|
+
!Number.isInteger(challenge.interval) ||
|
|
251
|
+
challenge.interval < 5 ||
|
|
252
|
+
challenge.interval > 30
|
|
253
|
+
)
|
|
254
|
+
throw new Error("The server returned invalid authorization timing.");
|
|
255
|
+
show(
|
|
256
|
+
`Sign in or create an account, choose a destination, and approve code ${challenge.user_code}.\n${link.href}`,
|
|
257
|
+
);
|
|
258
|
+
await launch(link.href);
|
|
259
|
+
const deadline = now() + challenge.expires_in * 1000;
|
|
260
|
+
let interval = challenge.interval;
|
|
261
|
+
while (now() < deadline) {
|
|
262
|
+
await wait(interval * 1000);
|
|
263
|
+
if (now() >= deadline) break;
|
|
264
|
+
try {
|
|
265
|
+
const result = await api.call("/auth/device/token", {
|
|
266
|
+
device_code: challenge.device_code,
|
|
267
|
+
});
|
|
268
|
+
if (
|
|
269
|
+
!/^hs_[a-f0-9]{32}_[a-f0-9]{64}$/.test(result.access_token) ||
|
|
270
|
+
result.user?.credential_type !== "cli" ||
|
|
271
|
+
!result.user.project ||
|
|
272
|
+
!result.user.environment ||
|
|
273
|
+
(result.scope_id && !/^[a-f0-9]{32}$/.test(result.scope_id)) ||
|
|
274
|
+
!(Date.parse(result.expires_at) > now())
|
|
275
|
+
)
|
|
276
|
+
throw new Error("The server returned an invalid scoped CLI session.");
|
|
277
|
+
return {
|
|
278
|
+
origin: api.origin,
|
|
279
|
+
token: result.access_token,
|
|
280
|
+
expires_at: result.expires_at,
|
|
281
|
+
scope_id: result.scope_id || "",
|
|
282
|
+
project: result.user.project,
|
|
283
|
+
environment: result.user.environment,
|
|
284
|
+
};
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (error.code === "authorization_pending") continue;
|
|
287
|
+
if (error.code === "slow_down") {
|
|
288
|
+
interval = Math.min(30, interval + 5);
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
throw new Error(
|
|
295
|
+
"Sign-in expired. Run hakopod-cloud login again to get a new code.",
|
|
296
|
+
);
|
|
297
|
+
}
|
package/src/main.mjs
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Writable } from "node:stream";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { stdin, stdout } from "node:process";
|
|
6
|
+
import { basename } from "node:path";
|
|
7
|
+
import { unlink } from "node:fs/promises";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import {
|
|
10
|
+
API,
|
|
11
|
+
APIError,
|
|
12
|
+
cloud,
|
|
13
|
+
clean,
|
|
14
|
+
origin,
|
|
15
|
+
repository,
|
|
16
|
+
git,
|
|
17
|
+
profilePath,
|
|
18
|
+
statePath,
|
|
19
|
+
readPrivate,
|
|
20
|
+
writePrivate,
|
|
21
|
+
deviceLogin,
|
|
22
|
+
openBrowser,
|
|
23
|
+
sleep,
|
|
24
|
+
} from "./core.mjs";
|
|
25
|
+
|
|
26
|
+
const help = `Hakopod — deploy committed Git repositories
|
|
27
|
+
|
|
28
|
+
npx @hakopod/cloud deploy
|
|
29
|
+
npx @hakopod/cloud login --url https://hakopod.example.com
|
|
30
|
+
npx @hakopod/cloud status --url https://hakopod.example.com
|
|
31
|
+
npx @hakopod/cloud logout --url https://hakopod.example.com
|
|
32
|
+
|
|
33
|
+
Options: --url <dashboard origin> --name <application> --context <directory>
|
|
34
|
+
--build <existing build ID> --yes (accept displayed reviews) --no-browser --help
|
|
35
|
+
|
|
36
|
+
Requires Node 22.12+, Git, and a pushed GitHub.com or GitLab.com branch.
|
|
37
|
+
Cloud is the default for noninteractive use. Self-hosted uses the same APIs.
|
|
38
|
+
Credentials are saved per installation with owner-only file permissions.
|
|
39
|
+
`;
|
|
40
|
+
let rl;
|
|
41
|
+
const say = (value) => stdout.write(`${clean(value)}\n`);
|
|
42
|
+
const show = (value) =>
|
|
43
|
+
stdout.write(
|
|
44
|
+
String(value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, "") + "\n",
|
|
45
|
+
);
|
|
46
|
+
async function ask(label, fallback = "") {
|
|
47
|
+
if (!stdin.isTTY) {
|
|
48
|
+
if (fallback) return fallback;
|
|
49
|
+
throw new Error(`${label}: run in an interactive terminal.`);
|
|
50
|
+
}
|
|
51
|
+
rl ||= createInterface({ input: stdin, output: stdout });
|
|
52
|
+
return (
|
|
53
|
+
(
|
|
54
|
+
await rl.question(`${label}${fallback ? ` [${clean(fallback)}]` : ""}: `)
|
|
55
|
+
).trim() || fallback
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
async function askSecret(label) {
|
|
59
|
+
if (!stdin.isTTY) throw new Error("Secret input requires an interactive terminal.");
|
|
60
|
+
rl?.close(); rl = undefined;
|
|
61
|
+
let muted = false;
|
|
62
|
+
const output = new Writable({ write(chunk, encoding, done) { if (!muted) stdout.write(chunk, encoding); done(); } });
|
|
63
|
+
const secretInput = createInterface({ input: stdin, output, terminal: true });
|
|
64
|
+
try {
|
|
65
|
+
const result = secretInput.question(`${label} (hidden): `);
|
|
66
|
+
muted = true;
|
|
67
|
+
return await result;
|
|
68
|
+
} finally { secretInput.close(); stdout.write("\n"); }
|
|
69
|
+
}
|
|
70
|
+
async function setupSecrets(api, config, plan) {
|
|
71
|
+
const missing = plan.missing_secrets || [];
|
|
72
|
+
if (!missing.length) return;
|
|
73
|
+
if (!stdin.isTTY) throw new Error(`Missing application secrets: ${missing.map(clean).join(", ")}. Save them in the dashboard or through POST /api/v1/secrets/{name}, then retry. No deployment was submitted.`);
|
|
74
|
+
for (const name of missing) {
|
|
75
|
+
say(`Missing secret: ${name}`);
|
|
76
|
+
const mode = await choose("Secret value", [
|
|
77
|
+
{ label: "Enter an existing value (hidden)", value: "value" },
|
|
78
|
+
{ label: "Generate a new random password (not a provider credential)", value: "generate" },
|
|
79
|
+
{ label: "Cancel deployment", value: "cancel" },
|
|
80
|
+
]);
|
|
81
|
+
if (mode === "cancel") throw new Error("Secret setup cancelled. No deployment was submitted.");
|
|
82
|
+
const body = mode === "generate" ? { generate: true } : { value: await askSecret(clean(name)) };
|
|
83
|
+
const query = new URLSearchParams({ project: config.project, environment: config.environment, application: plan.spec.name });
|
|
84
|
+
try { await api.call(`/secrets/${encodeURIComponent(name)}?${query}`, body); }
|
|
85
|
+
finally { delete body.value; }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function choose(label, items) {
|
|
89
|
+
if (!items.length) throw new Error(`No ${label.toLowerCase()} available.`);
|
|
90
|
+
items.forEach((item, index) => say(`${index + 1}. ${item.label}`));
|
|
91
|
+
for (;;) {
|
|
92
|
+
const value = Number(await ask(label, items.length === 1 ? "1" : ""));
|
|
93
|
+
if (Number.isInteger(value) && items[value - 1])
|
|
94
|
+
return items[value - 1].value;
|
|
95
|
+
say("Choose one of the numbers above.");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function confirm(label, yes) {
|
|
99
|
+
if (yes) {
|
|
100
|
+
say(`${label}: accepted with --yes`);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (!/^y(es)?$/i.test(await ask(`${label} (y/N)`, "n")))
|
|
104
|
+
throw new Error(
|
|
105
|
+
"Stopped. Saved configuration remains available for your next attempt.",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
async function waitFor(read, finished, label, timeout = 30 * 60 * 1000) {
|
|
109
|
+
let previous = "";
|
|
110
|
+
const until = Date.now() + timeout;
|
|
111
|
+
while (Date.now() < until) {
|
|
112
|
+
const item = await read();
|
|
113
|
+
if (item.status !== previous) {
|
|
114
|
+
say(`${label}: ${item.status}`);
|
|
115
|
+
previous = item.status;
|
|
116
|
+
}
|
|
117
|
+
if (finished(item)) return item;
|
|
118
|
+
await sleep(5000);
|
|
119
|
+
}
|
|
120
|
+
throw new Error(
|
|
121
|
+
`${label} is still running. Use the same deploy command to resume, or status to inspect it.`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
async function main() {
|
|
125
|
+
const { values: flags, positionals } = parseArgs({
|
|
126
|
+
allowPositionals: true,
|
|
127
|
+
options: {
|
|
128
|
+
url: { type: "string" },
|
|
129
|
+
name: { type: "string" },
|
|
130
|
+
context: { type: "string" },
|
|
131
|
+
build: { type: "string" },
|
|
132
|
+
yes: { type: "boolean" },
|
|
133
|
+
"no-browser": { type: "boolean" },
|
|
134
|
+
help: { type: "boolean" },
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
if (flags.help) {
|
|
138
|
+
show(help);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const command = positionals[0] || "deploy";
|
|
142
|
+
if (
|
|
143
|
+
positionals.length > 1 ||
|
|
144
|
+
!["deploy", "login", "logout", "status"].includes(command)
|
|
145
|
+
)
|
|
146
|
+
throw new Error(help);
|
|
147
|
+
let target = flags.url;
|
|
148
|
+
if (!target && stdin.isTTY) {
|
|
149
|
+
const kind = await choose("Deployment target", [
|
|
150
|
+
{ label: "Hakopod Cloud", value: "cloud" },
|
|
151
|
+
{ label: "Self-hosted Hakopod", value: "self" },
|
|
152
|
+
]);
|
|
153
|
+
target = kind === "cloud" ? cloud : await ask("Self-hosted dashboard URL");
|
|
154
|
+
}
|
|
155
|
+
target = origin(target || cloud);
|
|
156
|
+
const file = profilePath(target);
|
|
157
|
+
let profile = await readPrivate(file);
|
|
158
|
+
if (command === "logout") {
|
|
159
|
+
if (profile) {
|
|
160
|
+
try {
|
|
161
|
+
await new API(target, profile).call("/auth/logout", {});
|
|
162
|
+
say("CLI session revoked.");
|
|
163
|
+
} catch {
|
|
164
|
+
say(
|
|
165
|
+
`Server revocation was unavailable. Revoke this session in ${target}/settings/security.`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
await unlink(file);
|
|
169
|
+
say("Removed local credentials.");
|
|
170
|
+
} else say("No saved login for this installation.");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
let api = new API(target, profile);
|
|
174
|
+
if (
|
|
175
|
+
command === "login" ||
|
|
176
|
+
!profile ||
|
|
177
|
+
Date.parse(profile.expires_at) <= Date.now()
|
|
178
|
+
)
|
|
179
|
+
profile = null;
|
|
180
|
+
if (profile) {
|
|
181
|
+
try {
|
|
182
|
+
const me = await api.call("/me");
|
|
183
|
+
if (
|
|
184
|
+
me.credential_type !== "cli" ||
|
|
185
|
+
me.project !== profile.project ||
|
|
186
|
+
me.environment !== profile.environment
|
|
187
|
+
)
|
|
188
|
+
throw new Error(
|
|
189
|
+
"The saved CLI destination no longer matches. Run login again.",
|
|
190
|
+
);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (error.status === 401) profile = null;
|
|
193
|
+
else throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (!profile) {
|
|
197
|
+
profile = await deviceLogin(new API(target), {
|
|
198
|
+
show,
|
|
199
|
+
launch: flags["no-browser"] ? async () => {} : openBrowser,
|
|
200
|
+
});
|
|
201
|
+
await writePrivate(file, profile);
|
|
202
|
+
api = new API(target, profile);
|
|
203
|
+
}
|
|
204
|
+
say(`Destination: ${target} · ${profile.project} / ${profile.environment}`);
|
|
205
|
+
if (command === "login") return;
|
|
206
|
+
let source = await repository(process.cwd(), command !== "status");
|
|
207
|
+
const local = statePath(
|
|
208
|
+
target,
|
|
209
|
+
[profile.scope_id, profile.project, profile.environment],
|
|
210
|
+
source.root,
|
|
211
|
+
);
|
|
212
|
+
let saved = await readPrivate(local);
|
|
213
|
+
if (flags.build) {
|
|
214
|
+
if (!/^[a-f0-9]{32}$/.test(flags.build))
|
|
215
|
+
throw new Error("Use the build ID shown in the dashboard.");
|
|
216
|
+
if (saved?.build && saved.build !== flags.build)
|
|
217
|
+
throw new Error(
|
|
218
|
+
"This directory already has a linked build for this destination.",
|
|
219
|
+
);
|
|
220
|
+
const linked = await api.call(`/builds/${flags.build}`);
|
|
221
|
+
if (
|
|
222
|
+
linked.project !== profile.project ||
|
|
223
|
+
linked.environment !== profile.environment ||
|
|
224
|
+
linked.repository !== source.repository ||
|
|
225
|
+
linked.provider !== source.provider ||
|
|
226
|
+
linked.branch !== source.branch
|
|
227
|
+
)
|
|
228
|
+
throw new Error(
|
|
229
|
+
"Build does not match this repository and authorized destination.",
|
|
230
|
+
);
|
|
231
|
+
saved ||= { build: linked.id };
|
|
232
|
+
await writePrivate(local, saved);
|
|
233
|
+
}
|
|
234
|
+
if (command === "status") {
|
|
235
|
+
if (!saved?.build)
|
|
236
|
+
throw new Error(
|
|
237
|
+
"No saved deployment in this repository for this destination.",
|
|
238
|
+
);
|
|
239
|
+
const build = await api.call(`/builds/${saved.build}`);
|
|
240
|
+
say(`Application: ${build.name}`);
|
|
241
|
+
if (saved.run) {
|
|
242
|
+
const run = await api.call(`/builds/${saved.build}/runs/${saved.run}`);
|
|
243
|
+
say(`Build: ${run.status} ${run.conclusion}`);
|
|
244
|
+
if (run.deployment_id) {
|
|
245
|
+
const deployment = await api.call(`/deployments/${run.deployment_id}`);
|
|
246
|
+
say(`Deployment: ${deployment.status}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
let config;
|
|
252
|
+
if (saved?.build) {
|
|
253
|
+
config = await api.call(`/builds/${saved.build}`);
|
|
254
|
+
if (
|
|
255
|
+
config.repository !== source.repository ||
|
|
256
|
+
config.provider !== source.provider ||
|
|
257
|
+
config.branch !== source.branch ||
|
|
258
|
+
config.project !== profile.project ||
|
|
259
|
+
config.environment !== profile.environment
|
|
260
|
+
)
|
|
261
|
+
throw new Error(
|
|
262
|
+
"This directory is linked to another source or destination. Use a separate checkout or restore its original branch.",
|
|
263
|
+
);
|
|
264
|
+
if (
|
|
265
|
+
(flags.name && flags.name !== config.name) ||
|
|
266
|
+
(flags.context && flags.context !== config.context_path)
|
|
267
|
+
)
|
|
268
|
+
throw new Error(
|
|
269
|
+
"This deployment is already linked. Edit its build configuration in the dashboard before continuing.",
|
|
270
|
+
);
|
|
271
|
+
} else {
|
|
272
|
+
let connections = (await api.call("/git/connections")).items.filter(
|
|
273
|
+
(item) =>
|
|
274
|
+
item.provider === source.provider &&
|
|
275
|
+
item.enabled &&
|
|
276
|
+
item.capabilities.builds,
|
|
277
|
+
);
|
|
278
|
+
if (!connections.length) {
|
|
279
|
+
const url = `${target}/settings/git/connections/new`;
|
|
280
|
+
show(
|
|
281
|
+
`Connect ${source.provider} in the dashboard for this destination, then return here.\n${url}`,
|
|
282
|
+
);
|
|
283
|
+
if (!flags["no-browser"]) await openBrowser(url);
|
|
284
|
+
await ask("Press Enter after connecting Git", "continue");
|
|
285
|
+
connections = (await api.call("/git/connections")).items.filter(
|
|
286
|
+
(item) =>
|
|
287
|
+
item.provider === source.provider &&
|
|
288
|
+
item.enabled &&
|
|
289
|
+
item.capabilities.builds,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
const connection_id = await choose(
|
|
293
|
+
"Git connection",
|
|
294
|
+
connections.map((item) => ({ label: item.name, value: item.id })),
|
|
295
|
+
);
|
|
296
|
+
const name =
|
|
297
|
+
flags.name ||
|
|
298
|
+
(await ask(
|
|
299
|
+
"Application name",
|
|
300
|
+
basename(source.root)
|
|
301
|
+
.toLowerCase()
|
|
302
|
+
.replace(/[^a-z0-9-]/g, "-")
|
|
303
|
+
.slice(0, 40),
|
|
304
|
+
));
|
|
305
|
+
const context_path =
|
|
306
|
+
flags.context || (await ask("Directory inside repository", "."));
|
|
307
|
+
let input = {
|
|
308
|
+
project: profile.project,
|
|
309
|
+
environment: profile.environment,
|
|
310
|
+
name,
|
|
311
|
+
provider: source.provider,
|
|
312
|
+
repository: source.repository,
|
|
313
|
+
branch: source.branch,
|
|
314
|
+
connection_id,
|
|
315
|
+
context_path,
|
|
316
|
+
service: "web",
|
|
317
|
+
public: false,
|
|
318
|
+
auto_build: false,
|
|
319
|
+
auto_deploy: false,
|
|
320
|
+
};
|
|
321
|
+
const detected = await api.call("/builds/detect", input);
|
|
322
|
+
if (detected.commit_sha !== source.commit)
|
|
323
|
+
throw new Error(
|
|
324
|
+
"The remote branch changed during detection. Pull and review it, then retry.",
|
|
325
|
+
);
|
|
326
|
+
show(
|
|
327
|
+
`Detected ${detected.framework?.framework || "Dockerfile"} at ${source.commit}\n${(detected.warnings || []).join("\n")}`,
|
|
328
|
+
);
|
|
329
|
+
input = {
|
|
330
|
+
...input,
|
|
331
|
+
mode: detected.mode,
|
|
332
|
+
framework: detected.framework,
|
|
333
|
+
dockerfile: detected.dockerfile,
|
|
334
|
+
port: detected.framework?.port || 8080,
|
|
335
|
+
size: "small",
|
|
336
|
+
};
|
|
337
|
+
if (input.framework) {
|
|
338
|
+
show(JSON.stringify(input.framework, null, 2));
|
|
339
|
+
if (
|
|
340
|
+
!flags.yes &&
|
|
341
|
+
/^y(es)?$/i.test(await ask("Edit detected commands? (y/N)", "n"))
|
|
342
|
+
) {
|
|
343
|
+
for (const field of [
|
|
344
|
+
"install_command",
|
|
345
|
+
"build_command",
|
|
346
|
+
"start_command",
|
|
347
|
+
"output_directory",
|
|
348
|
+
]) {
|
|
349
|
+
if (input.framework[field] !== undefined)
|
|
350
|
+
input.framework[field] = await ask(
|
|
351
|
+
field.replaceAll("_", " "),
|
|
352
|
+
input.framework[field],
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
input.port = Number(await ask("Service port", String(input.port)));
|
|
358
|
+
if (!Number.isInteger(input.port) || input.port < 1 || input.port > 65535)
|
|
359
|
+
throw new Error("Choose a service port between 1 and 65535.");
|
|
360
|
+
if (input.framework) input.framework.port = input.port;
|
|
361
|
+
input.public = /^y(es)?$/i.test(
|
|
362
|
+
await ask("Expose this web service publicly? (y/N)", "n"),
|
|
363
|
+
);
|
|
364
|
+
show(`Review build settings\n${JSON.stringify(input, null, 2)}`);
|
|
365
|
+
await confirm("Save these build settings", flags.yes);
|
|
366
|
+
// A create response can be lost. Discover the unique saved name before retrying.
|
|
367
|
+
const existing = (
|
|
368
|
+
await api.call(
|
|
369
|
+
`/builds?project=${encodeURIComponent(profile.project)}&environment=${encodeURIComponent(profile.environment)}`,
|
|
370
|
+
)
|
|
371
|
+
).items.filter((item) => item.name === name);
|
|
372
|
+
if (existing.length)
|
|
373
|
+
throw new Error(
|
|
374
|
+
"A build with this name already exists. Rerun with --build plus its ID from the dashboard, or choose another application name.",
|
|
375
|
+
);
|
|
376
|
+
config = await api.call("/builds", input);
|
|
377
|
+
saved = { build: config.id };
|
|
378
|
+
await writePrivate(local, saved);
|
|
379
|
+
}
|
|
380
|
+
say(`Application: ${config.name} · ${source.repository} · ${source.branch}`);
|
|
381
|
+
if (config.installed_revision !== config.revision) {
|
|
382
|
+
const preview = await api.call(`/builds/${config.id}/preview`, {});
|
|
383
|
+
show(
|
|
384
|
+
`Workflow to write: ${preview.workflow_path}\n${preview.workflow}\nRequirements:\n${preview.requirements.join("\n")}`,
|
|
385
|
+
);
|
|
386
|
+
await confirm(
|
|
387
|
+
"Commit this workflow to the repository default branch (fast-forward locally if selected)",
|
|
388
|
+
flags.yes,
|
|
389
|
+
);
|
|
390
|
+
const installed = await api.call(`/builds/${config.id}/install`, {
|
|
391
|
+
expected_config_revision: config.revision,
|
|
392
|
+
});
|
|
393
|
+
config = installed.config;
|
|
394
|
+
if (!/^[a-f0-9]{40,64}$/.test(installed.commit_sha))
|
|
395
|
+
throw new Error("The provider returned an invalid workflow commit.");
|
|
396
|
+
if (!installed.workflow_branch)
|
|
397
|
+
throw new Error(
|
|
398
|
+
"The server must report the installed workflow branch. Upgrade this installation before continuing.",
|
|
399
|
+
);
|
|
400
|
+
if (installed.workflow_branch === source.branch) {
|
|
401
|
+
if (await git(["status", "--porcelain"], source.root))
|
|
402
|
+
throw new Error(
|
|
403
|
+
"Local files changed during review. Commit or stash them, pull the workflow commit, and rerun deploy.",
|
|
404
|
+
);
|
|
405
|
+
await git(["fetch", "origin", source.branch], source.root);
|
|
406
|
+
if (
|
|
407
|
+
(await git(["rev-parse", "FETCH_HEAD"], source.root)) !==
|
|
408
|
+
installed.commit_sha
|
|
409
|
+
)
|
|
410
|
+
throw new Error(
|
|
411
|
+
"The remote branch changed after workflow installation. Pull and review it before retrying.",
|
|
412
|
+
);
|
|
413
|
+
await git(["merge", "--ff-only", installed.commit_sha], source.root);
|
|
414
|
+
source = await repository(source.root);
|
|
415
|
+
}
|
|
416
|
+
say(
|
|
417
|
+
`Workflow installed on ${installed.workflow_branch}. Source remains ${source.branch}.`,
|
|
418
|
+
);
|
|
419
|
+
say(`Workflow ready at ${source.commit}.`);
|
|
420
|
+
}
|
|
421
|
+
if (saved.commit !== source.commit || saved.revision !== config.revision) {
|
|
422
|
+
saved = {
|
|
423
|
+
build: config.id,
|
|
424
|
+
commit: source.commit,
|
|
425
|
+
revision: config.revision,
|
|
426
|
+
idempotency: `cli-${randomUUID()}`,
|
|
427
|
+
};
|
|
428
|
+
await writePrivate(local, saved);
|
|
429
|
+
}
|
|
430
|
+
if (!saved.run) {
|
|
431
|
+
await confirm(
|
|
432
|
+
`Build committed source ${source.commit} using your Git provider`,
|
|
433
|
+
flags.yes,
|
|
434
|
+
);
|
|
435
|
+
const run = await api.call(
|
|
436
|
+
`/builds/${config.id}/run`,
|
|
437
|
+
{ expected_config_revision: config.revision, commit: source.commit },
|
|
438
|
+
{ idempotency: saved.idempotency },
|
|
439
|
+
);
|
|
440
|
+
saved.run = run.id;
|
|
441
|
+
await writePrivate(local, saved);
|
|
442
|
+
}
|
|
443
|
+
const base = `/builds/${config.id}/runs/${saved.run}`;
|
|
444
|
+
const run = await waitFor(
|
|
445
|
+
() => api.call(base),
|
|
446
|
+
(item) => ["completed", "failed", "cancelled"].includes(item.status),
|
|
447
|
+
"Build",
|
|
448
|
+
);
|
|
449
|
+
if (run.status !== "completed" || run.conclusion !== "success" || !run.image)
|
|
450
|
+
throw new Error(
|
|
451
|
+
`Build did not succeed. Inspect ${target}/builds/${config.id}. Fix it and push a new commit to start another build.`,
|
|
452
|
+
);
|
|
453
|
+
let deploymentID = run.deployment_id;
|
|
454
|
+
if (!deploymentID) {
|
|
455
|
+
const plan = await api.call(`${base}/plan`, {});
|
|
456
|
+
show(
|
|
457
|
+
`Review deployment\n${JSON.stringify({ image: run.image, changes: plan.changes, warnings: plan.warnings }, null, 2)}`,
|
|
458
|
+
);
|
|
459
|
+
await setupSecrets(api, config, plan);
|
|
460
|
+
await confirm("Deploy this built image", flags.yes);
|
|
461
|
+
const deployment = await api.call(`${base}/deploy`, {
|
|
462
|
+
expected_revision: plan.expected_revision,
|
|
463
|
+
expected_config_revision: plan.expected_config_revision,
|
|
464
|
+
});
|
|
465
|
+
deploymentID = deployment.id;
|
|
466
|
+
}
|
|
467
|
+
const deployment = await waitFor(
|
|
468
|
+
() => api.call(`/deployments/${deploymentID}`),
|
|
469
|
+
(item) =>
|
|
470
|
+
["succeeded", "failed", "cancelled", "superseded"].includes(item.status),
|
|
471
|
+
"Deployment",
|
|
472
|
+
);
|
|
473
|
+
if (deployment.status !== "succeeded")
|
|
474
|
+
throw new Error(
|
|
475
|
+
`Deployment ${deployment.status}. Inspect ${target}/applications/${deployment.application_id} for diagnostics.`,
|
|
476
|
+
);
|
|
477
|
+
say(
|
|
478
|
+
`Deployment succeeded. ${target}/applications/${deployment.application_id}`,
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
main()
|
|
482
|
+
.catch((error) => {
|
|
483
|
+
if (error instanceof APIError && error.code === "approval_required") {
|
|
484
|
+
say(
|
|
485
|
+
"Deployment awaits a Cloud Team review. Open the workspace approvals in the dashboard; rerun deploy after approval.",
|
|
486
|
+
);
|
|
487
|
+
} else show(error.message || "The command could not finish.");
|
|
488
|
+
process.exitCode = 1;
|
|
489
|
+
})
|
|
490
|
+
.finally(() => rl?.close());
|