@deepdynamic/cli 0.0.0-stage → 0.1.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.
Files changed (84) 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 +190 -0
  7. package/dist/agents/refresh.js +20 -0
  8. package/dist/agents/setup.js +29 -0
  9. package/dist/agents/targets.js +91 -0
  10. package/dist/auth/credentials.js +63 -0
  11. package/dist/auth/session.js +49 -0
  12. package/dist/cli.js +198 -0
  13. package/dist/commands/account.js +96 -0
  14. package/dist/commands/activity.js +80 -0
  15. package/dist/commands/blocked.js +89 -0
  16. package/dist/commands/deploy/agents.js +11 -0
  17. package/dist/commands/deploy/files.js +62 -0
  18. package/dist/commands/deploy/index.js +95 -0
  19. package/dist/commands/deploy/manifest.js +24 -0
  20. package/dist/commands/deploy/minify.js +27 -0
  21. package/dist/commands/deploy/progress.js +85 -0
  22. package/dist/commands/deploy/ship.js +117 -0
  23. package/dist/commands/deploy/upload.js +125 -0
  24. package/dist/commands/deployments.js +60 -0
  25. package/dist/commands/dns.js +777 -0
  26. package/dist/commands/domains.js +639 -0
  27. package/dist/commands/emails.js +74 -0
  28. package/dist/commands/env.js +194 -0
  29. package/dist/commands/help.js +148 -0
  30. package/dist/commands/keys.js +263 -0
  31. package/dist/commands/login/flow.js +155 -0
  32. package/dist/commands/login/index.js +26 -0
  33. package/dist/commands/logout.js +71 -0
  34. package/dist/commands/mail.js +241 -0
  35. package/dist/commands/notifications.js +133 -0
  36. package/dist/commands/plan.js +355 -0
  37. package/dist/commands/projects.js +838 -0
  38. package/dist/commands/reference.js +2187 -0
  39. package/dist/commands/search.js +86 -0
  40. package/dist/commands/server.js +301 -0
  41. package/dist/commands/sessions.js +114 -0
  42. package/dist/commands/sites.js +102 -0
  43. package/dist/commands/sms.js +65 -0
  44. package/dist/commands/status.js +87 -0
  45. package/dist/commands/support.js +115 -0
  46. package/dist/commands/update.js +100 -0
  47. package/dist/commands/usage.js +51 -0
  48. package/dist/commands/verify.js +149 -0
  49. package/dist/commands/version.js +6 -0
  50. package/dist/guide.js +37 -0
  51. package/dist/http/call.js +6 -0
  52. package/dist/http/request.js +54 -0
  53. package/dist/index.js +11 -0
  54. package/dist/metadata.js +4 -0
  55. package/dist/output.js +9 -0
  56. package/dist/pretty.js +70 -0
  57. package/dist/refresh-skills.js +5 -0
  58. package/dist/registry.js +688 -0
  59. package/dist/runtime/browser.js +15 -0
  60. package/dist/runtime/card-request.js +55 -0
  61. package/dist/runtime/confirm.js +21 -0
  62. package/dist/runtime/development.js +13 -0
  63. package/dist/runtime/domain-name.js +5 -0
  64. package/dist/runtime/dry-run.js +28 -0
  65. package/dist/runtime/env-file.js +55 -0
  66. package/dist/runtime/error-hints.js +26 -0
  67. package/dist/runtime/flags.js +48 -0
  68. package/dist/runtime/login-screen.js +78 -0
  69. package/dist/runtime/page.js +18 -0
  70. package/dist/runtime/project-name.js +1 -0
  71. package/dist/runtime/run-mode.js +7 -0
  72. package/dist/runtime/server-options.js +28 -0
  73. package/dist/runtime/spinner.js +17 -0
  74. package/dist/runtime/suggest.js +22 -0
  75. package/dist/runtime/support.js +13 -0
  76. package/dist/runtime/text-file.js +20 -0
  77. package/dist/runtime/timeout.js +22 -0
  78. package/dist/runtime/update-check.js +158 -0
  79. package/dist/runtime/update-install.js +80 -0
  80. package/dist/runtime/usage-error.js +9 -0
  81. package/dist/setup-agents.js +15 -0
  82. package/dist/site.js +1 -0
  83. package/dist/update-refresh.js +5 -0
  84. package/package.json +46 -3
@@ -0,0 +1,838 @@
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: '● Published', deploying: '◐ Deploying', failed: '✕ Deploy failed', none: '○ Not deployed' };
28
+ const plainFailure = (code, message) => ({ code, message, display: message });
29
+ const counted = (count, noun) => `${count.toLocaleString('en-US')} ${noun}${count === 1 ? '' : 's'}`;
30
+ function projectStatus(body, project) {
31
+ const value = body;
32
+ const server = value?.server;
33
+ const site = value?.publicUrl ?? null;
34
+ if (value?.ok !== true || value.project !== project || !server || typeof server.stage !== 'string' || !STAGES.includes(server.stage)
35
+ || (site !== null && (typeof site !== 'string' || !PUBLIC_URL.test(site)))
36
+ || typeof server.ready !== 'boolean' || (server.errorCode !== null && typeof server.errorCode !== 'string')
37
+ || typeof server.message !== 'string' || server.message.length > 500 || /[\x00-\x1f\x7f]/.test(server.message)
38
+ || (value.pollAfterMs !== null && (typeof value.pollAfterMs !== 'number' || value.pollAfterMs < 1000 || value.pollAfterMs > 60_000)))
39
+ return null;
40
+ return {
41
+ server: { stage: server.stage, ready: server.ready, errorCode: server.errorCode, message: server.message },
42
+ site: site,
43
+ poll: value.pollAfterMs
44
+ };
45
+ }
46
+ async function preview(command, pretty, depth, deps, url) {
47
+ const session = await signedIn(deps);
48
+ if ('login' in session)
49
+ return session.login;
50
+ return plannedRequest(command, pretty, depth, session.siteUrl, url(session.siteUrl));
51
+ }
52
+ function readStatus(session, project, deps) {
53
+ return request(new URL(`${PROJECTS_PATH}/${project}`, session.siteUrl).href, {
54
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
55
+ }, deps, null);
56
+ }
57
+ function exchangeFailure(result) {
58
+ if ('failure' in result)
59
+ return result.failure;
60
+ if (result.status === 401)
61
+ return LOGIN_EXPIRED;
62
+ if (result.status === 404)
63
+ return plainFailure('project_not_found', 'You have no project with that name. Create it with deepdynamic projects create <name>.');
64
+ if (result.status === 409)
65
+ return plainFailure('project_taken', 'Another account already uses that project name. Choose a different name.');
66
+ if (result.status === 400)
67
+ return plainFailure('invalid_arguments', 'The server rejected the project name. Follow the naming steps in deepdynamic projects create --help.');
68
+ if (result.status !== 200 && result.status !== 201)
69
+ return httpFailure(result.status);
70
+ return null;
71
+ }
72
+ function parseName(args) {
73
+ const parsed = parseCommand(args, []);
74
+ if ('error' in parsed)
75
+ return parsed;
76
+ const { names } = parsed;
77
+ if (names.length !== 1)
78
+ return { error: 'Specify exactly one project name.' };
79
+ if (!PROJECT.test(names[0]))
80
+ return { error: 'Project names are 1-63 lowercase letters, digits or hyphens and start and end with a letter or digit.' };
81
+ return names[0];
82
+ }
83
+ function finish(command, code, depth, pretty, siteUrl, project, server, site, failure, message) {
84
+ if (pretty) {
85
+ return prettyResult(code, depth, command, message, [
86
+ ['Server', siteUrl], ['Project', project], ...(site ? [['Site URL', site]] : []), ['Status', failure?.display ?? server.message]
87
+ ]);
88
+ }
89
+ return agentResult(code, {
90
+ command, siteUrl, project, publicUrl: site, server,
91
+ ...(failure ? { error: { code: failure.code, message: failure.message } } : {})
92
+ });
93
+ }
94
+ async function runProjects(command, args, pretty, depth, deps, waitMs) {
95
+ const { usage } = spec(command);
96
+ const project = parseName(args);
97
+ if (typeof project !== 'string') {
98
+ return pretty
99
+ ? prettyResult(2, depth, command, project.error, [['Usage', usage]])
100
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: project.error }, usage });
101
+ }
102
+ const sent = await authorized(deps, (session) => command === 'projects create'
103
+ ? postJson(new URL(PROJECTS_PATH, session.siteUrl).href, session.token, { project }, deps, pretty ? 'Creating the project.' : null)
104
+ : readStatus(session, project, deps));
105
+ if ('login' in sent)
106
+ return sent.login;
107
+ const { session } = sent;
108
+ if (cardRequired(sent.result))
109
+ return requestCard(command, pretty, depth, session, deps, { project });
110
+ let result = sent.result;
111
+ let lastOutput = '';
112
+ for (const deadline = Date.now() + waitMs;;) {
113
+ const failure = exchangeFailure(result);
114
+ const status = failure ? null : projectStatus(result.body, project);
115
+ if (!status) {
116
+ const shown = failure ?? UNEXPECTED;
117
+ return pretty
118
+ ? prettyResult(1, depth, command, 'Could not check the project.', [['Server', session.siteUrl], ['Project', project], ['Reason', shown.display]])
119
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
120
+ }
121
+ const { server, site, poll } = status;
122
+ if (server.stage === 'failed') {
123
+ const failed = supportFailure('server_failed');
124
+ return finish(command, 1, depth, pretty, session.siteUrl, project, server, site, failed, 'Could not prepare the project server.');
125
+ }
126
+ if (server.ready || command === 'projects status') {
127
+ return finish(command, 0, depth, pretty, session.siteUrl, project, server, site, null, server.ready ? 'The project server is ready.' : 'The project server is being prepared.');
128
+ }
129
+ const output = pretty ? `${plain(server.message)}\n` : jsonLine({ event: 'project_progress', project, server });
130
+ if (output !== lastOutput)
131
+ deps.stream.write(output);
132
+ lastOutput = output;
133
+ if (Date.now() >= deadline) {
134
+ 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: `Still being prepared. Keep checking with deepdynamic projects status ${project} until it is ready.` };
135
+ return finish(command, 1, depth, pretty, session.siteUrl, project, server, site, pending, 'The project server is still being prepared.');
136
+ }
137
+ await (deps.pause ?? pauseFor)(poll ?? 5000);
138
+ result = await readStatus(session, project, deps);
139
+ }
140
+ }
141
+ async function checkProjectName(args, pretty, depth, deps) {
142
+ const command = 'projects create';
143
+ const project = parseName(args);
144
+ if (typeof project !== 'string')
145
+ return usageError(command, project.error, pretty, depth);
146
+ const sent = await authorized(deps, (session) => postJson(new URL(PROJECTS_PATH, session.siteUrl).href, session.token, { project, dryRun: true }, deps, pretty ? 'Checking the name.' : null));
147
+ if ('login' in sent)
148
+ return sent.login;
149
+ const { session, result } = sent;
150
+ const failure = exchangeFailure(result);
151
+ const value = failure ? null : result.body;
152
+ if (failure || value?.ok !== true || value.dryRun !== true || value.project !== project || typeof value.available !== 'boolean' || typeof value.owned !== 'boolean') {
153
+ const shown = failure ?? UNEXPECTED;
154
+ return pretty
155
+ ? prettyResult(1, depth, command, 'Could not check the name.', [['Server', session.siteUrl], ['Project', project], ['Reason', shown.display]])
156
+ : agentResult(1, { command, siteUrl: session.siteUrl, dryRun: true, project, error: failureError(shown) });
157
+ }
158
+ const { available, owned } = value;
159
+ if (!pretty)
160
+ return agentResult(0, { command, siteUrl: session.siteUrl, dryRun: true, project, available, owned });
161
+ return prettyResult(0, depth, command, available
162
+ ? 'The name is available. No project was created.'
163
+ : owned ? 'You already own this project. Deploy to it instead of creating it again.' : 'Another account uses this name. Choose a different name.', [
164
+ ['Server', session.siteUrl], ['Project', project]
165
+ ]);
166
+ }
167
+ export async function runProjectsCreate(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
168
+ const timeout = parseTimeout(args, SERVER_WAIT_SECONDS);
169
+ if ('error' in timeout)
170
+ return usageError('projects create', timeout.error, pretty, depth);
171
+ return timeout.rest.includes('--dry-run')
172
+ ? checkProjectName(timeout.rest.filter((arg) => arg !== '--dry-run'), pretty, depth, deps)
173
+ : runProjects('projects create', timeout.rest, pretty, depth, deps, timeout.waitMs);
174
+ }
175
+ export async function runProjectsStatus(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
176
+ const command = 'projects status';
177
+ const { args: rest, dryRun } = splitDryRun(args);
178
+ if (!dryRun)
179
+ return runProjects(command, rest, pretty, depth, deps, 0);
180
+ const project = parseName(rest);
181
+ if (typeof project !== 'string')
182
+ return usageError(command, project.error, pretty, depth);
183
+ return preview(command, pretty, depth, deps, (siteUrl) => new URL(`${PROJECTS_PATH}/${project}`, siteUrl).href);
184
+ }
185
+ const isDate = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
186
+ const isCount = (value) => Number.isInteger(value) && value >= 0;
187
+ function isProjectSummary(item) {
188
+ const value = item;
189
+ const server = value?.server;
190
+ const latest = value?.latest;
191
+ const live = value?.live;
192
+ const build = latest?.manifest?.build;
193
+ return typeof value?.project === 'string' && PROJECT.test(value.project) && isDate(value.createdAt)
194
+ && (value.publicUrl === null || (typeof value.publicUrl === 'string' && PUBLIC_URL.test(value.publicUrl)))
195
+ && (server === null || (typeof server === 'object' && typeof server.stage === 'string' && STAGES.includes(server.stage)
196
+ && typeof server.ready === 'boolean' && (server.errorCode === null || typeof server.errorCode === 'string')
197
+ && typeof server.message === 'string' && server.message.length <= 500 && !/[\x00-\x1f\x7f]/.test(server.message)))
198
+ && typeof value.status === 'string' && DEPLOY_STATUSES.includes(value.status)
199
+ && (latest === null || (typeof latest === 'object' && typeof latest.stage === 'string' && DEPLOY_STAGES.includes(latest.stage)
200
+ && isCount(latest.percent) && latest.percent <= 100 && (latest.errorCode === null || typeof latest.errorCode === 'string')
201
+ && typeof latest.manifest === 'object' && latest.manifest !== null && !Array.isArray(latest.manifest)
202
+ && (build === undefined || (typeof build === 'string' && BUILD.test(build))) && isDate(latest.updatedAt)))
203
+ && (live === null || (typeof live === 'object' && typeof live.commit === 'string' && COMMIT.test(live.commit) && isDate(live.publishedAt)))
204
+ && isCount(value.deployments);
205
+ }
206
+ function ago(iso, now) {
207
+ const minutes = Math.floor((now - Date.parse(iso)) / 60_000);
208
+ if (minutes < 1)
209
+ return 'just now';
210
+ if (minutes < 60)
211
+ return `${counted(minutes, 'minute')} ago`;
212
+ if (minutes < 24 * 60)
213
+ return `${counted(Math.floor(minutes / 60), 'hour')} ago`;
214
+ const days = Math.floor(minutes / (24 * 60));
215
+ if (days === 1)
216
+ return 'yesterday';
217
+ return days < 30 ? `${days} days ago` : iso.slice(0, 10);
218
+ }
219
+ const offline = ({ server, status, live }) => server?.stage === 'stopped' && live !== null && status !== 'deploying';
220
+ function projectRow(item, now) {
221
+ const { project, status, latest, live, deployments } = item;
222
+ const label = offline(item) ? '■ Server off' : status === 'failed' && latest?.errorCode === 'publish_failed' ? '✕ Build failed' : STATUS_LABELS[status];
223
+ const build = !latest ? '-' : typeof latest.manifest.build === 'string' ? latest.manifest.build : 'static';
224
+ return [project, label, build, String(deployments), live ? ago(live.publishedAt, now) : '-'];
225
+ }
226
+ export async function runProjectsList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
227
+ const command = 'projects';
228
+ const invalid = (message) => usageError(command, message, pretty, depth);
229
+ const { args: rest, dryRun } = splitDryRun(args);
230
+ const flags = parseFlags(rest, ['--page']);
231
+ if ('error' in flags)
232
+ return invalid(flags.error);
233
+ const page = flags.entries[0]?.[1] ?? '1';
234
+ if (flags.entries.length > 1 || !/^[1-9]\d{0,5}$/.test(page))
235
+ return invalid('Give --page once, as a positive integer.');
236
+ if (dryRun)
237
+ return preview(command, pretty, depth, deps, (siteUrl) => `${new URL(PROJECTS_PATH, siteUrl).href}?page=${page}`);
238
+ const sent = await authorized(deps, (session) => request(`${new URL(PROJECTS_PATH, session.siteUrl).href}?page=${page}`, {
239
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
240
+ }, deps, pretty ? 'Loading projects.' : null));
241
+ if ('login' in sent)
242
+ return sent.login;
243
+ const { session, result } = sent;
244
+ const failure = exchangeFailure(result);
245
+ const value = failure ? null : result.body;
246
+ if (failure || value?.ok !== true || value.page !== Number(page) || !isCount(value.total) || !isCount(value.pageSize) || !isCount(value.totalPages)
247
+ || !Array.isArray(value.projects) || !value.projects.every(isProjectSummary)) {
248
+ const shown = failure ?? UNEXPECTED;
249
+ return pretty
250
+ ? prettyResult(1, depth, command, 'Could not load the project list.', [['Server', session.siteUrl], ['Reason', shown.display]])
251
+ : agentResult(1, { command, siteUrl: session.siteUrl, error: failureError(shown) });
252
+ }
253
+ const { total, pageSize, totalPages } = value;
254
+ const projects = value.projects.map(({ project, createdAt, publicUrl, server, status, latest, live, deployments }) => ({ project, createdAt, publicUrl, server, status, latest, live, deployments }));
255
+ const next = value.page < totalPages ? `deepdynamic projects --page ${value.page + 1}` : null;
256
+ if (!pretty)
257
+ return agentResult(0, { command, siteUrl: session.siteUrl, total, page: value.page, pageSize, totalPages, next, projects });
258
+ const footer = [
259
+ ['Page', `${value.page} / ${totalPages} (${total} total)`],
260
+ ...(next ? [['Next', next]] : []),
261
+ ...(projects.length ? [['URL', 'deepdynamic projects status <name>']] : [])
262
+ ];
263
+ if (!projects.length) {
264
+ return prettyResult(0, depth, command, total ? `Page ${value.page} has no projects.` : 'You have no projects yet. Create one with deepdynamic projects create <name>.', total ? footer : []);
265
+ }
266
+ const { accent, dim } = paint(depth);
267
+ const tones = { published: accent, none: dim };
268
+ const now = Date.now();
269
+ const table = [['Name', 'Status', 'Build', 'Deploys', 'Last published'], ...projects.map((item) => projectRow(item, now).map(plain))];
270
+ const widths = table[0].map((_, column) => Math.max(...table.map((row) => displayWidth(row[column]))));
271
+ const lines = table.map((row, index) => row.map((cell, column) => {
272
+ const text = column === 3 ? ' '.repeat(widths[column] - displayWidth(cell)) + cell : pad(cell, widths[column]);
273
+ if (index === 0)
274
+ return dim(text);
275
+ const item = projects[index - 1];
276
+ return column === 1 ? (offline(item) ? dim : tones[item.status] ?? String)(text) : text;
277
+ }).join(' ').trimEnd());
278
+ return prettyResult(0, depth, command, `Listed ${counted(projects.length, 'project')}, most recently active first.`, [
279
+ ...lines.map((line) => [null, new Styled(line)]),
280
+ [null, ''],
281
+ ...footer
282
+ ]);
283
+ }
284
+ function isDeployment(item) {
285
+ const value = item;
286
+ return typeof value?.commit === 'string' && COMMIT.test(value.commit)
287
+ && typeof value.publishedAt === 'string' && Number.isFinite(Date.parse(value.publishedAt))
288
+ && typeof value.current === 'boolean'
289
+ && typeof value.manifest === 'object' && value.manifest !== null && !Array.isArray(value.manifest);
290
+ }
291
+ function deploymentList(body, project) {
292
+ const value = body;
293
+ if (value?.ok !== true || value.project !== project || !Array.isArray(value.deployments) || !value.deployments.every(isDeployment))
294
+ return null;
295
+ return value.deployments.map(({ commit, publishedAt, current, manifest }) => ({ commit, publishedAt, current, manifest }));
296
+ }
297
+ async function loadHistory(command, project, pretty, depth, deps) {
298
+ const sent = await authorized(deps, (session) => request(new URL(`${PROJECTS_PATH}/${project}/deployments`, session.siteUrl).href, {
299
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
300
+ }, deps, null));
301
+ if ('login' in sent)
302
+ return { result: sent.login };
303
+ const failure = exchangeFailure(sent.result);
304
+ const deployments = failure ? null : deploymentList(sent.result.body, project);
305
+ if (deployments)
306
+ return { session: sent.session, deployments };
307
+ const shown = failure ?? UNEXPECTED;
308
+ return {
309
+ result: pretty
310
+ ? prettyResult(1, depth, command, 'Could not load the deploy history.', [['Server', sent.session.siteUrl], ['Project', project], ['Reason', shown.display]])
311
+ : agentResult(1, { command, siteUrl: sent.session.siteUrl, project, error: failureError(shown) })
312
+ };
313
+ }
314
+ export async function runProjectsHistory(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
315
+ const command = 'projects history';
316
+ const { args: rest, dryRun } = splitDryRun(args);
317
+ const project = parseName(rest);
318
+ if (typeof project !== 'string')
319
+ return usageError(command, project.error, pretty, depth);
320
+ if (dryRun)
321
+ return preview(command, pretty, depth, deps, (siteUrl) => new URL(`${PROJECTS_PATH}/${project}/deployments`, siteUrl).href);
322
+ const history = await loadHistory(command, project, pretty, depth, deps);
323
+ if ('result' in history)
324
+ return history.result;
325
+ const { session, deployments } = history;
326
+ if (!pretty)
327
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, deployments });
328
+ return prettyResult(0, depth, command, deployments.length ? `Found ${counted(deployments.length, 'published deployment')}.` : 'No deployment has been published yet.', [
329
+ ['Server', session.siteUrl], ['Project', project],
330
+ ...deployments.map(({ commit, publishedAt, current }, index) => [
331
+ index === 0 ? 'Deployments' : '',
332
+ `${commit.slice(0, 12)} ${new Date(publishedAt).toISOString().slice(0, 16).replace('T', ' ')} UTC${current ? ' (current)' : ''}`
333
+ ])
334
+ ]);
335
+ }
336
+ const METRIC_PERIODS = ['24h', '7d', '30d'];
337
+ const PERIOD_LABELS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days' };
338
+ const PERIOD_LENGTHS = { '24h': 24, '7d': 7, '30d': 30 };
339
+ const isMetricPeriod = (value) => METRIC_PERIODS.includes(value);
340
+ const isPercent = (value) => typeof value === 'number' && value >= 0 && value <= 100;
341
+ const isStrings = (value, length) => Array.isArray(value) && value.length === length && value.every((item) => typeof item === 'string');
342
+ const isCounts = (value, length) => Array.isArray(value) && value.length === length && value.every(isCount);
343
+ function isShares(value, key) {
344
+ return Array.isArray(value) && value.every((item) => {
345
+ const share = item;
346
+ return typeof share?.[key] === 'string' && isCount(share.count) && isPercent(share.share);
347
+ });
348
+ }
349
+ const isNullableText = (value) => value === null || typeof value === 'string';
350
+ const isAdvisory = (value) => {
351
+ const item = value;
352
+ return typeof item?.product === 'string' && typeof item?.version === 'string' && (item?.severity === 'critical' || item?.severity === 'high') && typeof item?.summary === 'string' && typeof item?.reference === 'string';
353
+ };
354
+ const isSoftware = (value) => {
355
+ if (value === null)
356
+ return true;
357
+ if (typeof value !== 'object')
358
+ return false;
359
+ const { server, poweredBy, advisories } = value;
360
+ return isNullableText(server) && isNullableText(poweredBy) && Array.isArray(advisories) && advisories.every(isAdvisory);
361
+ };
362
+ const isTraffic = (value) => {
363
+ if (value === null)
364
+ return true;
365
+ if (typeof value !== 'object')
366
+ return false;
367
+ const { requests, pageviews, visitors, bots, statuses, paths } = value;
368
+ if (typeof statuses !== 'object' || statuses === null)
369
+ return false;
370
+ const { ok, redirect, client, server } = statuses;
371
+ return [requests, pageviews, visitors, bots, ok, redirect, client, server].every(isCount) && Array.isArray(paths) && isShares(paths, 'path');
372
+ };
373
+ function metricReport(body, project, period) {
374
+ const value = body;
375
+ const report = value?.report;
376
+ if (value?.ok !== true || value.project !== project || value.period !== period || !isDate(value.endDate) || !report)
377
+ return null;
378
+ const length = PERIOD_LENGTHS[period];
379
+ const { dates, labels, visits, views, previousVisits, previousViews, range, totalVisits, totalViews, previousTotalVisits, previousTotalViews, duration, previousDuration, bounce, previousBounce, sources, devices, pages } = report;
380
+ if (!isStrings(dates, length) || !isStrings(labels, length) || !isCounts(visits, length) || !isCounts(views, length) || !isCounts(previousVisits, length) || !isCounts(previousViews, length))
381
+ return null;
382
+ if (typeof range !== 'string' || !isCount(totalVisits) || !isCount(totalViews) || !isCount(previousTotalVisits) || !isCount(previousTotalViews) || !isCount(duration) || !isCount(previousDuration))
383
+ return null;
384
+ if (!isPercent(bounce) || !isPercent(previousBounce) || !isShares(sources, 'label') || !isShares(devices, 'label') || !isShares(pages, 'path'))
385
+ return null;
386
+ if (!isSoftware(value.software) || !isTraffic(value.traffic))
387
+ return null;
388
+ return {
389
+ endDate: value.endDate,
390
+ report: { dates, labels, visits, views, previousVisits, previousViews, range, totalVisits, totalViews, previousTotalVisits, previousTotalViews, duration, previousDuration, bounce, previousBounce, sources, devices, pages },
391
+ software: value.software,
392
+ traffic: value.traffic
393
+ };
394
+ }
395
+ function parseMetric(args) {
396
+ const parsed = parseCommand(args, ['--period']);
397
+ if ('error' in parsed)
398
+ return parsed;
399
+ const project = parseName(parsed.names);
400
+ if (typeof project !== 'string')
401
+ return project;
402
+ if (parsed.entries.length > 1)
403
+ return { error: 'Give --period only once.' };
404
+ const period = parsed.entries[0]?.[1] ?? '7d';
405
+ if (!isMetricPeriod(period)) {
406
+ return { error: `--period must be one of ${METRIC_PERIODS.join(', ')}: ${period}` };
407
+ }
408
+ return { project, period };
409
+ }
410
+ const metricNumber = (value) => value.toLocaleString('en-US');
411
+ const metricChange = (value, previous) => previous === 0 ? 'no previous data' : `${value < previous ? '-' : '+'}${(Math.abs(value - previous) / previous * 100).toFixed(1)}% vs previous period`;
412
+ const compared = (shown, value, previous) => `${shown} · ${metricChange(value, previous)}`;
413
+ const stay = (seconds) => `${counted(Math.floor(seconds / 60), 'minute')} ${counted(seconds % 60, 'second')}`;
414
+ const shares = (items) => items.map(({ label, share }) => `${label} ${share.toFixed(1)}%`).join(' · ');
415
+ const BAR_WIDTH = 20;
416
+ const severityLabels = { critical: 'Critical', high: 'High' };
417
+ function trendRows(title, labels, current, previous) {
418
+ const peak = Math.max(1, ...current, ...previous);
419
+ return labels.map((label, index) => {
420
+ const width = current[index] > 0 ? Math.max(1, Math.round(current[index] / peak * BAR_WIDTH)) : 0;
421
+ return [index === 0 ? title : '', `${label.padEnd(8)}${'█'.repeat(width).padEnd(BAR_WIDTH)} ${metricNumber(current[index])} (previous ${metricNumber(previous[index])})`];
422
+ });
423
+ }
424
+ function softwareRows({ server, poweredBy, advisories }) {
425
+ const observed = [server, poweredBy].filter(Boolean).join(' · ');
426
+ if (!observed)
427
+ return [['Server software', 'No server responses observed yet.']];
428
+ const notes = advisories.length
429
+ ? advisories.map(({ severity, product, version, summary, reference }, index) => [index === 0 ? 'Vulnerable versions' : '', `[${severityLabels[severity]}] ${product}/${version} · ${summary} (${reference})`])
430
+ : [['Vulnerable versions', 'No known vulnerable versions.']];
431
+ return [['Server software', observed], ...notes];
432
+ }
433
+ function trafficRows(traffic) {
434
+ if (traffic.requests === 0)
435
+ return [['Edge traffic', 'No requests counted yet.']];
436
+ const ratio = (count) => `${metricNumber(count)} (${(count / traffic.requests * 100).toFixed(1)}%)`;
437
+ return [
438
+ ['Edge traffic', counted(traffic.requests, 'request')],
439
+ ['Server pageviews', metricNumber(traffic.pageviews)],
440
+ ['Visitors (hourly sum)', metricNumber(traffic.visitors)],
441
+ ['Bot requests', metricNumber(traffic.bots)],
442
+ ['Success (2xx)', ratio(traffic.statuses.ok)],
443
+ ['Redirects (3xx)', ratio(traffic.statuses.redirect)],
444
+ ['Client errors (4xx)', ratio(traffic.statuses.client)],
445
+ ['Server errors (5xx)', ratio(traffic.statuses.server)],
446
+ ...traffic.paths.map(({ path, count, share }, index) => [index === 0 ? 'Top paths (server pageviews)' : '', `${path} ${metricNumber(count)} (${share.toFixed(1)}%)`])
447
+ ];
448
+ }
449
+ function metricRows(siteUrl, project, period, { report, software, traffic }) {
450
+ const { labels, visits, previousVisits, views, previousViews, range, totalVisits, totalViews, previousTotalVisits, previousTotalViews, duration, previousDuration, bounce, previousBounce, sources, devices, pages } = report;
451
+ return [
452
+ ['Server', siteUrl], ['Project', project],
453
+ ['Period', `${PERIOD_LABELS[period]} · ${range} · KST`],
454
+ ['Visits', compared(metricNumber(totalVisits), totalVisits, previousTotalVisits)],
455
+ ['Pageviews', compared(metricNumber(totalViews), totalViews, previousTotalViews)],
456
+ ['Avg. visit duration', compared(stay(duration), duration, previousDuration)],
457
+ ['Bounce rate', compared(`${bounce.toFixed(1)}%`, bounce, previousBounce)],
458
+ ...trendRows('Visit trend', labels, visits, previousVisits),
459
+ ...trendRows('Pageview trend', labels, views, previousViews),
460
+ ['Traffic sources', shares(sources)],
461
+ ['Devices', shares(devices)],
462
+ ...(software ? softwareRows(software) : []),
463
+ ...(traffic ? trafficRows(traffic) : []),
464
+ ...(pages.length
465
+ ? pages.map(({ path, count, share }, index) => [index === 0 ? 'Top pages' : '', `${path} ${metricNumber(count)} (${share.toFixed(1)}%)`])
466
+ : [['Top pages', 'None']])
467
+ ];
468
+ }
469
+ export async function runProjectsMetric(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
470
+ const command = 'projects metric';
471
+ const { args: rest, dryRun } = splitDryRun(args);
472
+ const parsed = parseMetric(rest);
473
+ if ('error' in parsed)
474
+ return usageError(command, parsed.error, pretty, depth);
475
+ const { project, period } = parsed;
476
+ const url = (siteUrl) => `${new URL(`${PROJECTS_PATH}/${project}/metric`, siteUrl).href}?period=${period}`;
477
+ if (dryRun)
478
+ return preview(command, pretty, depth, deps, url);
479
+ const sent = await authorized(deps, (session) => request(url(session.siteUrl), {
480
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
481
+ }, deps, pretty ? 'Loading visit statistics.' : null));
482
+ if ('login' in sent)
483
+ return sent.login;
484
+ const { session, result } = sent;
485
+ const failure = exchangeFailure(result);
486
+ const metric = failure ? null : metricReport(result.body, project, period);
487
+ if (!metric) {
488
+ const shown = failure ?? UNEXPECTED;
489
+ return pretty
490
+ ? prettyResult(1, depth, command, 'Could not load the visit statistics.', [['Server', session.siteUrl], ['Project', project], ['Reason', shown.display]])
491
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
492
+ }
493
+ if (!pretty)
494
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, period, ...metric });
495
+ const message = metric.report.totalVisits ? `Loaded visit statistics for the last ${PERIOD_LABELS[period]}.` : `No visits in the last ${PERIOD_LABELS[period]}.`;
496
+ return prettyResult(0, depth, command, message, metricRows(session.siteUrl, project, period, metric));
497
+ }
498
+ export async function runProjectsRollback(args, pretty, depth, deps = { ...defaultAuthDeps(pretty, depth), restore: restoreDeployment }) {
499
+ const command = 'projects rollback';
500
+ const invalid = (message) => usageError(command, message, pretty, depth);
501
+ const { args: plain, dryRun } = splitDryRun(args);
502
+ const { args: rest, yes } = splitYes(plain);
503
+ const timeout = parseTimeout(rest, PUBLISH_WAIT_SECONDS);
504
+ if ('error' in timeout)
505
+ return invalid(timeout.error);
506
+ const parsed = parseCommand(timeout.rest, ['--to']);
507
+ if ('error' in parsed)
508
+ return invalid(parsed.error);
509
+ const project = parseName(parsed.names);
510
+ if (typeof project !== 'string')
511
+ return invalid(project.error);
512
+ const to = parsed.entries[0]?.[1];
513
+ if (parsed.entries.length > 1 || (to !== undefined && !COMMIT_PREFIX.test(to))) {
514
+ return invalid('Give --to once, as 7-40 lowercase hex characters of a commit from deepdynamic projects history.');
515
+ }
516
+ if (dryRun)
517
+ return plannedRollback(project, to ?? null, pretty, depth, deps);
518
+ if (!yes) {
519
+ return confirmationRequired(command, plain, pretty, depth, {
520
+ message: 'Rolling back replaces the live site with an earlier deployment.',
521
+ display: 'Rolling back replaces the live site with an earlier deployment. Confirm with the user, then run the command with --yes.'
522
+ }, { project });
523
+ }
524
+ const history = await loadHistory(command, project, pretty, depth, deps);
525
+ if ('result' in history)
526
+ return history.result;
527
+ const { session, deployments } = history;
528
+ const refuse = (code, message) => pretty
529
+ ? prettyResult(1, depth, command, message, [['Server', session.siteUrl], ['Project', project]])
530
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, deployments, error: { code, message } });
531
+ const matches = to === undefined ? deployments.slice(1, 2) : deployments.filter(({ commit }) => commit.startsWith(to));
532
+ if (matches.length !== 1) {
533
+ return to === undefined
534
+ ? refuse('no_previous_deployment', 'There is no earlier published deployment to roll back to. Nothing was changed.')
535
+ : refuse('deployment_not_found', `No single published deployment matches ${to}. Pick a commit from deepdynamic projects history ${project}. Nothing was changed.`);
536
+ }
537
+ const [target] = matches;
538
+ if (target.current)
539
+ return refuse('already_current', 'That deployment is already published. Nothing was changed.');
540
+ return shipDeployment({
541
+ command, project, manifest: target.manifest,
542
+ context: { project, target: { commit: target.commit, publishedAt: target.publishedAt } },
543
+ success: {},
544
+ rows: [['Project', project], ['Target', target.commit]],
545
+ waitMs: timeout.waitMs,
546
+ send: (remote, branch, token, onUploading) => deps.restore(remote, branch, token, target.commit, { onUploading })
547
+ }, pretty, depth, deps);
548
+ }
549
+ async function plannedRollback(project, to, pretty, depth, deps) {
550
+ const command = 'projects rollback';
551
+ const session = await signedIn(deps);
552
+ if ('login' in session)
553
+ return session.login;
554
+ const { siteUrl } = session;
555
+ const requests = [
556
+ { method: 'GET', url: new URL(`${PROJECTS_PATH}/${project}/deployments`, siteUrl).href },
557
+ { method: 'POST', url: new URL('/api/v1/deployments', siteUrl).href, body: { project } },
558
+ { method: 'POST', url: new URL('/api/v1/git/repository', siteUrl).href, body: { project } }
559
+ ];
560
+ if (!pretty)
561
+ return agentResult(0, { command, siteUrl, dryRun: true, applied: false, plan: { project, to }, requests });
562
+ return prettyResult(0, depth, command, 'Checked the rollback. Nothing was rolled back.', [
563
+ ['Server', siteUrl], ['Project', project], ['Target', to ?? 'The deployment before the live one'],
564
+ ...requests.map(({ method, url }, index) => [index === 0 ? 'Request' : '', `${method} ${url}`])
565
+ ]);
566
+ }
567
+ export async function runProjectsRename(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
568
+ const command = 'projects rename';
569
+ const invalid = (message) => usageError(command, message, pretty, depth);
570
+ const dryRun = args.includes('--dry-run');
571
+ const parsed = parseCommand(args.filter((arg) => arg !== '--dry-run'), []);
572
+ if ('error' in parsed)
573
+ return invalid(parsed.error);
574
+ const { names } = parsed;
575
+ if (names.length !== 2)
576
+ return invalid('Specify the current name and then the new name.');
577
+ const [project, name] = names.map((value) => parseName([value]));
578
+ if (typeof project !== 'string')
579
+ return invalid(project.error);
580
+ if (typeof name !== 'string')
581
+ return invalid(name.error);
582
+ if (project === name)
583
+ return invalid('The new name is the same as the current name.');
584
+ 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 ? 'Checking the name.' : 'Renaming the project.') : null));
585
+ if ('login' in sent)
586
+ return sent.login;
587
+ const { session, result } = sent;
588
+ const failure = !('failure' in result) && result.status === 409
589
+ ? plainFailure('project_taken', 'Another project already uses that name. Pick another name with the naming steps in deepdynamic projects create --help.')
590
+ : exchangeFailure(result);
591
+ const value = failure ? null : result.body;
592
+ const valid = dryRun
593
+ ? value?.ok === true && value.dryRun === true && value.project === project && value.name === name && typeof value.available === 'boolean'
594
+ : value?.ok === true && value.project === name && value.previous === project && value.renamed === true;
595
+ if (failure || !valid) {
596
+ const shown = failure ?? UNEXPECTED;
597
+ return pretty
598
+ ? prettyResult(1, depth, command, 'Could not rename the project.', [['Server', session.siteUrl], ['Project', project], ['New name', name], ['Reason', shown.display]])
599
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, name, renamed: false, error: failureError(shown) });
600
+ }
601
+ if (dryRun) {
602
+ const available = value?.available === true;
603
+ if (!pretty)
604
+ return agentResult(0, { command, siteUrl: session.siteUrl, dryRun: true, project, name, available });
605
+ return prettyResult(0, depth, command, available ? 'The name is available. The project was not renamed.' : 'The name is already taken. Choose a different name.', [
606
+ ['Server', session.siteUrl], ['Project', project], ['New name', name]
607
+ ]);
608
+ }
609
+ if (!pretty)
610
+ return agentResult(0, { command, siteUrl: session.siteUrl, project: name, previous: project, renamed: true });
611
+ return prettyResult(0, depth, command, 'Renamed the project. The site URL changes to the new name on the next deploy. The server, repository and deploy history stay the same.', [
612
+ ['Server', session.siteUrl], ['Previous', project], ['New name', name], ['Next', `deepdynamic projects deploy ${name} <directory> --agent <code>`]
613
+ ]);
614
+ }
615
+ const pwaLabel = (enabled) => enabled ? 'on' : 'off';
616
+ function pwaFailure(result) {
617
+ if ('failure' in result)
618
+ return result.failure;
619
+ if (result.status === 403)
620
+ return plainFailure('login_required', 'The access token lacks the project scope for this command. Run deepdynamic login again.');
621
+ if (result.status === 503)
622
+ return supportFailure('unavailable', { note: 'The setting was not applied.', retryable: true });
623
+ return exchangeFailure(result);
624
+ }
625
+ function pwaState(body, project) {
626
+ const value = body;
627
+ return value?.ok === true && value.project === project && typeof value.pwa === 'boolean' ? value.pwa : null;
628
+ }
629
+ export async function runProjectsPwa(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
630
+ const command = 'projects pwa';
631
+ const invalid = (message) => usageError(command, message, pretty, depth);
632
+ const { args: rest, dryRun } = splitDryRun(args);
633
+ const parsed = parseCommand(rest, []);
634
+ if ('error' in parsed)
635
+ return invalid(parsed.error);
636
+ const [input, state, ...extra] = parsed.names;
637
+ if (input === undefined)
638
+ return invalid('Specify the project name.');
639
+ const project = parseName([input]);
640
+ if (typeof project !== 'string')
641
+ return invalid(project.error);
642
+ if (state !== undefined && state !== 'on' && state !== 'off')
643
+ return invalid('After the project name give on or off, or nothing to show the current state.');
644
+ if (extra.length)
645
+ return invalid(unknownArgument(extra[0]));
646
+ const enabled = state === undefined ? null : state === 'on';
647
+ const url = (siteUrl) => new URL(`${PROJECTS_PATH}/${project}/pwa`, siteUrl).href;
648
+ if (dryRun) {
649
+ if (enabled === null)
650
+ return preview(command, pretty, depth, deps, url);
651
+ const session = await signedIn(deps);
652
+ if ('login' in session)
653
+ return session.login;
654
+ return plannedChange(command, pretty, depth, session.siteUrl, { url: url(session.siteUrl), body: { enabled } }, 'Checked the PWA change. Nothing was changed.', [['Project', project], ['PWA', pwaLabel(enabled)]], { project, pwa: enabled });
655
+ }
656
+ const sent = await authorized(deps, (session) => enabled === null
657
+ ? request(url(session.siteUrl), { method: 'GET', headers: { authorization: `Bearer ${session.token}` } }, deps, pretty ? 'Loading the PWA setting.' : null)
658
+ : postJson(url(session.siteUrl), session.token, { enabled }, deps, pretty ? 'Changing the PWA setting.' : null));
659
+ if ('login' in sent)
660
+ return sent.login;
661
+ const { session, result } = sent;
662
+ const failure = pwaFailure(result);
663
+ const pwa = failure ? null : pwaState(result.body, project);
664
+ if (pwa === null) {
665
+ const shown = failure ?? UNEXPECTED;
666
+ return pretty
667
+ ? prettyResult(1, depth, command, enabled === null ? 'Could not load the PWA setting.' : 'Could not change the PWA setting.', [['Server', session.siteUrl], ['Project', project], ['Reason', shown.display]])
668
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
669
+ }
670
+ if (!pretty)
671
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, pwa });
672
+ const message = enabled === null
673
+ ? (pwa ? 'PWA is on. Visitors can install this site as an app.' : 'PWA is off. Visitors cannot install this site as an app.')
674
+ : (pwa ? 'Turned PWA on. Visitors can install the site as an app.' : 'Turned PWA off. Visitors no longer see the install prompt.');
675
+ return prettyResult(0, depth, command, message, [['Server', session.siteUrl], ['Project', project], ['PWA', pwaLabel(pwa)]]);
676
+ }
677
+ function postProject(session, project, action, deps, spinner) {
678
+ return request(new URL(`${PROJECTS_PATH}/${project}/${action}`, session.siteUrl).href, {
679
+ method: 'POST', headers: { authorization: `Bearer ${session.token}` }
680
+ }, deps, spinner);
681
+ }
682
+ async function plannedProjectChange(command, project, action, message, pretty, depth, deps) {
683
+ const session = await signedIn(deps);
684
+ if ('login' in session)
685
+ return session.login;
686
+ return plannedChange(command, pretty, depth, session.siteUrl, { url: new URL(`${PROJECTS_PATH}/${project}/${action}`, session.siteUrl).href }, message, [['Project', project]], { project });
687
+ }
688
+ export async function runProjectsStop(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
689
+ const command = 'projects stop';
690
+ const { args: plain, dryRun } = splitDryRun(args);
691
+ const { args: rest, yes } = splitYes(plain);
692
+ const project = parseName(rest);
693
+ if (typeof project !== 'string')
694
+ return usageError(command, project.error, pretty, depth);
695
+ if (dryRun)
696
+ return plannedProjectChange(command, project, 'stop', 'Checked stopping the project server. Nothing was stopped.', pretty, depth, deps);
697
+ if (!yes) {
698
+ return confirmationRequired(command, plain, pretty, depth, {
699
+ message: 'Stopping cancels the running deploys of the project and turns its server off, so the site is offline until the next deploy.',
700
+ display: 'Stopping cancels running deploys and takes the site offline until the next deploy. Confirm with the user, then run the command with --yes.'
701
+ }, { project });
702
+ }
703
+ const sent = await authorized(deps, (session) => postProject(session, project, 'stop', deps, pretty ? 'Stopping the project server.' : null));
704
+ if ('login' in sent)
705
+ return sent.login;
706
+ const { session, result } = sent;
707
+ const failure = !('failure' in result) && result.status === 409
708
+ ? { code: 'server_updating', message: 'The project server is installing updates. Keep running deepdynamic projects stop until it no longer fails with server_updating.', display: 'The project server is installing updates. Try again after they finish.' }
709
+ : exchangeFailure(result);
710
+ const status = failure ? null : projectStatus(result.body, project);
711
+ if (!status) {
712
+ const shown = failure ?? UNEXPECTED;
713
+ return pretty
714
+ ? prettyResult(1, depth, command, 'Could not stop the project server.', [['Server', session.siteUrl], ['Project', project], ['Reason', shown.display]])
715
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, error: failureError(shown) });
716
+ }
717
+ const { server, site } = status;
718
+ return finish(command, 0, depth, pretty, session.siteUrl, project, server, site, null, server.stage === 'stopped' ? 'Stopped the project server. The next deploy turns it back on.' : 'No project server is running.');
719
+ }
720
+ export async function runProjectsDelete(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
721
+ const command = 'projects delete';
722
+ const { args: plain, dryRun } = splitDryRun(args);
723
+ const { args: rest, yes } = splitYes(plain);
724
+ const project = parseName(rest);
725
+ if (typeof project !== 'string')
726
+ return usageError(command, project.error, pretty, depth);
727
+ if (dryRun)
728
+ return plannedProjectChange(command, project, 'delete', 'Checked deleting the project. Nothing was deleted.', pretty, depth, deps);
729
+ if (!yes) {
730
+ return confirmationRequired(command, plain, pretty, depth, {
731
+ message: 'Deleting removes the project, its server and its deploy history permanently.',
732
+ display: 'Deleting removes the project, its server and its deploy history. This cannot be undone. Confirm with the user, then run the command with --yes.'
733
+ }, { project });
734
+ }
735
+ const sent = await authorized(deps, (session) => postProject(session, project, 'delete', deps, pretty ? 'Deleting the project.' : null));
736
+ if ('login' in sent)
737
+ return sent.login;
738
+ const { session, result } = sent;
739
+ const failure = !('failure' in result) && result.status === 409
740
+ ? { code: 'server_busy', message: 'The project server is busy with another job. Try again after it finishes.', display: 'The project server is still being created or is busy with another job. Try again after it finishes.' }
741
+ : exchangeFailure(result);
742
+ const value = failure ? null : result.body;
743
+ if (failure || value?.ok !== true || value.project !== project || value.deleted !== true) {
744
+ const shown = failure ?? UNEXPECTED;
745
+ return pretty
746
+ ? prettyResult(1, depth, command, 'Could not delete the project.', [['Server', session.siteUrl], ['Project', project], ['Reason', shown.display]])
747
+ : agentResult(1, { command, siteUrl: session.siteUrl, project, deleted: false, error: failureError(shown) });
748
+ }
749
+ if (!pretty)
750
+ return agentResult(0, { command, siteUrl: session.siteUrl, project, deleted: true });
751
+ return prettyResult(0, depth, command, 'Deleted the project. Its server is stopped and removed in the background.', [['Server', session.siteUrl], ['Project', project]]);
752
+ }
753
+ const PHOTOCARD_SIDES = [1, 2];
754
+ const PHOTOCARD_LABELS = { 1: 'Front', 2: 'Back' };
755
+ const FLIGHT_REQUIRED = {
756
+ code: 'flight_required',
757
+ message: 'The project has no flight yet. Deploy it once with deepdynamic projects deploy <name> <directory> --agent <code>, then run this again.',
758
+ display: 'The photocard needs a deploy made with --agent. Deploy the project once with --agent, then run this again.'
759
+ };
760
+ function attachmentName(header) {
761
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header ?? '')?.[1];
762
+ try {
763
+ return encoded ? decodeURIComponent(encoded) : null;
764
+ }
765
+ catch {
766
+ return null;
767
+ }
768
+ }
769
+ async function readPhotocard(response) {
770
+ if (response.status !== 200 || !response.headers.get('content-type')?.startsWith('image/png'))
771
+ return readJson(response);
772
+ return { bytes: new Uint8Array(await response.arrayBuffer()), filename: attachmentName(response.headers.get('content-disposition')) };
773
+ }
774
+ const isPhotocardImage = (body) => {
775
+ const value = body;
776
+ return value?.bytes instanceof Uint8Array && (value.filename === null || typeof value.filename === 'string');
777
+ };
778
+ const PHOTOCARD_FILE = /^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,240}\.png$/iu;
779
+ const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\.|$)/i;
780
+ function photocardFile(name, fallback) {
781
+ const cleaned = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} ._-]/gu, '_');
782
+ return PHOTOCARD_FILE.test(cleaned) && !WINDOWS_DEVICE.test(cleaned) ? cleaned : fallback;
783
+ }
784
+ export async function runProjectsPhotocard(args, pretty, depth, deps = { ...defaultAuthDeps(pretty, depth), writeFile: (path, bytes) => writeFile(path, bytes) }) {
785
+ const command = 'projects photocard';
786
+ const invalid = (message) => usageError(command, message, pretty, depth);
787
+ const { args: rest, dryRun } = splitDryRun(args);
788
+ const parsed = parseCommand(rest, ['--out']);
789
+ if ('error' in parsed)
790
+ return invalid(parsed.error);
791
+ const project = parseName(parsed.names);
792
+ if (typeof project !== 'string')
793
+ return invalid(project.error);
794
+ if (parsed.entries.length > 1)
795
+ return invalid('Give --out at most once.');
796
+ const out = parsed.entries[0]?.[1] ?? '.';
797
+ const url = (siteUrl, side) => `${new URL(`${PROJECTS_PATH}/${project}/photocard`, siteUrl).href}?side=${side}`;
798
+ if (dryRun) {
799
+ const session = await signedIn(deps);
800
+ if ('login' in session)
801
+ return session.login;
802
+ const requests = PHOTOCARD_SIDES.map((side) => ({ method: 'GET', url: url(session.siteUrl, side) }));
803
+ return pretty
804
+ ? prettyResult(0, depth, command, 'Checked without sending the requests.', [['Server', session.siteUrl], ['Project', project], ['Directory', out], ...requests.map(({ url }) => ['Request', `GET ${url}`])])
805
+ : agentResult(0, { command, siteUrl: session.siteUrl, dryRun: true, project, out, requests });
806
+ }
807
+ const images = [];
808
+ const failed = (siteUrl, shown) => pretty
809
+ ? prettyResult(1, depth, command, 'Could not save the photocard.', [['Server', siteUrl], ['Project', project], ['Reason', shown.display]])
810
+ : agentResult(1, { command, siteUrl, project, images, error: failureError(shown) });
811
+ let siteUrl = '';
812
+ for (const side of PHOTOCARD_SIDES) {
813
+ const sent = await authorized(deps, (session) => request(url(session.siteUrl, side), {
814
+ method: 'GET', headers: { authorization: `Bearer ${session.token}` }
815
+ }, deps, pretty ? `Rendering the photocard ${PHOTOCARD_LABELS[side].toLowerCase()}.` : null, readPhotocard));
816
+ if ('login' in sent)
817
+ return sent.login;
818
+ siteUrl = sent.session.siteUrl;
819
+ const { result } = sent;
820
+ const failure = !('failure' in result) && result.status === 409 ? FLIGHT_REQUIRED : exchangeFailure(result);
821
+ const image = failure ? null : isPhotocardImage(result.body) ? result.body : null;
822
+ if (!image)
823
+ return failed(siteUrl, failure ?? UNEXPECTED);
824
+ const path = join(out, photocardFile(image.filename, `${project}-${side}.png`));
825
+ try {
826
+ await deps.writeFile(path, image.bytes);
827
+ }
828
+ catch {
829
+ return failed(siteUrl, plainFailure('save_failed', `Could not write ${path}. Check that the directory exists and is writable.`));
830
+ }
831
+ images.push({ side, path, bytes: image.bytes.length });
832
+ }
833
+ if (!pretty)
834
+ return agentResult(0, { command, siteUrl, project, images });
835
+ return prettyResult(0, depth, command, 'Saved the photocard front and back as PNG files.', [
836
+ ['Server', siteUrl], ['Project', project], ...images.map(({ side, path }) => [PHOTOCARD_LABELS[side], path])
837
+ ]);
838
+ }