@joripspace/cli 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@joripspace/cli",
3
+ "version": "0.4.1",
4
+ "license": "MIT",
5
+ "description": "JoripSpace Control API command-line client for Node.js",
6
+ "type": "commonjs",
7
+ "bin": {
8
+ "joripspace": "bin/joripspace.js"
9
+ },
10
+ "homepage": "https://joripspace.com",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/JoripSpace/joripspace-cli.git"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/JoripSpace/joripspace-cli/issues"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "registry": "https://registry.npmjs.org/"
21
+ },
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "files": [
26
+ "bin/joripspace.js",
27
+ "lib/*.js",
28
+ "vendor/core/*.cjs",
29
+ "vendor/templates/index.js",
30
+ "vendor/templates/templates/**",
31
+ "README.md",
32
+ "LICENSE",
33
+ "THIRD_PARTY_NOTICES.md"
34
+ ],
35
+ "scripts": {
36
+ "check": "node scripts/check-package.mjs",
37
+ "test": "node scripts/test.mjs",
38
+ "test:package": "node scripts/verify-package.mjs",
39
+ "prepack": "node scripts/check-package.mjs"
40
+ },
41
+ "dependencies": {
42
+ "fflate": "^0.8.2",
43
+ "jsonc-parser": "^3.3.1",
44
+ "smol-toml": "^1.7.2"
45
+ }
46
+ }
@@ -0,0 +1,197 @@
1
+ function buildGithubWorkflow({ projectId, branch, buildCommand, artifactPath, entrypoint }) {
2
+ const commands = String(buildCommand)
3
+ .split('\n')
4
+ .map((line) => ` ${line}`)
5
+ .join('\n');
6
+ const deployScript = `${inlineDeployMain.toString()}\n\nawait inlineDeployMain();`
7
+ .split('\n')
8
+ .map((line) => ` ${line}`)
9
+ .join('\n');
10
+ return `# joripspace-workflow-version: 8
11
+ name: JoripSpace Deploy
12
+
13
+ on:
14
+ push:
15
+ branches:
16
+ - ${JSON.stringify(String(branch))}
17
+ workflow_dispatch:
18
+
19
+ permissions:
20
+ contents: read
21
+ id-token: write
22
+
23
+ concurrency:
24
+ group: ${JSON.stringify(`joripspace-${String(projectId)}`)}
25
+ cancel-in-progress: true
26
+
27
+ jobs:
28
+ deploy:
29
+ runs-on: ubuntu-latest
30
+ steps:
31
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
32
+ - name: Build
33
+ run: |
34
+ set -Eeuo pipefail
35
+ trap 'code=$?; echo "::error title=JoripSpace build failed::Build failed at line $LINENO (exit $code)"; exit "$code"' ERR
36
+ ${commands}
37
+ - name: Deploy to JoripSpace
38
+ shell: bash
39
+ env:
40
+ JORIPSPACE_PROJECT_ID: ${JSON.stringify(String(projectId))}
41
+ JORIPSPACE_ARTIFACT_PATH: ${JSON.stringify(String(artifactPath))}
42
+ JORIPSPACE_ENTRYPOINT: ${JSON.stringify(String(entrypoint))}
43
+ JORIPSPACE_API_URL: "https://api.joripspace.com"
44
+ run: |
45
+ set -euo pipefail
46
+ source_dir="$JORIPSPACE_ARTIFACT_PATH"
47
+ if [[ ! -d "$source_dir" ]]; then
48
+ echo "::error title=JoripSpace artifact preparation failed::JoripSpace artifact directory does not exist: $source_dir" >&2
49
+ exit 1
50
+ fi
51
+ stage_dir="$RUNNER_TEMP/joripspace-artifact-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
52
+ archive_path="$RUNNER_TEMP/joripspace-artifact-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.zip"
53
+ rm -rf "$stage_dir"
54
+ mkdir -p "$stage_dir"
55
+ cp -R "$source_dir"/. "$stage_dir"/
56
+ JORIPSPACE_STAGE_DIR="$stage_dir" node --input-type=module -e '
57
+ import { writeFile } from "node:fs/promises";
58
+ import { join } from "node:path";
59
+ const root = process.env.JORIPSPACE_STAGE_DIR;
60
+ const entrypoint = process.env.JORIPSPACE_ENTRYPOINT;
61
+ await writeFile(join(root, ".joripspace-deploy.json"), JSON.stringify({ entrypoint }) + "\\n");
62
+ '
63
+ (cd "$stage_dir" && find . -type f -exec zip -q "$archive_path" -- {} +)
64
+ JORIPSPACE_ARCHIVE_PATH="$archive_path" node --input-type=module <<'JORIPSPACE_SCRIPT'
65
+ ${deployScript}
66
+ JORIPSPACE_SCRIPT
67
+ `;
68
+ }
69
+
70
+ function projectGithubActionsTemplateFile(projectConfig = {}) {
71
+ return buildGithubWorkflow({
72
+ projectId: String(projectConfig.project_id || '__JORIPSPACE_PROJECT_ID__'),
73
+ branch: '__JORIPSPACE_BRANCH__',
74
+ buildCommand: '__JORIPSPACE_BUILD_COMMAND__',
75
+ artifactPath: '__JORIPSPACE_ARTIFACT_PATH__',
76
+ entrypoint: '__JORIPSPACE_ENTRYPOINT__',
77
+ });
78
+ }
79
+
80
+ async function inlineDeployMain() {
81
+ const { open } = await import('node:fs/promises');
82
+ const audience = 'https://api.joripspace.com/v1/external-builds/github';
83
+ const projectId = requiredEnv('JORIPSPACE_PROJECT_ID');
84
+ const archivePath = requiredEnv('JORIPSPACE_ARCHIVE_PATH');
85
+ const apiUrl = requiredEnv('JORIPSPACE_API_URL').replace(/\/+$/, '');
86
+ const oidcToken = await requestOidcToken();
87
+ const create = await api(`/v1/projects/${encodeURIComponent(projectId)}/checkpoint-uploads`, {
88
+ method: 'POST',
89
+ token: oidcToken,
90
+ json: { source_type: 'deployment' },
91
+ });
92
+ const file = await open(archivePath, 'r');
93
+ try {
94
+ const chunkSize = Number(create.chunk_size || 8 * 1024 * 1024);
95
+ const buffer = Buffer.alloc(chunkSize);
96
+ let partNumber = 1;
97
+ let position = 0;
98
+ while (true) {
99
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
100
+ if (bytesRead === 0) break;
101
+ const partPath = String(create.upload_part_url_template).replace('{part_number}', String(partNumber));
102
+ await api(partPath, {
103
+ method: 'PUT',
104
+ token: oidcToken,
105
+ body: buffer.subarray(0, bytesRead),
106
+ contentType: 'application/octet-stream',
107
+ });
108
+ position += bytesRead;
109
+ partNumber += 1;
110
+ }
111
+ if (position === 0) throw new Error('Build artifact ZIP is empty.');
112
+ } finally {
113
+ await file.close();
114
+ }
115
+ await api(create.complete_url, { method: 'POST', token: oidcToken, json: {} });
116
+ const deployPath = `/v1/projects/${encodeURIComponent(projectId)}/checkpoints/${encodeURIComponent(create.checkpoint_id)}/deploy`;
117
+ for (let attempt = 1; attempt <= 150; attempt += 1) {
118
+ const deployToken = await requestOidcToken();
119
+ const result = await api(deployPath, {
120
+ method: 'POST',
121
+ token: deployToken,
122
+ json: {},
123
+ allowedStatuses: [404, 409],
124
+ });
125
+ if (!result.__retry) {
126
+ process.stdout.write(
127
+ `JoripSpace deployment succeeded: ${result.url || result.default_url || result.deployment_id || projectId}\n`
128
+ );
129
+ return;
130
+ }
131
+ if (
132
+ !['checkpoint_not_found', 'checkpoint_not_ready', 'external_build_deploy_busy'].includes(
133
+ result.error?.code
134
+ )
135
+ ) {
136
+ throw apiError(result.__status, result);
137
+ }
138
+ await new Promise((resolve) => setTimeout(resolve, 2000));
139
+ }
140
+ throw new Error('JoripSpace artifact processing did not finish within 5 minutes.');
141
+
142
+ async function requestOidcToken() {
143
+ const requestUrl = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_URL');
144
+ const requestToken = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN');
145
+ const separator = requestUrl.includes('?') ? '&' : '?';
146
+ const response = await fetch(`${requestUrl}${separator}audience=${encodeURIComponent(audience)}`, {
147
+ headers: { Authorization: `Bearer ${requestToken}` },
148
+ });
149
+ const payload = await response.json().catch(() => ({}));
150
+ if (!response.ok || typeof payload.value !== 'string') {
151
+ throw new Error(`GitHub OIDC token request failed (${response.status}).`);
152
+ }
153
+ return payload.value;
154
+ }
155
+
156
+ async function api(path, options) {
157
+ const url = path.startsWith('http') ? path : `${apiUrl}${path}`;
158
+ const headers = new Headers({ Authorization: `Bearer ${options.token}`, Accept: 'application/json' });
159
+ let body = options.body;
160
+ if (options.json !== undefined) {
161
+ headers.set('Content-Type', 'application/json');
162
+ body = JSON.stringify(options.json);
163
+ } else if (options.contentType) headers.set('Content-Type', options.contentType);
164
+ const response = await fetch(url, { method: options.method, headers, body });
165
+ const text = await response.text();
166
+ const payload = text ? safeJson(text) : {};
167
+ if (response.ok) return payload;
168
+ if ((options.allowedStatuses || []).includes(response.status)) {
169
+ return { ...payload, __retry: true, __status: response.status };
170
+ }
171
+ throw apiError(response.status, payload);
172
+ }
173
+
174
+ function apiError(status, payload) {
175
+ const error = new Error(payload?.error?.message || `JoripSpace request failed (${status}).`);
176
+ error.code = payload?.error?.code || 'joripspace_request_failed';
177
+ const diagnostic = JSON.stringify({ http_status: status, code: error.code, message: error.message, details: payload?.error?.details || null })
178
+ .replace(/((?:authorization|[\w-]*(?:key|token|secret|password|credential)[\w-]*)["']?\s*[:=]\s*["']?)[^"'\s,}]+/gi, '$1[REDACTED]')
179
+ .replace(/Bearer\s+[^\s"']+/gi, 'Bearer [REDACTED]').slice(0, 16000);
180
+ console.error(`JORIPSPACE_DIAGNOSTIC ${diagnostic}`);
181
+ return error;
182
+ }
183
+ function safeJson(value) {
184
+ try {
185
+ return JSON.parse(value);
186
+ } catch {
187
+ return { error: { code: 'invalid_response', message: value.slice(0, 500) } };
188
+ }
189
+ }
190
+ function requiredEnv(name) {
191
+ const value = process.env[name];
192
+ if (!value) throw new Error(`${name} is required.`);
193
+ return value;
194
+ }
195
+ }
196
+
197
+ module.exports = { buildGithubWorkflow, projectGithubActionsTemplateFile };