@joripspace/cli 0.8.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.
@@ -1,450 +1,456 @@
1
- const crypto = require('node:crypto');
2
- const fs = require('node:fs');
3
- const path = require('node:path');
4
- const { unzipSync, zipSync } = require('fflate');
5
- const ignore = require('ignore');
6
- const {
7
- assertNonOverlappingFilePlan,
8
- backupAndRemoveProjectPaths,
9
- createExternalBackupRoot,
10
- resolveProjectFileTarget,
11
- safeProjectRelativePath,
12
- } = require('./project-paths');
13
- const { ensureProjectEnvIgnored } = require('./project-env');
14
- const { redactAuthError } = require('./auth-redaction');
15
-
16
- const HARD_DIRS = new Set(['.git', 'node_modules', '.wrangler', '.cache', 'coverage', 'tmp', 'temp']);
17
- const HARD_FILES = new Set(['.ds_store', 'thumbs.db', 'desktop.ini']);
18
- const AGENT_CONTROL_DIRS = new Set(['.agents', '.claude', '.codex', '.cursor', '.gemini', '.opencode']);
19
- const AGENT_CONTROL_FILES = new Set(['agents.md', 'claude.md']);
20
- const LOCAL_PROJECT_MARKER = '.joripspace/project';
21
- const LEGACY_IDENTITY_FILE = '.joripspace/project.json';
22
- const TRANSIENT_DEPLOY_MANIFEST = '.joripspace/deploy.json';
23
- const CHECKPOINT_METADATA_FILES = new Set([
24
- LOCAL_PROJECT_MARKER,
25
- LEGACY_IDENTITY_FILE,
26
- TRANSIENT_DEPLOY_MANIFEST,
27
- ]);
28
- const LOCAL_RESTORE_MARKERS = new Set([...CHECKPOINT_METADATA_FILES, '.gitignore']);
29
-
30
- async function runCheckpointOperation(command, options) {
31
- if (command === 'save') return saveCheckpoint(options);
32
- if (command === 'restore') return restoreCheckpoint(options);
33
- throw new Error(`unknown checkpoint operation: ${command}`);
34
- }
35
-
36
- async function saveCheckpoint(options, sourceType = 'agent') {
37
- ensureTokenIgnoreInvariant(options.workspaceDir);
38
- const label = String(options.label || '').trim();
39
- if (!label) throw new Error('checkpoint save requires --label');
40
- if (label.length > 120) throw new Error('checkpoint label must be 120 characters or fewer');
41
- const files = projectFiles(options.workspaceDir);
42
- if (options.entrypoint) {
43
- const entrypoint = safeRestorePath(options.entrypoint);
44
- if (!files.some(([name]) => name === entrypoint)) {
45
- throw new Error(`deployment entrypoint was excluded from the archive: ${entrypoint}`);
46
- }
47
- upsertDeployManifest(files, options.workspaceDir, entrypoint);
48
- }
49
- if (!files.length) throw new Error('there are no project files to save');
50
- assertNonOverlappingFilePlan(files.map(([relative]) => relative));
51
- const archive = zipSync(Object.fromEntries(files.map(([name, bytes]) => [name, [bytes, { level: 6 }]])), {
52
- level: 6,
53
- });
54
- const session = await apiFetch(
55
- options,
56
- `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoint-uploads`,
57
- {
58
- method: 'POST',
59
- json: { label, source_type: options.sourceType || sourceType, idempotency_key: crypto.randomUUID() },
60
- }
61
- );
62
- const chunkSize = Number(session.chunk_size || 6 * 1024 * 1024);
63
- if (!Number.isSafeInteger(chunkSize) || chunkSize < 1)
64
- throw new Error('invalid checkpoint upload chunk size');
65
- let part = 1;
66
- for (let offset = 0; offset < archive.byteLength; offset += chunkSize) {
67
- const route = String(session.upload_part_url_template || '').replace('{part_number}', String(part));
68
- if (!route) throw new Error('checkpoint upload part URL is missing');
69
- await apiFetch(options, route, {
70
- method: 'PUT',
71
- bytes: archive.subarray(offset, Math.min(offset + chunkSize, archive.byteLength)),
72
- timeoutMs: options.deploy ? null : 45_000,
73
- });
74
- part += 1;
75
- }
76
- await apiFetch(options, String(session.complete_url || '') + (options.deploy ? '?wait=ready' : ''), {
77
- method: 'POST',
78
- json: {},
79
- timeoutMs: options.deploy ? null : 45_000,
80
- });
81
- const checkpoint = await waitReady(options, session.checkpoint_id);
82
- let deployment = null;
83
- if (options.deploy) {
84
- if (!checkpoint.deployable) throw new Error('this checkpoint is backup-only and cannot be deployed');
85
- deployment = await apiFetch(
86
- options,
87
- `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoints/${encodeURIComponent(checkpoint.checkpoint_id)}/deploy`,
88
- { method: 'POST', json: {}, timeoutMs: null }
89
- );
90
- }
91
- return {
92
- status: 'saved',
93
- archive_bytes: archive.byteLength,
94
- file_count: files.length,
95
- checkpoint,
96
- deployment,
97
- };
98
- }
99
-
100
- async function restoreCheckpoint(options) {
101
- ensureTokenIgnoreInvariant(options.workspaceDir);
102
- const checkpointId = String(options.checkpointId || '').trim();
103
- if (!checkpointId) throw new Error('checkpoint restore requires --checkpoint');
104
- const base = `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoints/${encodeURIComponent(checkpointId)}`;
105
- const plan = await apiFetch(options, `${base}/restore-plan`);
106
- const response = await apiFetch(options, `${base}/download`, { raw: true, timeoutMs: 45_000 });
107
- const extracted = unzipSync(new Uint8Array(await response.arrayBuffer()));
108
- const planned = verifyRestoreArchive(plan, extracted);
109
- verifyCheckpointIdentity(planned, options.projectId);
110
- const writable = planned.filter(([relative]) => !isLocalRestoreMarker(relative));
111
- assertNonOverlappingFilePlan(writable.map(([relative]) => relative));
112
- const plannedPaths = new Set([
113
- ...planned.map(([relative]) => portablePathKey(relative)),
114
- ...LOCAL_RESTORE_MARKERS,
115
- ]);
116
- const additions = [];
117
- const overwrites = [];
118
- const conflictPaths = new Set();
119
- for (const [relative, bytes] of writable) {
120
- const location = resolveProjectFileTarget(options.workspaceDir, relative, 'unsafe checkpoint path');
121
- if (location.blockers.length) {
122
- overwrites.push(relative);
123
- location.blockers.forEach((blocker) => conflictPaths.add(blocker));
124
- } else if (!fs.existsSync(location.target)) additions.push(relative);
125
- else if (!Buffer.from(fs.readFileSync(location.target)).equals(Buffer.from(bytes))) {
126
- overwrites.push(relative);
127
- conflictPaths.add(relative);
128
- }
129
- }
130
- const deletions = projectFiles(options.workspaceDir)
131
- .map(([relative]) => relative)
132
- .filter((relative) => !plannedPaths.has(portablePathKey(relative)));
133
- const protectedSkipped = planned
134
- .filter(([relative]) => isLocalRestoreMarker(relative))
135
- .map(([relative]) => relative);
136
- const preview = { additions, overwrites, deletions, protected_files_skipped: protectedSkipped };
137
- if (!options.apply) return { status: 'preview', checkpoint_id: checkpointId, ...preview };
138
-
139
- const safety = await saveCheckpoint(
140
- { ...options, label: '복원 전 안전 저장본', deploy: false },
141
- 'restore_safety'
142
- );
143
- const backupRoot = createExternalBackupRoot(options.workspaceDir, 'checkpoint-restore', options.dataDir);
144
- backupAndRemoveProjectPaths(
145
- options.workspaceDir,
146
- [...conflictPaths, ...deletions],
147
- backupRoot,
148
- (relative) => hardExcluded(relative) || isLocalRestoreMarker(relative)
149
- );
150
- for (const [relative, bytes] of writable) {
151
- const location = resolveProjectFileTarget(options.workspaceDir, relative, 'unsafe checkpoint path');
152
- if (location.blockers.length) {
153
- throw new Error(`checkpoint target is blocked by a local path: ${location.blockers.join(', ')}`);
154
- }
155
- fs.mkdirSync(path.dirname(location.target), { recursive: true });
156
- fs.writeFileSync(location.target, bytes);
157
- }
158
- ensureTokenIgnoreInvariant(options.workspaceDir);
159
- for (const [relative, bytes] of writable) {
160
- const restored = fs.readFileSync(
161
- resolveProjectFileTarget(options.workspaceDir, relative, 'unsafe checkpoint path').target
162
- );
163
- if (!Buffer.from(restored).equals(Buffer.from(bytes))) {
164
- throw new Error(`checkpoint post-restore integrity check failed: ${relative}`);
165
- }
166
- }
167
- return {
168
- status: 'restored',
169
- checkpoint_id: checkpointId,
170
- ...preview,
171
- safety_checkpoint_id: safety.checkpoint.checkpoint_id,
172
- backup_root: backupRoot,
173
- };
174
- }
175
-
176
- function projectFiles(root) {
177
- return projectFileEntries(root).map(({ relative, path: filePath }) => [
178
- relative, new Uint8Array(fs.readFileSync(filePath)),
179
- ]);
180
- }
181
-
182
- function projectFileEntries(root) {
183
- root = path.resolve(root);
184
- const files = [];
185
- function walk(directory, inherited = []) {
186
- const names = directory === root ? ['.gitignore', '.ignore', '.joripspaceignore'] : ['.gitignore'];
187
- const rules = [...inherited, { directory, matcher: ignoreRules(directory, names) }];
188
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
189
- const full = path.join(directory, entry.name);
190
- let relative = toPosix(path.relative(root, full));
191
- if (hardExcluded(relative)) continue;
192
- let excluded = false;
193
- for (const rule of rules) {
194
- const candidate = toPosix(path.relative(rule.directory, full)) + (entry.isDirectory() ? '/' : '');
195
- const result = rule.matcher.test(candidate);
196
- if (result.ignored || result.unignored) excluded = result.ignored;
197
- }
198
- // Git cannot reinclude a child of an excluded directory without reopening the parent.
199
- if (excluded) continue;
200
- relative = safeProjectRelativePath(relative, 'unsafe checkpoint path');
201
- const stat = fs.lstatSync(full);
202
- if (stat.isSymbolicLink())
203
- throw new Error(`symbolic links cannot be included in checkpoints: ${relative}`);
204
- if (entry.isDirectory()) {
205
- walk(full, rules);
206
- } else if (entry.isFile()) {
207
- files.push({ relative, path: full, size: stat.size });
208
- }
209
- }
210
- }
211
- walk(root);
212
- return files;
213
- }
214
-
215
- function hardExcluded(relative) {
216
- const normalized = toPosix(relative).replace(/^\.\//, '').toLowerCase();
217
- const parts = normalized.split('/');
218
- const base = parts.at(-1) || '';
219
- return (
220
- HARD_FILES.has(base) ||
221
- parts.some((part) => HARD_DIRS.has(part)) ||
222
- parts.some((part) => AGENT_CONTROL_DIRS.has(part)) ||
223
- parts.some((part) => AGENT_CONTROL_FILES.has(part)) ||
224
- parts.includes('.joripspace') ||
225
- parts.includes('.env.joripspace') ||
226
- /\.(log|tmp|temp)$/i.test(base)
227
- );
228
- }
229
-
230
- function verifyCheckpointIdentity(planned, projectId) {
231
- for (const [relative, bytes] of planned) {
232
- if (isCanonicalProjectMarker(relative)) {
233
- const marker = Buffer.from(bytes).toString('utf8');
234
- if (!/^[a-z0-9](?:[a-z0-9-]{1,48}[a-z0-9])?\n?$/.test(marker)) {
235
- throw new Error('checkpoint project marker is not a canonical project slug');
236
- }
237
- if (marker.trim() !== String(projectId)) {
238
- throw new Error('checkpoint project metadata does not match the connected project');
239
- }
240
- continue;
241
- }
242
- if (!isLegacyIdentityFile(relative)) continue;
243
- let config;
244
- try {
245
- config = JSON.parse(Buffer.from(bytes).toString('utf8'));
246
- } catch {
247
- throw new Error('checkpoint project metadata is not valid JSON');
248
- }
249
- const identities = [config?.project_id, config?.project_slug]
250
- .filter(Boolean)
251
- .map((value) => String(value));
252
- if (!identities.length || identities.some((identity) => identity !== String(projectId))) {
253
- throw new Error('checkpoint project metadata does not match the connected project');
254
- }
255
- }
256
- }
257
-
258
- function ensureTokenIgnoreInvariant(workspaceDir) {
259
- if (fs.existsSync(path.join(workspaceDir, '.env.joripspace'))) {
260
- ensureProjectEnvIgnored(workspaceDir);
261
- }
262
- }
263
-
264
- function verifyRestoreArchive(plan, extracted) {
265
- if (!plan || !Array.isArray(plan.files)) throw new Error('checkpoint restore plan has no valid files');
266
- const expected = new Map();
267
- for (const file of plan.files) {
268
- const relative = safeRestorePath(file?.path);
269
- if (expected.has(relative))
270
- throw new Error(`checkpoint restore plan contains a duplicate path: ${relative}`);
271
- const byteSize = Number(file?.byte_size);
272
- if (!Number.isSafeInteger(byteSize) || byteSize < 0 || typeof file?.content_hash !== 'string') {
273
- throw new Error(`checkpoint restore plan metadata is invalid: ${relative}`);
274
- }
275
- expected.set(relative, { byteSize, contentHash: file.content_hash });
276
- }
277
- const planned = [];
278
- for (const [name, bytes] of Object.entries(extracted)) {
279
- const relative = safeRestorePath(name);
280
- const metadata = expected.get(relative);
281
- if (!metadata) throw new Error(`checkpoint archive contains an unplanned file: ${relative}`);
282
- if (bytes.byteLength !== metadata.byteSize) {
283
- throw new Error(`checkpoint byte size check failed: ${relative}`);
284
- }
285
- const actual = crypto.createHash('sha256').update(bytes).digest('base64url');
286
- if (!metadata.contentHash || metadata.contentHash !== actual) {
287
- throw new Error(`checkpoint integrity check failed: ${relative}`);
288
- }
289
- planned.push([relative, bytes]);
290
- expected.delete(relative);
291
- }
292
- if (expected.size) {
293
- throw new Error(`checkpoint archive is missing planned files: ${[...expected.keys()].join(', ')}`);
294
- }
295
- assertNonOverlappingFilePlan(planned.map(([relative]) => relative));
296
- return planned;
297
- }
298
-
299
- function upsertDeployManifest(files, workspaceDir, entrypoint) {
300
- const normalized = safeRestorePath(entrypoint);
301
- const bytes = new Uint8Array(Buffer.from(`${JSON.stringify({ entrypoint: normalized }, null, 2)}\n`));
302
- const index = files.findIndex(([name]) => isTransientDeployManifest(name));
303
- if (index >= 0) files[index] = [TRANSIENT_DEPLOY_MANIFEST, bytes];
304
- else files.push([TRANSIENT_DEPLOY_MANIFEST, bytes]);
305
- }
306
-
307
- function ignoreRules(directory, names) {
308
- const matcher = ignore({ ignorecase: false });
309
- for (const name of names) {
310
- const target = path.join(directory, name);
311
- let stat;
312
- try {
313
- stat = fs.lstatSync(target);
314
- } catch (error) {
315
- if (error?.code === 'ENOENT') continue;
316
- throw error;
317
- }
318
- if (!stat.isFile() || stat.isSymbolicLink())
319
- throw new Error(`ignore rules must be a regular file: ${name}`);
320
- matcher.add(fs.readFileSync(target, 'utf8'));
321
- }
322
- return matcher;
323
- }
324
-
325
- function safeRestorePath(name) {
326
- const normalized = safeProjectRelativePath(name, 'unsafe checkpoint path');
327
- if (
328
- (hardExcluded(normalized) && !isCheckpointMetadataFile(normalized)) ||
329
- [...LOCAL_RESTORE_MARKERS].some((marker) => portablePathKey(normalized).startsWith(`${marker}/`))
330
- ) {
331
- throw new Error(`protected file cannot be restored: ${normalized}`);
332
- }
333
- return normalized;
334
- }
335
-
336
- function portablePathKey(relative) {
337
- return toPosix(String(relative || '')).toLowerCase();
338
- }
339
-
340
- function isCheckpointMetadataFile(relative) {
341
- return CHECKPOINT_METADATA_FILES.has(portablePathKey(relative));
342
- }
343
-
344
- function isCanonicalProjectMarker(relative) {
345
- return portablePathKey(relative) === LOCAL_PROJECT_MARKER;
346
- }
347
-
348
- function isLegacyIdentityFile(relative) {
349
- return portablePathKey(relative) === LEGACY_IDENTITY_FILE;
350
- }
351
-
352
- function isTransientDeployManifest(relative) {
353
- return portablePathKey(relative) === TRANSIENT_DEPLOY_MANIFEST;
354
- }
355
-
356
- function isLocalRestoreMarker(relative) {
357
- return LOCAL_RESTORE_MARKERS.has(portablePathKey(relative));
358
- }
359
-
360
- async function waitReady(options, checkpointId) {
361
- for (let attempt = 0; options.deploy || attempt < 120; attempt += 1) {
362
- const result = await apiFetch(
363
- options,
364
- `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoints/${encodeURIComponent(checkpointId)}`
365
- );
366
- if (result.status === 'ready') return result;
367
- if (result.status === 'failed' || result.status === 'deleted') {
368
- throw new Error(result.error_message || 'checkpoint processing failed');
369
- }
370
- await new Promise((resolve) => setTimeout(resolve, 1_000));
371
- }
372
- throw new Error('checkpoint processing is still pending; check the checkpoint list before retrying');
373
- }
374
-
375
- async function apiFetch(options, route, request = {}) {
376
- if (!route) throw new Error('checkpoint API route is missing');
377
- const url = new URL(route, `${options.apiBaseUrl}/`);
378
- if (url.origin !== new URL(options.apiBaseUrl).origin)
379
- throw new Error('checkpoint upload URL changed origin');
380
- const controller = new AbortController();
381
- const timeoutMs = request.timeoutMs === null ? null : (request.timeoutMs ?? 25_000);
382
- const timer = timeoutMs === null ? undefined : setTimeout(() => controller.abort(), timeoutMs);
383
- let response;
384
- try {
385
- response = await fetch(url, {
386
- method: request.method || 'GET',
387
- headers: {
388
- authorization: `Bearer ${options.apiToken}`,
389
- 'x-joripspace-session-context': 'cli',
390
- ...(request.json === undefined ? {} : { 'content-type': 'application/json' }),
391
- },
392
- body: request.bytes || (request.json === undefined ? undefined : JSON.stringify(request.json)),
393
- signal: controller.signal,
394
- redirect: 'error',
395
- });
396
- } catch (error) {
397
- if (error?.name === 'AbortError') {
398
- const timeoutError = new Error('checkpoint request timed out');
399
- timeoutError.code = 'request_timeout';
400
- throw timeoutError;
401
- }
402
- const requestError = new Error(redactAuthError(
403
- error instanceof Error ? error.message : String(error), [options.apiToken]
404
- ));
405
- requestError.code = 'request_failed';
406
- throw requestError;
407
- } finally {
408
- clearTimeout(timer);
409
- }
410
- if (request.raw) {
411
- if (!response.ok) {
412
- const apiError = new Error(`checkpoint download failed (HTTP ${response.status})`);
413
- apiError.code = 'http_error';
414
- apiError.status = response.status;
415
- throw apiError;
416
- }
417
- return response;
418
- }
419
- const text = await response.text();
420
- let body = {};
421
- try {
422
- body = text ? JSON.parse(text) : {};
423
- } catch {
424
- body = { message: text };
425
- }
426
- if (!response.ok) {
427
- body = redactAuthError(body, [options.apiToken]);
428
- const apiError = new Error(
429
- body?.error?.message || body?.message || `checkpoint request failed (HTTP ${response.status})`
430
- );
431
- apiError.code = body?.error?.code || 'http_error';
432
- apiError.status = response.status;
433
- if (body?.error?.details !== undefined) apiError.details = body.error.details;
434
- throw apiError;
435
- }
436
- return body;
437
- }
438
-
439
- function toPosix(value) {
440
- return value.split(path.sep).join('/');
441
- }
442
-
443
- module.exports = {
444
- hardExcluded,
445
- projectFiles,
446
- projectFileEntries,
447
- runCheckpointOperation,
448
- safeRestorePath,
449
- verifyRestoreArchive,
450
- };
1
+ const crypto = require('node:crypto');
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { unzipSync, zipSync } = require('fflate');
5
+ const ignore = require('ignore');
6
+ const {
7
+ assertNonOverlappingFilePlan,
8
+ backupAndRemoveProjectPaths,
9
+ createExternalBackupRoot,
10
+ resolveProjectFileTarget,
11
+ safeProjectRelativePath,
12
+ } = require('./project-paths');
13
+ const { ensureProjectEnvIgnored } = require('./project-env');
14
+ const { redactAuthError } = require('./auth-redaction');
15
+
16
+ const HARD_DIRS = new Set(['.git', 'node_modules', '.wrangler', '.cache', 'coverage', 'tmp', 'temp']);
17
+ const HARD_FILES = new Set(['.ds_store', 'thumbs.db', 'desktop.ini']);
18
+ const AGENT_CONTROL_DIRS = new Set(['.agents', '.claude', '.codex', '.cursor', '.gemini', '.opencode']);
19
+ const AGENT_CONTROL_FILES = new Set(['agents.md', 'claude.md']);
20
+ const LOCAL_PROJECT_MARKER = '.joripspace/project';
21
+ const LEGACY_IDENTITY_FILE = '.joripspace/project.json';
22
+ const TRANSIENT_DEPLOY_MANIFEST = '.joripspace/deploy.json';
23
+ const CHECKPOINT_METADATA_FILES = new Set([
24
+ LOCAL_PROJECT_MARKER,
25
+ LEGACY_IDENTITY_FILE,
26
+ TRANSIENT_DEPLOY_MANIFEST,
27
+ ]);
28
+ const LOCAL_RESTORE_MARKERS = new Set([...CHECKPOINT_METADATA_FILES, '.gitignore']);
29
+
30
+ async function runCheckpointOperation(command, options) {
31
+ if (command === 'save') return saveCheckpoint(options);
32
+ if (command === 'restore') return restoreCheckpoint(options);
33
+ throw new Error(`unknown checkpoint operation: ${command}`);
34
+ }
35
+
36
+ async function saveCheckpoint(options, sourceType = 'agent') {
37
+ ensureTokenIgnoreInvariant(options.workspaceDir);
38
+ const label = String(options.label || '').trim();
39
+ if (!label) throw new Error('checkpoint save requires --label');
40
+ if (label.length > 120) throw new Error('checkpoint label must be 120 characters or fewer');
41
+ const files = projectFiles(options.workspaceDir);
42
+ if (options.entrypoint) {
43
+ const entrypoint = safeRestorePath(options.entrypoint);
44
+ if (!files.some(([name]) => name === entrypoint)) {
45
+ throw new Error(`deployment entrypoint was excluded from the archive: ${entrypoint}`);
46
+ }
47
+ upsertDeployManifest(files, options.workspaceDir, entrypoint);
48
+ }
49
+ if (!files.length) throw new Error('there are no project files to save');
50
+ assertNonOverlappingFilePlan(files.map(([relative]) => relative));
51
+ const archive = zipSync(Object.fromEntries(files.map(([name, bytes]) => [name, [bytes, { level: 6 }]])), {
52
+ level: 6,
53
+ });
54
+ const session = await apiFetch(
55
+ options,
56
+ `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoint-uploads`,
57
+ {
58
+ method: 'POST',
59
+ json: { label, source_type: options.sourceType || sourceType, idempotency_key: crypto.randomUUID() },
60
+ }
61
+ );
62
+ const chunkSize = Number(session.chunk_size || 6 * 1024 * 1024);
63
+ if (!Number.isSafeInteger(chunkSize) || chunkSize < 1)
64
+ throw new Error('invalid checkpoint upload chunk size');
65
+ let part = 1;
66
+ for (let offset = 0; offset < archive.byteLength; offset += chunkSize) {
67
+ const route = String(session.upload_part_url_template || '').replace('{part_number}', String(part));
68
+ if (!route) throw new Error('checkpoint upload part URL is missing');
69
+ await apiFetch(options, route, {
70
+ method: 'PUT',
71
+ bytes: archive.subarray(offset, Math.min(offset + chunkSize, archive.byteLength)),
72
+ timeoutMs: options.deploy ? null : 45_000,
73
+ });
74
+ part += 1;
75
+ }
76
+ await apiFetch(options, String(session.complete_url || '') + (options.deploy ? '?wait=ready' : ''), {
77
+ method: 'POST',
78
+ json: {},
79
+ timeoutMs: options.deploy ? null : 45_000,
80
+ });
81
+ const checkpoint = await waitReady(options, session.checkpoint_id);
82
+ let deployment = null;
83
+ if (options.deploy) {
84
+ if (!checkpoint.deployable) throw new Error('this checkpoint is backup-only and cannot be deployed');
85
+ deployment = await apiFetch(
86
+ options,
87
+ `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoints/${encodeURIComponent(checkpoint.checkpoint_id)}/deploy`,
88
+ { method: 'POST', json: {}, timeoutMs: null }
89
+ );
90
+ }
91
+ return {
92
+ status: 'saved',
93
+ archive_bytes: archive.byteLength,
94
+ file_count: files.length,
95
+ checkpoint,
96
+ deployment,
97
+ };
98
+ }
99
+
100
+ async function restoreCheckpoint(options) {
101
+ ensureTokenIgnoreInvariant(options.workspaceDir);
102
+ const { checkpointId, planned } = await readCheckpointFiles(options);
103
+ const writable = planned.filter(([relative]) => !isLocalRestoreMarker(relative));
104
+ assertNonOverlappingFilePlan(writable.map(([relative]) => relative));
105
+ const plannedPaths = new Set([
106
+ ...planned.map(([relative]) => portablePathKey(relative)),
107
+ ...LOCAL_RESTORE_MARKERS,
108
+ ]);
109
+ const additions = [];
110
+ const overwrites = [];
111
+ const conflictPaths = new Set();
112
+ for (const [relative, bytes] of writable) {
113
+ const location = resolveProjectFileTarget(options.workspaceDir, relative, 'unsafe checkpoint path');
114
+ if (location.blockers.length) {
115
+ overwrites.push(relative);
116
+ location.blockers.forEach((blocker) => conflictPaths.add(blocker));
117
+ } else if (!fs.existsSync(location.target)) additions.push(relative);
118
+ else if (!Buffer.from(fs.readFileSync(location.target)).equals(Buffer.from(bytes))) {
119
+ overwrites.push(relative);
120
+ conflictPaths.add(relative);
121
+ }
122
+ }
123
+ const deletions = projectFiles(options.workspaceDir)
124
+ .map(([relative]) => relative)
125
+ .filter((relative) => !plannedPaths.has(portablePathKey(relative)));
126
+ const protectedSkipped = planned
127
+ .filter(([relative]) => isLocalRestoreMarker(relative))
128
+ .map(([relative]) => relative);
129
+ const preview = { additions, overwrites, deletions, protected_files_skipped: protectedSkipped };
130
+ if (!options.apply) return { status: 'preview', checkpoint_id: checkpointId, ...preview };
131
+
132
+ const safety = await saveCheckpoint(
133
+ { ...options, label: '복원 전 안전 저장본', deploy: false },
134
+ 'restore_safety'
135
+ );
136
+ const backupRoot = createExternalBackupRoot(options.workspaceDir, 'checkpoint-restore', options.dataDir);
137
+ backupAndRemoveProjectPaths(
138
+ options.workspaceDir,
139
+ [...conflictPaths, ...deletions],
140
+ backupRoot,
141
+ (relative) => hardExcluded(relative) || isLocalRestoreMarker(relative)
142
+ );
143
+ for (const [relative, bytes] of writable) {
144
+ const location = resolveProjectFileTarget(options.workspaceDir, relative, 'unsafe checkpoint path');
145
+ if (location.blockers.length) {
146
+ throw new Error(`checkpoint target is blocked by a local path: ${location.blockers.join(', ')}`);
147
+ }
148
+ fs.mkdirSync(path.dirname(location.target), { recursive: true });
149
+ fs.writeFileSync(location.target, bytes);
150
+ }
151
+ ensureTokenIgnoreInvariant(options.workspaceDir);
152
+ for (const [relative, bytes] of writable) {
153
+ const restored = fs.readFileSync(
154
+ resolveProjectFileTarget(options.workspaceDir, relative, 'unsafe checkpoint path').target
155
+ );
156
+ if (!Buffer.from(restored).equals(Buffer.from(bytes))) {
157
+ throw new Error(`checkpoint post-restore integrity check failed: ${relative}`);
158
+ }
159
+ }
160
+ return {
161
+ status: 'restored',
162
+ checkpoint_id: checkpointId,
163
+ ...preview,
164
+ safety_checkpoint_id: safety.checkpoint.checkpoint_id,
165
+ backup_root: backupRoot,
166
+ };
167
+ }
168
+
169
+ async function readCheckpointFiles(options) {
170
+ const checkpointId = String(options.checkpointId || '').trim();
171
+ if (!checkpointId) throw new Error('checkpoint restore requires --checkpoint');
172
+ const base = `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoints/${encodeURIComponent(checkpointId)}`;
173
+ const plan = await apiFetch(options, `${base}/restore-plan`);
174
+ const response = await apiFetch(options, `${base}/download`, { raw: true, timeoutMs: 45_000 });
175
+ const extracted = unzipSync(new Uint8Array(await response.arrayBuffer()));
176
+ const planned = verifyRestoreArchive(plan, extracted);
177
+ verifyCheckpointIdentity(planned, options.projectId);
178
+ return { checkpointId, planned };
179
+ }
180
+
181
+ function projectFiles(root) {
182
+ return projectFileEntries(root).map(({ relative, path: filePath }) => [
183
+ relative, new Uint8Array(fs.readFileSync(filePath)),
184
+ ]);
185
+ }
186
+
187
+ function projectFileEntries(root) {
188
+ root = path.resolve(root);
189
+ const files = [];
190
+ function walk(directory, inherited = []) {
191
+ const names = directory === root ? ['.gitignore', '.ignore', '.joripspaceignore'] : ['.gitignore'];
192
+ const rules = [...inherited, { directory, matcher: ignoreRules(directory, names) }];
193
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
194
+ const full = path.join(directory, entry.name);
195
+ let relative = toPosix(path.relative(root, full));
196
+ if (hardExcluded(relative)) continue;
197
+ let excluded = false;
198
+ for (const rule of rules) {
199
+ const candidate = toPosix(path.relative(rule.directory, full)) + (entry.isDirectory() ? '/' : '');
200
+ const result = rule.matcher.test(candidate);
201
+ if (result.ignored || result.unignored) excluded = result.ignored;
202
+ }
203
+ // Git cannot reinclude a child of an excluded directory without reopening the parent.
204
+ if (excluded) continue;
205
+ relative = safeProjectRelativePath(relative, 'unsafe checkpoint path');
206
+ const stat = fs.lstatSync(full);
207
+ if (stat.isSymbolicLink())
208
+ throw new Error(`symbolic links cannot be included in checkpoints: ${relative}`);
209
+ if (entry.isDirectory()) {
210
+ walk(full, rules);
211
+ } else if (entry.isFile()) {
212
+ files.push({ relative, path: full, size: stat.size });
213
+ }
214
+ }
215
+ }
216
+ walk(root);
217
+ return files;
218
+ }
219
+
220
+ function hardExcluded(relative) {
221
+ const normalized = toPosix(relative).replace(/^\.\//, '').toLowerCase();
222
+ const parts = normalized.split('/');
223
+ const base = parts.at(-1) || '';
224
+ return (
225
+ HARD_FILES.has(base) ||
226
+ parts.some((part) => HARD_DIRS.has(part)) ||
227
+ parts.some((part) => AGENT_CONTROL_DIRS.has(part)) ||
228
+ parts.some((part) => AGENT_CONTROL_FILES.has(part)) ||
229
+ parts.includes('.joripspace') ||
230
+ parts.includes('.env.joripspace') ||
231
+ /\.(log|tmp|temp)$/i.test(base)
232
+ );
233
+ }
234
+
235
+ function verifyCheckpointIdentity(planned, projectId) {
236
+ for (const [relative, bytes] of planned) {
237
+ if (isCanonicalProjectMarker(relative)) {
238
+ const marker = Buffer.from(bytes).toString('utf8');
239
+ if (!/^[a-z0-9](?:[a-z0-9-]{1,48}[a-z0-9])?\n?$/.test(marker)) {
240
+ throw new Error('checkpoint project marker is not a canonical project slug');
241
+ }
242
+ if (marker.trim() !== String(projectId)) {
243
+ throw new Error('checkpoint project metadata does not match the connected project');
244
+ }
245
+ continue;
246
+ }
247
+ if (!isLegacyIdentityFile(relative)) continue;
248
+ let config;
249
+ try {
250
+ config = JSON.parse(Buffer.from(bytes).toString('utf8'));
251
+ } catch {
252
+ throw new Error('checkpoint project metadata is not valid JSON');
253
+ }
254
+ const identities = [config?.project_id, config?.project_slug]
255
+ .filter(Boolean)
256
+ .map((value) => String(value));
257
+ if (!identities.length || identities.some((identity) => identity !== String(projectId))) {
258
+ throw new Error('checkpoint project metadata does not match the connected project');
259
+ }
260
+ }
261
+ }
262
+
263
+ function ensureTokenIgnoreInvariant(workspaceDir) {
264
+ if (fs.existsSync(path.join(workspaceDir, '.env.joripspace'))) {
265
+ ensureProjectEnvIgnored(workspaceDir);
266
+ }
267
+ }
268
+
269
+ function verifyRestoreArchive(plan, extracted) {
270
+ if (!plan || !Array.isArray(plan.files)) throw new Error('checkpoint restore plan has no valid files');
271
+ const expected = new Map();
272
+ for (const file of plan.files) {
273
+ const relative = safeRestorePath(file?.path);
274
+ if (expected.has(relative))
275
+ throw new Error(`checkpoint restore plan contains a duplicate path: ${relative}`);
276
+ const byteSize = Number(file?.byte_size);
277
+ if (!Number.isSafeInteger(byteSize) || byteSize < 0 || typeof file?.content_hash !== 'string') {
278
+ throw new Error(`checkpoint restore plan metadata is invalid: ${relative}`);
279
+ }
280
+ expected.set(relative, { byteSize, contentHash: file.content_hash });
281
+ }
282
+ const planned = [];
283
+ for (const [name, bytes] of Object.entries(extracted)) {
284
+ const relative = safeRestorePath(name);
285
+ const metadata = expected.get(relative);
286
+ if (!metadata) throw new Error(`checkpoint archive contains an unplanned file: ${relative}`);
287
+ if (bytes.byteLength !== metadata.byteSize) {
288
+ throw new Error(`checkpoint byte size check failed: ${relative}`);
289
+ }
290
+ const actual = crypto.createHash('sha256').update(bytes).digest('base64url');
291
+ if (!metadata.contentHash || metadata.contentHash !== actual) {
292
+ throw new Error(`checkpoint integrity check failed: ${relative}`);
293
+ }
294
+ planned.push([relative, bytes]);
295
+ expected.delete(relative);
296
+ }
297
+ if (expected.size) {
298
+ throw new Error(`checkpoint archive is missing planned files: ${[...expected.keys()].join(', ')}`);
299
+ }
300
+ assertNonOverlappingFilePlan(planned.map(([relative]) => relative));
301
+ return planned;
302
+ }
303
+
304
+ function upsertDeployManifest(files, workspaceDir, entrypoint) {
305
+ const normalized = safeRestorePath(entrypoint);
306
+ const bytes = new Uint8Array(Buffer.from(`${JSON.stringify({ entrypoint: normalized }, null, 2)}\n`));
307
+ const index = files.findIndex(([name]) => isTransientDeployManifest(name));
308
+ if (index >= 0) files[index] = [TRANSIENT_DEPLOY_MANIFEST, bytes];
309
+ else files.push([TRANSIENT_DEPLOY_MANIFEST, bytes]);
310
+ }
311
+
312
+ function ignoreRules(directory, names) {
313
+ const matcher = ignore({ ignorecase: false });
314
+ for (const name of names) {
315
+ const target = path.join(directory, name);
316
+ let stat;
317
+ try {
318
+ stat = fs.lstatSync(target);
319
+ } catch (error) {
320
+ if (error?.code === 'ENOENT') continue;
321
+ throw error;
322
+ }
323
+ if (!stat.isFile() || stat.isSymbolicLink())
324
+ throw new Error(`ignore rules must be a regular file: ${name}`);
325
+ matcher.add(fs.readFileSync(target, 'utf8'));
326
+ }
327
+ return matcher;
328
+ }
329
+
330
+ function safeRestorePath(name) {
331
+ const normalized = safeProjectRelativePath(name, 'unsafe checkpoint path');
332
+ if (
333
+ (hardExcluded(normalized) && !isCheckpointMetadataFile(normalized)) ||
334
+ [...LOCAL_RESTORE_MARKERS].some((marker) => portablePathKey(normalized).startsWith(`${marker}/`))
335
+ ) {
336
+ throw new Error(`protected file cannot be restored: ${normalized}`);
337
+ }
338
+ return normalized;
339
+ }
340
+
341
+ function portablePathKey(relative) {
342
+ return toPosix(String(relative || '')).toLowerCase();
343
+ }
344
+
345
+ function isCheckpointMetadataFile(relative) {
346
+ return CHECKPOINT_METADATA_FILES.has(portablePathKey(relative));
347
+ }
348
+
349
+ function isCanonicalProjectMarker(relative) {
350
+ return portablePathKey(relative) === LOCAL_PROJECT_MARKER;
351
+ }
352
+
353
+ function isLegacyIdentityFile(relative) {
354
+ return portablePathKey(relative) === LEGACY_IDENTITY_FILE;
355
+ }
356
+
357
+ function isTransientDeployManifest(relative) {
358
+ return portablePathKey(relative) === TRANSIENT_DEPLOY_MANIFEST;
359
+ }
360
+
361
+ function isLocalRestoreMarker(relative) {
362
+ return LOCAL_RESTORE_MARKERS.has(portablePathKey(relative));
363
+ }
364
+
365
+ async function waitReady(options, checkpointId) {
366
+ for (let attempt = 0; options.deploy || attempt < 120; attempt += 1) {
367
+ const result = await apiFetch(
368
+ options,
369
+ `/v1/projects/${encodeURIComponent(options.projectId)}/checkpoints/${encodeURIComponent(checkpointId)}`
370
+ );
371
+ if (result.status === 'ready') return result;
372
+ if (result.status === 'failed' || result.status === 'deleted') {
373
+ throw new Error(result.error_message || 'checkpoint processing failed');
374
+ }
375
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
376
+ }
377
+ throw new Error('checkpoint processing is still pending; check the checkpoint list before retrying');
378
+ }
379
+
380
+ async function apiFetch(options, route, request = {}) {
381
+ if (!route) throw new Error('checkpoint API route is missing');
382
+ const url = new URL(route, `${options.apiBaseUrl}/`);
383
+ if (url.origin !== new URL(options.apiBaseUrl).origin)
384
+ throw new Error('checkpoint upload URL changed origin');
385
+ const controller = new AbortController();
386
+ const timeoutMs = request.timeoutMs === null ? null : (request.timeoutMs ?? 25_000);
387
+ const timer = timeoutMs === null ? undefined : setTimeout(() => controller.abort(), timeoutMs);
388
+ let response;
389
+ try {
390
+ response = await fetch(url, {
391
+ method: request.method || 'GET',
392
+ headers: {
393
+ authorization: `Bearer ${options.apiToken}`,
394
+ 'x-joripspace-session-context': 'cli',
395
+ ...(request.json === undefined ? {} : { 'content-type': 'application/json' }),
396
+ },
397
+ body: request.bytes || (request.json === undefined ? undefined : JSON.stringify(request.json)),
398
+ signal: controller.signal,
399
+ redirect: 'error',
400
+ });
401
+ } catch (error) {
402
+ if (error?.name === 'AbortError') {
403
+ const timeoutError = new Error('checkpoint request timed out');
404
+ timeoutError.code = 'request_timeout';
405
+ throw timeoutError;
406
+ }
407
+ const requestError = new Error(redactAuthError(
408
+ error instanceof Error ? error.message : String(error), [options.apiToken]
409
+ ));
410
+ requestError.code = 'request_failed';
411
+ throw requestError;
412
+ } finally {
413
+ clearTimeout(timer);
414
+ }
415
+ if (request.raw) {
416
+ if (!response.ok) {
417
+ const apiError = new Error(`checkpoint download failed (HTTP ${response.status})`);
418
+ apiError.code = 'http_error';
419
+ apiError.status = response.status;
420
+ throw apiError;
421
+ }
422
+ return response;
423
+ }
424
+ const text = await response.text();
425
+ let body = {};
426
+ try {
427
+ body = text ? JSON.parse(text) : {};
428
+ } catch {
429
+ body = { message: text };
430
+ }
431
+ if (!response.ok) {
432
+ body = redactAuthError(body, [options.apiToken]);
433
+ const apiError = new Error(
434
+ body?.error?.message || body?.message || `checkpoint request failed (HTTP ${response.status})`
435
+ );
436
+ apiError.code = body?.error?.code || 'http_error';
437
+ apiError.status = response.status;
438
+ if (body?.error?.details !== undefined) apiError.details = body.error.details;
439
+ throw apiError;
440
+ }
441
+ return body;
442
+ }
443
+
444
+ function toPosix(value) {
445
+ return value.split(path.sep).join('/');
446
+ }
447
+
448
+ module.exports = {
449
+ hardExcluded,
450
+ projectFiles,
451
+ projectFileEntries,
452
+ runCheckpointOperation,
453
+ readCheckpointFiles,
454
+ safeRestorePath,
455
+ verifyRestoreArchive,
456
+ };