@deepdynamic/cli 0.1.0 → 0.1.2

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 (58) hide show
  1. package/dist/agents/content.js +1 -1
  2. package/dist/agents/install.js +28 -12
  3. package/dist/agents/refresh.js +20 -0
  4. package/dist/agents/setup.js +7 -7
  5. package/dist/cli.js +8 -8
  6. package/dist/commands/account.js +19 -19
  7. package/dist/commands/activity.js +13 -13
  8. package/dist/commands/blocked.js +16 -16
  9. package/dist/commands/deploy/index.js +16 -16
  10. package/dist/commands/deploy/ship.js +8 -8
  11. package/dist/commands/deployments.js +8 -7
  12. package/dist/commands/dns.js +229 -243
  13. package/dist/commands/domains.js +188 -260
  14. package/dist/commands/emails.js +64 -26
  15. package/dist/commands/env.js +38 -38
  16. package/dist/commands/help.js +18 -19
  17. package/dist/commands/keys.js +84 -90
  18. package/dist/commands/login/flow.js +11 -11
  19. package/dist/commands/login/index.js +3 -3
  20. package/dist/commands/logout.js +11 -11
  21. package/dist/commands/mail.js +82 -69
  22. package/dist/commands/notifications.js +30 -29
  23. package/dist/commands/plan.js +109 -125
  24. package/dist/commands/projects.js +159 -157
  25. package/dist/commands/reference.js +139 -112
  26. package/dist/commands/search.js +29 -18
  27. package/dist/commands/server.js +100 -112
  28. package/dist/commands/sessions.js +38 -44
  29. package/dist/commands/sites.js +16 -16
  30. package/dist/commands/sms.js +31 -17
  31. package/dist/commands/status.js +9 -9
  32. package/dist/commands/support.js +19 -19
  33. package/dist/commands/update.js +18 -16
  34. package/dist/commands/usage.js +12 -12
  35. package/dist/commands/verify.js +16 -16
  36. package/dist/guide.js +9 -48
  37. package/dist/http/request.js +3 -3
  38. package/dist/pretty.js +4 -4
  39. package/dist/refresh-skills.js +5 -0
  40. package/dist/registry.js +74 -146
  41. package/dist/runtime/card-request.js +6 -6
  42. package/dist/runtime/confirm.js +1 -1
  43. package/dist/runtime/development.js +1 -1
  44. package/dist/runtime/dry-run.js +2 -2
  45. package/dist/runtime/env-file.js +6 -9
  46. package/dist/runtime/flags.js +11 -13
  47. package/dist/runtime/login-screen.js +5 -5
  48. package/dist/runtime/page.js +4 -4
  49. package/dist/runtime/server-options.js +4 -8
  50. package/dist/runtime/spinner.js +3 -1
  51. package/dist/runtime/support.js +2 -3
  52. package/dist/runtime/text-file.js +5 -5
  53. package/dist/runtime/timeout.js +2 -2
  54. package/dist/runtime/update-check.js +48 -14
  55. package/dist/runtime/update-install.js +40 -5
  56. package/dist/runtime/usage-error.js +2 -2
  57. package/dist/setup-agents.js +9 -2
  58. package/package.json +1 -1
@@ -33,12 +33,12 @@ export async function requestCard(command, pretty, depth, session, deps, extra =
33
33
  const url = await registrationUrl(session, agent, ip, deps) ?? new URL(REGISTER_PATH, session.siteUrl).href;
34
34
  (deps.openBrowser ?? openBrowser)(url);
35
35
  if (pretty) {
36
- return prettyResult(1, depth, command, '결제 카드를 등록해야 합니다.', [
37
- ['서버', session.siteUrl],
38
- ['원인', '무료 이용 범위를 넘어서 결제 카드가 필요합니다. 아무것도 바꾸지 않았습니다.'],
39
- ['카드 등록', url],
40
- ['로그인', '이 주소는 한 시간 안에 한 번 자동으로 로그인됩니다. 다른 곳에 보내지 마세요.'],
41
- ['다음', '브라우저에서 카드를 등록한 뒤 같은 명령을 다시 실행하세요.']
36
+ return prettyResult(1, depth, command, 'A payment card is required.', [
37
+ ['Server', session.siteUrl],
38
+ ['Reason', 'This goes beyond the free tier, so a payment card is needed. Nothing was changed.'],
39
+ ['Add card', url],
40
+ ['Login', 'This link logs you in automatically once within one hour. Do not share it.'],
41
+ ['Next', 'Add the card in the browser, then run the same command again.']
42
42
  ]);
43
43
  }
44
44
  return agentResult(1, {
@@ -16,6 +16,6 @@ export function confirmCommand(command, args) {
16
16
  export function confirmationRequired(command, args, pretty, depth, reason, data = {}) {
17
17
  const next = confirmCommand(command, args);
18
18
  return pretty
19
- ? prettyResult(3, depth, command, reason.display, [['실행', next]])
19
+ ? prettyResult(3, depth, command, reason.display, [['Run', next]])
20
20
  : agentResult(3, { command, ...data, error: { code: 'confirmation_required', message: `${reason.message} Confirm with the user, then run: ${next}`, next, retryable: false } });
21
21
  }
@@ -5,7 +5,7 @@ import { LOGIN_TIMEOUT_OPTION, parseTimeout } from "./timeout.js";
5
5
  export const LOCAL_SITE_URL = 'http://localhost:5173';
6
6
  export const SERVER_COMMANDS = commands.filter(({ usage }) => usage.includes(SERVER_OPTION)).map(({ name }) => name);
7
7
  export function developmentArgs(args) {
8
- const timeout = parseTimeout(args.filter((arg) => arg !== '--pretty'), LOGIN_TIMEOUT_MS / 1000, false, LOGIN_TIMEOUT_OPTION, 1);
8
+ const timeout = parseTimeout(args.filter((arg) => arg !== '--pretty'), LOGIN_TIMEOUT_MS / 1000, LOGIN_TIMEOUT_OPTION, 1);
9
9
  const [command, action] = 'error' in timeout ? [] : timeout.rest;
10
10
  return SERVER_COMMANDS.includes(`${command} ${action}`) || SERVER_COMMANDS.includes(command ?? '')
11
11
  ? [...args, SERVER_OPTION, LOCAL_SITE_URL]
@@ -9,7 +9,7 @@ export function splitDryRun(args) {
9
9
  }
10
10
  export function plannedRequest(command, pretty, depth, siteUrl, url) {
11
11
  return pretty
12
- ? prettyResult(0, depth, command, '요청을 보내지 않고 확인만 했습니다.', [['서버', siteUrl], ['요청', `GET ${url}`]])
12
+ ? prettyResult(0, depth, command, 'Checked without sending the request.', [['Server', siteUrl], ['Request', `GET ${url}`]])
13
13
  : agentResult(0, { command, siteUrl, dryRun: true, request: { method: 'GET', url } });
14
14
  }
15
15
  export async function rehearse(command, steps, pretty, stream, pause = pauseFor) {
@@ -23,6 +23,6 @@ export async function rehearse(command, steps, pretty, stream, pause = pauseFor)
23
23
  }
24
24
  export function plannedChange(command, pretty, depth, siteUrl, request, message, rows, plan) {
25
25
  return pretty
26
- ? prettyResult(0, depth, command, message, [['서버', siteUrl], ...rows, ['요청', `POST ${request.url}`]])
26
+ ? prettyResult(0, depth, command, message, [['Server', siteUrl], ...rows, ['Request', `POST ${request.url}`]])
27
27
  : agentResult(0, { command, siteUrl, dryRun: true, applied: false, plan, request: { method: 'POST', ...request } });
28
28
  }
@@ -24,24 +24,21 @@ export function readEnv(text) {
24
24
  vars = { ...parseEnv(text.replace(/^/, '')) };
25
25
  }
26
26
  catch {
27
- return { error: ['The env file could not be parsed. Use KEY=value lines.', '환경변수 파일을 읽지 못했습니다. KEY=값 형식으로 적어 주세요.'] };
27
+ return { error: 'The env file could not be parsed. Use KEY=value lines.' };
28
28
  }
29
29
  const names = Object.keys(vars);
30
30
  if (names.length === 0)
31
- return { error: ['The env file has no variables. Use deepdynamic projects env clear to remove all variables.', '환경변수 파일에 변수가 없습니다. 모두 지우려면 deepdynamic projects env clear 를 쓰세요.'] };
31
+ return { error: 'The env file has no variables. Use deepdynamic projects env clear to remove all variables.' };
32
32
  if (names.length > ENV_COUNT_MAX)
33
- return { error: [`The env file has ${names.length} variables; at most ${ENV_COUNT_MAX} are allowed.`, `변수는 ${ENV_COUNT_MAX}개까지 넣을 수 있습니다. 지금 ${names.length}개입니다.`] };
33
+ return { error: `The env file has ${names.length} variables; at most ${ENV_COUNT_MAX} are allowed.` };
34
34
  const invalid = names.find((name) => !validEnvName(name));
35
35
  if (invalid !== undefined) {
36
- return { error: [
37
- `${JSON.stringify(invalid)} is not allowed. Names must match [A-Za-z_][A-Za-z0-9_]* (up to 128 characters) and must not be ${RESERVED.join(', ')} or start with LD_.`,
38
- `${JSON.stringify(invalid)} 은(는) 쓸 수 없는 이름입니다. 영문·숫자·밑줄로 128자까지이고 숫자로 시작할 수 없으며, ${RESERVED.join('·')}·LD_ 로 시작하는 이름은 쓸 수 없습니다.`
39
- ] };
36
+ return { error: `${JSON.stringify(invalid)} is not allowed. Names must match [A-Za-z_][A-Za-z0-9_]* (up to 128 characters) and must not be ${RESERVED.join(', ')} or start with LD_.` };
40
37
  }
41
38
  if (Object.values(vars).some((value) => value.includes('\0')))
42
- return { error: ['Values must not contain NUL characters.', '값에 NUL 문자를 넣을 수 없습니다.'] };
39
+ return { error: 'Values must not contain NUL characters.' };
43
40
  if (shellSize(vars) > ENV_FILE_MAX)
44
- return { error: [`The variables are larger than ${ENV_FILE_MAX} bytes.`, `변수 전체 크기가 ${ENV_FILE_MAX} 바이트를 넘습니다.`] };
41
+ return { error: `The variables are larger than ${ENV_FILE_MAX} bytes.` };
45
42
  return { vars };
46
43
  }
47
44
  export function sealEnv(vars, seal, source = randomSource) {
@@ -1,32 +1,30 @@
1
1
  import { closest } from "./suggest.js";
2
- const UNKNOWN_OPTION = /^(?:Unknown option|알 수 없는 옵션입니다): (-.*)$/;
2
+ const UNKNOWN_OPTION = /^Unknown option: (-.*)$/;
3
3
  const COMMAND_OPTIONS = ['--help', '--pretty', '--login-timeout'];
4
- export function unknownArgument(arg, pretty) {
5
- return pretty
6
- ? `알 수 없는 ${arg.startsWith('-') ? '옵션' : '인자'}입니다: ${arg}`
7
- : `Unknown ${arg.startsWith('-') ? 'option' : 'argument'}: ${arg}`;
4
+ export function unknownArgument(arg) {
5
+ return `Unknown ${arg.startsWith('-') ? 'option' : 'argument'}: ${arg}`;
8
6
  }
9
7
  export function optionSuggestion(message, usage) {
10
8
  const option = UNKNOWN_OPTION.exec(message)?.[1].split('=')[0];
11
9
  return option ? closest(option, [...new Set([...(usage.match(/--[a-z][a-z-]*/g) ?? []), ...COMMAND_OPTIONS])]) : null;
12
10
  }
13
- export function parseFlags(args, flags, pretty) {
11
+ export function parseFlags(args, flags) {
14
12
  const entries = [];
15
13
  for (let index = 0; index < args.length; index++) {
16
14
  const arg = args[index];
17
15
  const flag = flags.find((name) => arg === name || arg.startsWith(`${name}=`));
18
16
  if (!flag) {
19
- return { error: unknownArgument(arg, pretty) };
17
+ return { error: unknownArgument(arg) };
20
18
  }
21
19
  const value = arg === flag ? args[++index] : arg.slice(flag.length + 1);
22
20
  if (value === undefined || !value.trim()) {
23
- return { error: missingValue(flag, pretty) };
21
+ return { error: missingValue(flag) };
24
22
  }
25
23
  entries.push([flag, value]);
26
24
  }
27
25
  return { entries };
28
26
  }
29
- export function parseCommand(args, flags, pretty) {
27
+ export function parseCommand(args, flags) {
30
28
  const names = [];
31
29
  const entries = [];
32
30
  for (let index = 0; index < args.length; index++) {
@@ -37,14 +35,14 @@ export function parseCommand(args, flags, pretty) {
37
35
  }
38
36
  const flag = flags.find((name) => arg === name || arg.startsWith(`${name}=`));
39
37
  if (!flag)
40
- return { error: unknownArgument(arg, pretty) };
38
+ return { error: unknownArgument(arg) };
41
39
  const value = arg !== flag ? arg.slice(flag.length + 1) : args[index + 1]?.startsWith('-') ? undefined : args[++index];
42
40
  if (value === undefined || !value.trim())
43
- return { error: missingValue(flag, pretty) };
41
+ return { error: missingValue(flag) };
44
42
  entries.push([flag, value]);
45
43
  }
46
44
  return { names, entries };
47
45
  }
48
- function missingValue(flag, pretty) {
49
- return pretty ? `${flag} 에 값을 지정하세요.` : `${flag} requires a value.`;
46
+ function missingValue(flag) {
47
+ return `${flag} requires a value.`;
50
48
  }
@@ -33,7 +33,7 @@ export function startLoginScreen(url, stream) {
33
33
  };
34
34
  const link = (text) => `\x1b]8;id=dd-login;${url}\x1b\\${text}\x1b]8;;\x1b\\`;
35
35
  const urlLines = url.match(new RegExp(`.{1,${Math.max(1, columns - 6)}}`, 'g')).map((part) => rail('│', link(part)));
36
- const status = `${style(warm, '●')} ${style('1', '로그인 진행 중')}`;
36
+ const status = `${style(warm, '●')} ${style('1', 'Logging in')}`;
37
37
  const render = (compact) => [
38
38
  ...(compact ? [
39
39
  ` ${style(blue, '//')} ${style('1', 'DeepDynamic Cloud')}`,
@@ -42,14 +42,14 @@ export function startLoginScreen(url, stream) {
42
42
  '',
43
43
  ...logo.map((line) => ` ${line}`),
44
44
  '',
45
- rail('╭', `${style('2', 'CLI / 계정 연결')} ${status}`),
45
+ rail('╭', `${style('2', 'CLI / Account link')} ${status}`),
46
46
  rail('│')
47
47
  ]),
48
- ...wrap('├', '브라우저에서 로그인을 마무리하세요.'),
49
- ...wrap('│', '브라우저가 열리지 않으면 아래 주소를 직접 여세요.', (line) => style('2', line)),
48
+ ...wrap('├', 'Finish logging in in your browser.'),
49
+ ...wrap('│', 'If the browser does not open, open this URL yourself.', (line) => style('2', line)),
50
50
  ...urlLines,
51
51
  ...(compact ? [] : [rail('│')]),
52
- rail('╰', style('2', 'Ctrl+C 취소'))
52
+ rail('╰', style('2', 'Ctrl+C to cancel'))
53
53
  ];
54
54
  const height = (lines) => lines.reduce((total, line) => total + Math.max(1, Math.ceil(displayWidth(line) / columns)), 0);
55
55
  let lines = render(columns < wordmarkWidth + 4);
@@ -1,18 +1,18 @@
1
1
  import { parseFlags } from "./flags.js";
2
2
  const PAGE = /^[1-9]\d{0,5}$/;
3
- export function parsePage(args, pretty) {
4
- const parsed = parseFlags(args, ['--page'], pretty);
3
+ export function parsePage(args) {
4
+ const parsed = parseFlags(args, ['--page']);
5
5
  if ('error' in parsed)
6
6
  return parsed;
7
7
  const values = parsed.entries.map(([, value]) => value);
8
8
  const [page = '1'] = values;
9
9
  if (values.length > 1 || !PAGE.test(page))
10
- return { error: pretty ? '--page 에는 1 이상의 정수를 한 번만 지정하세요.' : 'Give --page once, as a positive integer.' };
10
+ return { error: 'Give --page once, as a positive integer.' };
11
11
  return Number(page);
12
12
  }
13
13
  export function pagination({ total, page, pageSize, totalPages }, command) {
14
14
  return { total, page, pageSize, totalPages, next: Number.isSafeInteger(page) && Number.isSafeInteger(totalPages) && page < totalPages ? `deepdynamic ${command} --page ${page + 1}` : null };
15
15
  }
16
16
  export function pageRows({ total, page, totalPages, next }) {
17
- return [['페이지', `${page} / ${totalPages} (${total}개)`], ...(next ? [['다음', next]] : [])];
17
+ return [['Page', `${page} / ${totalPages} (${total} total)`], ...(next ? [['Next', next]] : [])];
18
18
  }
@@ -2,28 +2,24 @@ import { SITE_URL } from "../metadata.js";
2
2
  import { unknownArgument } from "./flags.js";
3
3
  import { allowedServer } from "./run-mode.js";
4
4
  export const SERVER_OPTION = '--server';
5
- export function parseServerArgs(args, pretty = false) {
5
+ export function parseServerArgs(args) {
6
6
  let siteUrl = null;
7
7
  for (let index = 0; index < args.length; index++) {
8
8
  const arg = args[index];
9
9
  const inline = arg.startsWith(`${SERVER_OPTION}=`);
10
10
  if (arg !== SERVER_OPTION && !inline) {
11
- return { error: unknownArgument(arg, pretty) };
11
+ return { error: unknownArgument(arg) };
12
12
  }
13
13
  const value = inline ? arg.slice(SERVER_OPTION.length + 1) : (args[++index] ?? '');
14
14
  const url = URL.canParse(value) ? new URL(value) : null;
15
15
  if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
16
16
  return {
17
- error: pretty
18
- ? `${SERVER_OPTION} 에는 http:// 또는 https:// 로 시작하는 주소를 지정하세요${value ? `: ${value}` : ''}`
19
- : `${SERVER_OPTION} requires a URL starting with http:// or https://${value ? `: ${value}` : ''}`
17
+ error: `${SERVER_OPTION} requires a URL starting with http:// or https://${value ? `: ${value}` : ''}`
20
18
  };
21
19
  }
22
20
  if (!allowedServer(url.origin)) {
23
21
  return {
24
- error: pretty
25
- ? `${SERVER_OPTION} 에는 ${SITE_URL} 만 지정할 수 있습니다. 다른 서버 주소는 저장소의 개발 실행(pnpm cli)에서만 씁니다: ${value}`
26
- : `The released CLI only accepts ${SERVER_OPTION} ${SITE_URL}. Other servers work only in development runs from the repository (pnpm cli): ${value}`
22
+ error: `The released CLI only accepts ${SERVER_OPTION} ${SITE_URL}. Other servers work only in development runs from the repository (pnpm cli): ${value}`
27
23
  };
28
24
  }
29
25
  siteUrl = url.origin;
@@ -5,7 +5,9 @@ export function startSpinner(message, stream = process.stderr) {
5
5
  const { accent } = paint(stream.getColorDepth?.() ?? 1);
6
6
  const frames = ['┤', '┘', '┴', '└', '├', '┌', '┬', '┐'];
7
7
  let frame = 0;
8
- const draw = () => stream.write(`\r${accent(frames[frame++ % frames.length])} ${message}`);
8
+ const text = typeof message === 'string' ? () => message : message;
9
+ const clear = typeof message === 'string' ? '' : '\x1b[2K';
10
+ const draw = () => stream.write(`\r${clear}${accent(frames[frame++ % frames.length])} ${text()}`);
9
11
  draw();
10
12
  const timer = setInterval(draw, 100);
11
13
  return () => {
@@ -2,13 +2,12 @@ import { SITE_URL } from "../metadata.js";
2
2
  export const CONTACT_PAGE = `${SITE_URL}/contact`;
3
3
  export const SUPPORT_EMAIL = 'mail@deepdynamic.net';
4
4
  export const SUPPORT_HELP = `Contact support with the error code: deepdynamic support contact, ${CONTACT_PAGE} or ${SUPPORT_EMAIL}.`;
5
- export const supportMessage = (code, note) => `Error ${code}.${note ? ` ${note.en}` : ''} Contact support with this code: deepdynamic support contact, ${CONTACT_PAGE} or ${SUPPORT_EMAIL}.`;
6
- export const supportDisplay = (code, note) => `오류 코드 ${code}.${note ? ` ${note.ko}` : ''} 이 코드로 문의해 주세요: deepdynamic support contact, ${CONTACT_PAGE}, ${SUPPORT_EMAIL}`;
5
+ export const supportMessage = (code, note) => `Error ${code}.${note ? ` ${note}` : ''} Contact support with this code: deepdynamic support contact, ${CONTACT_PAGE} or ${SUPPORT_EMAIL}.`;
7
6
  export function supportFailure(code, options = {}) {
8
7
  return {
9
8
  code,
10
9
  message: supportMessage(code, options.note),
11
- display: supportDisplay(code, options.note),
10
+ display: supportMessage(code, options.note),
12
11
  ...(options.retryable === undefined ? {} : { retryable: options.retryable })
13
12
  };
14
13
  }
@@ -1,11 +1,11 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- export async function readText(flag, text, path, pretty) {
2
+ export async function readText(flag, text, path) {
3
3
  const fileFlag = `${flag}-file`;
4
4
  if (text !== undefined && path !== undefined) {
5
- return { error: pretty ? `${flag} 와 ${fileFlag} 중 하나만 지정하세요.` : `Give either ${flag} or ${fileFlag}, not both.` };
5
+ return { error: `Give either ${flag} or ${fileFlag}, not both.` };
6
6
  }
7
7
  if (path === undefined) {
8
- return text === undefined ? { error: pretty ? `${flag} 또는 ${fileFlag} 를 지정하세요.` : `${flag} or ${fileFlag} is required.` } : { text };
8
+ return text === undefined ? { error: `${flag} or ${fileFlag} is required.` } : { text };
9
9
  }
10
10
  let content;
11
11
  try {
@@ -13,8 +13,8 @@ export async function readText(flag, text, path, pretty) {
13
13
  }
14
14
  catch (error) {
15
15
  const reason = error.code ?? String(error);
16
- return { error: pretty ? `${fileFlag} 파일을 읽지 못했습니다(${reason}): ${path}` : `Cannot read the ${fileFlag} file (${reason}): ${path}` };
16
+ return { error: `Cannot read the ${fileFlag} file (${reason}): ${path}` };
17
17
  }
18
18
  const stripped = content.replace(/^/, '').replace(/\r?\n$/, '');
19
- return stripped.trim() ? { text: stripped } : { error: pretty ? `${fileFlag} 파일이 비어 있습니다: ${path}` : `The ${fileFlag} file is empty: ${path}` };
19
+ return stripped.trim() ? { text: stripped } : { error: `The ${fileFlag} file is empty: ${path}` };
20
20
  }
@@ -1,6 +1,6 @@
1
1
  export const TIMEOUT_OPTION = '--timeout';
2
2
  export const LOGIN_TIMEOUT_OPTION = '--login-timeout';
3
- export function parseTimeout(args, maxSeconds, pretty, option = TIMEOUT_OPTION, minSeconds = 0) {
3
+ export function parseTimeout(args, maxSeconds, option = TIMEOUT_OPTION, minSeconds = 0) {
4
4
  const rest = [];
5
5
  const values = [];
6
6
  for (let index = 0; index < args.length; index++) {
@@ -16,7 +16,7 @@ export function parseTimeout(args, maxSeconds, pretty, option = TIMEOUT_OPTION,
16
16
  return { rest, waitMs: maxSeconds * 1000 };
17
17
  const seconds = Number(values[0]);
18
18
  if (values.length > 1 || !/^\d+$/.test(values[0]) || seconds < minSeconds || seconds > maxSeconds) {
19
- return { error: pretty ? `${option} 에는 ${minSeconds}~${maxSeconds} 사이의 초를 한 번만 지정하세요.` : `Give ${option} once, as whole seconds from ${minSeconds} to ${maxSeconds}.` };
19
+ return { error: `Give ${option} once, as whole seconds from ${minSeconds} to ${maxSeconds}.` };
20
20
  }
21
21
  return { rest, waitMs: seconds * 1000 };
22
22
  }
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
4
  import { dirname, join } from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
@@ -7,12 +8,13 @@ import { call } from "../http/call.js";
7
8
  import { jsonLine } from "../output.js";
8
9
  import { developmentRun } from "./run-mode.js";
9
10
  export const PACKAGE_NAME = '@deepdynamic/cli';
10
- export const REGISTRY_URL = 'https://registry.npmjs.org/-/package/@deepdynamic%2fcli/dist-tags';
11
+ export const REGISTRY_URL = 'https://registry.npmjs.org/-/package/@deepdynamic/cli/dist-tags';
11
12
  export const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
12
13
  export const REFRESH_TIMEOUT_MS = 10_000;
13
14
  export const LOCK_STALE_MS = 30 * 60 * 1000;
14
15
  export const UPDATE_NEXT = 'deepdynamic update --yes';
15
16
  export const REFRESH_ENTRY = fileURLToPath(new URL('../update-refresh.js', import.meta.url));
17
+ export const SKILL_REFRESH_ENTRY = fileURLToPath(new URL('../refresh-skills.js', import.meta.url));
16
18
  const VERSION = /^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?$/;
17
19
  export const isVersion = (value) => typeof value === 'string' && VERSION.test(value);
18
20
  export function latestOf(body) {
@@ -52,24 +54,45 @@ export async function saveUpdateCache(path, cache) {
52
54
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
53
55
  await writeFile(path, `${JSON.stringify(cache)}\n`);
54
56
  }
55
- export async function withUpdateLock(path, task, now = Date.now) {
56
- const age = await stat(path).then(({ mtimeMs }) => now() - mtimeMs, () => null);
57
- if (age !== null && age < LOCK_STALE_MS)
58
- return null;
59
- if (age !== null)
60
- await rm(path, { force: true });
57
+ const createLock = (path, token) => writeFile(path, token, { flag: 'wx' }).then(() => true, () => false);
58
+ const lockAge = (path, now) => stat(path).then(({ mtimeMs }) => now() - mtimeMs, () => null);
59
+ async function claimLock(path, token, now) {
61
60
  try {
62
61
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
63
- await writeFile(path, `${process.pid}\n`, { flag: 'wx' });
64
62
  }
65
63
  catch {
66
- return null;
64
+ return false;
65
+ }
66
+ if (await createLock(path, token))
67
+ return true;
68
+ const age = await lockAge(path, now);
69
+ if (age === null || age < LOCK_STALE_MS)
70
+ return false;
71
+ const takeover = `${path}.takeover`;
72
+ if (((await lockAge(takeover, now)) ?? 0) >= LOCK_STALE_MS)
73
+ await rm(takeover, { force: true });
74
+ if (!(await createLock(takeover, token)))
75
+ return false;
76
+ try {
77
+ if (((await lockAge(path, now)) ?? LOCK_STALE_MS) < LOCK_STALE_MS)
78
+ return false;
79
+ await rm(path, { force: true });
80
+ return await createLock(path, token);
67
81
  }
82
+ finally {
83
+ await rm(takeover, { force: true });
84
+ }
85
+ }
86
+ export async function withUpdateLock(path, task, now = Date.now) {
87
+ const token = `${process.pid} ${randomUUID()}\n`;
88
+ if (!(await claimLock(path, token, now)))
89
+ return null;
68
90
  try {
69
91
  return await task();
70
92
  }
71
93
  finally {
72
- await rm(path, { force: true });
94
+ if (await readFile(path, 'utf8').catch(() => null) === token)
95
+ await rm(path, { force: true });
73
96
  }
74
97
  }
75
98
  export async function refreshUpdateCache(path, current, install, fetcher = fetch, now = Date.now) {
@@ -86,12 +109,18 @@ export async function refreshUpdateCache(path, current, install, fetcher = fetch
86
109
  }
87
110
  }
88
111
  export const refreshArgs = () => [REFRESH_ENTRY, developmentRun() ? 'check' : 'install'];
89
- export function startRefresh() {
90
- const child = spawn(process.execPath, refreshArgs(), { detached: true, stdio: 'ignore', windowsHide: true });
112
+ function startDetached(args) {
113
+ const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore', windowsHide: true });
91
114
  child.on('error', () => { });
92
115
  child.unref();
93
116
  }
94
- export const defaultUpdateDeps = () => ({ path: updateCachePath(), env: process.env, now: Date.now, startRefresh });
117
+ export function startRefresh() {
118
+ startDetached(refreshArgs());
119
+ }
120
+ export function startSkillRefresh() {
121
+ startDetached([SKILL_REFRESH_ENTRY]);
122
+ }
123
+ export const defaultUpdateDeps = () => ({ path: updateCachePath(), env: process.env, now: Date.now, startRefresh, startSkillRefresh });
95
124
  export async function pendingUpdate(current, deps = defaultUpdateDeps()) {
96
125
  if (!updateCheckEnabled(deps.env))
97
126
  return null;
@@ -102,7 +131,12 @@ export async function pendingUpdate(current, deps = defaultUpdateDeps()) {
102
131
  if (stale || updated) {
103
132
  const kept = cache?.installed && !updated ? { installed: cache.installed } : {};
104
133
  await saveUpdateCache(deps.path, { checkedAt: stale ? now : cache.checkedAt, latest: cache?.latest ?? null, ...kept })
105
- .then(() => stale && deps.startRefresh(), () => { });
134
+ .then(() => {
135
+ if (stale)
136
+ deps.startRefresh();
137
+ if (updated)
138
+ deps.startSkillRefresh();
139
+ }, () => { });
106
140
  }
107
141
  if (updated)
108
142
  return { event: 'updated', previous: updated.previous };
@@ -1,14 +1,31 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { realpath } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
- import { join } from 'node:path';
4
+ import { join, win32 } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { PACKAGE_NAME } from "./update-check.js";
7
+ export const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
8
+ const TASKKILL = win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe');
7
9
  export const PACKAGE_DIR = fileURLToPath(new URL('../..', import.meta.url));
8
10
  export const packageManagerOf = (path) => (/[\\/]\.pnpm[\\/]/.test(path) ? 'pnpm' : 'npm');
9
11
  export const installArgs = (manager, version) => [manager === 'pnpm' ? 'add' : 'install', '--global', `${PACKAGE_NAME}@${version}`];
10
- export function runProgram(path, args, platform = process.platform) {
11
- const options = { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true };
12
+ function stopProgram(child, platform) {
13
+ if (platform !== 'win32' || child.pid === undefined) {
14
+ child.kill();
15
+ return;
16
+ }
17
+ const fallback = () => child.kill();
18
+ const killer = spawn(TASKKILL, ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore', windowsHide: true });
19
+ killer.on('error', fallback);
20
+ killer.on('close', fallback);
21
+ }
22
+ export function runProgram(path, args, platform = process.platform, timeoutMs = INSTALL_TIMEOUT_MS) {
23
+ const options = {
24
+ stdio: ['ignore', 'pipe', 'pipe'],
25
+ windowsHide: true,
26
+ cwd: homedir(),
27
+ ...(platform === 'win32' ? { env: { ...process.env, NoDefaultCurrentDirectoryInExePath: '1' } } : {})
28
+ };
12
29
  const child = platform === 'win32' && /\.(cmd|bat)$/i.test(path)
13
30
  ? spawn(`"${path}" ${args.join(' ')}`, { ...options, shell: true })
14
31
  : spawn(path, args, options);
@@ -22,8 +39,26 @@ export function runProgram(path, args, platform = process.platform) {
22
39
  output = `${output}${chunk.toString('utf8')}`.slice(-4000);
23
40
  });
24
41
  return new Promise((resolve) => {
25
- child.on('error', (error) => resolve({ status: null, stdout: '', output: error.message }));
26
- child.on('close', (status) => resolve({ status, stdout, output: output.trim().slice(-500) }));
42
+ let timedOut = false;
43
+ let settled = false;
44
+ const settle = (result) => {
45
+ if (settled)
46
+ return;
47
+ settled = true;
48
+ clearTimeout(timer);
49
+ resolve(result);
50
+ };
51
+ const timer = setTimeout(() => {
52
+ timedOut = true;
53
+ stopProgram(child, platform);
54
+ }, timeoutMs);
55
+ const expired = () => ({ status: null, stdout, output: `Timed out after ${timeoutMs / 60_000} minutes. ${output.trim()}`.trim().slice(-500) });
56
+ child.on('error', (error) => settle({ status: null, stdout: '', output: error.message }));
57
+ child.on('exit', () => {
58
+ if (timedOut)
59
+ settle(expired());
60
+ });
61
+ child.on('close', (status) => settle(timedOut ? expired() : { status, stdout, output: output.trim().slice(-500) }));
27
62
  });
28
63
  }
29
64
  export const findPackageManager = async (name) => (await import("../agents/install.js")).systemCommands({ home: homedir(), platform: process.platform, vars: process.env }).find(name);
@@ -2,8 +2,8 @@ import { agentResult } from "../output.js";
2
2
  import { prettyResult } from "../pretty.js";
3
3
  import { spec } from "../registry.js";
4
4
  export function usageError(command, message, pretty, depth) {
5
- const { usage, prettyUsage } = spec(command);
5
+ const { usage } = spec(command);
6
6
  return pretty
7
- ? prettyResult(2, depth, command, message, [['사용법', prettyUsage]])
7
+ ? prettyResult(2, depth, command, message, [['Usage', usage]])
8
8
  : agentResult(2, { command, error: { code: 'invalid_arguments', message }, usage });
9
9
  }
@@ -1,8 +1,15 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { systemCommands } from "./agents/install.js";
3
3
  import { runAgentSetup } from "./agents/setup.js";
4
+ import { startSpinner } from "./runtime/spinner.js";
4
5
  const env = { home: homedir(), platform: process.platform, vars: process.env };
5
- const result = await runAgentSetup(env, systemCommands(env), process.getuid?.() ?? null);
6
- process.stdout.write(result.stdout);
6
+ let step = '';
7
+ const stop = startSpinner(() => `Installing skills${step}`, process.stderr);
8
+ const result = await runAgentSetup(env, systemCommands(env), process.getuid?.() ?? null, (agent, item) => {
9
+ step = ` · ${agent} ${item}`;
10
+ });
11
+ stop();
12
+ if (!process.stdout.isTTY)
13
+ process.stdout.write(result.stdout);
7
14
  process.stderr.write(result.stderr);
8
15
  process.exitCode = result.code;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdynamic/cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Command-line tool for deploying and managing sites on DeepDynamic Cloud.",
5
5
  "keywords": [
6
6
  "deepdynamic",