@joripspace/cli 0.9.0 → 0.9.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joripspace/cli",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "license": "MIT",
5
5
  "description": "The official JoripSpace CLI. Build and deploy web apps with AI agents. Powered by Cosmosfarm.",
6
6
  "type": "commonjs",
@@ -0,0 +1,98 @@
1
+ function githubSourceSnapshotStep() {
2
+ const script = `${snapshotGithubSource.toString()}\n\nawait snapshotGithubSource();`
3
+ .split('\n')
4
+ .map((line) => ` ${line}`)
5
+ .join('\n');
6
+ return ` - name: Preserve original source
7
+ shell: bash
8
+ run: |
9
+ node --input-type=module <<'JORIPSPACE_SOURCE'
10
+ ${script}
11
+ JORIPSPACE_SOURCE
12
+ `;
13
+ }
14
+
15
+ const GITHUB_SOURCE_STAGE_COMMAND = ` if [[ -e "$stage_dir/.joripspace-source" || -L "$stage_dir/.joripspace-source" ]]; then
16
+ echo "::error::Artifact uses the reserved .joripspace-source path" >&2
17
+ exit 1
18
+ fi
19
+ cp -R "$RUNNER_TEMP/joripspace-source-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" "$stage_dir/.joripspace-source"`;
20
+
21
+ async function snapshotGithubSource() {
22
+ const { execFileSync, spawnSync } = await import('node:child_process');
23
+ const { lstat, mkdir, copyFile } = await import('node:fs/promises');
24
+ const { join } = await import('node:path');
25
+ const root = process.env.GITHUB_WORKSPACE;
26
+ const target = join(
27
+ process.env.RUNNER_TEMP,
28
+ `joripspace-source-${process.env.GITHUB_RUN_ID}-${process.env.GITHUB_RUN_ATTEMPT}`
29
+ );
30
+ const files = execFileSync('git', ['ls-files', '--cached', '-z'], {
31
+ cwd: root,
32
+ encoding: 'utf8',
33
+ maxBuffer: 16 * 1024 * 1024,
34
+ })
35
+ .split('\0')
36
+ .filter(Boolean);
37
+ const excluded = new Set();
38
+ for (const rules of ['.ignore', '.joripspaceignore']) {
39
+ const result = spawnSync(
40
+ 'git',
41
+ ['-c', `core.excludesFile=${join(root, rules)}`, 'check-ignore', '--no-index', '-z', '--stdin'],
42
+ {
43
+ cwd: root,
44
+ input: files.join('\0') + '\0',
45
+ encoding: 'utf8',
46
+ maxBuffer: 16 * 1024 * 1024,
47
+ }
48
+ );
49
+ if (result.error || ![0, 1].includes(result.status))
50
+ throw new Error('Original source ignore check failed.');
51
+ for (const file of result.stdout.split('\0').filter(Boolean)) excluded.add(file);
52
+ }
53
+ await mkdir(target);
54
+ for (const file of files) {
55
+ const parts = file.toLowerCase().split('/');
56
+ const base = parts.at(-1);
57
+ if (
58
+ excluded.has(file) ||
59
+ parts.some((part) =>
60
+ [
61
+ '.git',
62
+ 'node_modules',
63
+ '.wrangler',
64
+ '.cache',
65
+ 'coverage',
66
+ 'tmp',
67
+ 'temp',
68
+ '.joripspace',
69
+ '.joripspace-artifact',
70
+ '.joripspace-source',
71
+ '.agents',
72
+ '.claude',
73
+ '.codex',
74
+ '.cursor',
75
+ '.gemini',
76
+ '.opencode',
77
+ ].includes(part)
78
+ ) ||
79
+ ['agents.md', 'claude.md', '.ds_store', 'thumbs.db', 'desktop.ini'].includes(base) ||
80
+ base.startsWith('.env') ||
81
+ base.startsWith('.dev.vars') ||
82
+ /\.(?:log|tmp|temp|pem|key)$/i.test(base)
83
+ )
84
+ continue;
85
+ let source = root;
86
+ for (const part of file.split('/')) {
87
+ if (!part || part === '.' || part === '..') throw new Error('Unsafe original source path.');
88
+ source = join(source, part);
89
+ if ((await lstat(source)).isSymbolicLink())
90
+ throw new Error('Original source contains a symbolic link.');
91
+ }
92
+ if (!(await lstat(source)).isFile()) throw new Error('Original source must be a regular file.');
93
+ await mkdir(join(target, ...file.split('/').slice(0, -1)), { recursive: true });
94
+ await copyFile(source, join(target, file));
95
+ }
96
+ }
97
+
98
+ module.exports = { githubSourceSnapshotStep, GITHUB_SOURCE_STAGE_COMMAND, snapshotGithubSource };
@@ -1,210 +1,213 @@
1
- function buildGithubWorkflow({
2
- projectId,
3
- branch,
4
- triggerType = 'branch',
5
- triggerRef = branch,
6
- connectionId = 'legacy',
7
- buildCommand,
8
- artifactPath,
9
- entrypoint,
10
- }) {
11
- const commands = String(buildCommand)
12
- .split('\n')
13
- .map((line) => ` ${line}`)
14
- .join('\n');
15
- const deployScript = `${inlineDeployMain.toString()}\n\nawait inlineDeployMain();`
16
- .split('\n')
17
- .map((line) => ` ${line}`)
18
- .join('\n');
19
- const trigger =
20
- triggerType === 'release'
21
- ? ` release:\n types:\n - published`
22
- : ` push:\n branches:\n - ${JSON.stringify(String(triggerRef || branch))}\n workflow_dispatch:`;
23
- return `# joripspace-workflow-version: 8
24
- name: JoripSpace Deploy ${JSON.stringify(`(${connectionId})`)}
25
-
26
- on:
27
- ${trigger}
28
-
29
- permissions:
30
- contents: read
31
- id-token: write
32
-
33
- concurrency:
34
- group: ${JSON.stringify(`joripspace-${String(projectId)}-${String(connectionId)}`)}
35
- cancel-in-progress: true
36
-
37
- jobs:
38
- deploy:
39
- runs-on: ubuntu-latest
40
- steps:
41
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
42
- - name: Build
43
- run: |
44
- set -Eeuo pipefail
45
- trap 'code=$?; echo "::error title=JoripSpace build failed::Build failed at line $LINENO (exit $code)"; exit "$code"' ERR
46
- ${commands}
47
- - name: Deploy to JoripSpace
48
- shell: bash
49
- env:
50
- JORIPSPACE_PROJECT_ID: ${JSON.stringify(String(projectId))}
51
- JORIPSPACE_CONNECTION_ID: ${JSON.stringify(String(connectionId))}
52
- JORIPSPACE_ARTIFACT_PATH: ${JSON.stringify(String(artifactPath))}
53
- JORIPSPACE_ENTRYPOINT: ${JSON.stringify(String(entrypoint))}
54
- JORIPSPACE_API_URL: "https://api.joripspace.com"
55
- run: |
56
- set -euo pipefail
57
- source_dir="$JORIPSPACE_ARTIFACT_PATH"
58
- if [[ ! -d "$source_dir" ]]; then
59
- echo "::error title=JoripSpace artifact preparation failed::JoripSpace artifact directory does not exist: $source_dir" >&2
60
- exit 1
61
- fi
62
- stage_dir="$RUNNER_TEMP/joripspace-artifact-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
63
- archive_path="$RUNNER_TEMP/joripspace-artifact-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.zip"
64
- rm -rf "$stage_dir"
65
- mkdir -p "$stage_dir"
66
- cp -R "$source_dir"/. "$stage_dir"/
67
- JORIPSPACE_STAGE_DIR="$stage_dir" node --input-type=module -e '
68
- import { writeFile } from "node:fs/promises";
69
- import { join } from "node:path";
70
- const root = process.env.JORIPSPACE_STAGE_DIR;
71
- const entrypoint = process.env.JORIPSPACE_ENTRYPOINT;
72
- await writeFile(join(root, ".joripspace-deploy.json"), JSON.stringify({ entrypoint }) + "\\n");
73
- '
74
- (cd "$stage_dir" && find . -type f -exec zip -q "$archive_path" -- {} +)
75
- JORIPSPACE_ARCHIVE_PATH="$archive_path" node --input-type=module <<'JORIPSPACE_SCRIPT'
76
- ${deployScript}
77
- JORIPSPACE_SCRIPT
78
- `;
79
- }
80
-
81
- function projectGithubActionsTemplateFile(projectConfig = {}) {
82
- return buildGithubWorkflow({
83
- projectId: String(projectConfig.project_id || '__JORIPSPACE_PROJECT_ID__'),
84
- branch: '__JORIPSPACE_BRANCH__',
85
- buildCommand: '__JORIPSPACE_BUILD_COMMAND__',
86
- artifactPath: '__JORIPSPACE_ARTIFACT_PATH__',
87
- entrypoint: '__JORIPSPACE_ENTRYPOINT__',
88
- });
89
- }
90
-
91
- async function inlineDeployMain() {
92
- const { open } = await import('node:fs/promises');
93
- const audience = 'https://api.joripspace.com/v1/external-builds/github';
94
- const projectId = requiredEnv('JORIPSPACE_PROJECT_ID');
95
- const connectionId = String(process.env.JORIPSPACE_CONNECTION_ID || '').trim();
96
- const archivePath = requiredEnv('JORIPSPACE_ARCHIVE_PATH');
97
- const apiUrl = requiredEnv('JORIPSPACE_API_URL').replace(/\/+$/, '');
98
- const oidcToken = await requestOidcToken();
99
- const create = await api(`/v1/projects/${encodeURIComponent(projectId)}/checkpoint-uploads`, {
100
- method: 'POST',
101
- token: oidcToken,
102
- json: { source_type: 'deployment' },
103
- });
104
- const file = await open(archivePath, 'r');
105
- try {
106
- const chunkSize = Number(create.chunk_size || 8 * 1024 * 1024);
107
- const buffer = Buffer.alloc(chunkSize);
108
- let partNumber = 1;
109
- let position = 0;
110
- while (true) {
111
- const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
112
- if (bytesRead === 0) break;
113
- const partPath = String(create.upload_part_url_template).replace('{part_number}', String(partNumber));
114
- await api(partPath, {
115
- method: 'PUT',
116
- token: oidcToken,
117
- body: buffer.subarray(0, bytesRead),
118
- contentType: 'application/octet-stream',
119
- });
120
- position += bytesRead;
121
- partNumber += 1;
122
- }
123
- if (position === 0) throw new Error('Build artifact ZIP is empty.');
124
- } finally {
125
- await file.close();
126
- }
127
- await api(create.complete_url, { method: 'POST', token: oidcToken, json: {} });
128
- const deployPath = `/v1/projects/${encodeURIComponent(projectId)}/checkpoints/${encodeURIComponent(create.checkpoint_id)}/deploy`;
129
- for (let attempt = 1; attempt <= 150; attempt += 1) {
130
- const deployToken = await requestOidcToken();
131
- const result = await api(deployPath, {
132
- method: 'POST',
133
- token: deployToken,
134
- json: {},
135
- allowedStatuses: [404, 409],
136
- });
137
- if (!result.__retry) {
138
- process.stdout.write(
139
- `JoripSpace deployment succeeded: ${result.url || result.default_url || result.deployment_id || projectId}\n`
140
- );
141
- return;
142
- }
143
- if (
144
- !['checkpoint_not_found', 'checkpoint_not_ready', 'external_build_deploy_busy'].includes(
145
- result.error?.code
146
- )
147
- ) {
148
- throw apiError(result.__status, result);
149
- }
150
- await new Promise((resolve) => setTimeout(resolve, 2000));
151
- }
152
- throw new Error('JoripSpace artifact processing did not finish within 5 minutes.');
153
-
154
- async function requestOidcToken() {
155
- const requestUrl = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_URL');
156
- const requestToken = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN');
157
- const separator = requestUrl.includes('?') ? '&' : '?';
158
- const response = await fetch(`${requestUrl}${separator}audience=${encodeURIComponent(audience)}`, {
159
- headers: { Authorization: `Bearer ${requestToken}` },
160
- });
161
- const payload = await response.json().catch(() => ({}));
162
- if (!response.ok || typeof payload.value !== 'string') {
163
- throw new Error(`GitHub OIDC token request failed (${response.status}).`);
164
- }
165
- return payload.value;
166
- }
167
-
168
- async function api(path, options) {
169
- const url = path.startsWith('http') ? path : `${apiUrl}${path}`;
170
- const headers = new Headers({ Authorization: `Bearer ${options.token}`, Accept: 'application/json' });
171
- if (connectionId) headers.set('X-JoripSpace-Connection-ID', connectionId);
172
- let body = options.body;
173
- if (options.json !== undefined) {
174
- headers.set('Content-Type', 'application/json');
175
- body = JSON.stringify(options.json);
176
- } else if (options.contentType) headers.set('Content-Type', options.contentType);
177
- const response = await fetch(url, { method: options.method, headers, body });
178
- const text = await response.text();
179
- const payload = text ? safeJson(text) : {};
180
- if (response.ok) return payload;
181
- if ((options.allowedStatuses || []).includes(response.status)) {
182
- return { ...payload, __retry: true, __status: response.status };
183
- }
184
- throw apiError(response.status, payload);
185
- }
186
-
187
- function apiError(status, payload) {
188
- const error = new Error(payload?.error?.message || `JoripSpace request failed (${status}).`);
189
- error.code = payload?.error?.code || 'joripspace_request_failed';
190
- const diagnostic = JSON.stringify({ http_status: status, code: error.code, message: error.message, details: payload?.error?.details || null })
191
- .replace(/((?:authorization|[\w-]*(?:key|token|secret|password|credential)[\w-]*)["']?\s*[:=]\s*["']?)[^"'\s,}]+/gi, '$1[REDACTED]')
192
- .replace(/Bearer\s+[^\s"']+/gi, 'Bearer [REDACTED]').slice(0, 16000);
193
- console.error(`JORIPSPACE_DIAGNOSTIC ${diagnostic}`);
194
- return error;
195
- }
196
- function safeJson(value) {
197
- try {
198
- return JSON.parse(value);
199
- } catch {
200
- return { error: { code: 'invalid_response', message: value.slice(0, 500) } };
201
- }
202
- }
203
- function requiredEnv(name) {
204
- const value = process.env[name];
205
- if (!value) throw new Error(`${name} is required.`);
206
- return value;
207
- }
208
- }
209
-
210
- module.exports = { buildGithubWorkflow, projectGithubActionsTemplateFile };
1
+ const { githubSourceSnapshotStep, GITHUB_SOURCE_STAGE_COMMAND } = require('./github-source.cjs');
2
+
3
+ function buildGithubWorkflow({
4
+ projectId,
5
+ branch,
6
+ triggerType = 'branch',
7
+ triggerRef = branch,
8
+ connectionId = 'legacy',
9
+ buildCommand,
10
+ artifactPath,
11
+ entrypoint,
12
+ }) {
13
+ const commands = String(buildCommand)
14
+ .split('\n')
15
+ .map((line) => ` ${line}`)
16
+ .join('\n');
17
+ const deployScript = `${inlineDeployMain.toString()}\n\nawait inlineDeployMain();`
18
+ .split('\n')
19
+ .map((line) => ` ${line}`)
20
+ .join('\n');
21
+ const trigger =
22
+ triggerType === 'release'
23
+ ? ` release:\n types:\n - published`
24
+ : ` push:\n branches:\n - ${JSON.stringify(String(triggerRef || branch))}\n workflow_dispatch:`;
25
+ return `# joripspace-workflow-version: 9
26
+ name: JoripSpace Deploy ${JSON.stringify(`(${connectionId})`)}
27
+
28
+ on:
29
+ ${trigger}
30
+
31
+ permissions:
32
+ contents: read
33
+ id-token: write
34
+
35
+ concurrency:
36
+ group: ${JSON.stringify(`joripspace-${String(projectId)}-${String(connectionId)}`)}
37
+ cancel-in-progress: true
38
+
39
+ jobs:
40
+ deploy:
41
+ runs-on: ubuntu-latest
42
+ steps:
43
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
44
+ ${githubSourceSnapshotStep()} - name: Build
45
+ run: |
46
+ set -Eeuo pipefail
47
+ trap 'code=$?; echo "::error title=JoripSpace build failed::Build failed at line $LINENO (exit $code)"; exit "$code"' ERR
48
+ ${commands}
49
+ - name: Deploy to JoripSpace
50
+ shell: bash
51
+ env:
52
+ JORIPSPACE_PROJECT_ID: ${JSON.stringify(String(projectId))}
53
+ JORIPSPACE_CONNECTION_ID: ${JSON.stringify(String(connectionId))}
54
+ JORIPSPACE_ARTIFACT_PATH: ${JSON.stringify(String(artifactPath))}
55
+ JORIPSPACE_ENTRYPOINT: ${JSON.stringify(String(entrypoint))}
56
+ JORIPSPACE_API_URL: "https://api.joripspace.com"
57
+ run: |
58
+ set -euo pipefail
59
+ source_dir="$JORIPSPACE_ARTIFACT_PATH"
60
+ if [[ ! -d "$source_dir" ]]; then
61
+ echo "::error title=JoripSpace artifact preparation failed::JoripSpace artifact directory does not exist: $source_dir" >&2
62
+ exit 1
63
+ fi
64
+ stage_dir="$RUNNER_TEMP/joripspace-artifact-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
65
+ archive_path="$RUNNER_TEMP/joripspace-artifact-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.zip"
66
+ rm -rf "$stage_dir"
67
+ mkdir -p "$stage_dir"
68
+ cp -R "$source_dir"/. "$stage_dir"/
69
+ ${GITHUB_SOURCE_STAGE_COMMAND}
70
+ JORIPSPACE_STAGE_DIR="$stage_dir" node --input-type=module -e '
71
+ import { writeFile } from "node:fs/promises";
72
+ import { join } from "node:path";
73
+ const root = process.env.JORIPSPACE_STAGE_DIR;
74
+ const entrypoint = process.env.JORIPSPACE_ENTRYPOINT;
75
+ await writeFile(join(root, ".joripspace-deploy.json"), JSON.stringify({ entrypoint }) + "\\n");
76
+ '
77
+ (cd "$stage_dir" && find . -type f -exec zip -q "$archive_path" -- {} +)
78
+ JORIPSPACE_ARCHIVE_PATH="$archive_path" node --input-type=module <<'JORIPSPACE_SCRIPT'
79
+ ${deployScript}
80
+ JORIPSPACE_SCRIPT
81
+ `;
82
+ }
83
+
84
+ function projectGithubActionsTemplateFile(projectConfig = {}) {
85
+ return buildGithubWorkflow({
86
+ projectId: String(projectConfig.project_id || '__JORIPSPACE_PROJECT_ID__'),
87
+ branch: '__JORIPSPACE_BRANCH__',
88
+ buildCommand: '__JORIPSPACE_BUILD_COMMAND__',
89
+ artifactPath: '__JORIPSPACE_ARTIFACT_PATH__',
90
+ entrypoint: '__JORIPSPACE_ENTRYPOINT__',
91
+ });
92
+ }
93
+
94
+ async function inlineDeployMain() {
95
+ const { open } = await import('node:fs/promises');
96
+ const audience = 'https://api.joripspace.com/v1/external-builds/github';
97
+ const projectId = requiredEnv('JORIPSPACE_PROJECT_ID');
98
+ const connectionId = String(process.env.JORIPSPACE_CONNECTION_ID || '').trim();
99
+ const archivePath = requiredEnv('JORIPSPACE_ARCHIVE_PATH');
100
+ const apiUrl = requiredEnv('JORIPSPACE_API_URL').replace(/\/+$/, '');
101
+ const oidcToken = await requestOidcToken();
102
+ const create = await api(`/v1/projects/${encodeURIComponent(projectId)}/checkpoint-uploads`, {
103
+ method: 'POST',
104
+ token: oidcToken,
105
+ json: { source_type: 'deployment' },
106
+ });
107
+ const file = await open(archivePath, 'r');
108
+ try {
109
+ const chunkSize = Number(create.chunk_size || 8 * 1024 * 1024);
110
+ const buffer = Buffer.alloc(chunkSize);
111
+ let partNumber = 1;
112
+ let position = 0;
113
+ while (true) {
114
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
115
+ if (bytesRead === 0) break;
116
+ const partPath = String(create.upload_part_url_template).replace('{part_number}', String(partNumber));
117
+ await api(partPath, {
118
+ method: 'PUT',
119
+ token: oidcToken,
120
+ body: buffer.subarray(0, bytesRead),
121
+ contentType: 'application/octet-stream',
122
+ });
123
+ position += bytesRead;
124
+ partNumber += 1;
125
+ }
126
+ if (position === 0) throw new Error('Build artifact ZIP is empty.');
127
+ } finally {
128
+ await file.close();
129
+ }
130
+ await api(create.complete_url, { method: 'POST', token: oidcToken, json: {} });
131
+ const deployPath = `/v1/projects/${encodeURIComponent(projectId)}/checkpoints/${encodeURIComponent(create.checkpoint_id)}/deploy`;
132
+ for (let attempt = 1; attempt <= 150; attempt += 1) {
133
+ const deployToken = await requestOidcToken();
134
+ const result = await api(deployPath, {
135
+ method: 'POST',
136
+ token: deployToken,
137
+ json: {},
138
+ allowedStatuses: [404, 409],
139
+ });
140
+ if (!result.__retry) {
141
+ process.stdout.write(
142
+ `JoripSpace deployment succeeded: ${result.url || result.default_url || result.deployment_id || projectId}\n`
143
+ );
144
+ return;
145
+ }
146
+ if (
147
+ !['checkpoint_not_found', 'checkpoint_not_ready', 'external_build_deploy_busy'].includes(
148
+ result.error?.code
149
+ )
150
+ ) {
151
+ throw apiError(result.__status, result);
152
+ }
153
+ await new Promise((resolve) => setTimeout(resolve, 2000));
154
+ }
155
+ throw new Error('JoripSpace artifact processing did not finish within 5 minutes.');
156
+
157
+ async function requestOidcToken() {
158
+ const requestUrl = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_URL');
159
+ const requestToken = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN');
160
+ const separator = requestUrl.includes('?') ? '&' : '?';
161
+ const response = await fetch(`${requestUrl}${separator}audience=${encodeURIComponent(audience)}`, {
162
+ headers: { Authorization: `Bearer ${requestToken}` },
163
+ });
164
+ const payload = await response.json().catch(() => ({}));
165
+ if (!response.ok || typeof payload.value !== 'string') {
166
+ throw new Error(`GitHub OIDC token request failed (${response.status}).`);
167
+ }
168
+ return payload.value;
169
+ }
170
+
171
+ async function api(path, options) {
172
+ const url = path.startsWith('http') ? path : `${apiUrl}${path}`;
173
+ const headers = new Headers({ Authorization: `Bearer ${options.token}`, Accept: 'application/json' });
174
+ if (connectionId) headers.set('X-JoripSpace-Connection-ID', connectionId);
175
+ let body = options.body;
176
+ if (options.json !== undefined) {
177
+ headers.set('Content-Type', 'application/json');
178
+ body = JSON.stringify(options.json);
179
+ } else if (options.contentType) headers.set('Content-Type', options.contentType);
180
+ const response = await fetch(url, { method: options.method, headers, body });
181
+ const text = await response.text();
182
+ const payload = text ? safeJson(text) : {};
183
+ if (response.ok) return payload;
184
+ if ((options.allowedStatuses || []).includes(response.status)) {
185
+ return { ...payload, __retry: true, __status: response.status };
186
+ }
187
+ throw apiError(response.status, payload);
188
+ }
189
+
190
+ function apiError(status, payload) {
191
+ const error = new Error(payload?.error?.message || `JoripSpace request failed (${status}).`);
192
+ error.code = payload?.error?.code || 'joripspace_request_failed';
193
+ const diagnostic = JSON.stringify({ http_status: status, code: error.code, message: error.message, details: payload?.error?.details || null })
194
+ .replace(/((?:authorization|[\w-]*(?:key|token|secret|password|credential)[\w-]*)["']?\s*[:=]\s*["']?)[^"'\s,}]+/gi, '$1[REDACTED]')
195
+ .replace(/Bearer\s+[^\s"']+/gi, 'Bearer [REDACTED]').slice(0, 16000);
196
+ console.error(`JORIPSPACE_DIAGNOSTIC ${diagnostic}`);
197
+ return error;
198
+ }
199
+ function safeJson(value) {
200
+ try {
201
+ return JSON.parse(value);
202
+ } catch {
203
+ return { error: { code: 'invalid_response', message: value.slice(0, 500) } };
204
+ }
205
+ }
206
+ function requiredEnv(name) {
207
+ const value = process.env[name];
208
+ if (!value) throw new Error(`${name} is required.`);
209
+ return value;
210
+ }
211
+ }
212
+
213
+ module.exports = { buildGithubWorkflow, projectGithubActionsTemplateFile };