@dsh-workbench/adapter-runtime 1.3.1 → 1.4.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workbench",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "DSH 工作台的公共通道:用浏览器登录态在 Node 侧发请求",
5
- "opencli": ">=1.8.0 <2.0.0"
5
+ "opencli": ">=2.0.0 <3.0.0"
6
6
  }
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "opencli-plugin-workbench",
3
- "version": "1.3.1",
3
+ "version": "1.4.0-beta.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "description": "DSH 工作台的公共通道:带浏览器登录态的 Node 侧 fetch,只服务 cookie / cookieValue 两种凭据来源",
7
7
  "peerDependencies": {
8
- "@jackwener/opencli": ">=1.8.0 <2.0.0"
8
+ "@jackwener/opencli": ">=2.0.0 <3.0.0"
9
9
  }
10
10
  }
@@ -2,4 +2,5 @@ export * from './opencli-window.js';
2
2
  export * from './opencli-types.js';
3
3
  export * from './opencli-runtime.js';
4
4
  export * from './opencli.js';
5
+ export * from './opencli-report.js';
5
6
  export * from './command.js';
package/dist/cli/index.js CHANGED
@@ -2,4 +2,5 @@ export * from './opencli-window.js';
2
2
  export * from './opencli-types.js';
3
3
  export * from './opencli-runtime.js';
4
4
  export * from './opencli.js';
5
+ export * from './opencli-report.js';
5
6
  export * from './command.js';
@@ -0,0 +1,2 @@
1
+ export declare function jsonAt(file: string): Readonly<Record<string, unknown>> | undefined;
2
+ export declare function textOf(value: unknown): string | undefined;
@@ -0,0 +1,17 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ export function jsonAt(file) {
3
+ if (!existsSync(file))
4
+ return undefined;
5
+ try {
6
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
7
+ return typeof parsed === 'object' && parsed !== null
8
+ ? parsed
9
+ : undefined;
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ }
15
+ export function textOf(value) {
16
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
17
+ }
@@ -0,0 +1,18 @@
1
+ import { type PluginPeerProblem } from './plugin-peers.js';
2
+ export interface OpencliVersionReport {
3
+ readonly pin: string;
4
+ readonly cli?: string;
5
+ readonly channel?: string;
6
+ readonly peer: string;
7
+ readonly peerProblems: readonly PluginPeerProblem[];
8
+ readonly compatible: boolean;
9
+ }
10
+ export declare function opencliChannelDir(): string;
11
+ export declare function opencliPeerRange(): string;
12
+ export declare function opencliVersionReport(): OpencliVersionReport;
13
+ export declare function opencliHandshakeOk(report: OpencliVersionReport): boolean;
14
+ export declare function opencliHandshakeNote(report: OpencliVersionReport): {
15
+ readonly zh: string;
16
+ readonly en: string;
17
+ } | undefined;
18
+ export declare function opencliHandshakeText(report: OpencliVersionReport): string;
@@ -0,0 +1,82 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { join } from 'node:path';
3
+ import { OPENCLI_PIN, OPENCLI_PIN_ENV, checkVersionRange, runtimePinOf } from '@dsh-workbench/shared/host';
4
+ import { toolchainOpencliDir, vendorPluginsDir } from '../foundation/paths.js';
5
+ import { pluginPeerProblems } from './plugin-peers.js';
6
+ import { jsonAt as jsonOf, textOf } from './json-file.js';
7
+ const CHANNEL_SOURCE = new URL('../../channel/opencli-plugin.json', import.meta.url);
8
+ export function opencliChannelDir() {
9
+ return join(vendorPluginsDir(), 'opencli-plugin-workbench');
10
+ }
11
+ export function opencliPeerRange() {
12
+ return textOf(jsonOf(fileURLToPath(CHANNEL_SOURCE))?.['opencli']) ?? '';
13
+ }
14
+ export function opencliVersionReport() {
15
+ const pin = runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV);
16
+ const cli = textOf(jsonOf(join(toolchainOpencliDir(), 'package.json'))?.['version']);
17
+ const channel = textOf(jsonOf(join(opencliChannelDir(), 'opencli-plugin.json'))?.['version']);
18
+ const peer = opencliPeerRange();
19
+ const peerProblems = pluginPeerProblems(pin);
20
+ return {
21
+ pin,
22
+ ...(cli === undefined ? {} : { cli }),
23
+ ...(channel === undefined ? {} : { channel }),
24
+ peer,
25
+ peerProblems,
26
+ compatible: checkVersionRange(peer, pin) !== 'unsatisfied' && peerProblems.length === 0,
27
+ };
28
+ }
29
+ export function opencliHandshakeOk(report) {
30
+ return report.compatible && report.cli === report.pin;
31
+ }
32
+ export function opencliHandshakeNote(report) {
33
+ if (report.peerProblems.length > 0) {
34
+ return {
35
+ zh: `${pluginRangesOf(report)}只适配别的运行时版本,本版是 ${report.pin} —— 插件更新后再试`,
36
+ en: `${pluginRangesOf(report)} only accept another runtime version; this build is ${report.pin} — try again after those plugins update`,
37
+ };
38
+ }
39
+ if (!report.compatible) {
40
+ return {
41
+ zh: `插件只认 ${report.peer},这个版本用的是 ${report.pin} —— 换兼容的插件,或重装工作台`,
42
+ en: `the plugin only accepts ${report.peer} but this build uses ${report.pin} — switch to a compatible plugin, or reinstall the workbench`,
43
+ };
44
+ }
45
+ if (report.cli === undefined) {
46
+ return {
47
+ zh: `运行环境里还没有 ${report.pin} —— 重启一次 dsh;还不行就重装工作台`,
48
+ en: `the runtime does not have ${report.pin} yet — restart dsh; if it persists, reinstall the workbench`,
49
+ };
50
+ }
51
+ if (report.cli !== report.pin) {
52
+ return {
53
+ zh: `装的是 ${report.cli},这个版本要 ${report.pin} —— 重启一次 dsh;还不行就重装工作台`,
54
+ en: `installed ${report.cli} but this build needs ${report.pin} — restart dsh; if it persists, reinstall the workbench`,
55
+ };
56
+ }
57
+ return undefined;
58
+ }
59
+ function pluginRangesOf(report) {
60
+ const seen = new Map();
61
+ for (const problem of report.peerProblems) {
62
+ const names = seen.get(problem.range) ?? [];
63
+ names.push(problem.name);
64
+ seen.set(problem.range, names);
65
+ }
66
+ return [...seen.entries()]
67
+ .map(([range, names]) => `${names.join('、')}(要 ${range})`)
68
+ .join(';');
69
+ }
70
+ export function opencliHandshakeText(report) {
71
+ if (report.peerProblems.length > 0) {
72
+ return `${pluginRangesOf(report)}不认本版的 ${report.pin}`;
73
+ }
74
+ if (!report.compatible) {
75
+ return `通道插件只接受 ${report.peer},本版固定 ${report.pin}`;
76
+ }
77
+ if (report.cli === undefined)
78
+ return `隔离运行时里还没有 ${report.pin}`;
79
+ if (report.cli !== report.pin)
80
+ return `已装 ${report.cli},本版固定 ${report.pin}`;
81
+ return `${report.pin} · 通道插件 ${report.channel ?? '未装'}`;
82
+ }
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { DEFAULT_NPM_REGISTRY, OPENCLI_CATALOG_ENV, OPENCLI_PIN, OPENCLI_REGISTRY_ENV, } from '@dsh-workbench/shared/host';
3
+ import { DEFAULT_NPM_REGISTRY, OPENCLI_CATALOG_ENV, OPENCLI_PIN, OPENCLI_PIN_ENV, OPENCLI_REGISTRY_ENV, runtimePinOf, } from '@dsh-workbench/shared/host';
4
4
  import { quoteShellArg } from '@dsh-workbench/shared/host';
5
5
  import { isolatedRoot, libsPrefix, storeDirFor, toolchainOpencliDir } from '../foundation/paths.js';
6
6
  import { OPENCLI_NPM_PACKAGE } from '../foundation/paths.js';
@@ -12,7 +12,7 @@ export function toolchainManifestOf() {
12
12
  return `${JSON.stringify({
13
13
  name: 'dsh-workbench-toolchain',
14
14
  private: true,
15
- dependencies: { [OPENCLI_NPM_PACKAGE]: OPENCLI_PIN },
15
+ dependencies: { [OPENCLI_NPM_PACKAGE]: runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV) },
16
16
  }, null, 2)}\n`;
17
17
  }
18
18
  export function toolchainNpmrcOf() {
@@ -44,10 +44,10 @@ export function opencliReadinessAt(projectDir) {
44
44
  return { ready: false, detail: '隔离副本缺 dist/src/main.js' };
45
45
  }
46
46
  const version = packageVersionOf(join(dir, 'package.json'));
47
- if (version !== OPENCLI_PIN) {
48
- return { ready: false, detail: `隔离副本是 ${version ?? '读不到的版本'},要 ${OPENCLI_PIN}` };
47
+ if (version !== runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV)) {
48
+ return { ready: false, detail: `隔离副本是 ${version ?? '读不到的版本'},要 ${runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV)}` };
49
49
  }
50
- return { ready: true, detail: OPENCLI_PIN };
50
+ return { ready: true, detail: runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV) };
51
51
  }
52
52
  export function opencliReadiness() {
53
53
  return opencliReadinessAt(toolchainDir());
@@ -91,11 +91,11 @@ export function pnpmIsolationFlags() {
91
91
  }
92
92
  export function isolatedInstallCommand(dir = toolchainDir(), store = storeDirFor(dir)) {
93
93
  const pnpm = process.env.DSH_WB_PNPM?.trim() || 'pnpm';
94
- return `${pnpm} add --dir ${quoteShellArg(dir)} ${OPENCLI_NPM_PACKAGE}@${OPENCLI_PIN} --store-dir ${quoteShellArg(store)} ${pnpmIsolationFlags()} --allow-build=${OPENCLI_NPM_PACKAGE} --save-exact`;
94
+ return `${pnpm} add --dir ${quoteShellArg(dir)} ${OPENCLI_NPM_PACKAGE}@${runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV)} --store-dir ${quoteShellArg(store)} ${pnpmIsolationFlags()} --allow-build=${OPENCLI_NPM_PACKAGE} --save-exact`;
95
95
  }
96
96
  export function isolatedPnpmInstallCommand(pnpmCjs, dir = toolchainDir(), store = storeDirFor(dir)) {
97
97
  return (`node ${quoteShellArg(pnpmCjs)} add --dir ${quoteShellArg(dir)} ` +
98
- `${OPENCLI_NPM_PACKAGE}@${OPENCLI_PIN} --store-dir ${quoteShellArg(store)} ` +
98
+ `${OPENCLI_NPM_PACKAGE}@${runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV)} --store-dir ${quoteShellArg(store)} ` +
99
99
  `${pnpmIsolationFlags()} --allow-build=${OPENCLI_NPM_PACKAGE} --save-exact`);
100
100
  }
101
101
  export { isolatedHome, isolatedRoot, libsBinDir, npmCacheDir, toolchainOpencliDir, vendorPeerLink, vendorPluginsDir, vendorPrefix } from '../foundation/paths.js';
@@ -1,2 +1,3 @@
1
1
  export declare const OPENCLI_WINDOW_ENV: Readonly<Record<string, string>>;
2
+ export declare const OPENCLI_SITE_SESSION_ENV: Readonly<Record<string, string>>;
2
3
  export declare function backgroundLine(command: string, argv: readonly string[], platform?: NodeJS.Platform): string;
@@ -1,5 +1,8 @@
1
- import { quoteShellArgFor } from '@dsh-workbench/shared/host';
1
+ import { quoteShellArgFor, sessionArgv } from '@dsh-workbench/shared/host';
2
2
  export const OPENCLI_WINDOW_ENV = { OPENCLI_WINDOW: 'background' };
3
+ export const OPENCLI_SITE_SESSION_ENV = {
4
+ OPENCLI_SITE_SESSION: 'persistent',
5
+ };
3
6
  export function backgroundLine(command, argv, platform = process.platform) {
4
- return [quoteShellArgFor(command, platform), ...argv.map((arg) => quoteShellArgFor(arg, platform))].join(' ');
7
+ return [quoteShellArgFor(command, platform), ...sessionArgv(argv).map((arg) => quoteShellArgFor(arg, platform))].join(' ');
5
8
  }
@@ -67,7 +67,7 @@ export function createOpencli(options) {
67
67
  });
68
68
  }
69
69
  if (result.timedOut) {
70
- throw new WorkbenchDataError('cli-timeout', `opencli 超过 ${Math.round(timeoutMs / 1000)} 秒没有返回`, { hint: '无头浏览器可能没起来,重试一次通常就好。' });
70
+ throw new WorkbenchDataError('cli-timeout', `opencli 超过 ${Math.round(timeoutMs / 1000)} 秒没有返回`, { hint: 'opencli 的本地 daemon 没回应(或浏览器扩展没连上),重试一次通常就好。' });
71
71
  }
72
72
  if (result.exitCode !== 0) {
73
73
  const detail = tailLines(result.stderr || result.stdout, 6);
@@ -0,0 +1,5 @@
1
+ export interface PluginPeerProblem {
2
+ readonly name: string;
3
+ readonly range: string;
4
+ }
5
+ export declare function pluginPeerProblems(pin: string): readonly PluginPeerProblem[];
@@ -0,0 +1,45 @@
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { checkVersionRange } from '@dsh-workbench/shared/host';
4
+ import { OPENCLI_NPM_PACKAGE, vendorPluginsDir } from '../foundation/paths.js';
5
+ import { jsonAt as jsonOf } from './json-file.js';
6
+ function packageDirs(root) {
7
+ if (!existsSync(root))
8
+ return [];
9
+ const found = [];
10
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
11
+ if (!entry.isDirectory())
12
+ continue;
13
+ if (!entry.name.startsWith('@')) {
14
+ found.push(join(root, entry.name));
15
+ continue;
16
+ }
17
+ const scoped = join(root, entry.name);
18
+ for (const inner of readdirSync(scoped, { withFileTypes: true })) {
19
+ if (inner.isDirectory())
20
+ found.push(join(scoped, inner.name));
21
+ }
22
+ }
23
+ return found;
24
+ }
25
+ export function pluginPeerProblems(pin) {
26
+ const found = [];
27
+ for (const dir of packageDirs(vendorPluginsDir())) {
28
+ const manifest = jsonOf(join(dir, 'package.json'));
29
+ const name = manifest?.['name'];
30
+ if (typeof name !== 'string' || name.trim() === '')
31
+ continue;
32
+ const peers = manifest?.['peerDependencies'];
33
+ const declared = typeof peers === 'object' && peers !== null
34
+ ? peers[OPENCLI_NPM_PACKAGE]
35
+ : undefined;
36
+ const range = typeof declared === 'string' ? declared.trim() : '';
37
+ if (range === '')
38
+ continue;
39
+ const verdict = checkVersionRange(range, pin);
40
+ if (verdict === 'satisfied')
41
+ continue;
42
+ found.push({ name: name.trim(), range });
43
+ }
44
+ return found.sort((a, b) => a.name.localeCompare(b.name));
45
+ }
@@ -1,6 +1,8 @@
1
1
  import type { PluginPlanStep } from '@dsh-workbench/shared/host';
2
2
  export declare const CHANNEL_PLUGIN_NAME = "opencli-plugin-workbench";
3
3
  export declare const CHANNEL_PLUGIN_SITE = "workbench";
4
+ export declare function channelPluginDir(): string;
5
+ export declare function legacyChannelPluginDir(): string;
4
6
  export interface ChannelPluginPlan {
5
7
  readonly dest: string;
6
8
  readonly version: string;
@@ -1,9 +1,15 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { planLineOf, quoteShellArg } from '@dsh-workbench/shared/host';
4
- import { isolatedHome, toolchainOpencliDir, vendorPeerLink, vendorPluginsDir } from '../foundation/paths.js';
4
+ import { isolatedHome, toolchainOpencliDir, vendorPeerLink, vendorPrefix, vendorPluginsDir } from '../foundation/paths.js';
5
5
  export const CHANNEL_PLUGIN_NAME = 'opencli-plugin-workbench';
6
6
  export const CHANNEL_PLUGIN_SITE = 'workbench';
7
+ export function channelPluginDir() {
8
+ return join(vendorPrefix(), 'plugins', CHANNEL_PLUGIN_NAME);
9
+ }
10
+ export function legacyChannelPluginDir() {
11
+ return join(vendorPluginsDir(), CHANNEL_PLUGIN_NAME);
12
+ }
7
13
  function textOf(value) {
8
14
  return typeof value === 'string' ? value.trim() : '';
9
15
  }
@@ -24,10 +30,11 @@ export function channelPluginPlan(options) {
24
30
  if (version === undefined)
25
31
  return undefined;
26
32
  const command = options.command ?? 'opencli';
27
- const dest = join(vendorPluginsDir(), CHANNEL_PLUGIN_NAME);
33
+ const dest = channelPluginDir();
28
34
  const peer = vendorPeerLink();
29
35
  const steps = [
30
36
  { kind: 'copy', from: options.channelDir, to: dest },
37
+ { kind: 'remove', path: legacyChannelPluginDir() },
31
38
  { kind: 'remove', path: peer.dir },
32
39
  { kind: 'mkdir', path: peer.parent },
33
40
  { kind: 'link', target: toolchainOpencliDir(), path: peer.dir },
@@ -41,7 +48,7 @@ export function channelPluginPlan(options) {
41
48
  return { dest, version, steps, line: planLineOf(steps) };
42
49
  }
43
50
  export function channelInstalledVersion() {
44
- return channelVersionOf(join(vendorPluginsDir(), CHANNEL_PLUGIN_NAME));
51
+ return channelVersionOf(channelPluginDir());
45
52
  }
46
53
  export function channelSiteInstalled() {
47
54
  return existsSync(join(isolatedHome(), '.opencli', 'plugins', CHANNEL_PLUGIN_SITE));
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from 'node:url';
2
- import { DEFAULT_RECIPE_MAX_BYTES, PlanStepError, productWrite, quoteShellArg, runPlan, } from '@dsh-workbench/shared/host';
2
+ import { CHANNEL_API_VERSION, DEFAULT_RECIPE_MAX_BYTES, PlanStepError, productWrite, quoteShellArg, runPlan, } from '@dsh-workbench/shared/host';
3
3
  import { channelInstalledVersion, channelPluginPlan, channelSiteInstalled, channelVersionOf, } from './channel-plugin.js';
4
4
  export const CHANNEL_DIR = fileURLToPath(new URL('../../channel/', import.meta.url));
5
5
  function authOf(recipe) {
@@ -73,7 +73,7 @@ export function channelCallOf(recipe, overrides, command) {
73
73
  'workbench',
74
74
  write ? 'send' : 'fetch',
75
75
  '--api',
76
- '1',
76
+ String(CHANNEL_API_VERSION),
77
77
  '--url',
78
78
  channelUrlOf(recipe, overrides),
79
79
  '--jar',
@@ -1,11 +1,12 @@
1
- import { callsProblemOf, noWrite, now, planProblemOf, planResultsOf, recipeProblemOf, scriptOf, scriptOfMany, scriptOfPlan, allSame, } from '@dsh-workbench/shared/host';
1
+ import { BROWSER_READ_SESSIONS, BROWSER_SESSION_IDLE_MS, callsProblemOf, noWrite, now, planProblemOf, planResultsOf, recipeProblemOf, scriptOf, scriptOfMany, scriptOfPlan, allSame, } from '@dsh-workbench/shared/host';
2
2
  import { browserRead } from '../browser/index.js';
3
3
  import { attachOf } from './attachment.js';
4
4
  import { readHttp } from './http.js';
5
5
  import { createCommandRead } from './command-read.js';
6
6
  import { createSessionQueue } from './queue.js';
7
+ import { createSessionKeeper } from './sessions.js';
7
8
  import { submitPlanOf } from './submit-plan.js';
8
- import { sessionOf } from './types.js';
9
+ import { readSessionOf, sessionOf, writeSessionOf } from './types.js';
9
10
  import { allFailure, asRecord, browserFailure, failure, pageFailure, pickOf, } from './result.js';
10
11
  import { channelCallOf, channelCommandLine, ensureChannel, } from './channel.js';
11
12
  export * from './channel-plugin.js';
@@ -22,6 +23,15 @@ export function createDataReader(options = {}) {
22
23
  const command = options.command ?? 'opencli';
23
24
  const queue = createSessionQueue();
24
25
  const queueWaitMs = options.queueWaitMs ?? 30_000;
26
+ const sessions = createSessionKeeper({
27
+ seam: options.seam,
28
+ command,
29
+ max: options.readSessions ?? BROWSER_READ_SESSIONS,
30
+ ...(options.sessionRegistryDir === undefined
31
+ ? {}
32
+ : { registryDir: options.sessionRegistryDir }),
33
+ idleMs: options.sessionIdleMs ?? BROWSER_SESSION_IDLE_MS,
34
+ });
25
35
  const readCommand = createCommandRead({ seam: options.seam, command });
26
36
  function browserCall(input) {
27
37
  return {
@@ -60,11 +70,16 @@ export function createDataReader(options = {}) {
60
70
  const argv = scriptArgProblemOf(input.script);
61
71
  if (argv !== undefined)
62
72
  return { kind: 'failed', result: failure('invalid-request', argv) };
63
- const session = sessionOf(input.session);
64
- return serialGuard(session, input.signal, () => browserRead(browserCall({ ...input, session })));
73
+ const write = input.purpose === 'write';
74
+ const session = input.finalSession ??
75
+ (write ? writeSessionOf(input.session, input.url) : readSessionOf(input.session, input.url));
76
+ return serialGuard(session, input.signal, () => browserRead(browserCall({ ...input, session })), write);
65
77
  }
66
- async function serialGuard(session, signal, work) {
78
+ const inFlight = new Map();
79
+ async function serialGuard(session, signal, work, write = false) {
80
+ inFlight.set(session, (inFlight.get(session) ?? 0) + 1);
67
81
  const started = now();
82
+ sessions.begin(session);
68
83
  const outcome = await queue.acquire(session, signal, queueWaitMs);
69
84
  try {
70
85
  options.onQueue?.({ session, waitedMs: now() - started, outcome });
@@ -85,6 +100,7 @@ export function createDataReader(options = {}) {
85
100
  }
86
101
  finally {
87
102
  queue.release(session);
103
+ await sessions.end(session, write);
88
104
  }
89
105
  }
90
106
  async function readBrowser(request, callOptions) {
@@ -185,7 +201,10 @@ export function createDataReader(options = {}) {
185
201
  catch (error) {
186
202
  return failure('invalid-request', error instanceof Error ? error.message : String(error));
187
203
  }
188
- const got = await guardedBrowser(recipeBrowserInput(recipe, script, seam, callOptions));
204
+ const got = await guardedBrowser({
205
+ ...recipeBrowserInput(recipe, script, seam, callOptions),
206
+ ...(mode === 'submit' ? { purpose: 'write' } : {}),
207
+ });
189
208
  const unwrapped = unwrapBrowser(got, recipe.loginUrl);
190
209
  if (!unwrapped.ok)
191
210
  return unwrapped;
@@ -336,17 +355,19 @@ export function createDataReader(options = {}) {
336
355
  if (options.seam === undefined) {
337
356
  return allSame(plan, { code: 'invalid-request', message: '没有执行缝,写不了' });
338
357
  }
358
+ const session = writeSessionOf(plan.session, plan.origin);
339
359
  const run = async (script) => {
340
360
  const got = await guardedBrowser({
341
361
  seam: options.seam,
342
362
  script,
343
363
  url: plan.origin,
344
364
  ...(plan.loginUrl === undefined ? {} : { loginUrl: plan.loginUrl }),
345
- ...(plan.session === undefined ? {} : { session: plan.session }),
346
365
  open: submitOptions.open ?? false,
347
366
  ...(plan.timeoutMs === undefined ? {} : { timeoutMs: plan.timeoutMs }),
348
367
  ...(submitOptions.signal === undefined ? {} : { signal: submitOptions.signal }),
349
368
  retry: false,
369
+ purpose: 'write',
370
+ finalSession: session,
350
371
  });
351
372
  if (got.kind === 'failed')
352
373
  return got.result;
@@ -354,7 +375,7 @@ export function createDataReader(options = {}) {
354
375
  return browserFailure(got.value, plan.loginUrl);
355
376
  return { ok: true, value: got.value.value };
356
377
  };
357
- return submitPlanOf(plan, submitOptions, run, options.saveBytes);
378
+ return sessions.hold(session, () => submitPlanOf(plan, submitOptions, run, options.saveBytes));
358
379
  },
359
380
  async submit(recipe, overrides, callOptions = {}) {
360
381
  return (await readRecipe(recipe, overrides, 'submit', callOptions));
@@ -0,0 +1,11 @@
1
+ export interface SessionPool {
2
+ touch(session: string): void;
3
+ hold(session: string): void;
4
+ idle(session: string): string | undefined;
5
+ drop(session: string): void;
6
+ expire(idleMs: number): readonly string[];
7
+ }
8
+ export declare function createSessionPool(input: {
9
+ readonly max: number;
10
+ readonly close: (session: string) => void;
11
+ }): SessionPool;
@@ -0,0 +1,60 @@
1
+ import { now } from '@dsh-workbench/shared/host';
2
+ export function createSessionPool(input) {
3
+ const seen = new Map();
4
+ const busy = new Set();
5
+ let clock = 0;
6
+ function mark(session) {
7
+ clock += 1;
8
+ seen.set(session, { seq: clock, at: now() });
9
+ }
10
+ function sweep(keep) {
11
+ if (seen.size <= input.max)
12
+ return;
13
+ const idle = [...seen.entries()]
14
+ .filter(([session]) => !busy.has(session) && session !== keep)
15
+ .sort((a, b) => a[1].seq - b[1].seq);
16
+ for (const [session] of idle) {
17
+ if (seen.size <= input.max)
18
+ break;
19
+ seen.delete(session);
20
+ input.close(session);
21
+ }
22
+ }
23
+ return {
24
+ touch(session) {
25
+ mark(session);
26
+ sweep(session);
27
+ },
28
+ hold(session) {
29
+ busy.add(session);
30
+ mark(session);
31
+ sweep(session);
32
+ },
33
+ drop(session) {
34
+ busy.delete(session);
35
+ seen.delete(session);
36
+ },
37
+ expire(idleMs) {
38
+ if (idleMs <= 0)
39
+ return [];
40
+ const at = now();
41
+ const found = [];
42
+ for (const [session, entry] of [...seen.entries()]) {
43
+ if (busy.has(session))
44
+ continue;
45
+ if (at - entry.at < idleMs)
46
+ continue;
47
+ seen.delete(session);
48
+ found.push(session);
49
+ }
50
+ return found;
51
+ },
52
+ idle(session) {
53
+ busy.delete(session);
54
+ mark(session);
55
+ const before = seen.size;
56
+ sweep(session);
57
+ return before === seen.size ? undefined : session;
58
+ },
59
+ };
60
+ }
@@ -0,0 +1,9 @@
1
+ export interface SessionRegistry {
2
+ claim(session: string): void;
3
+ stale(): readonly string[];
4
+ release(): void;
5
+ }
6
+ export declare function createSessionRegistry(input: {
7
+ readonly dir: string;
8
+ readonly processId?: number | undefined;
9
+ }): SessionRegistry;
@@ -0,0 +1,66 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { ensureDir, pidAlive, removePath, writeTextFile } from '@dsh-workbench/shared/host';
4
+ function readFileAt(file) {
5
+ try {
6
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
7
+ if (typeof parsed !== 'object' || parsed === null)
8
+ return undefined;
9
+ const pid = parsed['pid'];
10
+ const sessions = parsed['sessions'];
11
+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0)
12
+ return undefined;
13
+ const list = Array.isArray(sessions) ? sessions.filter((one) => typeof one === 'string') : [];
14
+ return { pid, sessions: list };
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ export function createSessionRegistry(input) {
21
+ const processId = input.processId ?? process.pid;
22
+ const own = join(input.dir, `${String(processId)}.json`);
23
+ const claimed = new Set();
24
+ function write() {
25
+ try {
26
+ ensureDir(input.dir);
27
+ writeTextFile(own, `${JSON.stringify({ pid: processId, sessions: [...claimed] })}\n`);
28
+ }
29
+ catch {
30
+ return;
31
+ }
32
+ }
33
+ return {
34
+ claim(session) {
35
+ if (claimed.has(session))
36
+ return;
37
+ claimed.add(session);
38
+ write();
39
+ },
40
+ stale() {
41
+ if (!existsSync(input.dir))
42
+ return [];
43
+ const found = [];
44
+ for (const entry of readdirSync(input.dir)) {
45
+ if (!entry.endsWith('.json'))
46
+ continue;
47
+ const file = join(input.dir, entry);
48
+ const parsed = readFileAt(file);
49
+ if (parsed === undefined) {
50
+ removePath(file);
51
+ continue;
52
+ }
53
+ if (parsed.pid === processId)
54
+ continue;
55
+ if (pidAlive(parsed.pid))
56
+ continue;
57
+ found.push(...parsed.sessions);
58
+ removePath(file);
59
+ }
60
+ return [...new Set(found)];
61
+ },
62
+ release() {
63
+ removePath(own);
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,13 @@
1
+ import { type Seam } from '@dsh-workbench/shared/host';
2
+ export interface SessionKeeper {
3
+ begin(session: string): void;
4
+ end(session: string, write: boolean): Promise<void>;
5
+ hold<T>(session: string, work: () => Promise<T>): Promise<T>;
6
+ }
7
+ export declare function createSessionKeeper(input: {
8
+ readonly seam?: Seam | undefined;
9
+ readonly command: string;
10
+ readonly max: number;
11
+ readonly registryDir?: string | undefined;
12
+ readonly idleMs?: number | undefined;
13
+ }): SessionKeeper;
@@ -0,0 +1,69 @@
1
+ import { productWrite } from '@dsh-workbench/shared/host';
2
+ import { createSessionPool } from './session-pool.js';
3
+ import { createSessionRegistry } from './session-registry.js';
4
+ export function createSessionKeeper(input) {
5
+ const inFlight = new Map();
6
+ const opened = new Set();
7
+ async function close(session) {
8
+ if (input.seam === undefined)
9
+ return;
10
+ await input.seam
11
+ .run({
12
+ argv: [input.command, 'browser', '--session', session, 'close'],
13
+ intent: productWrite(),
14
+ timeoutMs: 15_000,
15
+ bestEffort: true,
16
+ })
17
+ .catch(() => undefined);
18
+ }
19
+ const pool = createSessionPool({ max: input.max, close: (session) => void close(session) });
20
+ const registry = input.registryDir === undefined ? undefined : createSessionRegistry({ dir: input.registryDir });
21
+ async function leave(session, write) {
22
+ const left = (inFlight.get(session) ?? 1) - 1;
23
+ if (left > 0) {
24
+ inFlight.set(session, left);
25
+ return;
26
+ }
27
+ inFlight.delete(session);
28
+ if (!write)
29
+ return;
30
+ if (!opened.delete(session))
31
+ return;
32
+ pool.drop(session);
33
+ await close(session);
34
+ }
35
+ void (async () => {
36
+ for (const session of registry?.stale() ?? [])
37
+ await close(session);
38
+ })();
39
+ if (input.idleMs !== undefined && input.idleMs > 0) {
40
+ const timer = setInterval(() => {
41
+ void (async () => {
42
+ for (const session of pool.expire(input.idleMs ?? 0))
43
+ await close(session);
44
+ })();
45
+ }, Math.min(input.idleMs, 60_000));
46
+ timer.unref?.();
47
+ }
48
+ return {
49
+ begin(session) {
50
+ inFlight.set(session, (inFlight.get(session) ?? 0) + 1);
51
+ registry?.claim(session);
52
+ opened.add(session);
53
+ pool.hold(session);
54
+ },
55
+ async end(session, write) {
56
+ pool.idle(session);
57
+ await leave(session, write);
58
+ },
59
+ async hold(session, work) {
60
+ inFlight.set(session, (inFlight.get(session) ?? 0) + 1);
61
+ try {
62
+ return await work();
63
+ }
64
+ finally {
65
+ await leave(session, true);
66
+ }
67
+ },
68
+ };
69
+ }
@@ -13,7 +13,12 @@ export interface DataReaderOptions {
13
13
  readonly channel?: boolean | undefined;
14
14
  readonly channelInstalled?: (() => boolean) | undefined;
15
15
  readonly queueWaitMs?: number | undefined;
16
+ readonly readSessions?: number | undefined;
17
+ readonly sessionRegistryDir?: string | undefined;
18
+ readonly sessionIdleMs?: number | undefined;
16
19
  readonly onQueue?: ((event: QueueWaitEvent) => void) | undefined;
17
20
  readonly saveBytes?: SaveBytes | undefined;
18
21
  }
19
22
  export declare function sessionOf(value: string | undefined): string;
23
+ export declare function readSessionOf(value: string | undefined, url: string | undefined): string;
24
+ export declare function writeSessionOf(value: string | undefined, url: string | undefined): string;
@@ -1,4 +1,32 @@
1
- import { BROWSER_READ_SESSION } from '@dsh-workbench/shared/host';
1
+ import { BROWSER_READ_SESSION, BROWSER_WRITE_SESSION } from '@dsh-workbench/shared/host';
2
2
  export function sessionOf(value) {
3
3
  return value === undefined || value === '' ? BROWSER_READ_SESSION : value;
4
4
  }
5
+ const HOST_RE = /^[a-z0-9-]+$/;
6
+ function hostKeyOf(url) {
7
+ if (url === undefined || url.trim() === '')
8
+ return undefined;
9
+ let host;
10
+ try {
11
+ host = new URL(url).host.toLowerCase();
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ if (host === '')
17
+ return undefined;
18
+ const key = host.replaceAll(/[^a-z0-9]+/g, '-').replaceAll(/^-+|-+$/g, '');
19
+ return HOST_RE.test(key) ? key : undefined;
20
+ }
21
+ export function readSessionOf(value, url) {
22
+ if (value !== undefined && value !== '')
23
+ return value;
24
+ const host = hostKeyOf(url);
25
+ return host === undefined ? BROWSER_READ_SESSION : `${BROWSER_READ_SESSION}-${host}`;
26
+ }
27
+ export function writeSessionOf(value, url) {
28
+ if (value !== undefined && value !== '')
29
+ return `${value}-write`;
30
+ const host = hostKeyOf(url);
31
+ return host === undefined ? BROWSER_WRITE_SESSION : `${BROWSER_WRITE_SESSION}-${host}`;
32
+ }
@@ -1,9 +1,11 @@
1
1
  import { OPENCLI_NPM_PACKAGE } from '@dsh-workbench/shared/host';
2
2
  export declare const OPENCLI_RUNTIME_ID = "opencli";
3
3
  export declare const OPENCLI_MANIFEST_FILE = "opencli-plugin.json";
4
+ export declare const OPENCLI_RUNTIME_FIELD = "opencli";
4
5
  export { OPENCLI_NPM_PACKAGE };
5
6
  export declare function isolatedRoot(): string;
6
7
  export declare function isolatedHome(): string;
8
+ export declare function sessionStateDir(): string;
7
9
  export declare function vendorPrefix(): string;
8
10
  export declare function vendorPluginsDir(): string;
9
11
  export declare function libsPrefix(): string;
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
  import { OPENCLI_NPM_PACKAGE, runtimeLayoutOf } from '@dsh-workbench/shared/host';
4
4
  export const OPENCLI_RUNTIME_ID = 'opencli';
5
5
  export const OPENCLI_MANIFEST_FILE = 'opencli-plugin.json';
6
+ export const OPENCLI_RUNTIME_FIELD = 'opencli';
6
7
  export { OPENCLI_NPM_PACKAGE };
7
8
  const layout = () => runtimeLayoutOf(OPENCLI_RUNTIME_ID);
8
9
  export function isolatedRoot() {
@@ -11,6 +12,9 @@ export function isolatedRoot() {
11
12
  export function isolatedHome() {
12
13
  return layout().home;
13
14
  }
15
+ export function sessionStateDir() {
16
+ return join(layout().root, 'state', 'sessions');
17
+ }
14
18
  export function vendorPrefix() {
15
19
  return layout().vendorPrefix;
16
20
  }
@@ -1,2 +1,5 @@
1
1
  export declare function ensureLibsBinOnPath(env?: NodeJS.ProcessEnv): boolean;
2
+ export declare function libsOpencliPeerLink(): string;
3
+ export declare function detachLibsOpencliPeer(): boolean;
2
4
  export declare function ensureLibsOpencliPeer(): boolean;
5
+ export declare function ensureVendorOpencliPeer(): boolean;
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, realpathSync } from 'node:fs';
2
2
  import { delimiter, dirname, join } from 'node:path';
3
- import { linkDir } from '@dsh-workbench/shared/host';
4
- import { OPENCLI_NPM_PACKAGE, libsBinDir, libsPrefix, toolchainOpencliDir } from '../foundation/paths.js';
3
+ import { linkDir, removePath } from '@dsh-workbench/shared/host';
4
+ import { OPENCLI_NPM_PACKAGE, libsBinDir, libsPrefix, toolchainOpencliDir, vendorPluginsDir, } from '../foundation/paths.js';
5
5
  export function ensureLibsBinOnPath(env = process.env) {
6
6
  const dir = libsBinDir();
7
7
  const parts = (env.PATH ?? '').split(delimiter).filter((one) => one !== '');
@@ -18,8 +18,22 @@ function pointsAt(link, target) {
18
18
  return false;
19
19
  }
20
20
  }
21
- export function ensureLibsOpencliPeer() {
22
- const link = join(libsPrefix(), 'node_modules', ...OPENCLI_NPM_PACKAGE.split('/'));
21
+ export function libsOpencliPeerLink() {
22
+ return join(libsPrefix(), 'node_modules', ...OPENCLI_NPM_PACKAGE.split('/'));
23
+ }
24
+ export function detachLibsOpencliPeer() {
25
+ const link = libsOpencliPeerLink();
26
+ if (!existsSync(link))
27
+ return false;
28
+ try {
29
+ removePath(link);
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ function linkRuntimePeer(link) {
23
37
  const target = toolchainOpencliDir();
24
38
  if (!existsSync(target))
25
39
  return false;
@@ -34,3 +48,9 @@ export function ensureLibsOpencliPeer() {
34
48
  return false;
35
49
  }
36
50
  }
51
+ export function ensureLibsOpencliPeer() {
52
+ return linkRuntimePeer(libsOpencliPeerLink());
53
+ }
54
+ export function ensureVendorOpencliPeer() {
55
+ return linkRuntimePeer(join(vendorPluginsDir(), ...OPENCLI_NPM_PACKAGE.split('/')));
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-workbench/adapter-runtime",
3
- "version": "1.3.1",
3
+ "version": "1.4.0-beta.0",
4
4
  "description": "Opencli, browser and data runtime adapters.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,7 +17,8 @@
17
17
  "bin"
18
18
  ],
19
19
  "dependencies": {
20
- "@dsh-workbench/shared": "1.3.1"
20
+ "execa": "^10.2.0",
21
+ "@dsh-workbench/shared": "1.4.0-beta.0"
21
22
  },
22
23
  "devDependencies": {
23
24
  "@types/node": "^24.19.0",