@dsh-workbench/adapter-runtime 1.0.0-beta.0 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencli-plugin-workbench",
3
- "version": "1.0.0-beta.0",
3
+ "version": "1.0.0-beta.1",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "description": "DSH 工作台的公共通道:带浏览器登录态的 Node 侧 fetch,只服务 cookie / cookieValue 两种凭据来源",
@@ -0,0 +1,7 @@
1
+ import type { DshShell } from '@dsh-workbench/shared';
2
+ import type { CommandReader } from '@dsh-workbench/shared';
3
+ export interface CommandReaderOptions {
4
+ readonly shell: DshShell;
5
+ readonly tmpRoot?: string | undefined;
6
+ }
7
+ export declare function createCommandReader(options: CommandReaderOptions): CommandReader;
@@ -0,0 +1,71 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { quoteShellArg, runShell } from '@dsh-workbench/shared/host';
5
+ function quoteAll(argv) {
6
+ return argv.map((arg) => quoteShellArg(arg)).join(' ');
7
+ }
8
+ function writeFiles(request, tmpRoot) {
9
+ if (request.files === undefined || request.files.length === 0)
10
+ return undefined;
11
+ const dir = mkdtempSync(join(tmpRoot, 'dsh-wb-command-'));
12
+ const paths = request.files.map((file, index) => {
13
+ const suffix = file.suffix === undefined || file.suffix === '' ? '' : `.${file.suffix}`;
14
+ const path = join(dir, `file-${String(index)}${suffix}`);
15
+ writeFileSync(path, file.content, 'utf8');
16
+ return path;
17
+ });
18
+ return { dir, paths };
19
+ }
20
+ export function createCommandReader(options) {
21
+ const { shell } = options;
22
+ const tmpRoot = options.tmpRoot ?? tmpdir();
23
+ return {
24
+ async run(request) {
25
+ let temp;
26
+ try {
27
+ temp = writeFiles(request, tmpRoot);
28
+ const argv = [...request.argv];
29
+ if (temp !== undefined && request.appendFileArgs !== undefined) {
30
+ for (const path of temp.paths)
31
+ argv.push(request.appendFileArgs, path);
32
+ }
33
+ const result = await runShell(shell, quoteAll(argv), {
34
+ ...(request.timeoutMs === undefined ? {} : { timeoutMs: request.timeoutMs }),
35
+ ...(request.cwd === undefined ? {} : { workdir: request.cwd }),
36
+ });
37
+ const filePaths = temp?.paths ?? [];
38
+ if (result.timedOut) {
39
+ return {
40
+ stdout: result.stdout,
41
+ stderr: result.stderr,
42
+ exitCode: result.exitCode ?? -1,
43
+ timedOut: true,
44
+ filePaths,
45
+ };
46
+ }
47
+ return {
48
+ stdout: result.stdout,
49
+ stderr: result.stderr,
50
+ exitCode: result.exitCode ?? -1,
51
+ timedOut: false,
52
+ filePaths,
53
+ };
54
+ }
55
+ catch (error) {
56
+ return {
57
+ stdout: '',
58
+ stderr: String(error),
59
+ exitCode: -1,
60
+ timedOut: false,
61
+ filePaths: temp?.paths ?? [],
62
+ error: String(error),
63
+ };
64
+ }
65
+ finally {
66
+ if (temp !== undefined)
67
+ rmSync(temp.dir, { recursive: true, force: true });
68
+ }
69
+ },
70
+ };
71
+ }
@@ -1,5 +1,7 @@
1
1
  import { callsProblemOf, recipeProblemOf, runShell, scriptOf, scriptOfMany } from '@dsh-workbench/shared/host';
2
2
  import { browserRead } from '../browser/index.js';
3
+ import { createOpencli } from '../cli/index.js';
4
+ import { WorkbenchDataError } from '@dsh-workbench/shared/host';
3
5
  import { channelCallOf, channelCommandLine, ensureChannel, } from './channel.js';
4
6
  const DEFAULT_TIMEOUT_MS = 20_000;
5
7
  function failure(code, message, extra = {}) {
@@ -287,17 +289,52 @@ export function createDataReader(options = {}) {
287
289
  }
288
290
  return out;
289
291
  }
292
+ const openclis = new Map();
293
+ function opencliOf(plugin, timeoutMs) {
294
+ const key = `${plugin}:${String(timeoutMs)}`;
295
+ const cached = openclis.get(key);
296
+ if (cached !== undefined)
297
+ return cached;
298
+ const created = createOpencli({
299
+ shell: options.shell,
300
+ plugin,
301
+ command,
302
+ timeoutMs,
303
+ });
304
+ openclis.set(key, created);
305
+ return created;
306
+ }
290
307
  async function readCommand(request) {
291
308
  if (options.shell === undefined)
292
309
  return failure('invalid-request', '没有 shell,跑不了命令');
310
+ if (request.adapter !== 'opencli') {
311
+ return failure('invalid-request', `不认识的命令适配器:${request.adapter}`);
312
+ }
313
+ const plugin = request.argv[0];
314
+ if (plugin === undefined)
315
+ return failure('invalid-request', '命令缺少 argv[0](插件名)');
293
316
  const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS;
294
- const result = await runShell(options.shell, request.command, { timeoutMs });
295
- if (result.timedOut)
296
- return failure('timeout', `命令超时(${timeoutMs}ms)`);
297
- if (result.exitCode !== 0) {
298
- return failure('command', `命令退出码 ${String(result.exitCode)}`, { detail: result.stderr.slice(0, 2000) });
317
+ try {
318
+ const { value } = await opencliOf(plugin, timeoutMs).json(request.argv.slice(1));
319
+ return { ok: true, data: value };
320
+ }
321
+ catch (error) {
322
+ if (!(error instanceof WorkbenchDataError))
323
+ return failure('command', String(error));
324
+ const code = error.code === 'auth-required' || error.code === 'permission-denied'
325
+ ? 'auth'
326
+ : error.code === 'cli-timeout'
327
+ ? 'timeout'
328
+ : error.code === 'cli-bad-output'
329
+ ? 'parse'
330
+ : 'command';
331
+ return failure(code, error.message, {
332
+ ...(error.detail === undefined ? {} : { detail: error.detail }),
333
+ ...(error.hint === undefined ? {} : { hint: error.hint }),
334
+ ...(error.helpUrl === undefined ? {} : { helpUrl: error.helpUrl }),
335
+ pageCode: error.code,
336
+ });
299
337
  }
300
- return parse(result.stdout);
301
338
  }
302
339
  return {
303
340
  async read(request) {
@@ -0,0 +1,10 @@
1
+ import type { DshShell } from '@dsh-workbench/shared';
2
+ import type { ExtensionReader } from '@dsh-workbench/shared/host';
3
+ export interface ExtensionReaderOptions {
4
+ readonly shell?: DshShell | undefined;
5
+ readonly command?: string | undefined;
6
+ readonly logger?: {
7
+ warn?(message: string): void;
8
+ } | undefined;
9
+ }
10
+ export declare function createExtensionReader(options: ExtensionReaderOptions): ExtensionReader;
@@ -0,0 +1,36 @@
1
+ import { WorkbenchDataError } from '@dsh-workbench/shared/host';
2
+ import { createOpencli } from '../cli/index.js';
3
+ export function createExtensionReader(options) {
4
+ const readers = new Map();
5
+ function readerOf(need) {
6
+ if (need.runtime !== 'opencli') {
7
+ throw new WorkbenchDataError('unsupported-runtime', `没有能跑 ${need.runtime} 扩展的适配器:这个模块要的是 ${need.name}`, { hint: '换一个带这种运行时的适配器集合,或把这条需要改成 opencli 扩展。' });
8
+ }
9
+ if (options.shell === undefined) {
10
+ throw new WorkbenchDataError('cli-exec-failed', `读不了:这台机器上没有 shell 服务(${need.name})`, {
11
+ hint: '工作台的 shell 服务没起来,重启一下工作台再试',
12
+ });
13
+ }
14
+ const cached = readers.get(need.name);
15
+ if (cached !== undefined)
16
+ return cached;
17
+ const created = createOpencli({
18
+ shell: options.shell,
19
+ plugin: need.name,
20
+ ...(options.command === undefined ? {} : { command: options.command }),
21
+ ...(options.logger === undefined ? {} : { logger: options.logger }),
22
+ });
23
+ readers.set(need.name, created);
24
+ return created;
25
+ }
26
+ return {
27
+ async json(need, args, callOptions = {}) {
28
+ const result = await readerOf(need).json(args, {
29
+ ...(callOptions.key === undefined ? {} : { key: callOptions.key }),
30
+ ...(callOptions.workdir === undefined ? {} : { workdir: callOptions.workdir }),
31
+ ...(callOptions.session === undefined ? {} : { session: callOptions.session }),
32
+ });
33
+ return result;
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,9 @@
1
+ import type { DshShell } from '@dsh-workbench/shared';
2
+ import type { GitReader } from '@dsh-workbench/shared';
3
+ export interface GitReaderOptions {
4
+ readonly shell: DshShell;
5
+ readonly logger?: {
6
+ warn?(message: string): void;
7
+ } | undefined;
8
+ }
9
+ export declare function createGitReader(options: GitReaderOptions): GitReader;
@@ -0,0 +1,60 @@
1
+ import { quoteShellArg, runShell, tailLines } from '@dsh-workbench/shared/host';
2
+ function keyOf(path) {
3
+ return String(path ?? '').trim();
4
+ }
5
+ export function createGitReader(options) {
6
+ const { shell, logger } = options;
7
+ return {
8
+ async origin(path) {
9
+ const key = keyOf(path);
10
+ if (!key)
11
+ return { kind: 'unknown', reason: 'no-path' };
12
+ let result;
13
+ try {
14
+ result = await runShell(shell, `git -C ${quoteShellArg(key)} remote get-url origin`);
15
+ }
16
+ catch (error) {
17
+ logger?.warn?.(`[dsh-workbench] git remote 执行失败:${String(error)}`);
18
+ return { kind: 'unknown', reason: 'exec-failed', detail: String(error) };
19
+ }
20
+ if (result.exitCode !== 0)
21
+ return { kind: 'no-origin', detail: tailLines(result.stderr, 3) };
22
+ return { kind: 'ok', remote: result.stdout.trim() };
23
+ },
24
+ async branch(path) {
25
+ const key = keyOf(path);
26
+ if (!key)
27
+ return { kind: 'unknown', reason: 'no-path' };
28
+ let result;
29
+ try {
30
+ result = await runShell(shell, `git -C ${quoteShellArg(key)} rev-parse --abbrev-ref HEAD`);
31
+ }
32
+ catch (error) {
33
+ logger?.warn?.(`[dsh-workbench] git rev-parse --abbrev-ref 执行失败:${String(error)}`);
34
+ return { kind: 'unknown', reason: 'exec-failed', detail: String(error) };
35
+ }
36
+ const name = result.stdout.trim();
37
+ if (result.exitCode !== 0)
38
+ return { kind: 'no-branch', detail: tailLines(result.stderr, 3) };
39
+ if (name === '' || name === 'HEAD')
40
+ return { kind: 'no-branch', detail: name };
41
+ return { kind: 'ok', branch: name };
42
+ },
43
+ async head(path) {
44
+ const key = keyOf(path);
45
+ if (!key)
46
+ return { kind: 'unknown', reason: 'no-path' };
47
+ let result;
48
+ try {
49
+ result = await runShell(shell, `git -C ${quoteShellArg(key)} rev-parse HEAD`);
50
+ }
51
+ catch (error) {
52
+ logger?.warn?.(`[dsh-workbench] git rev-parse 执行失败:${String(error)}`);
53
+ return { kind: 'unknown', reason: 'exec-failed', detail: String(error) };
54
+ }
55
+ if (result.exitCode !== 0)
56
+ return { kind: 'no-head', detail: tailLines(result.stderr, 3) };
57
+ return { kind: 'ok', commit: result.stdout.trim() };
58
+ },
59
+ };
60
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export * from './cli/index.js';
2
2
  export * from './browser/index.js';
3
3
  export * from './data/index.js';
4
+ export * from './libs/index.js';
5
+ export * from './git/index.js';
6
+ export * from './command/index.js';
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
1
  export * from './cli/index.js';
2
2
  export * from './browser/index.js';
3
3
  export * from './data/index.js';
4
+ export * from './libs/index.js';
5
+ export * from './git/index.js';
6
+ export * from './command/index.js';
@@ -0,0 +1,6 @@
1
+ import type { LibReader } from '@dsh-workbench/shared/host';
2
+ export interface LibReaderOptions {
3
+ readonly roots?: readonly string[] | undefined;
4
+ readonly env?: Readonly<Record<string, string | undefined>> | undefined;
5
+ }
6
+ export declare function createLibReader(options?: LibReaderOptions): LibReader;
@@ -0,0 +1,46 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join, normalize } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { libInstallCommand, WorkbenchDataError } from '@dsh-workbench/shared/host';
6
+ function rootsOf(env) {
7
+ const home = env['DSH_HOME'] ?? join(homedir(), '.dsh');
8
+ return [
9
+ join(home, 'workbench', 'opencli', 'libs', 'node_modules'),
10
+ join(home, 'workbench', 'opencli', 'toolchain', 'node_modules'),
11
+ ];
12
+ }
13
+ function entryProblem(entry) {
14
+ if (entry.trim() === '')
15
+ return '入口是空串';
16
+ if (entry.startsWith('/') || /^[A-Za-z]:[\\/]/u.test(entry))
17
+ return '入口不能是绝对路径';
18
+ if (normalize(entry).split(/[\\/]/u).includes('..'))
19
+ return '入口不能跳出 lib 目录';
20
+ return null;
21
+ }
22
+ export function createLibReader(options = {}) {
23
+ const env = options.env ?? process.env;
24
+ const roots = options.roots ?? rootsOf(env);
25
+ return {
26
+ async load(need, entry) {
27
+ const problem = entryProblem(entry);
28
+ if (problem !== null) {
29
+ throw new WorkbenchDataError('lib-path-invalid', `${need.name}: ${problem}`, {
30
+ hint: '入口写相对路径,比如 src/utils.js',
31
+ });
32
+ }
33
+ for (const root of roots) {
34
+ const file = join(root, need.name, entry);
35
+ if (!existsSync(file))
36
+ continue;
37
+ return (await import(pathToFileURL(file).href));
38
+ }
39
+ const source = need.sources?.find((one) => one.kind === 'npm');
40
+ const hint = source === undefined
41
+ ? `装它:${need.name}${need.version === undefined ? '' : `@${need.version}`}`
42
+ : `装它:${libInstallCommand({ need, source, ...(need.version === undefined ? {} : { version: need.version }) })}`;
43
+ throw new WorkbenchDataError('lib-missing', `没有找到 ${need.name} 的 ${entry}`, { hint });
44
+ },
45
+ };
46
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-workbench/adapter-runtime",
3
- "version": "1.0.0-beta.0",
3
+ "version": "1.0.0-beta.1",
4
4
  "description": "Opencli, browser and data runtime adapters.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -14,7 +14,7 @@
14
14
  "channel"
15
15
  ],
16
16
  "dependencies": {
17
- "@dsh-workbench/shared": "1.0.0-beta.0"
17
+ "@dsh-workbench/shared": "1.0.0-beta.1"
18
18
  },
19
19
  "devDependencies": {
20
20
  "@types/node": "^24.19.0",