@joripspace/cli 0.5.6 → 0.5.8

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.
@@ -1,3 +1,4 @@
1
+ const { message } = require('./locale');
1
2
  const fs = require('node:fs');
2
3
  const path = require('node:path');
3
4
  const { resolveProjectRoot, startProject, createStartOnboarding } = require('./start');
@@ -55,7 +56,10 @@ function createStartProjectCommand(
55
56
  cwd,
56
57
  executable,
57
58
  connect_url: 'https://joripspace.com/connect/',
58
- message: '브라우저에서 연결을 승인하고 표시된 5분 일회용 연결 코드를 먼저 교환하세요.',
59
+ message: message(
60
+ 'Approve the connection in your browser and exchange the displayed five-minute one-time code first.',
61
+ '브라우저에서 연결을 승인하고 표시된 5분 일회용 연결 코드를 먼저 교환하세요.'
62
+ ),
59
63
  login_command: loginCommand,
60
64
  resume_command: resumeCommand,
61
65
  next_action: 'run-login-command-then-resume-command',
@@ -80,7 +84,7 @@ function createStartProjectCommand(
80
84
  executable,
81
85
  allowLegacyCredentialSession: connection.source === 'legacy-project-session',
82
86
  beforeWorkspaceMigration: persistConnection
83
- ? () => persistConnection(resolvedFlags, connection)
87
+ ? (context) => persistConnection(resolvedFlags, connection, context)
84
88
  : undefined,
85
89
  }).catch((error) => {
86
90
  error.details = {
@@ -119,7 +123,9 @@ function createStartProjectCommand(
119
123
  for (const file of result.onboarding.read_files) console.log(file);
120
124
  console.log('Use --json for the inline guide and executable/argument objects for this session.');
121
125
  if (result.template_choice?.status === 'ready') {
122
- console.log(`Templates: ${result.template_choice.templates.length} available plus no-template option`);
126
+ console.log(
127
+ `Templates: ${result.template_choice.templates.length} available plus no-template option`
128
+ );
123
129
  }
124
130
  if (result.context?.source_sync?.operation === 'deployment_restore') {
125
131
  console.log('Latest deployment source restored with conflict backups.');
package/lib/start.js CHANGED
@@ -170,7 +170,7 @@ async function startProject(options) {
170
170
 
171
171
  const existingWorkBeforeGuidance = workspaceHasApplicationFiles(workspace);
172
172
  if (options.beforeWorkspaceMigration) {
173
- await Promise.resolve(options.beforeWorkspaceMigration({ project: projectSlug, workspace }));
173
+ await Promise.resolve(options.beforeWorkspaceMigration({ project: projectSlug, workspace, accountId: projectsContext.account_id }));
174
174
  }
175
175
  const migrationState = inspectProjectWorkspace(workspace, projectSlug, {
176
176
  allowLegacyCredentialSession: options.allowLegacyCredentialSession === true,
@@ -4,6 +4,11 @@ const os = require('node:os');
4
4
  const path = require('node:path');
5
5
  const { spawnSync } = require('node:child_process');
6
6
  const zlib = require('node:zlib');
7
+ const {
8
+ assertNonOverlappingFilePlan,
9
+ resolveProjectFileTarget,
10
+ safeProjectRelativePath,
11
+ } = require('./project-paths');
7
12
 
8
13
  function createTemplateCommands(deps) {
9
14
  async function list(flags) {
@@ -749,19 +754,28 @@ function parseArchive(archive) {
749
754
  }
750
755
 
751
756
  function writeFiles(targetDir, files, force) {
752
- const collisions = files
753
- .map((file) => path.resolve(targetDir, ...file.path.split('/')))
754
- .filter(fs.existsSync);
757
+ assertNonOverlappingFilePlan(files.map((file) => safePath(file.path)));
758
+ fs.mkdirSync(targetDir, { recursive: true });
759
+ const resolve = (file) => {
760
+ const location = resolveProjectFileTarget(targetDir, file.path, 'unsafe template path');
761
+ if (location.blockers.length) throw new Error(`template path is blocked: ${file.path}`);
762
+ return location.target;
763
+ };
764
+ const collisions = files.map(resolve).filter(fs.existsSync);
755
765
  if (collisions.length && !force)
756
766
  throw new Error(`template would overwrite ${collisions.length} existing file(s). Re-run with --force.`);
757
- fs.mkdirSync(targetDir, { recursive: true });
758
767
  for (const file of files) {
759
- const outputPath = path.resolve(targetDir, ...file.path.split('/'));
760
- const relative = path.relative(targetDir, outputPath);
761
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
762
- throw new Error('unsafe template path');
768
+ const outputPath = resolve(file);
763
769
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
764
- fs.writeFileSync(outputPath, file.data, { mode: file.mode & 0o111 ? 0o755 : 0o644 });
770
+ const temporary = path.join(path.dirname(outputPath), `.joripspace-template-${crypto.randomUUID()}.tmp`);
771
+ try {
772
+ fs.writeFileSync(temporary, file.data, { flag: 'wx', mode: file.mode & 0o111 ? 0o755 : 0o644 });
773
+ resolve(file);
774
+ if (!force && fs.existsSync(outputPath)) throw new Error('template would overwrite an existing file');
775
+ fs.renameSync(temporary, outputPath);
776
+ } finally {
777
+ fs.rmSync(temporary, { force: true });
778
+ }
765
779
  }
766
780
  }
767
781
 
@@ -789,17 +803,7 @@ function stripRoot(value) {
789
803
  return parts.length > 1 ? parts.slice(1).join('/') : '';
790
804
  }
791
805
  function safePath(value) {
792
- const normalized = String(value || '')
793
- .replace(/\\/g, '/')
794
- .replace(/^\.\//, '');
795
- const parts = normalized.split('/');
796
- if (
797
- !normalized ||
798
- normalized.startsWith('/') ||
799
- parts.some((part) => !part || part === '.' || part === '..')
800
- )
801
- throw new Error('template contains an unsafe path');
802
- return normalized;
806
+ return safeProjectRelativePath(value, 'template contains an unsafe path');
803
807
  }
804
808
  function normalizeSourceRoot(value) {
805
809
  const normalized = String(value || '.')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joripspace/cli",
3
- "version": "0.5.6",
3
+ "version": "0.5.8",
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",
@@ -39,8 +39,10 @@
39
39
  "prepack": "node scripts/check-package.mjs"
40
40
  },
41
41
  "dependencies": {
42
+ "@napi-rs/keyring": "2.1.2",
42
43
  "fflate": "^0.8.2",
44
+ "ignore": "7.0.12",
43
45
  "jsonc-parser": "^3.3.1",
44
- "smol-toml": "^1.7.2"
46
+ "smol-toml": "^1.9.1"
45
47
  }
46
48
  }
@@ -10,10 +10,11 @@ const JORIPSPACE_CLI_GUIDE = [
10
10
  '## Workspace and connection',
11
11
  '',
12
12
  'Use the project name supplied by the user. The connection flow does not create a missing project. Use the current Git root when one exists, otherwise the current working directory; use --cwd to specify the intended workspace. Never use the npm cache or package installation folder as the project workspace.',
13
+ "Only when the user explicitly requests a new Free project, run create --name NAME --json. Present every returned agreement faithfully in the user's language, link to the terms, and obtain explicit consent before passing --agree-noncommercial --agree-billing --agree-retention. Never infer agreement from the creation request. start never creates a project, and create does not link the workspace. If creation state is unknown, list projects and check the name before retrying.",
13
14
  'The JoripSpace project is stored in `.joripspace/project`. Resolve different or invalid markers, symlinks, and conflicting local work without overwriting user files.',
14
15
  'Use the installed JoripSpace CLI for JoripSpace infrastructure, domains, and deployment. Do not configure or wait for MCP. Existing MCP integrations remain available for users who choose that workflow; this start session continues through the CLI.',
15
- 'When start returns connection_required, show connect_url as a clickable link, ask the user to approve the connection and provide the five-minute one-time code, then execute login_command and resume_command. Never request or print the exchanged token. Reuse the existing connection on later runs.',
16
- 'Authentication is stored only in `.env.joripspace`, which is Git-ignored and excluded from deployments and checkpoints. Do not copy credentials into documents, skills, logs, or source code.',
16
+ 'When start returns connection_required, show connect_url as a clickable link, ask the user to approve the connection and provide the five-minute one-time code, then execute login_command and resume_command. A successful connection also logs in; do not add a separate login step. Never request or print the exchanged token. Reuse the existing connection on later runs. Use logout to remove the current local login without revoking server tokens.',
17
+ 'New CLI logins keep tokens in the OS credential store and reuse them across project folders for the same OS user. `.env.joripspace` keeps only the API URL and account reference for new logins. Older CLI versions and existing token-bearing `.env.joripspace` files remain supported; keep that file Git-ignored and excluded from deployments and checkpoints. Do not copy credentials into documents, skills, logs, or source code.',
17
18
  '',
18
19
  '## Execute commands reliably',
19
20
  '',
@@ -1,169 +1,169 @@
1
- function buildTemplatePublishWorkflow({
2
- templateId,
3
- branch = 'main',
4
- manifestPath = 'joripspace-template.json',
5
- }) {
6
- const publishScript = `${inlineTemplatePublishMain.toString()}\n\nawait inlineTemplatePublishMain();`
7
- .split('\n')
8
- .map((line) => ` ${line}`)
9
- .join('\n');
10
- return `# joripspace-template-workflow-version: 3
11
- #
12
- # JoripSpace 템플릿 배포 가이드
13
- # 1. 이 파일과 joripspace-template.json이 추가된 설정 PR을 기본 브랜치에 병합합니다.
14
- # 2. GitHub 저장소의 Releases에서 배포할 버전 태그를 만들고 Release를 Publish합니다.
15
- # 3. Release 태그가 조립스페이스에 표시되는 공식 버전이 됩니다. 예: 1.0.1 또는 v1.0.1
16
- # 4. Actions 탭의 "JoripSpace Template Publish" 작업이 초록색으로 완료되는지 확인합니다.
17
- #
18
- # 알아두세요
19
- # - 일반 push나 Release 초안 저장만으로는 배포되지 않습니다. Published Release만 배포됩니다.
20
- # - 별도 API 키나 Secret은 필요하지 않습니다. GitHub OIDC로 저장소와 Release를 검증합니다.
21
- # - Release 태그는 아래에 지정된 기준 브랜치에 포함된 커밋을 가리켜야 합니다.
22
- # - 오류가 나면 Actions 실행에서 실패한 단계와 메시지를 먼저 확인하세요.
23
- # - 이 워크플로와 joripspace-template.json을 삭제하면 이후 업데이트를 배포할 수 없습니다.
24
- name: JoripSpace Template Publish
25
-
26
- on:
27
- release:
28
- types: [published]
29
-
30
- permissions:
31
- contents: read
32
- id-token: write
33
-
34
- concurrency:
35
- group: ${JSON.stringify(`joripspace-template-${String(templateId)}`)}
36
- cancel-in-progress: false
37
-
38
- jobs:
39
- publish:
40
- runs-on: ubuntu-latest
41
- steps:
42
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
43
- with:
44
- fetch-depth: 0
45
- - name: Build Git Bundle and files archive
46
- shell: bash
47
- env:
48
- JORIPSPACE_TEMPLATE_ID: ${JSON.stringify(String(templateId))}
49
- JORIPSPACE_MANIFEST_PATH: ${JSON.stringify(String(manifestPath))}
50
- JORIPSPACE_SOURCE_BRANCH: ${JSON.stringify(String(branch))}
51
- run: |
52
- set -euo pipefail
53
- manifest="$GITHUB_WORKSPACE/$JORIPSPACE_MANIFEST_PATH"
54
- test -f "$manifest" || { echo "joripspace-template.json is required" >&2; exit 1; }
55
- git show-ref --verify --quiet "refs/remotes/origin/$JORIPSPACE_SOURCE_BRANCH" || { echo "Registered source branch was not fetched" >&2; exit 1; }
56
- git merge-base --is-ancestor "$GITHUB_SHA" "refs/remotes/origin/$JORIPSPACE_SOURCE_BRANCH" || { echo "Release tag must point to a commit on the registered source branch" >&2; exit 1; }
57
- source_root=$(node -e 'const m=require(process.argv[1]); const v=String(m.source_root || "."); if (v !== "." && (v.startsWith("/") || v.includes("\\\\") || v.split("/").some((p) => !p || p === "." || p === ".."))) throw new Error("Unsafe source_root"); process.stdout.write(v)' "$manifest")
58
- if [[ "$source_root" == "." ]]; then
59
- distribution_sha="$GITHUB_SHA"
60
- else
61
- distribution_sha=$(git subtree split --prefix="$source_root" "$GITHUB_SHA")
62
- fi
63
- if git ls-tree -r "$distribution_sha" | grep -Eq '^(120000|160000) '; then
64
- echo "Symlinks and submodules are not allowed in a template release" >&2
65
- exit 1
66
- fi
67
- bare="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.git"
68
- bundle="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.bundle"
69
- archive="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.tar.gz"
70
- stage="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-stage"
71
- git init --bare "$bare"
72
- git push "$bare" "$distribution_sha:refs/heads/main"
73
- git --git-dir="$bare" bundle create --version=2 "$bundle" refs/heads/main
74
- git --git-dir="$bare" bundle verify "$bundle"
75
- mkdir -p "$stage/release"
76
- if [[ "$source_root" == "." ]]; then
77
- git archive "$GITHUB_SHA" | tar -x -C "$stage/release"
78
- else
79
- mkdir -p "$stage/release/$source_root"
80
- git archive "$GITHUB_SHA:$source_root" | tar -x -C "$stage/release/$source_root"
81
- fi
82
- cp "$manifest" "$stage/release/joripspace-template.json"
83
- tar -czf "$archive" -C "$stage" release
84
- file_count=$(git ls-tree -r --name-only "$distribution_sha" | wc -l | tr -d ' ')
85
- source_bytes=$(git ls-tree -r -l "$distribution_sha" | awk '{ total += $4 } END { print total + 0 }')
86
- echo "JORIPSPACE_BUNDLE_PATH=$bundle" >> "$GITHUB_ENV"
87
- echo "JORIPSPACE_ARCHIVE_PATH=$archive" >> "$GITHUB_ENV"
88
- echo "JORIPSPACE_MANIFEST_PATH=$manifest" >> "$GITHUB_ENV"
89
- echo "JORIPSPACE_FILE_COUNT=$file_count" >> "$GITHUB_ENV"
90
- echo "JORIPSPACE_SOURCE_BYTES=$source_bytes" >> "$GITHUB_ENV"
91
- - name: Publish to JoripSpace
92
- shell: bash
93
- env:
94
- JORIPSPACE_TEMPLATE_ID: ${JSON.stringify(String(templateId))}
95
- JORIPSPACE_API_URL: "https://api.joripspace.com"
96
- run: |
97
- set -euo pipefail
98
- node --input-type=module <<'JORIPSPACE_SCRIPT'
99
- // Cloudflare's production bundler may annotate nested function names with
100
- // __name(). Keep the generated standalone Node script compatible with it.
101
- const __name = (value) => value;
102
- ${publishScript}
103
- JORIPSPACE_SCRIPT
104
- `;
105
- }
106
-
107
- async function inlineTemplatePublishMain() {
108
- const { readFile } = await import('node:fs/promises');
109
- const audience = 'https://api.joripspace.com/v1/template-publish/github';
110
- const templateId = requiredEnv('JORIPSPACE_TEMPLATE_ID');
111
- const apiUrl = requiredEnv('JORIPSPACE_API_URL').replace(/\/+$/, '');
112
- const [bundle, archive, manifest] = await Promise.all([
113
- readFile(requiredEnv('JORIPSPACE_BUNDLE_PATH')),
114
- readFile(requiredEnv('JORIPSPACE_ARCHIVE_PATH')),
115
- readFile(requiredEnv('JORIPSPACE_MANIFEST_PATH')),
116
- ]);
117
- const form = new FormData();
118
- form.append('bundle', new Blob([bundle], { type: 'application/x-git-bundle' }), 'template.bundle');
119
- form.append('archive', new Blob([archive], { type: 'application/gzip' }), 'template.tar.gz');
120
- form.append('manifest', new Blob([manifest], { type: 'application/json' }), 'joripspace-template.json');
121
- form.append('file_count', requiredEnv('JORIPSPACE_FILE_COUNT'));
122
- form.append('source_bytes', requiredEnv('JORIPSPACE_SOURCE_BYTES'));
123
- const token = await requestOidcToken();
124
- const response = await fetch(`${apiUrl}/v1/template-publish/${encodeURIComponent(templateId)}/versions`, {
125
- method: 'POST',
126
- headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
127
- body: form,
128
- });
129
- const text = await response.text();
130
- const payload = text ? safeJson(text) : {};
131
- if (!response.ok)
132
- throw new Error(payload?.error?.message || `JoripSpace publish failed (${response.status}).`);
133
- process.stdout.write(`JoripSpace template published: ${payload.version || payload.version_id}\n`);
134
-
135
- async function requestOidcToken() {
136
- const requestUrl = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_URL');
137
- const requestToken = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN');
138
- const separator = requestUrl.includes('?') ? '&' : '?';
139
- const response = await fetch(`${requestUrl}${separator}audience=${encodeURIComponent(audience)}`, {
140
- headers: { Authorization: `Bearer ${requestToken}` },
141
- });
142
- const payload = await response.json().catch(() => ({}));
143
- if (!response.ok || typeof payload.value !== 'string')
144
- throw new Error(`GitHub OIDC token request failed (${response.status}).`);
145
- return payload.value;
146
- }
147
- function safeJson(value) {
148
- try {
149
- return JSON.parse(value);
150
- } catch {
151
- return { error: { message: value.slice(0, 500) } };
152
- }
153
- }
154
- function requiredEnv(name) {
155
- const value = process.env[name];
156
- if (!value) throw new Error(`${name} is required.`);
157
- return value;
158
- }
159
- }
160
-
161
- function templateGithubActionsPublishFile(templateConfig = {}) {
162
- return buildTemplatePublishWorkflow({
163
- templateId: String(templateConfig.template_id || '__JORIPSPACE_TEMPLATE_ID__'),
164
- branch: String(templateConfig.default_ref || 'main'),
165
- manifestPath: String(templateConfig.manifest_path || 'joripspace-template.json'),
166
- });
167
- }
168
-
169
- module.exports = { buildTemplatePublishWorkflow, templateGithubActionsPublishFile };
1
+ function buildTemplatePublishWorkflow({
2
+ templateId,
3
+ branch = 'main',
4
+ manifestPath = 'joripspace-template.json',
5
+ }) {
6
+ const publishScript = `${inlineTemplatePublishMain.toString()}\n\nawait inlineTemplatePublishMain();`
7
+ .split('\n')
8
+ .map((line) => ` ${line}`)
9
+ .join('\n');
10
+ return `# joripspace-template-workflow-version: 3
11
+ #
12
+ # JoripSpace 템플릿 배포 가이드
13
+ # 1. 이 파일과 joripspace-template.json이 추가된 설정 PR을 기본 브랜치에 병합합니다.
14
+ # 2. GitHub 저장소의 Releases에서 배포할 버전 태그를 만들고 Release를 Publish합니다.
15
+ # 3. Release 태그가 조립스페이스에 표시되는 공식 버전이 됩니다. 예: 1.0.1 또는 v1.0.1
16
+ # 4. Actions 탭의 "JoripSpace Template Publish" 작업이 초록색으로 완료되는지 확인합니다.
17
+ #
18
+ # 알아두세요
19
+ # - 일반 push나 Release 초안 저장만으로는 배포되지 않습니다. Published Release만 배포됩니다.
20
+ # - 별도 API 키나 Secret은 필요하지 않습니다. GitHub OIDC로 저장소와 Release를 검증합니다.
21
+ # - Release 태그는 아래에 지정된 기준 브랜치에 포함된 커밋을 가리켜야 합니다.
22
+ # - 오류가 나면 Actions 실행에서 실패한 단계와 메시지를 먼저 확인하세요.
23
+ # - 이 워크플로와 joripspace-template.json을 삭제하면 이후 업데이트를 배포할 수 없습니다.
24
+ name: JoripSpace Template Publish
25
+
26
+ on:
27
+ release:
28
+ types: [published]
29
+
30
+ permissions:
31
+ contents: read
32
+ id-token: write
33
+
34
+ concurrency:
35
+ group: ${JSON.stringify(`joripspace-template-${String(templateId)}`)}
36
+ cancel-in-progress: false
37
+
38
+ jobs:
39
+ publish:
40
+ runs-on: ubuntu-latest
41
+ steps:
42
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
43
+ with:
44
+ fetch-depth: 0
45
+ - name: Build Git Bundle and files archive
46
+ shell: bash
47
+ env:
48
+ JORIPSPACE_TEMPLATE_ID: ${JSON.stringify(String(templateId))}
49
+ JORIPSPACE_MANIFEST_PATH: ${JSON.stringify(String(manifestPath))}
50
+ JORIPSPACE_SOURCE_BRANCH: ${JSON.stringify(String(branch))}
51
+ run: |
52
+ set -euo pipefail
53
+ manifest="$GITHUB_WORKSPACE/$JORIPSPACE_MANIFEST_PATH"
54
+ test -f "$manifest" || { echo "joripspace-template.json is required" >&2; exit 1; }
55
+ git show-ref --verify --quiet "refs/remotes/origin/$JORIPSPACE_SOURCE_BRANCH" || { echo "Registered source branch was not fetched" >&2; exit 1; }
56
+ git merge-base --is-ancestor "$GITHUB_SHA" "refs/remotes/origin/$JORIPSPACE_SOURCE_BRANCH" || { echo "Release tag must point to a commit on the registered source branch" >&2; exit 1; }
57
+ source_root=$(node -e 'const m=require(process.argv[1]); const v=String(m.source_root || "."); if (v !== "." && (v.startsWith("/") || v.includes("\\\\") || v.split("/").some((p) => !p || p === "." || p === ".."))) throw new Error("Unsafe source_root"); process.stdout.write(v)' "$manifest")
58
+ if [[ "$source_root" == "." ]]; then
59
+ distribution_sha="$GITHUB_SHA"
60
+ else
61
+ distribution_sha=$(git subtree split --prefix="$source_root" "$GITHUB_SHA")
62
+ fi
63
+ if git ls-tree -r "$distribution_sha" | grep -Eq '^(120000|160000) '; then
64
+ echo "Symlinks and submodules are not allowed in a template release" >&2
65
+ exit 1
66
+ fi
67
+ bare="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.git"
68
+ bundle="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.bundle"
69
+ archive="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.tar.gz"
70
+ stage="$RUNNER_TEMP/joripspace-template-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-stage"
71
+ git init --bare "$bare"
72
+ git push "$bare" "$distribution_sha:refs/heads/main"
73
+ git --git-dir="$bare" bundle create --version=2 "$bundle" refs/heads/main
74
+ git --git-dir="$bare" bundle verify "$bundle"
75
+ mkdir -p "$stage/release"
76
+ if [[ "$source_root" == "." ]]; then
77
+ git archive "$GITHUB_SHA" | tar -x -C "$stage/release"
78
+ else
79
+ mkdir -p "$stage/release/$source_root"
80
+ git archive "$GITHUB_SHA:$source_root" | tar -x -C "$stage/release/$source_root"
81
+ fi
82
+ cp "$manifest" "$stage/release/joripspace-template.json"
83
+ tar -czf "$archive" -C "$stage" release
84
+ file_count=$(git ls-tree -r --name-only "$distribution_sha" | wc -l | tr -d ' ')
85
+ source_bytes=$(git ls-tree -r -l "$distribution_sha" | awk '{ total += $4 } END { print total + 0 }')
86
+ echo "JORIPSPACE_BUNDLE_PATH=$bundle" >> "$GITHUB_ENV"
87
+ echo "JORIPSPACE_ARCHIVE_PATH=$archive" >> "$GITHUB_ENV"
88
+ echo "JORIPSPACE_MANIFEST_PATH=$manifest" >> "$GITHUB_ENV"
89
+ echo "JORIPSPACE_FILE_COUNT=$file_count" >> "$GITHUB_ENV"
90
+ echo "JORIPSPACE_SOURCE_BYTES=$source_bytes" >> "$GITHUB_ENV"
91
+ - name: Publish to JoripSpace
92
+ shell: bash
93
+ env:
94
+ JORIPSPACE_TEMPLATE_ID: ${JSON.stringify(String(templateId))}
95
+ JORIPSPACE_API_URL: "https://api.joripspace.com"
96
+ run: |
97
+ set -euo pipefail
98
+ node --input-type=module <<'JORIPSPACE_SCRIPT'
99
+ // Cloudflare's production bundler may annotate nested function names with
100
+ // __name(). Keep the generated standalone Node script compatible with it.
101
+ const __name = (value) => value;
102
+ ${publishScript}
103
+ JORIPSPACE_SCRIPT
104
+ `;
105
+ }
106
+
107
+ async function inlineTemplatePublishMain() {
108
+ const { readFile } = await import('node:fs/promises');
109
+ const audience = 'https://api.joripspace.com/v1/template-publish/github';
110
+ const templateId = requiredEnv('JORIPSPACE_TEMPLATE_ID');
111
+ const apiUrl = requiredEnv('JORIPSPACE_API_URL').replace(/\/+$/, '');
112
+ const [bundle, archive, manifest] = await Promise.all([
113
+ readFile(requiredEnv('JORIPSPACE_BUNDLE_PATH')),
114
+ readFile(requiredEnv('JORIPSPACE_ARCHIVE_PATH')),
115
+ readFile(requiredEnv('JORIPSPACE_MANIFEST_PATH')),
116
+ ]);
117
+ const form = new FormData();
118
+ form.append('bundle', new Blob([bundle], { type: 'application/x-git-bundle' }), 'template.bundle');
119
+ form.append('archive', new Blob([archive], { type: 'application/gzip' }), 'template.tar.gz');
120
+ form.append('manifest', new Blob([manifest], { type: 'application/json' }), 'joripspace-template.json');
121
+ form.append('file_count', requiredEnv('JORIPSPACE_FILE_COUNT'));
122
+ form.append('source_bytes', requiredEnv('JORIPSPACE_SOURCE_BYTES'));
123
+ const token = await requestOidcToken();
124
+ const response = await fetch(`${apiUrl}/v1/template-publish/${encodeURIComponent(templateId)}/versions`, {
125
+ method: 'POST',
126
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
127
+ body: form,
128
+ });
129
+ const text = await response.text();
130
+ const payload = text ? safeJson(text) : {};
131
+ if (!response.ok)
132
+ throw new Error(payload?.error?.message || `JoripSpace publish failed (${response.status}).`);
133
+ process.stdout.write(`JoripSpace template published: ${payload.version || payload.version_id}\n`);
134
+
135
+ async function requestOidcToken() {
136
+ const requestUrl = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_URL');
137
+ const requestToken = requiredEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN');
138
+ const separator = requestUrl.includes('?') ? '&' : '?';
139
+ const response = await fetch(`${requestUrl}${separator}audience=${encodeURIComponent(audience)}`, {
140
+ headers: { Authorization: `Bearer ${requestToken}` },
141
+ });
142
+ const payload = await response.json().catch(() => ({}));
143
+ if (!response.ok || typeof payload.value !== 'string')
144
+ throw new Error(`GitHub OIDC token request failed (${response.status}).`);
145
+ return payload.value;
146
+ }
147
+ function safeJson(value) {
148
+ try {
149
+ return JSON.parse(value);
150
+ } catch {
151
+ return { error: { message: value.slice(0, 500) } };
152
+ }
153
+ }
154
+ function requiredEnv(name) {
155
+ const value = process.env[name];
156
+ if (!value) throw new Error(`${name} is required.`);
157
+ return value;
158
+ }
159
+ }
160
+
161
+ function templateGithubActionsPublishFile(templateConfig = {}) {
162
+ return buildTemplatePublishWorkflow({
163
+ templateId: String(templateConfig.template_id || '__JORIPSPACE_TEMPLATE_ID__'),
164
+ branch: String(templateConfig.default_ref || 'main'),
165
+ manifestPath: String(templateConfig.manifest_path || 'joripspace-template.json'),
166
+ });
167
+ }
168
+
169
+ module.exports = { buildTemplatePublishWorkflow, templateGithubActionsPublishFile };