@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.
- package/LICENSE +201 -0
- package/README.md +32 -2
- package/THIRD_PARTY_NOTICES.txt +102 -0
- package/dist/agents/content.js +12 -0
- package/dist/agents/edit.js +140 -0
- package/dist/agents/install.js +190 -0
- package/dist/agents/refresh.js +20 -0
- package/dist/agents/setup.js +29 -0
- package/dist/agents/targets.js +91 -0
- package/dist/auth/credentials.js +63 -0
- package/dist/auth/session.js +49 -0
- package/dist/cli.js +198 -0
- package/dist/commands/account.js +96 -0
- package/dist/commands/activity.js +80 -0
- package/dist/commands/blocked.js +89 -0
- package/dist/commands/deploy/agents.js +11 -0
- package/dist/commands/deploy/files.js +62 -0
- package/dist/commands/deploy/index.js +95 -0
- package/dist/commands/deploy/manifest.js +24 -0
- package/dist/commands/deploy/minify.js +27 -0
- package/dist/commands/deploy/progress.js +85 -0
- package/dist/commands/deploy/ship.js +117 -0
- package/dist/commands/deploy/upload.js +125 -0
- package/dist/commands/deployments.js +60 -0
- package/dist/commands/dns.js +777 -0
- package/dist/commands/domains.js +639 -0
- package/dist/commands/emails.js +74 -0
- package/dist/commands/env.js +194 -0
- package/dist/commands/help.js +148 -0
- package/dist/commands/keys.js +263 -0
- package/dist/commands/login/flow.js +155 -0
- package/dist/commands/login/index.js +26 -0
- package/dist/commands/logout.js +71 -0
- package/dist/commands/mail.js +241 -0
- package/dist/commands/notifications.js +133 -0
- package/dist/commands/plan.js +355 -0
- package/dist/commands/projects.js +838 -0
- package/dist/commands/reference.js +2187 -0
- package/dist/commands/search.js +86 -0
- package/dist/commands/server.js +301 -0
- package/dist/commands/sessions.js +114 -0
- package/dist/commands/sites.js +102 -0
- package/dist/commands/sms.js +65 -0
- package/dist/commands/status.js +87 -0
- package/dist/commands/support.js +115 -0
- package/dist/commands/update.js +100 -0
- package/dist/commands/usage.js +51 -0
- package/dist/commands/verify.js +149 -0
- package/dist/commands/version.js +6 -0
- package/dist/guide.js +37 -0
- package/dist/http/call.js +6 -0
- package/dist/http/request.js +54 -0
- package/dist/index.js +11 -0
- package/dist/metadata.js +4 -0
- package/dist/output.js +9 -0
- package/dist/pretty.js +70 -0
- package/dist/refresh-skills.js +5 -0
- package/dist/registry.js +688 -0
- package/dist/runtime/browser.js +15 -0
- package/dist/runtime/card-request.js +55 -0
- package/dist/runtime/confirm.js +21 -0
- package/dist/runtime/development.js +13 -0
- package/dist/runtime/domain-name.js +5 -0
- package/dist/runtime/dry-run.js +28 -0
- package/dist/runtime/env-file.js +55 -0
- package/dist/runtime/error-hints.js +26 -0
- package/dist/runtime/flags.js +48 -0
- package/dist/runtime/login-screen.js +78 -0
- package/dist/runtime/page.js +18 -0
- package/dist/runtime/project-name.js +1 -0
- package/dist/runtime/run-mode.js +7 -0
- package/dist/runtime/server-options.js +28 -0
- package/dist/runtime/spinner.js +17 -0
- package/dist/runtime/suggest.js +22 -0
- package/dist/runtime/support.js +13 -0
- package/dist/runtime/text-file.js +20 -0
- package/dist/runtime/timeout.js +22 -0
- package/dist/runtime/update-check.js +158 -0
- package/dist/runtime/update-install.js +80 -0
- package/dist/runtime/usage-error.js +9 -0
- package/dist/setup-agents.js +15 -0
- package/dist/site.js +1 -0
- package/dist/update-refresh.js +5 -0
- package/package.json +46 -3
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { readAccountEmail } from "../auth/credentials.js";
|
|
2
|
+
import { defaultAuthDeps, fetchCaptainMode, loginSiteUrl } from "../auth/session.js";
|
|
3
|
+
import { httpFailure } from "../http/request.js";
|
|
4
|
+
import { SITE_URL } from "../metadata.js";
|
|
5
|
+
import { agentResult } from "../output.js";
|
|
6
|
+
import { prettyResult } from "../pretty.js";
|
|
7
|
+
import { spec } from "../registry.js";
|
|
8
|
+
import { openBrowser } from "../runtime/browser.js";
|
|
9
|
+
import { unknownArgument } from "../runtime/flags.js";
|
|
10
|
+
import { plannedRequest, splitDryRun } from "../runtime/dry-run.js";
|
|
11
|
+
import { usageError } from "../runtime/usage-error.js";
|
|
12
|
+
import { rehearsed } from "./dns.js";
|
|
13
|
+
const { name: command } = spec('account get');
|
|
14
|
+
const DELETE = spec('account delete');
|
|
15
|
+
export const DELETE_REQUEST_PATH = '/api/v1/me/delete-request';
|
|
16
|
+
export const DELETE_PAGE_PATH = '/projects#account-delete';
|
|
17
|
+
const BLOCKER_TEXT = {
|
|
18
|
+
subscription: 'A paid plan is active. Cancel it with deepdynamic plan cancel.',
|
|
19
|
+
charges: 'There are unpaid charges. Pay them with deepdynamic plan pay.',
|
|
20
|
+
card: 'A payment card is registered. Delete it in the plan section of the opened page.',
|
|
21
|
+
domains: 'Purchased domains have not expired yet. Turn off auto-renewal and request deletion after they expire.'
|
|
22
|
+
};
|
|
23
|
+
const PROJECTS_PAGE = `${SITE_URL}/projects`;
|
|
24
|
+
const guideNotes = {
|
|
25
|
+
developer: [
|
|
26
|
+
`The user has turned on captain mode (기장 모드) on the My Projects page (${PROJECTS_PAGE}). Assume the user is a developer and explain with technical terms such as commands, commits, build logs and error codes. Do not use airline metaphors.`,
|
|
27
|
+
'For deploy progress, relay percent and forHuman.detail only.'
|
|
28
|
+
],
|
|
29
|
+
non_developer: [
|
|
30
|
+
`The user has not turned on captain mode (기장 모드) on the My Projects page (${PROJECTS_PAGE}). Assume the user is not a developer and explain in plain words.`,
|
|
31
|
+
'Explain with the airline terms of the My Projects page: a project is a flight (항공편), its number such as KR4821 is the flight number (편명), a deploy is a departure (출발), a deploy in progress is 비행 중, a published site is 도착, a failed deploy is 결항, a project not deployed yet is 출발 전, the project server is the aircraft (항공기), CPU is the engine (엔진), RAM is the navigation system (항법장치), the site address is the gate (접속 게이트), the agent that deployed is the origin (출발지) and the deploy region is the destination (도착지).',
|
|
32
|
+
'Do not show the user technical terms such as commit, build, Git, repository, VM, DNS, JSON, exit code or error code, nor commands or logs. Explain them only when the user asks.',
|
|
33
|
+
'For deploy progress, relay percent and forHuman.message only. Do not relay forHuman.detail.',
|
|
34
|
+
'When something fails, tell the user in plain words only what did not work and what happens next, and handle the technical fix yourself. When the error message says to contact support, also give the user its error code and the contact options it lists.',
|
|
35
|
+
'When you need the user to confirm something, such as a project name or a deletion, ask in plain words too.'
|
|
36
|
+
]
|
|
37
|
+
};
|
|
38
|
+
export function guide(captainMode) {
|
|
39
|
+
const audience = captainMode ? 'developer' : 'non_developer';
|
|
40
|
+
return { captainMode, audience, notes: guideNotes[audience] };
|
|
41
|
+
}
|
|
42
|
+
function deletionShown(pretty, depth, body, siteUrl, open) {
|
|
43
|
+
const { requested, requestedAt, blockers, resources } = body;
|
|
44
|
+
const deletePage = new URL(DELETE_PAGE_PATH, siteUrl).href;
|
|
45
|
+
open(deletePage);
|
|
46
|
+
if (!pretty)
|
|
47
|
+
return agentResult(0, { command: DELETE.name, siteUrl, requested, requestedAt, blockers, resources, deletePage });
|
|
48
|
+
const message = requested
|
|
49
|
+
? 'Account deletion was requested and support is reviewing it. The request can be cancelled on the opened page.'
|
|
50
|
+
: blockers.length
|
|
51
|
+
? 'Resolve the blockers before deleting the account.'
|
|
52
|
+
: 'The account can be deleted. The user must request deletion on the opened page.';
|
|
53
|
+
return prettyResult(0, depth, DELETE.name, message, [
|
|
54
|
+
['Server', siteUrl],
|
|
55
|
+
['Request', requestedAt ?? 'None'],
|
|
56
|
+
...blockers.map((blocker) => ['Blocker', BLOCKER_TEXT[blocker]]),
|
|
57
|
+
['URL', deletePage]
|
|
58
|
+
]);
|
|
59
|
+
}
|
|
60
|
+
export async function runAccountDelete(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
|
|
61
|
+
return rehearsed(DELETE.name, args, pretty, depth, deps, (rest) => {
|
|
62
|
+
if (rest.length)
|
|
63
|
+
return { error: unknownArgument(rest[0]) };
|
|
64
|
+
const url = (siteUrl) => new URL(DELETE_REQUEST_PATH, siteUrl).href;
|
|
65
|
+
return {
|
|
66
|
+
steps: [{ stage: 'prepare_request', message: 'Preparing the account deletion status request.' }],
|
|
67
|
+
result: (siteUrl) => plannedRequest(DELETE.name, pretty, depth, siteUrl, url(siteUrl)),
|
|
68
|
+
send: {
|
|
69
|
+
method: 'GET',
|
|
70
|
+
url,
|
|
71
|
+
spinner: 'Checking the account deletion conditions.',
|
|
72
|
+
failed: 'Could not check the account deletion conditions.',
|
|
73
|
+
notFound: httpFailure(404),
|
|
74
|
+
succeeded: ({ status }) => status === 200,
|
|
75
|
+
done: (body, siteUrl) => deletionShown(pretty, depth, body, siteUrl, deps.openBrowser ?? openBrowser)
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
export async function runAccountGet(args, pretty, depth, readCaptainMode = fetchCaptainMode) {
|
|
81
|
+
const { args: rest, dryRun } = splitDryRun(args);
|
|
82
|
+
if (rest.length)
|
|
83
|
+
return usageError(command, unknownArgument(rest[0]), pretty, depth);
|
|
84
|
+
if (dryRun) {
|
|
85
|
+
const siteUrl = await loginSiteUrl();
|
|
86
|
+
return plannedRequest(command, pretty, depth, siteUrl, new URL('/api/v1/me', siteUrl).href);
|
|
87
|
+
}
|
|
88
|
+
const email = await readAccountEmail();
|
|
89
|
+
const captainMode = await readCaptainMode();
|
|
90
|
+
if (!pretty)
|
|
91
|
+
return agentResult(0, { command, account: email ? { email } : null, guide: guide(captainMode) });
|
|
92
|
+
return prettyResult(0, depth, command, 'Loaded the account information.', [
|
|
93
|
+
['Account', email ?? 'Not logged in'],
|
|
94
|
+
['Captain mode', captainMode === null ? 'Unknown' : captainMode ? 'On' : 'Off']
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { defaultAuthDeps } from "../auth/session.js";
|
|
2
|
+
import { httpFailure } from "../http/request.js";
|
|
3
|
+
import { agentResult } from "../output.js";
|
|
4
|
+
import { prettyResult } from "../pretty.js";
|
|
5
|
+
import { plannedRequest } from "../runtime/dry-run.js";
|
|
6
|
+
import { parseFlags } from "../runtime/flags.js";
|
|
7
|
+
import { rehearsed } from "./dns.js";
|
|
8
|
+
export const ACTIVITY_PATH = '/api/v1/activity';
|
|
9
|
+
const command = 'account activity';
|
|
10
|
+
const FLAGS = ['--page', '--kind', '--date', '--source'];
|
|
11
|
+
const KINDS = ['login', 'change'];
|
|
12
|
+
const SOURCES = ['web', 'cli'];
|
|
13
|
+
const PAGE_RE = /^[1-9]\d{0,5}$/;
|
|
14
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
15
|
+
const STEPS = [
|
|
16
|
+
{ stage: 'validate_filters', message: 'Checking the filters.' },
|
|
17
|
+
{ stage: 'prepare_request', message: 'Preparing the account activity request.' }
|
|
18
|
+
];
|
|
19
|
+
function isCalendarDate(value) {
|
|
20
|
+
const time = DATE_RE.test(value) ? Date.parse(`${value}T00:00:00Z`) : NaN;
|
|
21
|
+
return !Number.isNaN(time) && new Date(time).toISOString().startsWith(value);
|
|
22
|
+
}
|
|
23
|
+
function parseActivityArgs(args) {
|
|
24
|
+
const parsed = parseFlags(args, FLAGS);
|
|
25
|
+
if ('error' in parsed)
|
|
26
|
+
return parsed;
|
|
27
|
+
const repeated = FLAGS.find((flag) => parsed.entries.filter(([name]) => name === flag).length > 1);
|
|
28
|
+
if (repeated)
|
|
29
|
+
return { error: `${repeated} can be given only once.` };
|
|
30
|
+
const { '--page': page = '1', '--kind': kind, '--date': date, '--source': source } = Object.fromEntries(parsed.entries);
|
|
31
|
+
if (!PAGE_RE.test(page))
|
|
32
|
+
return { error: `--page requires a positive integer: ${page}` };
|
|
33
|
+
if (kind !== undefined && !KINDS.includes(kind))
|
|
34
|
+
return { error: `--kind must be login or change: ${kind}` };
|
|
35
|
+
if (date !== undefined && !isCalendarDate(date))
|
|
36
|
+
return { error: `--date requires a real calendar date as YYYY-MM-DD: ${date}` };
|
|
37
|
+
if (source !== undefined && !SOURCES.includes(source))
|
|
38
|
+
return { error: `--source must be web or cli: ${source}` };
|
|
39
|
+
return { page: Number(page), kind: kind ?? null, date: date ?? null, source: source ?? null };
|
|
40
|
+
}
|
|
41
|
+
const seoulTime = (iso) => `${new Date(iso).toLocaleString('sv-SE', { timeZone: 'Asia/Seoul' }).slice(0, 16)} KST`;
|
|
42
|
+
function recordLine(record) {
|
|
43
|
+
const parts = [record.kind, record.source, record.action, ...(record.target ? [record.target] : []), ...(record.ip ? [`IP ${record.ip}`] : [])];
|
|
44
|
+
return [seoulTime(record.at), parts.join(' · ')];
|
|
45
|
+
}
|
|
46
|
+
export async function runActivity(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
|
|
47
|
+
return rehearsed(command, args, pretty, depth, deps, (rest) => {
|
|
48
|
+
const options = parseActivityArgs(rest);
|
|
49
|
+
if ('error' in options)
|
|
50
|
+
return options;
|
|
51
|
+
const url = (siteUrl) => {
|
|
52
|
+
const endpoint = new URL(ACTIVITY_PATH, siteUrl);
|
|
53
|
+
endpoint.searchParams.set('page', String(options.page));
|
|
54
|
+
if (options.kind)
|
|
55
|
+
endpoint.searchParams.set('kind', options.kind);
|
|
56
|
+
if (options.date)
|
|
57
|
+
endpoint.searchParams.set('date', options.date);
|
|
58
|
+
if (options.source)
|
|
59
|
+
endpoint.searchParams.set('source', options.source);
|
|
60
|
+
return endpoint.href;
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
steps: STEPS,
|
|
64
|
+
result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, url(siteUrl)),
|
|
65
|
+
send: {
|
|
66
|
+
method: 'GET',
|
|
67
|
+
url,
|
|
68
|
+
spinner: 'Loading account activity.',
|
|
69
|
+
failed: 'Could not load account activity.',
|
|
70
|
+
notFound: httpFailure(404),
|
|
71
|
+
done: (body, siteUrl) => {
|
|
72
|
+
const { page, pageSize, total, date, source, records } = body;
|
|
73
|
+
if (!pretty)
|
|
74
|
+
return agentResult(0, { command, siteUrl, page, pageSize, total, date, source, records });
|
|
75
|
+
return prettyResult(0, depth, command, `Loaded page ${page} of the account activity (${total} total).`, [['Server', siteUrl], ...records.map(recordLine)]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { defaultAuthDeps } from "../auth/session.js";
|
|
2
|
+
import { httpFailure } from "../http/request.js";
|
|
3
|
+
import { agentResult } from "../output.js";
|
|
4
|
+
import { CONTROL, prettyResult } from "../pretty.js";
|
|
5
|
+
import { plannedRequest } from "../runtime/dry-run.js";
|
|
6
|
+
import { parseFlags } from "../runtime/flags.js";
|
|
7
|
+
import { rehearsed } from "./dns.js";
|
|
8
|
+
export const BLOCKED_PATH = '/api/v1/blocked-requests';
|
|
9
|
+
const command = 'sites blocked';
|
|
10
|
+
const FLAGS = ['--page', '--ray', '--host', '--date'];
|
|
11
|
+
const PAGE_RE = /^[1-9]\d{0,5}$/;
|
|
12
|
+
const RAY_RE = /^[0-9a-f]{16}$/;
|
|
13
|
+
const HOST_RE = /^(?=.{1,253}$)[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?(?:\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?)*$/;
|
|
14
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
15
|
+
const STEPS = [
|
|
16
|
+
{ stage: 'validate_filters', message: 'Checking the filters.' },
|
|
17
|
+
{ stage: 'prepare_request', message: 'Preparing the blocked requests query.' }
|
|
18
|
+
];
|
|
19
|
+
function isCalendarDate(value) {
|
|
20
|
+
const time = DATE_RE.test(value) ? Date.parse(`${value}T00:00:00Z`) : NaN;
|
|
21
|
+
return !Number.isNaN(time) && new Date(time).toISOString().startsWith(value);
|
|
22
|
+
}
|
|
23
|
+
function parseBlockedArgs(args) {
|
|
24
|
+
const parsed = parseFlags(args, FLAGS);
|
|
25
|
+
if ('error' in parsed)
|
|
26
|
+
return parsed;
|
|
27
|
+
const repeated = FLAGS.find((flag) => parsed.entries.filter(([name]) => name === flag).length > 1);
|
|
28
|
+
if (repeated)
|
|
29
|
+
return { error: `${repeated} can be given only once.` };
|
|
30
|
+
const { '--page': page = '1', '--ray': ray, '--host': host, '--date': date } = Object.fromEntries(parsed.entries);
|
|
31
|
+
if (!PAGE_RE.test(page))
|
|
32
|
+
return { error: `--page requires a positive integer: ${page}` };
|
|
33
|
+
if (ray !== undefined && !RAY_RE.test(ray))
|
|
34
|
+
return { error: `--ray requires the 16 lowercase hex character ID shown on the block page: ${ray}` };
|
|
35
|
+
if (host !== undefined && !HOST_RE.test(host))
|
|
36
|
+
return { error: `--host requires a lowercase host name: ${host}` };
|
|
37
|
+
if (date !== undefined && !isCalendarDate(date))
|
|
38
|
+
return { error: `--date requires a real calendar date as YYYY-MM-DD (UTC): ${date}` };
|
|
39
|
+
return { page: Number(page), ray: ray ?? null, host: host ?? null, date: date ?? null };
|
|
40
|
+
}
|
|
41
|
+
const plain = (text) => text.replace(CONTROL, ' ');
|
|
42
|
+
function recordLine(record) {
|
|
43
|
+
const parts = [
|
|
44
|
+
record.ray,
|
|
45
|
+
record.site ?? '(direct access)',
|
|
46
|
+
...(record.method || record.path ? [plain(`${record.method ?? ''} ${record.path ?? ''}`.trim())] : []),
|
|
47
|
+
...(record.ip ? [`IP ${record.ip}`] : [])
|
|
48
|
+
];
|
|
49
|
+
return [`${record.at.slice(0, 19).replace('T', ' ')} UTC`, parts.join(' · ')];
|
|
50
|
+
}
|
|
51
|
+
export async function runBlocked(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
|
|
52
|
+
return rehearsed(command, args, pretty, depth, deps, (rest) => {
|
|
53
|
+
const options = parseBlockedArgs(rest);
|
|
54
|
+
if ('error' in options)
|
|
55
|
+
return options;
|
|
56
|
+
const url = (siteUrl) => {
|
|
57
|
+
const endpoint = new URL(BLOCKED_PATH, siteUrl);
|
|
58
|
+
endpoint.searchParams.set('page', String(options.page));
|
|
59
|
+
if (options.ray)
|
|
60
|
+
endpoint.searchParams.set('ray', options.ray);
|
|
61
|
+
if (options.host)
|
|
62
|
+
endpoint.searchParams.set('host', options.host);
|
|
63
|
+
if (options.date)
|
|
64
|
+
endpoint.searchParams.set('date', options.date);
|
|
65
|
+
return endpoint.href;
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
steps: STEPS,
|
|
69
|
+
result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, url(siteUrl)),
|
|
70
|
+
send: {
|
|
71
|
+
method: 'GET',
|
|
72
|
+
url,
|
|
73
|
+
spinner: 'Loading blocked requests.',
|
|
74
|
+
failed: 'Could not load blocked requests.',
|
|
75
|
+
notFound: httpFailure(404),
|
|
76
|
+
done: (body, siteUrl) => {
|
|
77
|
+
const { scope, page, pageSize, total, ray, host, date, records } = body;
|
|
78
|
+
if (!pretty)
|
|
79
|
+
return agentResult(0, { command, siteUrl, scope, page, pageSize, total, ray, host, date, records });
|
|
80
|
+
return prettyResult(0, depth, command, `Loaded page ${page} of the blocked requests (${total} total).`, [
|
|
81
|
+
['Server', siteUrl],
|
|
82
|
+
['Scope', scope === 'all' ? 'All sites' : 'Your sites'],
|
|
83
|
+
...records.map(recordLine)
|
|
84
|
+
]);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const AGENTS = [
|
|
2
|
+
['CLD', 'Claude'],
|
|
3
|
+
['CCD', 'Claude Code'],
|
|
4
|
+
['CDX', 'Codex'],
|
|
5
|
+
['GPT', 'ChatGPT'],
|
|
6
|
+
['OPC', 'OpenCode'],
|
|
7
|
+
['CRS', 'Crush'],
|
|
8
|
+
['CUR', 'Cursor'],
|
|
9
|
+
['OTH', 'any other agent or a person']
|
|
10
|
+
];
|
|
11
|
+
export const AGENT_CODES = AGENTS.map(([code]) => code);
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { credentialsPath } from "../../auth/credentials.js";
|
|
4
|
+
const EXCLUDED_NAMES = [
|
|
5
|
+
'node_modules', '.git', '.cache', '.ds_store', 'thumbs.db', '.env', '.envrc', '.dev.vars', '.wrangler', '.cloudflare', '.npmrc', '.netrc', '_netrc',
|
|
6
|
+
'.yarnrc', '.yarnrc.yml', '.git-credentials', '.pypirc', '.ssh', '.aws', '.docker', '.kube', '.gnupg', '.svn', '.hg'
|
|
7
|
+
];
|
|
8
|
+
const sameFile = (first, second) => first.dev === second.dev && first.ino === second.ino;
|
|
9
|
+
function isExcluded(name) {
|
|
10
|
+
const normalized = name.toLowerCase();
|
|
11
|
+
return EXCLUDED_NAMES.includes(normalized) || normalized.startsWith('.env.') || normalized.startsWith('.dev.vars.') || /^git~\d+$/.test(normalized) || /^\.git[. ]+$/.test(normalized);
|
|
12
|
+
}
|
|
13
|
+
export async function collectDeployFiles(root) {
|
|
14
|
+
const files = [];
|
|
15
|
+
const paths = ['', '1'].map((development) => credentialsPath({ ...process.env, DEEPDYNAMIC_DEVELOPMENT: development }));
|
|
16
|
+
const credentials = paths.map((path) => path.toLowerCase());
|
|
17
|
+
const names = paths.map((path) => basename(path).toLowerCase());
|
|
18
|
+
const saved = (await Promise.all(paths.map((path) => stat(path, { bigint: true }).catch(() => null)))).filter((info) => info !== null && info.ino !== 0n);
|
|
19
|
+
const isCredentials = async (path, name) => {
|
|
20
|
+
if (credentials.includes(path.toLowerCase()))
|
|
21
|
+
return true;
|
|
22
|
+
if (!saved.length || !names.includes(name.toLowerCase()))
|
|
23
|
+
return false;
|
|
24
|
+
const info = await stat(path, { bigint: true }).catch(() => null);
|
|
25
|
+
return info !== null && saved.some((credential) => sameFile(credential, info));
|
|
26
|
+
};
|
|
27
|
+
const walk = async (directory, prefix) => {
|
|
28
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
29
|
+
if (isExcluded(entry.name))
|
|
30
|
+
continue;
|
|
31
|
+
const path = join(directory, entry.name);
|
|
32
|
+
if (await isCredentials(path, entry.name))
|
|
33
|
+
continue;
|
|
34
|
+
if (entry.isDirectory())
|
|
35
|
+
await walk(path, `${prefix}${entry.name}/`);
|
|
36
|
+
else if (entry.isFile())
|
|
37
|
+
files.push(`${prefix}${entry.name}`);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
await walk(root, '');
|
|
41
|
+
return files.sort();
|
|
42
|
+
}
|
|
43
|
+
const comparable = (path) => process.platform === 'linux' ? path : path.normalize('NFC').toLowerCase();
|
|
44
|
+
export async function deployFileReader(root) {
|
|
45
|
+
const base = await realpath(root);
|
|
46
|
+
return async (file) => {
|
|
47
|
+
const path = join(root, file);
|
|
48
|
+
const handle = await open(path, 'r');
|
|
49
|
+
try {
|
|
50
|
+
const opened = await handle.stat({ bigint: true });
|
|
51
|
+
const real = await realpath(path);
|
|
52
|
+
const current = await lstat(real, { bigint: true });
|
|
53
|
+
if (comparable(real) !== comparable(join(base, file)) || !current.isFile() || !sameFile(current, opened)) {
|
|
54
|
+
throw new Error('A deploy file changed or points outside the deployed directory.');
|
|
55
|
+
}
|
|
56
|
+
return await handle.readFile();
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
await handle.close();
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { agentResult } from "../../output.js";
|
|
4
|
+
import { displayWidth, pad, prettyResult } from "../../pretty.js";
|
|
5
|
+
import { spec } from "../../registry.js";
|
|
6
|
+
import { collectDeployFiles, deployFileReader } from "./files.js";
|
|
7
|
+
import { minifyFile } from "./minify.js";
|
|
8
|
+
import { defaultAuthDeps } from "../../auth/session.js";
|
|
9
|
+
import { uploadDeployment } from "./upload.js";
|
|
10
|
+
import { MANIFEST_FILE, readManifest } from "./manifest.js";
|
|
11
|
+
import { PUBLISH_WAIT_SECONDS, shipDeployment } from "./ship.js";
|
|
12
|
+
import { AGENT_CODES } from "./agents.js";
|
|
13
|
+
import { parseCommand } from "../../runtime/flags.js";
|
|
14
|
+
import { PROJECT } from "../../runtime/project-name.js";
|
|
15
|
+
import { parseTimeout } from "../../runtime/timeout.js";
|
|
16
|
+
const { name: command, usage } = spec('projects deploy');
|
|
17
|
+
function formatSize(bytes) {
|
|
18
|
+
if (bytes < 1024)
|
|
19
|
+
return `${bytes} B`;
|
|
20
|
+
if (bytes < 1024 * 1024)
|
|
21
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
22
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
23
|
+
}
|
|
24
|
+
export async function runDeploy(input, pretty, depth, deps = { ...defaultAuthDeps(pretty, depth), upload: uploadDeployment }) {
|
|
25
|
+
const invalid = (message) => pretty
|
|
26
|
+
? prettyResult(2, depth, command, message, [['Usage', usage]])
|
|
27
|
+
: agentResult(2, { command, error: { code: 'invalid_arguments', message }, usage });
|
|
28
|
+
const timeout = parseTimeout(input, PUBLISH_WAIT_SECONDS);
|
|
29
|
+
if ('error' in timeout)
|
|
30
|
+
return invalid(timeout.error);
|
|
31
|
+
const dryRun = timeout.rest.includes('--dry-run');
|
|
32
|
+
const parsed = parseCommand(timeout.rest.filter((arg) => arg !== '--dry-run'), ['--agent']);
|
|
33
|
+
if ('error' in parsed)
|
|
34
|
+
return invalid(parsed.error);
|
|
35
|
+
const [project, target] = parsed.names;
|
|
36
|
+
const agent = parsed.entries.find(([flag]) => flag === '--agent')?.[1];
|
|
37
|
+
const problem = parsed.names.length !== 2
|
|
38
|
+
? 'Specify the project name and exactly one directory to deploy.'
|
|
39
|
+
: !PROJECT.test(project)
|
|
40
|
+
? 'The project name must be 1-63 lowercase letters, digits or hyphens that start and end with a letter or digit.'
|
|
41
|
+
: agent !== undefined && !AGENT_CODES.includes(agent)
|
|
42
|
+
? `--agent must be one of ${AGENT_CODES.join(', ')}.`
|
|
43
|
+
: null;
|
|
44
|
+
if (problem)
|
|
45
|
+
return invalid(problem);
|
|
46
|
+
if (!dryRun && !agent) {
|
|
47
|
+
return pretty
|
|
48
|
+
? prettyResult(2, depth, command, 'Specify the code of the agent running this deploy with --agent. No files were uploaded.', [['Usage', usage], ['Code', AGENT_CODES.join(' ')]])
|
|
49
|
+
: agentResult(2, { command, project, uploaded: false, deployed: false, error: { code: 'agent_required', message: `Specify --agent <code> for the agent running this deploy, one of ${AGENT_CODES.join(', ')}. No files were uploaded.` }, usage });
|
|
50
|
+
}
|
|
51
|
+
const directory = resolve(target);
|
|
52
|
+
if (!(await stat(directory).catch(() => null))?.isDirectory()) {
|
|
53
|
+
return pretty
|
|
54
|
+
? prettyResult(1, depth, command, 'Could not find the directory to deploy.', [['Directory', directory]])
|
|
55
|
+
: agentResult(1, { command, project, directory, error: { code: 'directory_not_found', message: 'The directory does not exist.' } });
|
|
56
|
+
}
|
|
57
|
+
const reader = await deployFileReader(directory);
|
|
58
|
+
const files = await collectDeployFiles(directory);
|
|
59
|
+
if (files.length === 0) {
|
|
60
|
+
return pretty
|
|
61
|
+
? prettyResult(1, depth, command, 'No files to upload after exclusions.', [['Directory', directory]])
|
|
62
|
+
: agentResult(1, { command, project, directory, error: { code: 'no_files', message: 'No files to upload after exclusions.' } });
|
|
63
|
+
}
|
|
64
|
+
const read = await readManifest(directory);
|
|
65
|
+
if ('error' in read) {
|
|
66
|
+
return pretty
|
|
67
|
+
? prettyResult(1, depth, command, `Check ${MANIFEST_FILE}.`, [['Directory', directory], ['Reason', read.error]])
|
|
68
|
+
: agentResult(1, { command, project, directory, error: { code: 'invalid_manifest', message: read.error } });
|
|
69
|
+
}
|
|
70
|
+
const { manifest } = read;
|
|
71
|
+
const app = manifest?.start !== undefined;
|
|
72
|
+
const minify = typeof manifest?.build !== 'string' && !app;
|
|
73
|
+
if (!dryRun) {
|
|
74
|
+
return shipDeployment({
|
|
75
|
+
command, project, agent, manifest, context: { project, directory }, success: { files }, rows: [['Directory', directory]], waitMs: timeout.waitMs,
|
|
76
|
+
send: (remote, branch, token, onUploading) => deps.upload(directory, files, remote, branch, token, { onUploading, minify, read: reader })
|
|
77
|
+
}, pretty, depth, deps);
|
|
78
|
+
}
|
|
79
|
+
if (!pretty) {
|
|
80
|
+
return agentResult(0, { command, project, directory, dryRun: true, files, uploaded: false, ...(manifest ? { manifest } : {}) });
|
|
81
|
+
}
|
|
82
|
+
const nameWidth = Math.max(...files.map(displayWidth));
|
|
83
|
+
const rows = [];
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
const content = await readFile(join(directory, file));
|
|
86
|
+
const minified = minify ? await minifyFile(file, content) : content;
|
|
87
|
+
const size = minified.length < content.length ? `${formatSize(content.length)} → ${formatSize(minified.length)}` : formatSize(content.length);
|
|
88
|
+
rows.push([rows.length === 0 ? 'Files' : '', `${pad(file, nameWidth)} ${size}`]);
|
|
89
|
+
}
|
|
90
|
+
return prettyResult(0, depth, command, `Checked ${files.length} file${files.length === 1 ? '' : 's'} to upload. Nothing was uploaded.`, [
|
|
91
|
+
['Directory', directory],
|
|
92
|
+
...(manifest ? [['Build', `${typeof manifest.build === 'string' ? manifest.build : 'no build'} → ${app ? `${String(manifest.start)} (port ${String(manifest.port)})` : String(manifest.output)}`]] : []),
|
|
93
|
+
...rows
|
|
94
|
+
]);
|
|
95
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export const MANIFEST_FILE = 'deepdynamic.json';
|
|
4
|
+
const MANIFEST_MAX = 1024;
|
|
5
|
+
export async function readManifest(directory) {
|
|
6
|
+
let text;
|
|
7
|
+
try {
|
|
8
|
+
text = await readFile(join(directory, MANIFEST_FILE), 'utf8');
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
return error.code === 'ENOENT' ? { manifest: null } : { error: `Could not read ${MANIFEST_FILE}.` };
|
|
12
|
+
}
|
|
13
|
+
if (Buffer.byteLength(text) > MANIFEST_MAX)
|
|
14
|
+
return { error: `${MANIFEST_FILE} must be at most ${MANIFEST_MAX} bytes.` };
|
|
15
|
+
try {
|
|
16
|
+
const value = JSON.parse(text);
|
|
17
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
18
|
+
? { manifest: value }
|
|
19
|
+
: { error: `${MANIFEST_FILE} must contain a JSON object.` };
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return { error: `${MANIFEST_FILE} is not valid JSON.` };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { extname } from 'node:path';
|
|
2
|
+
const TARGET = ['chrome107', 'edge107', 'firefox104', 'safari16'];
|
|
3
|
+
const CUSTOM_FRAGMENT = /<%[\s\S]*?%>|<\?[\s\S]*?\?>/;
|
|
4
|
+
const minifyHtml = async (text) => CUSTOM_FRAGMENT.test(text)
|
|
5
|
+
? text
|
|
6
|
+
: (await import('html-minifier-terser')).minify(text, { collapseWhitespace: true, conservativeCollapse: true, removeComments: true, minifyCSS: { inline: false }, minifyJS: true });
|
|
7
|
+
const minifyScript = async (text) => (await (await import('esbuild')).transform(text, { loader: 'js', minify: true, target: TARGET })).code;
|
|
8
|
+
const MINIFIERS = {
|
|
9
|
+
'.html': minifyHtml,
|
|
10
|
+
'.htm': minifyHtml,
|
|
11
|
+
'.css': async (text) => (await (await import('esbuild')).transform(text, { loader: 'css', minify: true, target: TARGET })).code,
|
|
12
|
+
'.js': minifyScript,
|
|
13
|
+
'.mjs': minifyScript
|
|
14
|
+
};
|
|
15
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
16
|
+
export async function minifyFile(path, content) {
|
|
17
|
+
const minifier = MINIFIERS[extname(path).toLowerCase()];
|
|
18
|
+
if (!minifier)
|
|
19
|
+
return content;
|
|
20
|
+
try {
|
|
21
|
+
const minified = Buffer.from(await minifier(utf8.decode(content)));
|
|
22
|
+
return minified.length < content.length ? minified : content;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return content;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { LoginExpiredError, postJson, request } from "../../http/request.js";
|
|
2
|
+
import { jsonLine } from "../../output.js";
|
|
3
|
+
import { plain } from "../../pretty.js";
|
|
4
|
+
import { PROJECT } from "../../runtime/project-name.js";
|
|
5
|
+
const STAGES = ['preparing', 'packing', 'uploading', 'verifying', 'awaiting_publish', 'publishing', 'published', 'failed'];
|
|
6
|
+
const STATUSES = ['running', 'blocked', 'succeeded', 'failed', 'interrupted'];
|
|
7
|
+
const ERROR_CODES = ['publishing_not_configured', 'upload_failed', 'git_verification_failed', 'progress_interrupted', 'publish_failed', 'publish_timeout', 'server_failed', 'project_not_found', 'deploy_stopped'];
|
|
8
|
+
const NEXT_ACTIONS = ['wait_for_publishing_integration', 'inspect_and_retry', 'poll', 'continue_upload', 'done'];
|
|
9
|
+
const LOG_MAX = 4000;
|
|
10
|
+
export const PUBLIC_URL = /^https?:\/\/[a-z0-9.-]{1,250}$/;
|
|
11
|
+
export class ProgressRejected extends Error {
|
|
12
|
+
status;
|
|
13
|
+
constructor(status) {
|
|
14
|
+
super('The server rejected the deployment.');
|
|
15
|
+
this.status = status;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export const DEPLOYMENT_ID = /^[a-f0-9-]{36}$/;
|
|
19
|
+
export function parseProgress(body, token, expected) {
|
|
20
|
+
const value = body;
|
|
21
|
+
const agent = value?.forAgent;
|
|
22
|
+
const human = value?.forHuman;
|
|
23
|
+
const safeText = (text) => typeof text === 'string' && text.length <= 2000 && !/[\x00-\x1f\x7f]/.test(text) && !text.includes(token);
|
|
24
|
+
const safeLog = (text) => text === null
|
|
25
|
+
|| (typeof text === 'string' && text.length <= LOG_MAX && !/[\x00-\x08\x0b-\x1f\x7f]/.test(text) && !text.includes(token));
|
|
26
|
+
const site = value?.publicUrl ?? null;
|
|
27
|
+
if (!value || value.ok !== true || typeof value.id !== 'string' || !DEPLOYMENT_ID.test(value.id) || (expected.id && expected.id !== value.id)
|
|
28
|
+
|| (expected.project ? value.project !== expected.project : typeof value.project !== 'string' || !PROJECT.test(value.project))
|
|
29
|
+
|| (site !== null && (typeof site !== 'string' || !PUBLIC_URL.test(site) || agent?.stage !== 'published'))
|
|
30
|
+
|| !Number.isInteger(value.percent) || value.percent < 0 || value.percent > 100 || typeof value.updatedAt !== 'string' || !Number.isFinite(Date.parse(value.updatedAt))
|
|
31
|
+
|| !human || !safeText(human.message) || !safeText(human.detail) || !agent
|
|
32
|
+
|| !STAGES.includes(agent.stage) || !STATUSES.includes(agent.status)
|
|
33
|
+
|| typeof agent.gitUploaded !== 'boolean' || agent.deployed !== (agent.stage === 'published') || agent.progressBasis !== 'milestones'
|
|
34
|
+
|| (agent.commit !== null && (typeof agent.commit !== 'string' || !/^[a-f0-9]{40}$/.test(agent.commit)))
|
|
35
|
+
|| (agent.errorCode !== null && !ERROR_CODES.includes(agent.errorCode))
|
|
36
|
+
|| !safeLog(agent.publishLog ?? null)
|
|
37
|
+
|| !NEXT_ACTIONS.includes(agent.nextAction)
|
|
38
|
+
|| (agent.pollAfterMs !== null && agent.pollAfterMs !== 2000))
|
|
39
|
+
return null;
|
|
40
|
+
return {
|
|
41
|
+
ok: true, id: value.id, project: value.project, percent: value.percent, updatedAt: new Date(value.updatedAt).toISOString(), publicUrl: site,
|
|
42
|
+
forHuman: { message: human.message, detail: human.detail },
|
|
43
|
+
forAgent: {
|
|
44
|
+
stage: agent.stage, status: agent.status, gitUploaded: agent.gitUploaded, deployed: agent.deployed,
|
|
45
|
+
commit: agent.commit, errorCode: agent.errorCode, publishLog: agent.publishLog ?? null, progressBasis: 'milestones',
|
|
46
|
+
nextAction: agent.nextAction, pollAfterMs: agent.pollAfterMs,
|
|
47
|
+
userMessageFields: ['forHuman.message', 'forHuman.detail']
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export function progressTracker(siteUrl, token, project, deps, pretty) {
|
|
52
|
+
let id;
|
|
53
|
+
let latest;
|
|
54
|
+
let lastOutput = '';
|
|
55
|
+
const read = async (body) => {
|
|
56
|
+
const url = new URL(`/api/v1/deployments${id ? `/${id}` : ''}`, siteUrl).href;
|
|
57
|
+
const result = body
|
|
58
|
+
? await postJson(url, token, body, deps, null)
|
|
59
|
+
: await request(url, { method: 'GET', headers: { authorization: `Bearer ${token}` } }, deps, null);
|
|
60
|
+
if (!('failure' in result) && result.status === 401)
|
|
61
|
+
throw new LoginExpiredError('The access token was rejected.');
|
|
62
|
+
if (!id && !('failure' in result) && (result.status === 400 || result.status === 404))
|
|
63
|
+
throw new ProgressRejected(result.status);
|
|
64
|
+
if ('failure' in result || result.status !== 200)
|
|
65
|
+
throw new Error('Progress tracking is unavailable.');
|
|
66
|
+
const parsed = parseProgress(result.body, token, { id, project });
|
|
67
|
+
if (!parsed)
|
|
68
|
+
throw new Error('Invalid progress response.');
|
|
69
|
+
id = parsed.id;
|
|
70
|
+
latest = parsed;
|
|
71
|
+
const output = pretty ? `[${latest.percent}%] ${plain(latest.forHuman.message)}\n${plain(latest.forHuman.detail)}\n`
|
|
72
|
+
: jsonLine({ event: 'deployment_progress', ...latest });
|
|
73
|
+
if (output !== lastOutput)
|
|
74
|
+
deps.stream.write(output);
|
|
75
|
+
lastOutput = output;
|
|
76
|
+
return latest;
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
start: (manifest, agent) => read({ project, ...(manifest ? { manifest } : {}), ...(agent ? { agent } : {}) }),
|
|
80
|
+
update: (stage, commit) => read({ stage, ...(commit ? { commit } : {}) }),
|
|
81
|
+
read: () => read(),
|
|
82
|
+
get latest() { return latest; },
|
|
83
|
+
get url() { return id ? new URL(`/api/v1/deployments/${id}`, siteUrl).href : null; }
|
|
84
|
+
};
|
|
85
|
+
}
|