@deepdynamic/cli 0.0.0-stage → 0.1.0

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.
Files changed (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +32 -2
  3. package/THIRD_PARTY_NOTICES.txt +102 -0
  4. package/dist/agents/content.js +12 -0
  5. package/dist/agents/edit.js +140 -0
  6. package/dist/agents/install.js +180 -0
  7. package/dist/agents/setup.js +29 -0
  8. package/dist/agents/targets.js +91 -0
  9. package/dist/auth/credentials.js +63 -0
  10. package/dist/auth/session.js +49 -0
  11. package/dist/cli.js +198 -0
  12. package/dist/commands/account.js +96 -0
  13. package/dist/commands/activity.js +80 -0
  14. package/dist/commands/blocked.js +89 -0
  15. package/dist/commands/deploy/agents.js +11 -0
  16. package/dist/commands/deploy/files.js +62 -0
  17. package/dist/commands/deploy/index.js +95 -0
  18. package/dist/commands/deploy/manifest.js +24 -0
  19. package/dist/commands/deploy/minify.js +27 -0
  20. package/dist/commands/deploy/progress.js +85 -0
  21. package/dist/commands/deploy/ship.js +117 -0
  22. package/dist/commands/deploy/upload.js +125 -0
  23. package/dist/commands/deployments.js +59 -0
  24. package/dist/commands/dns.js +791 -0
  25. package/dist/commands/domains.js +711 -0
  26. package/dist/commands/emails.js +74 -0
  27. package/dist/commands/env.js +194 -0
  28. package/dist/commands/help.js +149 -0
  29. package/dist/commands/keys.js +269 -0
  30. package/dist/commands/login/flow.js +155 -0
  31. package/dist/commands/login/index.js +26 -0
  32. package/dist/commands/logout.js +71 -0
  33. package/dist/commands/mail.js +241 -0
  34. package/dist/commands/notifications.js +132 -0
  35. package/dist/commands/plan.js +371 -0
  36. package/dist/commands/projects.js +836 -0
  37. package/dist/commands/reference.js +2180 -0
  38. package/dist/commands/search.js +75 -0
  39. package/dist/commands/server.js +314 -0
  40. package/dist/commands/sessions.js +120 -0
  41. package/dist/commands/sites.js +102 -0
  42. package/dist/commands/sms.js +65 -0
  43. package/dist/commands/status.js +87 -0
  44. package/dist/commands/support.js +115 -0
  45. package/dist/commands/update.js +98 -0
  46. package/dist/commands/usage.js +51 -0
  47. package/dist/commands/verify.js +149 -0
  48. package/dist/commands/version.js +6 -0
  49. package/dist/guide.js +76 -0
  50. package/dist/http/call.js +6 -0
  51. package/dist/http/request.js +54 -0
  52. package/dist/index.js +11 -0
  53. package/dist/metadata.js +4 -0
  54. package/dist/output.js +9 -0
  55. package/dist/pretty.js +70 -0
  56. package/dist/registry.js +760 -0
  57. package/dist/runtime/browser.js +15 -0
  58. package/dist/runtime/card-request.js +55 -0
  59. package/dist/runtime/confirm.js +21 -0
  60. package/dist/runtime/development.js +13 -0
  61. package/dist/runtime/domain-name.js +5 -0
  62. package/dist/runtime/dry-run.js +28 -0
  63. package/dist/runtime/env-file.js +58 -0
  64. package/dist/runtime/error-hints.js +26 -0
  65. package/dist/runtime/flags.js +50 -0
  66. package/dist/runtime/login-screen.js +78 -0
  67. package/dist/runtime/page.js +18 -0
  68. package/dist/runtime/project-name.js +1 -0
  69. package/dist/runtime/run-mode.js +7 -0
  70. package/dist/runtime/server-options.js +32 -0
  71. package/dist/runtime/spinner.js +15 -0
  72. package/dist/runtime/suggest.js +22 -0
  73. package/dist/runtime/support.js +14 -0
  74. package/dist/runtime/text-file.js +20 -0
  75. package/dist/runtime/timeout.js +22 -0
  76. package/dist/runtime/update-check.js +124 -0
  77. package/dist/runtime/update-install.js +50 -0
  78. package/dist/runtime/usage-error.js +9 -0
  79. package/dist/setup-agents.js +8 -0
  80. package/dist/site.js +1 -0
  81. package/dist/update-refresh.js +5 -0
  82. package/package.json +46 -3
@@ -0,0 +1,836 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { authorized, defaultAuthDeps, signedIn } from "../auth/session.js";
4
+ import { LOGIN_EXPIRED, UNEXPECTED, failureError, httpFailure, postJson, readJson, request } from "../http/request.js";
5
+ import { agentResult, jsonLine } from "../output.js";
6
+ import { Styled, displayWidth, pad, paint, plain, prettyResult } from "../pretty.js";
7
+ import { parseCommand, parseFlags, unknownArgument } from "../runtime/flags.js";
8
+ import { PROJECT } from "../runtime/project-name.js";
9
+ import { parseTimeout } from "../runtime/timeout.js";
10
+ import { spec } from "../registry.js";
11
+ import { cardRequired, requestCard } from "../runtime/card-request.js";
12
+ import { confirmationRequired, splitYes } from "../runtime/confirm.js";
13
+ import { pauseFor, plannedChange, plannedRequest, splitDryRun } from "../runtime/dry-run.js";
14
+ import { supportFailure } from "../runtime/support.js";
15
+ import { usageError } from "../runtime/usage-error.js";
16
+ import { PUBLIC_URL } from "./deploy/progress.js";
17
+ import { PUBLISH_WAIT_SECONDS, shipDeployment } from "./deploy/ship.js";
18
+ import { restoreDeployment } from "./deploy/upload.js";
19
+ export const PROJECTS_PATH = '/api/v1/projects';
20
+ const STAGES = ['network', 'provisioning', 'stopped', 'running', 'failed'];
21
+ export const SERVER_WAIT_SECONDS = 20 * 60;
22
+ const COMMIT = /^[a-f0-9]{40}$/;
23
+ const COMMIT_PREFIX = /^[a-f0-9]{7,40}$/;
24
+ const DEPLOY_STATUSES = ['published', 'deploying', 'failed', 'none'];
25
+ const DEPLOY_STAGES = ['preparing', 'packing', 'uploading', 'verifying', 'awaiting_publish', 'publishing', 'published', 'failed'];
26
+ const BUILD = /^pnpm (build|run [A-Za-z0-9][A-Za-z0-9:._-]{0,63})$/;
27
+ const STATUS_LABELS = { published: '● 게시됨', deploying: '◐ 게시 중', failed: '✕ 배포 실패', none: '○ 배포 전' };
28
+ function projectStatus(body, project) {
29
+ const value = body;
30
+ const server = value?.server;
31
+ const site = value?.publicUrl ?? null;
32
+ if (value?.ok !== true || value.project !== project || !server || typeof server.stage !== 'string' || !STAGES.includes(server.stage)
33
+ || (site !== null && (typeof site !== 'string' || !PUBLIC_URL.test(site)))
34
+ || typeof server.ready !== 'boolean' || (server.errorCode !== null && typeof server.errorCode !== 'string')
35
+ || typeof server.message !== 'string' || server.message.length > 500 || /[\x00-\x1f\x7f]/.test(server.message)
36
+ || (value.pollAfterMs !== null && (typeof value.pollAfterMs !== 'number' || value.pollAfterMs < 1000 || value.pollAfterMs > 60_000)))
37
+ return null;
38
+ return {
39
+ server: { stage: server.stage, ready: server.ready, errorCode: server.errorCode, message: server.message },
40
+ site: site,
41
+ poll: value.pollAfterMs
42
+ };
43
+ }
44
+ async function preview(command, pretty, depth, deps, url) {
45
+ const session = await signedIn(deps);
46
+ if ('login' in session)
47
+ return session.login;
48
+ return plannedRequest(command, pretty, depth, session.siteUrl, url(session.siteUrl));
49
+ }
50
+ function readStatus(session, project, deps) {
51
+ return request(new URL(`${PROJECTS_PATH}/${project}`, session.siteUrl).href, {
52
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
53
+ }, deps, null);
54
+ }
55
+ function exchangeFailure(result) {
56
+ if ('failure' in result)
57
+ return result.failure;
58
+ if (result.status === 401)
59
+ return LOGIN_EXPIRED;
60
+ if (result.status === 404)
61
+ return { code: 'project_not_found', message: 'You have no project with that name. Create it with deepdynamic projects create <name>.', display: '그 이름의 내 프로젝트가 없습니다.' };
62
+ if (result.status === 409)
63
+ return { code: 'project_taken', message: 'Another account already uses that project name. Choose a different name.', display: '다른 계정이 이미 쓰는 이름입니다.' };
64
+ if (result.status === 400)
65
+ return { code: 'invalid_arguments', message: 'The server rejected the project name. Follow the naming steps in deepdynamic projects create --help.', display: '프로젝트 이름을 확인하세요.' };
66
+ if (result.status !== 200 && result.status !== 201)
67
+ return httpFailure(result.status);
68
+ return null;
69
+ }
70
+ function parseName(args, pretty) {
71
+ const parsed = parseCommand(args, [], pretty);
72
+ if ('error' in parsed)
73
+ return parsed;
74
+ const { names } = parsed;
75
+ if (names.length !== 1)
76
+ return { error: pretty ? '프로젝트 이름을 하나만 지정하세요.' : 'Specify exactly one project name.' };
77
+ if (!PROJECT.test(names[0]))
78
+ return { error: pretty ? '프로젝트 이름은 영문 소문자·숫자로 시작하고 끝나는 1~63자의 소문자·숫자·하이픈입니다.' : 'Project names are 1-63 lowercase letters, digits or hyphens and start and end with a letter or digit.' };
79
+ return names[0];
80
+ }
81
+ function finish(command, code, depth, pretty, siteUrl, project, server, site, failure, message) {
82
+ if (pretty) {
83
+ return prettyResult(code, depth, command, message, [
84
+ ['서버', siteUrl], ['프로젝트', project], ...(site ? [['발급 주소', site]] : []), ['상태', failure?.display ?? server.message]
85
+ ]);
86
+ }
87
+ return agentResult(code, {
88
+ command, siteUrl, project, publicUrl: site, server,
89
+ ...(failure ? { error: { code: failure.code, message: failure.message } } : {})
90
+ });
91
+ }
92
+ async function runProjects(command, args, pretty, depth, deps, waitMs) {
93
+ const { usage, prettyUsage } = spec(command);
94
+ const project = parseName(args, pretty);
95
+ if (typeof project !== 'string') {
96
+ return pretty
97
+ ? prettyResult(2, depth, command, project.error, [['사용법', prettyUsage]])
98
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: project.error }, usage });
99
+ }
100
+ const sent = await authorized(deps, (session) => command === 'projects create'
101
+ ? postJson(new URL(PROJECTS_PATH, session.siteUrl).href, session.token, { project }, deps, pretty ? '프로젝트를 만들고 있습니다.' : null)
102
+ : readStatus(session, project, deps));
103
+ if ('login' in sent)
104
+ return sent.login;
105
+ const { session } = sent;
106
+ if (cardRequired(sent.result))
107
+ return requestCard(command, pretty, depth, session, deps, { project });
108
+ let result = sent.result;
109
+ let lastOutput = '';
110
+ for (const deadline = Date.now() + waitMs;;) {
111
+ const failure = exchangeFailure(result);
112
+ const status = failure ? null : projectStatus(result.body, project);
113
+ if (!status) {
114
+ const shown = failure ?? UNEXPECTED;
115
+ return pretty
116
+ ? prettyResult(1, depth, command, '프로젝트를 확인하지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
117
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
118
+ }
119
+ const { server, site, poll } = status;
120
+ if (server.stage === 'failed') {
121
+ const failed = supportFailure('server_failed');
122
+ return finish(command, 1, depth, pretty, session.siteUrl, project, server, site, failed, '프로젝트 서버를 준비하지 못했습니다.');
123
+ }
124
+ if (server.ready || command === 'projects status') {
125
+ return finish(command, 0, depth, pretty, session.siteUrl, project, server, site, null, server.ready ? '프로젝트 서버가 준비되었습니다.' : '프로젝트 서버를 준비하고 있습니다.');
126
+ }
127
+ const output = pretty ? `${plain(server.message)}\n` : jsonLine({ event: 'project_progress', project, server });
128
+ if (output !== lastOutput)
129
+ deps.stream.write(output);
130
+ lastOutput = output;
131
+ if (Date.now() >= deadline) {
132
+ const pending = { code: 'server_pending', message: `The project server is still being prepared. Keep running deepdynamic projects status ${project} until server.ready is true or server.stage is failed.`, display: `아직 준비 중입니다. 준비될 때까지 deepdynamic projects status ${project} 로 계속 확인하세요.` };
133
+ return finish(command, 1, depth, pretty, session.siteUrl, project, server, site, pending, '프로젝트 서버가 아직 준비 중입니다.');
134
+ }
135
+ await (deps.pause ?? pauseFor)(poll ?? 5000);
136
+ result = await readStatus(session, project, deps);
137
+ }
138
+ }
139
+ async function checkProjectName(args, pretty, depth, deps) {
140
+ const command = 'projects create';
141
+ const project = parseName(args, pretty);
142
+ if (typeof project !== 'string')
143
+ return usageError(command, project.error, pretty, depth);
144
+ const sent = await authorized(deps, (session) => postJson(new URL(PROJECTS_PATH, session.siteUrl).href, session.token, { project, dryRun: true }, deps, pretty ? '이름을 확인하고 있습니다.' : null));
145
+ if ('login' in sent)
146
+ return sent.login;
147
+ const { session, result } = sent;
148
+ const failure = exchangeFailure(result);
149
+ const value = failure ? null : result.body;
150
+ if (failure || value?.ok !== true || value.dryRun !== true || value.project !== project || typeof value.available !== 'boolean' || typeof value.owned !== 'boolean') {
151
+ const shown = failure ?? UNEXPECTED;
152
+ return pretty
153
+ ? prettyResult(1, depth, command, '이름을 확인하지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
154
+ : agentResult(1, { command, siteUrl: session.siteUrl, dryRun: true, project, error: failureError(shown) });
155
+ }
156
+ const { available, owned } = value;
157
+ if (!pretty)
158
+ return agentResult(0, { command, siteUrl: session.siteUrl, dryRun: true, project, available, owned });
159
+ return prettyResult(0, depth, command, available
160
+ ? '쓸 수 있는 이름입니다. 프로젝트는 만들지 않았습니다.'
161
+ : owned ? '이미 내 프로젝트입니다. 새로 만들지 말고 이 이름으로 배포하세요.' : '다른 계정이 쓰는 이름입니다. 다른 이름을 고르세요.', [
162
+ ['서버', session.siteUrl], ['프로젝트', project]
163
+ ]);
164
+ }
165
+ export async function runProjectsCreate(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
166
+ const timeout = parseTimeout(args, SERVER_WAIT_SECONDS, pretty);
167
+ if ('error' in timeout)
168
+ return usageError('projects create', timeout.error, pretty, depth);
169
+ return timeout.rest.includes('--dry-run')
170
+ ? checkProjectName(timeout.rest.filter((arg) => arg !== '--dry-run'), pretty, depth, deps)
171
+ : runProjects('projects create', timeout.rest, pretty, depth, deps, timeout.waitMs);
172
+ }
173
+ export async function runProjectsStatus(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
174
+ const command = 'projects status';
175
+ const { args: rest, dryRun } = splitDryRun(args);
176
+ if (!dryRun)
177
+ return runProjects(command, rest, pretty, depth, deps, 0);
178
+ const project = parseName(rest, pretty);
179
+ if (typeof project !== 'string')
180
+ return usageError(command, project.error, pretty, depth);
181
+ return preview(command, pretty, depth, deps, (siteUrl) => new URL(`${PROJECTS_PATH}/${project}`, siteUrl).href);
182
+ }
183
+ const isDate = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
184
+ const isCount = (value) => Number.isInteger(value) && value >= 0;
185
+ function isProjectSummary(item) {
186
+ const value = item;
187
+ const server = value?.server;
188
+ const latest = value?.latest;
189
+ const live = value?.live;
190
+ const build = latest?.manifest?.build;
191
+ return typeof value?.project === 'string' && PROJECT.test(value.project) && isDate(value.createdAt)
192
+ && (value.publicUrl === null || (typeof value.publicUrl === 'string' && PUBLIC_URL.test(value.publicUrl)))
193
+ && (server === null || (typeof server === 'object' && typeof server.stage === 'string' && STAGES.includes(server.stage)
194
+ && typeof server.ready === 'boolean' && (server.errorCode === null || typeof server.errorCode === 'string')
195
+ && typeof server.message === 'string' && server.message.length <= 500 && !/[\x00-\x1f\x7f]/.test(server.message)))
196
+ && typeof value.status === 'string' && DEPLOY_STATUSES.includes(value.status)
197
+ && (latest === null || (typeof latest === 'object' && typeof latest.stage === 'string' && DEPLOY_STAGES.includes(latest.stage)
198
+ && isCount(latest.percent) && latest.percent <= 100 && (latest.errorCode === null || typeof latest.errorCode === 'string')
199
+ && typeof latest.manifest === 'object' && latest.manifest !== null && !Array.isArray(latest.manifest)
200
+ && (build === undefined || (typeof build === 'string' && BUILD.test(build))) && isDate(latest.updatedAt)))
201
+ && (live === null || (typeof live === 'object' && typeof live.commit === 'string' && COMMIT.test(live.commit) && isDate(live.publishedAt)))
202
+ && isCount(value.deployments);
203
+ }
204
+ function ago(iso, now) {
205
+ const minutes = Math.floor((now - Date.parse(iso)) / 60_000);
206
+ if (minutes < 1)
207
+ return '방금';
208
+ if (minutes < 60)
209
+ return `${minutes}분 전`;
210
+ if (minutes < 24 * 60)
211
+ return `${Math.floor(minutes / 60)}시간 전`;
212
+ const days = Math.floor(minutes / (24 * 60));
213
+ if (days === 1)
214
+ return '어제';
215
+ return days < 30 ? `${days}일 전` : iso.slice(0, 10);
216
+ }
217
+ const offline = ({ server, status, live }) => server?.stage === 'stopped' && live !== null && status !== 'deploying';
218
+ function projectRow(item, now) {
219
+ const { project, status, latest, live, deployments } = item;
220
+ const label = offline(item) ? '■ 서버 꺼짐' : status === 'failed' && latest?.errorCode === 'publish_failed' ? '✕ 빌드 실패' : STATUS_LABELS[status];
221
+ const build = !latest ? '-' : typeof latest.manifest.build === 'string' ? latest.manifest.build : '정적';
222
+ return [project, label, build, String(deployments), live ? ago(live.publishedAt, now) : '-'];
223
+ }
224
+ export async function runProjectsList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
225
+ const command = 'projects';
226
+ const invalid = (message) => usageError(command, message, pretty, depth);
227
+ const { args: rest, dryRun } = splitDryRun(args);
228
+ const flags = parseFlags(rest, ['--page'], pretty);
229
+ if ('error' in flags)
230
+ return invalid(flags.error);
231
+ const page = flags.entries[0]?.[1] ?? '1';
232
+ if (flags.entries.length > 1 || !/^[1-9]\d{0,5}$/.test(page))
233
+ return invalid(pretty ? '--page 에는 1 이상의 정수를 한 번만 지정하세요.' : 'Give --page once, as a positive integer.');
234
+ if (dryRun)
235
+ return preview(command, pretty, depth, deps, (siteUrl) => `${new URL(PROJECTS_PATH, siteUrl).href}?page=${page}`);
236
+ const sent = await authorized(deps, (session) => request(`${new URL(PROJECTS_PATH, session.siteUrl).href}?page=${page}`, {
237
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
238
+ }, deps, pretty ? '프로젝트 목록을 불러오고 있습니다.' : null));
239
+ if ('login' in sent)
240
+ return sent.login;
241
+ const { session, result } = sent;
242
+ const failure = exchangeFailure(result);
243
+ const value = failure ? null : result.body;
244
+ if (failure || value?.ok !== true || value.page !== Number(page) || !isCount(value.total) || !isCount(value.pageSize) || !isCount(value.totalPages)
245
+ || !Array.isArray(value.projects) || !value.projects.every(isProjectSummary)) {
246
+ const shown = failure ?? UNEXPECTED;
247
+ return pretty
248
+ ? prettyResult(1, depth, command, '프로젝트 목록을 확인하지 못했습니다.', [['서버', session.siteUrl], ['원인', shown.display]])
249
+ : agentResult(1, { command, siteUrl: session.siteUrl, error: failureError(shown) });
250
+ }
251
+ const { total, pageSize, totalPages } = value;
252
+ const projects = value.projects.map(({ project, createdAt, publicUrl, server, status, latest, live, deployments }) => ({ project, createdAt, publicUrl, server, status, latest, live, deployments }));
253
+ const next = value.page < totalPages ? `deepdynamic projects --page ${value.page + 1}` : null;
254
+ if (!pretty)
255
+ return agentResult(0, { command, siteUrl: session.siteUrl, total, page: value.page, pageSize, totalPages, next, projects });
256
+ const footer = [
257
+ ['페이지', `${value.page} / ${totalPages} (${total}개)`],
258
+ ...(next ? [['다음', next]] : []),
259
+ ...(projects.length ? [['주소', 'deepdynamic projects status <이름>']] : [])
260
+ ];
261
+ if (!projects.length) {
262
+ return prettyResult(0, depth, command, total ? `${value.page}페이지에는 프로젝트가 없습니다.` : '아직 프로젝트가 없습니다. deepdynamic projects create <이름> 으로 만드세요.', total ? footer : []);
263
+ }
264
+ const { accent, dim } = paint(depth);
265
+ const tones = { published: accent, none: dim };
266
+ const now = Date.now();
267
+ const table = [['이름', '상태', '빌드', '배포', '마지막 게시'], ...projects.map((item) => projectRow(item, now).map(plain))];
268
+ const widths = table[0].map((_, column) => Math.max(...table.map((row) => displayWidth(row[column]))));
269
+ const lines = table.map((row, index) => row.map((cell, column) => {
270
+ const text = column === 3 ? ' '.repeat(widths[column] - displayWidth(cell)) + cell : pad(cell, widths[column]);
271
+ if (index === 0)
272
+ return dim(text);
273
+ const item = projects[index - 1];
274
+ return column === 1 ? (offline(item) ? dim : tones[item.status] ?? String)(text) : text;
275
+ }).join(' ').trimEnd());
276
+ return prettyResult(0, depth, command, `최근 활동 순으로 ${projects.length}개를 표시했습니다.`, [
277
+ ...lines.map((line) => [null, new Styled(line)]),
278
+ [null, ''],
279
+ ...footer
280
+ ]);
281
+ }
282
+ function isDeployment(item) {
283
+ const value = item;
284
+ return typeof value?.commit === 'string' && COMMIT.test(value.commit)
285
+ && typeof value.publishedAt === 'string' && Number.isFinite(Date.parse(value.publishedAt))
286
+ && typeof value.current === 'boolean'
287
+ && typeof value.manifest === 'object' && value.manifest !== null && !Array.isArray(value.manifest);
288
+ }
289
+ function deploymentList(body, project) {
290
+ const value = body;
291
+ if (value?.ok !== true || value.project !== project || !Array.isArray(value.deployments) || !value.deployments.every(isDeployment))
292
+ return null;
293
+ return value.deployments.map(({ commit, publishedAt, current, manifest }) => ({ commit, publishedAt, current, manifest }));
294
+ }
295
+ async function loadHistory(command, project, pretty, depth, deps) {
296
+ const sent = await authorized(deps, (session) => request(new URL(`${PROJECTS_PATH}/${project}/deployments`, session.siteUrl).href, {
297
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
298
+ }, deps, null));
299
+ if ('login' in sent)
300
+ return { result: sent.login };
301
+ const failure = exchangeFailure(sent.result);
302
+ const deployments = failure ? null : deploymentList(sent.result.body, project);
303
+ if (deployments)
304
+ return { session: sent.session, deployments };
305
+ const shown = failure ?? UNEXPECTED;
306
+ return {
307
+ result: pretty
308
+ ? prettyResult(1, depth, command, '배포 이력을 확인하지 못했습니다.', [['서버', sent.session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
309
+ : agentResult(1, { command, siteUrl: sent.session.siteUrl, project, error: failureError(shown) })
310
+ };
311
+ }
312
+ export async function runProjectsHistory(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
313
+ const command = 'projects history';
314
+ const { args: rest, dryRun } = splitDryRun(args);
315
+ const project = parseName(rest, pretty);
316
+ if (typeof project !== 'string')
317
+ return usageError(command, project.error, pretty, depth);
318
+ if (dryRun)
319
+ return preview(command, pretty, depth, deps, (siteUrl) => new URL(`${PROJECTS_PATH}/${project}/deployments`, siteUrl).href);
320
+ const history = await loadHistory(command, project, pretty, depth, deps);
321
+ if ('result' in history)
322
+ return history.result;
323
+ const { session, deployments } = history;
324
+ if (!pretty)
325
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, deployments });
326
+ return prettyResult(0, depth, command, deployments.length ? `게시된 배포 ${deployments.length}개를 찾았습니다.` : '아직 게시된 배포가 없습니다.', [
327
+ ['서버', session.siteUrl], ['프로젝트', project],
328
+ ...deployments.map(({ commit, publishedAt, current }, index) => [
329
+ index === 0 ? '배포' : '',
330
+ `${commit.slice(0, 12)} ${new Date(publishedAt).toISOString().slice(0, 16).replace('T', ' ')} UTC${current ? ' (현재)' : ''}`
331
+ ])
332
+ ]);
333
+ }
334
+ const METRIC_PERIODS = ['24h', '7d', '30d'];
335
+ const PERIOD_LABELS = { '24h': '24시간', '7d': '7일', '30d': '30일' };
336
+ const PERIOD_LENGTHS = { '24h': 24, '7d': 7, '30d': 30 };
337
+ const isMetricPeriod = (value) => METRIC_PERIODS.includes(value);
338
+ const isPercent = (value) => typeof value === 'number' && value >= 0 && value <= 100;
339
+ const isStrings = (value, length) => Array.isArray(value) && value.length === length && value.every((item) => typeof item === 'string');
340
+ const isCounts = (value, length) => Array.isArray(value) && value.length === length && value.every(isCount);
341
+ function isShares(value, key) {
342
+ return Array.isArray(value) && value.every((item) => {
343
+ const share = item;
344
+ return typeof share?.[key] === 'string' && isCount(share.count) && isPercent(share.share);
345
+ });
346
+ }
347
+ const isNullableText = (value) => value === null || typeof value === 'string';
348
+ const isAdvisory = (value) => {
349
+ const item = value;
350
+ return typeof item?.product === 'string' && typeof item?.version === 'string' && (item?.severity === 'critical' || item?.severity === 'high') && typeof item?.summary === 'string' && typeof item?.reference === 'string';
351
+ };
352
+ const isSoftware = (value) => {
353
+ if (value === null)
354
+ return true;
355
+ if (typeof value !== 'object')
356
+ return false;
357
+ const { server, poweredBy, advisories } = value;
358
+ return isNullableText(server) && isNullableText(poweredBy) && Array.isArray(advisories) && advisories.every(isAdvisory);
359
+ };
360
+ const isTraffic = (value) => {
361
+ if (value === null)
362
+ return true;
363
+ if (typeof value !== 'object')
364
+ return false;
365
+ const { requests, pageviews, visitors, bots, statuses, paths } = value;
366
+ if (typeof statuses !== 'object' || statuses === null)
367
+ return false;
368
+ const { ok, redirect, client, server } = statuses;
369
+ return [requests, pageviews, visitors, bots, ok, redirect, client, server].every(isCount) && Array.isArray(paths) && isShares(paths, 'path');
370
+ };
371
+ function metricReport(body, project, period) {
372
+ const value = body;
373
+ const report = value?.report;
374
+ if (value?.ok !== true || value.project !== project || value.period !== period || !isDate(value.endDate) || !report)
375
+ return null;
376
+ const length = PERIOD_LENGTHS[period];
377
+ const { dates, labels, visits, views, previousVisits, previousViews, range, totalVisits, totalViews, previousTotalVisits, previousTotalViews, duration, previousDuration, bounce, previousBounce, sources, devices, pages } = report;
378
+ if (!isStrings(dates, length) || !isStrings(labels, length) || !isCounts(visits, length) || !isCounts(views, length) || !isCounts(previousVisits, length) || !isCounts(previousViews, length))
379
+ return null;
380
+ if (typeof range !== 'string' || !isCount(totalVisits) || !isCount(totalViews) || !isCount(previousTotalVisits) || !isCount(previousTotalViews) || !isCount(duration) || !isCount(previousDuration))
381
+ return null;
382
+ if (!isPercent(bounce) || !isPercent(previousBounce) || !isShares(sources, 'label') || !isShares(devices, 'label') || !isShares(pages, 'path'))
383
+ return null;
384
+ if (!isSoftware(value.software) || !isTraffic(value.traffic))
385
+ return null;
386
+ return {
387
+ endDate: value.endDate,
388
+ report: { dates, labels, visits, views, previousVisits, previousViews, range, totalVisits, totalViews, previousTotalVisits, previousTotalViews, duration, previousDuration, bounce, previousBounce, sources, devices, pages },
389
+ software: value.software,
390
+ traffic: value.traffic
391
+ };
392
+ }
393
+ function parseMetric(args, pretty) {
394
+ const parsed = parseCommand(args, ['--period'], pretty);
395
+ if ('error' in parsed)
396
+ return parsed;
397
+ const project = parseName(parsed.names, pretty);
398
+ if (typeof project !== 'string')
399
+ return project;
400
+ if (parsed.entries.length > 1)
401
+ return { error: pretty ? '--period 는 한 번만 지정하세요.' : 'Give --period only once.' };
402
+ const period = parsed.entries[0]?.[1] ?? '7d';
403
+ if (!isMetricPeriod(period)) {
404
+ return { error: pretty ? `--period 에는 ${METRIC_PERIODS.join(', ')} 중 하나를 지정하세요: ${period}` : `--period must be one of ${METRIC_PERIODS.join(', ')}: ${period}` };
405
+ }
406
+ return { project, period };
407
+ }
408
+ const metricNumber = (value) => value.toLocaleString('ko-KR');
409
+ const metricChange = (value, previous) => previous === 0 ? '비교 데이터 없음' : `이전 기간 대비 ${value < previous ? '-' : '+'}${(Math.abs(value - previous) / previous * 100).toFixed(1)}%`;
410
+ const compared = (shown, value, previous) => `${shown} · ${metricChange(value, previous)}`;
411
+ const stay = (seconds) => `${Math.floor(seconds / 60)}분 ${seconds % 60}초`;
412
+ const shares = (items) => items.map(({ label, share }) => `${label} ${share.toFixed(1)}%`).join(' · ');
413
+ const BAR_WIDTH = 20;
414
+ const severityLabels = { critical: '긴급', high: '주의' };
415
+ function trendRows(title, labels, current, previous) {
416
+ const peak = Math.max(1, ...current, ...previous);
417
+ return labels.map((label, index) => {
418
+ const width = current[index] > 0 ? Math.max(1, Math.round(current[index] / peak * BAR_WIDTH)) : 0;
419
+ return [index === 0 ? title : '', `${label.padEnd(8)}${'█'.repeat(width).padEnd(BAR_WIDTH)} ${metricNumber(current[index])}회 (이전 ${metricNumber(previous[index])}회)`];
420
+ });
421
+ }
422
+ function softwareRows({ server, poweredBy, advisories }) {
423
+ const observed = [server, poweredBy].filter(Boolean).join(' · ');
424
+ if (!observed)
425
+ return [['서버 소프트웨어', '아직 관측된 서버 응답이 없습니다.']];
426
+ const notes = advisories.length
427
+ ? advisories.map(({ severity, product, version, summary, reference }, index) => [index === 0 ? '취약 버전 안내' : '', `[${severityLabels[severity]}] ${product}/${version} · ${summary} (${reference})`])
428
+ : [['취약 버전 안내', '알려진 취약 버전이 없습니다.']];
429
+ return [['서버 소프트웨어', observed], ...notes];
430
+ }
431
+ function trafficRows(traffic) {
432
+ if (traffic.requests === 0)
433
+ return [['엣지 트래픽', '아직 집계된 요청이 없습니다.']];
434
+ const ratio = (count) => `${metricNumber(count)}회 (${(count / traffic.requests * 100).toFixed(1)}%)`;
435
+ return [
436
+ ['엣지 트래픽', `요청 수 ${metricNumber(traffic.requests)}회`],
437
+ ['서버 페이지뷰', `${metricNumber(traffic.pageviews)}회`],
438
+ ['방문자 (시간별 합)', `${metricNumber(traffic.visitors)}명`],
439
+ ['봇 요청', `${metricNumber(traffic.bots)}회`],
440
+ ['응답 정상 (2xx)', ratio(traffic.statuses.ok)],
441
+ ['응답 이동 (3xx)', ratio(traffic.statuses.redirect)],
442
+ ['요청 오류 (4xx)', ratio(traffic.statuses.client)],
443
+ ['서버 오류 (5xx)', ratio(traffic.statuses.server)],
444
+ ...traffic.paths.map(({ path, count, share }, index) => [index === 0 ? '서버 페이지뷰가 많은 경로' : '', `${path} ${metricNumber(count)}회 (${share.toFixed(1)}%)`])
445
+ ];
446
+ }
447
+ function metricRows(siteUrl, project, period, { report, software, traffic }) {
448
+ const { labels, visits, previousVisits, views, previousViews, range, totalVisits, totalViews, previousTotalVisits, previousTotalViews, duration, previousDuration, bounce, previousBounce, sources, devices, pages } = report;
449
+ return [
450
+ ['서버', siteUrl], ['프로젝트', project],
451
+ ['기간', `${PERIOD_LABELS[period]} · ${range} · 한국 시간`],
452
+ ['방문 수', compared(`${metricNumber(totalVisits)}회`, totalVisits, previousTotalVisits)],
453
+ ['페이지뷰', compared(`${metricNumber(totalViews)}회`, totalViews, previousTotalViews)],
454
+ ['평균 체류 시간', compared(stay(duration), duration, previousDuration)],
455
+ ['이탈률', compared(`${bounce.toFixed(1)}%`, bounce, previousBounce)],
456
+ ...trendRows('방문 추이', labels, visits, previousVisits),
457
+ ...trendRows('페이지뷰 추이', labels, views, previousViews),
458
+ ['유입 경로', shares(sources)],
459
+ ['기기', shares(devices)],
460
+ ...(software ? softwareRows(software) : []),
461
+ ...(traffic ? trafficRows(traffic) : []),
462
+ ...(pages.length
463
+ ? pages.map(({ path, count, share }, index) => [index === 0 ? '많이 찾은 페이지' : '', `${path} ${metricNumber(count)}회 (${share.toFixed(1)}%)`])
464
+ : [['많이 찾은 페이지', '없음']])
465
+ ];
466
+ }
467
+ export async function runProjectsMetric(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
468
+ const command = 'projects metric';
469
+ const { args: rest, dryRun } = splitDryRun(args);
470
+ const parsed = parseMetric(rest, pretty);
471
+ if ('error' in parsed)
472
+ return usageError(command, parsed.error, pretty, depth);
473
+ const { project, period } = parsed;
474
+ const url = (siteUrl) => `${new URL(`${PROJECTS_PATH}/${project}/metric`, siteUrl).href}?period=${period}`;
475
+ if (dryRun)
476
+ return preview(command, pretty, depth, deps, url);
477
+ const sent = await authorized(deps, (session) => request(url(session.siteUrl), {
478
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
479
+ }, deps, pretty ? '방문 통계를 불러오고 있습니다.' : null));
480
+ if ('login' in sent)
481
+ return sent.login;
482
+ const { session, result } = sent;
483
+ const failure = exchangeFailure(result);
484
+ const metric = failure ? null : metricReport(result.body, project, period);
485
+ if (!metric) {
486
+ const shown = failure ?? UNEXPECTED;
487
+ return pretty
488
+ ? prettyResult(1, depth, command, '방문 통계를 확인하지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
489
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
490
+ }
491
+ if (!pretty)
492
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, period, ...metric });
493
+ const message = metric.report.totalVisits ? `${PERIOD_LABELS[period]} 방문 통계를 불러왔습니다.` : `${PERIOD_LABELS[period]} 동안 방문 기록이 없습니다.`;
494
+ return prettyResult(0, depth, command, message, metricRows(session.siteUrl, project, period, metric));
495
+ }
496
+ export async function runProjectsRollback(args, pretty, depth, deps = { ...defaultAuthDeps(pretty, depth), restore: restoreDeployment }) {
497
+ const command = 'projects rollback';
498
+ const invalid = (message) => usageError(command, message, pretty, depth);
499
+ const { args: plain, dryRun } = splitDryRun(args);
500
+ const { args: rest, yes } = splitYes(plain);
501
+ const timeout = parseTimeout(rest, PUBLISH_WAIT_SECONDS, pretty);
502
+ if ('error' in timeout)
503
+ return invalid(timeout.error);
504
+ const parsed = parseCommand(timeout.rest, ['--to'], pretty);
505
+ if ('error' in parsed)
506
+ return invalid(parsed.error);
507
+ const project = parseName(parsed.names, pretty);
508
+ if (typeof project !== 'string')
509
+ return invalid(project.error);
510
+ const to = parsed.entries[0]?.[1];
511
+ if (parsed.entries.length > 1 || (to !== undefined && !COMMIT_PREFIX.test(to))) {
512
+ return invalid(pretty ? '--to 에는 deepdynamic projects history 에 나온 커밋을 7~40자로 한 번만 지정하세요.' : 'Give --to once, as 7-40 lowercase hex characters of a commit from deepdynamic projects history.');
513
+ }
514
+ if (dryRun)
515
+ return plannedRollback(project, to ?? null, pretty, depth, deps);
516
+ if (!yes) {
517
+ return confirmationRequired(command, plain, pretty, depth, {
518
+ message: 'Rolling back replaces the live site with an earlier deployment.',
519
+ display: '되돌리면 지금 게시된 사이트가 이전 배포로 바뀝니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.'
520
+ }, { project });
521
+ }
522
+ const history = await loadHistory(command, project, pretty, depth, deps);
523
+ if ('result' in history)
524
+ return history.result;
525
+ const { session, deployments } = history;
526
+ const refuse = (code, message, display) => pretty
527
+ ? prettyResult(1, depth, command, display, [['서버', session.siteUrl], ['프로젝트', project]])
528
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, deployments, error: { code, message } });
529
+ const matches = to === undefined ? deployments.slice(1, 2) : deployments.filter(({ commit }) => commit.startsWith(to));
530
+ if (matches.length !== 1) {
531
+ return to === undefined
532
+ ? refuse('no_previous_deployment', 'There is no earlier published deployment to roll back to. Nothing was changed.', '되돌릴 이전 배포가 없습니다. 바꾼 것이 없습니다.')
533
+ : refuse('deployment_not_found', `No single published deployment matches ${to}. Pick a commit from deepdynamic projects history ${project}. Nothing was changed.`, `${to} 에 맞는 배포를 하나로 정하지 못했습니다. deepdynamic projects history ${project} 로 커밋을 확인하세요.`);
534
+ }
535
+ const [target] = matches;
536
+ if (target.current)
537
+ return refuse('already_current', 'That deployment is already published. Nothing was changed.', '이미 게시 중인 배포입니다. 바꾼 것이 없습니다.');
538
+ return shipDeployment({
539
+ command, project, manifest: target.manifest,
540
+ context: { project, target: { commit: target.commit, publishedAt: target.publishedAt } },
541
+ success: {},
542
+ rows: [['프로젝트', project], ['되돌릴 커밋', target.commit]],
543
+ waitMs: timeout.waitMs,
544
+ send: (remote, branch, token, onUploading) => deps.restore(remote, branch, token, target.commit, { onUploading })
545
+ }, pretty, depth, deps);
546
+ }
547
+ async function plannedRollback(project, to, pretty, depth, deps) {
548
+ const command = 'projects rollback';
549
+ const session = await signedIn(deps);
550
+ if ('login' in session)
551
+ return session.login;
552
+ const { siteUrl } = session;
553
+ const requests = [
554
+ { method: 'GET', url: new URL(`${PROJECTS_PATH}/${project}/deployments`, siteUrl).href },
555
+ { method: 'POST', url: new URL('/api/v1/deployments', siteUrl).href, body: { project } },
556
+ { method: 'POST', url: new URL('/api/v1/git/repository', siteUrl).href, body: { project } }
557
+ ];
558
+ if (!pretty)
559
+ return agentResult(0, { command, siteUrl, dryRun: true, applied: false, plan: { project, to }, requests });
560
+ return prettyResult(0, depth, command, '되돌리기를 확인했습니다. 되돌리지 않았습니다.', [
561
+ ['서버', siteUrl], ['프로젝트', project], ['되돌릴 커밋', to ?? '지금 게시된 배포의 바로 전 배포'],
562
+ ...requests.map(({ method, url }, index) => [index === 0 ? '요청' : '', `${method} ${url}`])
563
+ ]);
564
+ }
565
+ export async function runProjectsRename(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
566
+ const command = 'projects rename';
567
+ const invalid = (message) => usageError(command, message, pretty, depth);
568
+ const dryRun = args.includes('--dry-run');
569
+ const parsed = parseCommand(args.filter((arg) => arg !== '--dry-run'), [], pretty);
570
+ if ('error' in parsed)
571
+ return invalid(parsed.error);
572
+ const { names } = parsed;
573
+ if (names.length !== 2)
574
+ return invalid(pretty ? '지금 이름과 새 이름을 차례로 지정하세요.' : 'Specify the current name and then the new name.');
575
+ const [project, name] = names.map((value) => parseName([value], pretty));
576
+ if (typeof project !== 'string')
577
+ return invalid(project.error);
578
+ if (typeof name !== 'string')
579
+ return invalid(name.error);
580
+ if (project === name)
581
+ return invalid(pretty ? '새 이름이 지금 이름과 같습니다.' : 'The new name is the same as the current name.');
582
+ const sent = await authorized(deps, (session) => postJson(new URL(`${PROJECTS_PATH}/${project}/rename`, session.siteUrl).href, session.token, dryRun ? { name, dryRun: true } : { name }, deps, pretty ? (dryRun ? '이름을 확인하고 있습니다.' : '프로젝트 이름을 바꾸고 있습니다.') : null));
583
+ if ('login' in sent)
584
+ return sent.login;
585
+ const { session, result } = sent;
586
+ const failure = !('failure' in result) && result.status === 409
587
+ ? { code: 'project_taken', message: 'Another project already uses that name. Pick another name with the naming steps in deepdynamic projects create --help.', display: '이미 쓰이는 이름입니다. 다른 이름을 고르세요.' }
588
+ : exchangeFailure(result);
589
+ const value = failure ? null : result.body;
590
+ const valid = dryRun
591
+ ? value?.ok === true && value.dryRun === true && value.project === project && value.name === name && typeof value.available === 'boolean'
592
+ : value?.ok === true && value.project === name && value.previous === project && value.renamed === true;
593
+ if (failure || !valid) {
594
+ const shown = failure ?? UNEXPECTED;
595
+ return pretty
596
+ ? prettyResult(1, depth, command, '프로젝트 이름을 바꾸지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['새 이름', name], ['원인', shown.display]])
597
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, name, renamed: false, error: failureError(shown) });
598
+ }
599
+ if (dryRun) {
600
+ const available = value?.available === true;
601
+ if (!pretty)
602
+ return agentResult(0, { command, siteUrl: session.siteUrl, dryRun: true, project, name, available });
603
+ return prettyResult(0, depth, command, available ? '쓸 수 있는 이름입니다. 이름은 바꾸지 않았습니다.' : '이미 쓰이는 이름입니다. 다른 이름을 고르세요.', [
604
+ ['서버', session.siteUrl], ['프로젝트', project], ['새 이름', name]
605
+ ]);
606
+ }
607
+ if (!pretty)
608
+ return agentResult(0, { command, siteUrl: session.siteUrl, project: name, previous: project, renamed: true });
609
+ return prettyResult(0, depth, command, '프로젝트 이름을 바꿨습니다. 발급 주소는 새 이름으로 바뀌고 다음 배포 때 연결됩니다. 서버·저장소·배포 이력은 그대로입니다.', [
610
+ ['서버', session.siteUrl], ['이전 이름', project], ['새 이름', name], ['배포', `deepdynamic projects deploy ${name} <폴더> --agent <코드>`]
611
+ ]);
612
+ }
613
+ const pwaLabel = (enabled) => enabled ? '켬' : '끔';
614
+ function pwaFailure(result) {
615
+ if ('failure' in result)
616
+ return result.failure;
617
+ if (result.status === 403)
618
+ return { code: 'login_required', message: 'The access token lacks the project scope for this command. Run deepdynamic login again.', display: '이 로그인으로는 할 수 없습니다. deepdynamic login 으로 다시 로그인하세요.' };
619
+ if (result.status === 503)
620
+ return supportFailure('unavailable', { note: { en: 'The setting was not applied.', ko: '설정은 바뀌지 않았습니다.' }, retryable: true });
621
+ return exchangeFailure(result);
622
+ }
623
+ function pwaState(body, project) {
624
+ const value = body;
625
+ return value?.ok === true && value.project === project && typeof value.pwa === 'boolean' ? value.pwa : null;
626
+ }
627
+ export async function runProjectsPwa(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
628
+ const command = 'projects pwa';
629
+ const invalid = (message) => usageError(command, message, pretty, depth);
630
+ const { args: rest, dryRun } = splitDryRun(args);
631
+ const parsed = parseCommand(rest, [], pretty);
632
+ if ('error' in parsed)
633
+ return invalid(parsed.error);
634
+ const [input, state, ...extra] = parsed.names;
635
+ if (input === undefined)
636
+ return invalid(pretty ? '프로젝트 이름을 지정하세요.' : 'Specify the project name.');
637
+ const project = parseName([input], pretty);
638
+ if (typeof project !== 'string')
639
+ return invalid(project.error);
640
+ if (state !== undefined && state !== 'on' && state !== 'off')
641
+ return invalid(pretty ? '프로젝트 이름 뒤에는 on 또는 off 만 올 수 있습니다.' : 'After the project name give on or off, or nothing to show the current state.');
642
+ if (extra.length)
643
+ return invalid(unknownArgument(extra[0], pretty));
644
+ const enabled = state === undefined ? null : state === 'on';
645
+ const url = (siteUrl) => new URL(`${PROJECTS_PATH}/${project}/pwa`, siteUrl).href;
646
+ if (dryRun) {
647
+ if (enabled === null)
648
+ return preview(command, pretty, depth, deps, url);
649
+ const session = await signedIn(deps);
650
+ if ('login' in session)
651
+ return session.login;
652
+ return plannedChange(command, pretty, depth, session.siteUrl, { url: url(session.siteUrl), body: { enabled } }, '앱 설치(PWA) 변경을 확인했습니다. 바꾸지 않았습니다.', [['프로젝트', project], ['바꿀 설정', `앱 설치(PWA) ${pwaLabel(enabled)}`]], { project, pwa: enabled });
653
+ }
654
+ const sent = await authorized(deps, (session) => enabled === null
655
+ ? request(url(session.siteUrl), { method: 'GET', headers: { authorization: `Bearer ${session.token}` } }, deps, pretty ? '앱 설치 설정을 불러오고 있습니다.' : null)
656
+ : postJson(url(session.siteUrl), session.token, { enabled }, deps, pretty ? '앱 설치 설정을 바꾸고 있습니다.' : null));
657
+ if ('login' in sent)
658
+ return sent.login;
659
+ const { session, result } = sent;
660
+ const failure = pwaFailure(result);
661
+ const pwa = failure ? null : pwaState(result.body, project);
662
+ if (pwa === null) {
663
+ const shown = failure ?? UNEXPECTED;
664
+ return pretty
665
+ ? prettyResult(1, depth, command, enabled === null ? '앱 설치 설정을 확인하지 못했습니다.' : '앱 설치 설정을 바꾸지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
666
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
667
+ }
668
+ if (!pretty)
669
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, pwa });
670
+ const message = enabled === null
671
+ ? (pwa ? '방문자가 이 사이트를 앱으로 설치할 수 있습니다.' : '앱 설치가 꺼져 있습니다.')
672
+ : (pwa ? '앱 설치(PWA)를 켰습니다. 방문자가 사이트를 앱으로 설치할 수 있습니다.' : '앱 설치(PWA)를 껐습니다. 설치 안내가 더 이상 뜨지 않습니다.');
673
+ return prettyResult(0, depth, command, message, [['서버', session.siteUrl], ['프로젝트', project], ['앱 설치(PWA)', pwaLabel(pwa)]]);
674
+ }
675
+ function postProject(session, project, action, deps, spinner) {
676
+ return request(new URL(`${PROJECTS_PATH}/${project}/${action}`, session.siteUrl).href, {
677
+ method: 'POST', headers: { authorization: `Bearer ${session.token}` }
678
+ }, deps, spinner);
679
+ }
680
+ async function plannedProjectChange(command, project, action, message, pretty, depth, deps) {
681
+ const session = await signedIn(deps);
682
+ if ('login' in session)
683
+ return session.login;
684
+ return plannedChange(command, pretty, depth, session.siteUrl, { url: new URL(`${PROJECTS_PATH}/${project}/${action}`, session.siteUrl).href }, message, [['프로젝트', project]], { project });
685
+ }
686
+ export async function runProjectsStop(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
687
+ const command = 'projects stop';
688
+ const { args: plain, dryRun } = splitDryRun(args);
689
+ const { args: rest, yes } = splitYes(plain);
690
+ const project = parseName(rest, pretty);
691
+ if (typeof project !== 'string')
692
+ return usageError(command, project.error, pretty, depth);
693
+ if (dryRun)
694
+ return plannedProjectChange(command, project, 'stop', '프로젝트 서버 끄기를 확인했습니다. 끄지 않았습니다.', pretty, depth, deps);
695
+ if (!yes) {
696
+ return confirmationRequired(command, plain, pretty, depth, {
697
+ message: 'Stopping cancels the running deploys of the project and turns its server off, so the site is offline until the next deploy.',
698
+ display: '끄면 진행 중인 배포가 취소되고 다음 배포 전까지 사이트가 내려갑니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.'
699
+ }, { project });
700
+ }
701
+ const sent = await authorized(deps, (session) => postProject(session, project, 'stop', deps, pretty ? '프로젝트 서버를 끄고 있습니다.' : null));
702
+ if ('login' in sent)
703
+ return sent.login;
704
+ const { session, result } = sent;
705
+ const failure = !('failure' in result) && result.status === 409
706
+ ? { code: 'server_updating', message: 'The project server is installing updates. Keep running deepdynamic projects stop until it no longer fails with server_updating.', display: '프로젝트 서버가 업데이트를 설치하고 있습니다. 업데이트가 끝나면 다시 시도하세요.' }
707
+ : exchangeFailure(result);
708
+ const status = failure ? null : projectStatus(result.body, project);
709
+ if (!status) {
710
+ const shown = failure ?? UNEXPECTED;
711
+ return pretty
712
+ ? prettyResult(1, depth, command, '프로젝트 서버를 끄지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
713
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
714
+ }
715
+ const { server, site } = status;
716
+ return finish(command, 0, depth, pretty, session.siteUrl, project, server, site, null, server.stage === 'stopped' ? '프로젝트 서버를 껐습니다. 다시 배포하면 켜집니다.' : '켜져 있는 프로젝트 서버가 없습니다.');
717
+ }
718
+ export async function runProjectsDelete(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
719
+ const command = 'projects delete';
720
+ const { args: plain, dryRun } = splitDryRun(args);
721
+ const { args: rest, yes } = splitYes(plain);
722
+ const project = parseName(rest, pretty);
723
+ if (typeof project !== 'string')
724
+ return usageError(command, project.error, pretty, depth);
725
+ if (dryRun)
726
+ return plannedProjectChange(command, project, 'delete', '프로젝트 삭제를 확인했습니다. 삭제하지 않았습니다.', pretty, depth, deps);
727
+ if (!yes) {
728
+ return confirmationRequired(command, plain, pretty, depth, {
729
+ message: 'Deleting removes the project, its server and its deploy history permanently.',
730
+ display: '삭제하면 프로젝트와 서버, 배포 이력이 모두 사라지고 되돌릴 수 없습니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.'
731
+ }, { project });
732
+ }
733
+ const sent = await authorized(deps, (session) => postProject(session, project, 'delete', deps, pretty ? '프로젝트를 삭제하고 있습니다.' : null));
734
+ if ('login' in sent)
735
+ return sent.login;
736
+ const { session, result } = sent;
737
+ const failure = !('failure' in result) && result.status === 409
738
+ ? { code: 'server_busy', message: 'The project server is busy with another job. Try again after it finishes.', display: '프로젝트 서버가 아직 만들어지는 중이거나 다른 작업을 하고 있습니다. 작업이 끝나면 다시 시도하세요.' }
739
+ : exchangeFailure(result);
740
+ const value = failure ? null : result.body;
741
+ if (failure || value?.ok !== true || value.project !== project || value.deleted !== true) {
742
+ const shown = failure ?? UNEXPECTED;
743
+ return pretty
744
+ ? prettyResult(1, depth, command, '프로젝트를 삭제하지 못했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['원인', shown.display]])
745
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, deleted: false, error: failureError(shown) });
746
+ }
747
+ if (!pretty)
748
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, deleted: true });
749
+ return prettyResult(0, depth, command, '프로젝트를 삭제했습니다. 서버는 뒤에서 끄고 지웁니다.', [['서버', session.siteUrl], ['프로젝트', project]]);
750
+ }
751
+ const PHOTOCARD_SIDES = [1, 2];
752
+ const PHOTOCARD_LABELS = { 1: '앞면', 2: '뒷면' };
753
+ const FLIGHT_REQUIRED = {
754
+ code: 'flight_required',
755
+ message: 'The project has no flight yet. Deploy it once with deepdynamic projects deploy <name> <directory> --agent <code>, then run this again.',
756
+ display: '아직 편명이 없는 프로젝트입니다. --agent 를 붙여 한 번 배포한 뒤 다시 실행하세요.'
757
+ };
758
+ function attachmentName(header) {
759
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header ?? '')?.[1];
760
+ try {
761
+ return encoded ? decodeURIComponent(encoded) : null;
762
+ }
763
+ catch {
764
+ return null;
765
+ }
766
+ }
767
+ async function readPhotocard(response) {
768
+ if (response.status !== 200 || !response.headers.get('content-type')?.startsWith('image/png'))
769
+ return readJson(response);
770
+ return { bytes: new Uint8Array(await response.arrayBuffer()), filename: attachmentName(response.headers.get('content-disposition')) };
771
+ }
772
+ const isPhotocardImage = (body) => {
773
+ const value = body;
774
+ return value?.bytes instanceof Uint8Array && (value.filename === null || typeof value.filename === 'string');
775
+ };
776
+ const PHOTOCARD_FILE = /^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,240}\.png$/iu;
777
+ const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\.|$)/i;
778
+ function photocardFile(name, fallback) {
779
+ const cleaned = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} ._-]/gu, '_');
780
+ return PHOTOCARD_FILE.test(cleaned) && !WINDOWS_DEVICE.test(cleaned) ? cleaned : fallback;
781
+ }
782
+ export async function runProjectsPhotocard(args, pretty, depth, deps = { ...defaultAuthDeps(pretty, depth), writeFile: (path, bytes) => writeFile(path, bytes) }) {
783
+ const command = 'projects photocard';
784
+ const invalid = (message) => usageError(command, message, pretty, depth);
785
+ const { args: rest, dryRun } = splitDryRun(args);
786
+ const parsed = parseCommand(rest, ['--out'], pretty);
787
+ if ('error' in parsed)
788
+ return invalid(parsed.error);
789
+ const project = parseName(parsed.names, pretty);
790
+ if (typeof project !== 'string')
791
+ return invalid(project.error);
792
+ if (parsed.entries.length > 1)
793
+ return invalid(pretty ? '--out 은 한 번만 지정하세요.' : 'Give --out at most once.');
794
+ const out = parsed.entries[0]?.[1] ?? '.';
795
+ const url = (siteUrl, side) => `${new URL(`${PROJECTS_PATH}/${project}/photocard`, siteUrl).href}?side=${side}`;
796
+ if (dryRun) {
797
+ const session = await signedIn(deps);
798
+ if ('login' in session)
799
+ return session.login;
800
+ const requests = PHOTOCARD_SIDES.map((side) => ({ method: 'GET', url: url(session.siteUrl, side) }));
801
+ return pretty
802
+ ? prettyResult(0, depth, command, '요청을 보내지 않고 확인만 했습니다.', [['서버', session.siteUrl], ['프로젝트', project], ['저장 폴더', out], ...requests.map(({ url }) => ['요청', `GET ${url}`])])
803
+ : agentResult(0, { command, siteUrl: session.siteUrl, dryRun: true, project, out, requests });
804
+ }
805
+ const images = [];
806
+ const failed = (siteUrl, shown) => pretty
807
+ ? prettyResult(1, depth, command, '포토카드를 저장하지 못했습니다.', [['서버', siteUrl], ['프로젝트', project], ['원인', shown.display]])
808
+ : agentResult(1, { command, siteUrl, project, images, error: failureError(shown) });
809
+ let siteUrl = '';
810
+ for (const side of PHOTOCARD_SIDES) {
811
+ const sent = await authorized(deps, (session) => request(url(session.siteUrl, side), {
812
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
813
+ }, deps, pretty ? `포토카드 ${PHOTOCARD_LABELS[side]}을 만들고 있습니다.` : null, readPhotocard));
814
+ if ('login' in sent)
815
+ return sent.login;
816
+ siteUrl = sent.session.siteUrl;
817
+ const { result } = sent;
818
+ const failure = !('failure' in result) && result.status === 409 ? FLIGHT_REQUIRED : exchangeFailure(result);
819
+ const image = failure ? null : isPhotocardImage(result.body) ? result.body : null;
820
+ if (!image)
821
+ return failed(siteUrl, failure ?? UNEXPECTED);
822
+ const path = join(out, photocardFile(image.filename, `${project}-${side}.png`));
823
+ try {
824
+ await deps.writeFile(path, image.bytes);
825
+ }
826
+ catch {
827
+ return failed(siteUrl, { code: 'save_failed', message: `Could not write ${path}. Check that the directory exists and is writable.`, display: `${path} 에 쓰지 못했습니다. 폴더가 있고 쓸 수 있는지 확인하세요.` });
828
+ }
829
+ images.push({ side, path, bytes: image.bytes.length });
830
+ }
831
+ if (!pretty)
832
+ return agentResult(0, { command, siteUrl, project, images });
833
+ return prettyResult(0, depth, command, '포토카드 앞면과 뒷면을 PNG 로 저장했습니다.', [
834
+ ['서버', siteUrl], ['프로젝트', project], ...images.map(({ side, path }) => [PHOTOCARD_LABELS[side], path])
835
+ ]);
836
+ }