dsh-plugin-container-windows 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/README.zh-CN.md +110 -0
  4. package/cordis.patch.yml +3 -0
  5. package/docs/ai-chat.png +0 -0
  6. package/docs/ai-new-session.png +0 -0
  7. package/docs/apple-container.png +0 -0
  8. package/docs/attach.png +0 -0
  9. package/docs/docker-console.png +0 -0
  10. package/docs/docker-overview.png +0 -0
  11. package/docs/docker-volumes.png +0 -0
  12. package/docs/image-architecture.png +0 -0
  13. package/docs/package-install.png +0 -0
  14. package/docs/provider-switch.png +0 -0
  15. package/docs/run-container.png +0 -0
  16. package/index.js +141 -0
  17. package/lib/client.js +4092 -0
  18. package/package.json +72 -4
  19. package/src/client/api.js +98 -0
  20. package/src/client/attach.jsx +134 -0
  21. package/src/client/build-image.jsx +224 -0
  22. package/src/client/components.jsx +325 -0
  23. package/src/client/hooks.js +161 -0
  24. package/src/client/i18n.js +602 -0
  25. package/src/client/icons.jsx +239 -0
  26. package/src/client/index.jsx +90 -0
  27. package/src/client/page.jsx +854 -0
  28. package/src/client/platforms.js +2 -0
  29. package/src/client/push-image.jsx +113 -0
  30. package/src/client/run-container.jsx +187 -0
  31. package/src/client/runs.js +182 -0
  32. package/src/client/store.js +91 -0
  33. package/src/client/styles.js +383 -0
  34. package/src/client/tabs/compose.jsx +94 -0
  35. package/src/client/tabs/console.jsx +211 -0
  36. package/src/client/tabs/containers.jsx +148 -0
  37. package/src/client/tabs/images.jsx +154 -0
  38. package/src/client/tabs/networks.jsx +91 -0
  39. package/src/client/tabs/overview.jsx +266 -0
  40. package/src/client/tabs/volumes.jsx +76 -0
  41. package/src/host/apple-cli.js +319 -0
  42. package/src/host/apple.js +495 -0
  43. package/src/host/attach.js +246 -0
  44. package/src/host/commands.js +241 -0
  45. package/src/host/docker-cli.js +468 -0
  46. package/src/host/images.js +143 -0
  47. package/src/host/jobs.js +245 -0
  48. package/src/host/parsers.js +484 -0
  49. package/src/host/runtime.js +379 -0
  50. package/src/host/service.js +892 -0
  51. package/src/host/tools.js +198 -0
  52. package/src/host/util.js +97 -0
@@ -0,0 +1,468 @@
1
+ /**
2
+ * Docker CLI discovery and fully-specified child process execution.
3
+ *
4
+ * No shell is involved: every command is an argv array handed to the
5
+ * subprocess seam. The CLI path is pinned for the lifetime of a process but
6
+ * re-resolved when a status check fails with a missing executable.
7
+ */
8
+ import { accessSync, constants, statSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path'
11
+
12
+ import { codeOf, messageOf } from './util.js'
13
+ import { summarizeStderr } from './parsers.js'
14
+
15
+ const DEFAULT_MAX_OUTPUT = 1024 * 1024
16
+ const DEFAULT_QUERY_TIMEOUT = 20_000
17
+ const RESOLVE_RETRY_MS = 10_000
18
+
19
+ export class DockerCliError extends Error {
20
+ /** @param {string} message @param {string} [code] @param {Record<string, unknown>} [details] */
21
+ constructor(message, code = 'docker/cli-missing', details = {}) {
22
+ super(message)
23
+ this.name = 'DockerCliError'
24
+ this.code = code
25
+ this.details = details
26
+ }
27
+ }
28
+
29
+ export class DockerCommandError extends Error {
30
+ /** @param {string} message @param {{code?: string, stderr?: string, details?: Record<string, unknown>}} [options] */
31
+ constructor(message, options = {}) {
32
+ super(message)
33
+ this.name = 'DockerCommandError'
34
+ this.code = options.code ?? 'docker/exec-failed'
35
+ this.stderr = options.stderr ?? ''
36
+ this.details = options.details ?? {}
37
+ }
38
+ }
39
+
40
+ /** @param {number} bytes */
41
+ function clampBytes(bytes) {
42
+ if (!Number.isFinite(bytes)) return DEFAULT_MAX_OUTPUT
43
+ return Math.min(Math.max(Math.trunc(bytes), 64 * 1024), 8 * 1024 * 1024)
44
+ }
45
+
46
+ /**
47
+ * @param {string} path
48
+ * @param {NodeJS.Platform} platform
49
+ */
50
+ function executable(path, platform) {
51
+ try {
52
+ // Node's X_OK check is a no-op on Windows; require a real executable suffix.
53
+ if (platform === 'win32' && !/\.(?:exe|cmd|bat|com)$/iu.test(path)) return false
54
+ accessSync(path, constants.X_OK)
55
+ return statSync(path).isFile()
56
+ } catch {
57
+ return false
58
+ }
59
+ }
60
+
61
+ export class DockerCli {
62
+ /**
63
+ * @param {{
64
+ * subprocess: any,
65
+ * config?: Record<string, any>,
66
+ * env?: NodeJS.ProcessEnv,
67
+ * home?: string,
68
+ * platform?: NodeJS.Platform,
69
+ * logger?: any,
70
+ * }} options
71
+ */
72
+ constructor(options) {
73
+ this.subprocess = options.subprocess
74
+ this.config = options.config ?? {}
75
+ this.env = options.env ?? process.env
76
+ this.home = options.home ?? homedir()
77
+ this.platform = options.platform ?? process.platform
78
+ this.logger = options.logger
79
+ this.maxOutput = clampBytes(Number(this.config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT))
80
+ this.queryTimeoutMs = Number(this.config.queryTimeoutMs ?? DEFAULT_QUERY_TIMEOUT)
81
+ this.dockerPath = undefined
82
+ this.colimaPath = undefined
83
+ this.dockerError = undefined
84
+ this.lastDockerAttempt = 0
85
+ this.lastColimaAttempt = 0
86
+ }
87
+
88
+ /**
89
+ * @param {string} name
90
+ * @returns {string | undefined}
91
+ */
92
+ envValue(name) {
93
+ const exact = this.env[name]
94
+ if (exact !== undefined || this.platform !== 'win32') return exact
95
+ const upper = name.toUpperCase()
96
+ return Object.entries(this.env).find(([key]) => key.toUpperCase() === upper)?.[1]
97
+ }
98
+
99
+ /** @returns {string[]} */
100
+ dockerCandidates() {
101
+ const configured = typeof this.config.dockerPath === 'string' && this.config.dockerPath.trim() !== '' ? this.config.dockerPath.trim() : null
102
+ const envPath = typeof this.env.DOCKER_PATH === 'string' && this.env.DOCKER_PATH.trim() !== '' ? this.env.DOCKER_PATH.trim() : null
103
+ const defaults = this.platform === 'win32'
104
+ ? [
105
+ join(this.envValue('ProgramFiles') ?? 'C:\\Program Files', 'Docker', 'Docker', 'resources', 'bin', 'docker.exe'),
106
+ join(this.envValue('ProgramFiles(X86)') ?? 'C:\\Program Files (x86)', 'Docker', 'Docker', 'resources', 'bin', 'docker.exe'),
107
+ join(this.envValue('LOCALAPPDATA') ?? join(this.home, 'AppData', 'Local'), 'Docker', 'Docker', 'resources', 'bin', 'docker.exe'),
108
+ join(this.home, 'AppData', 'Local', 'Docker', 'bin', 'docker.exe'),
109
+ ]
110
+ : [
111
+ '/opt/homebrew/bin/docker',
112
+ '/usr/local/bin/docker',
113
+ join(this.home, '.docker/bin/docker'),
114
+ '/Applications/Docker.app/Contents/Resources/bin/docker',
115
+ ]
116
+ return [configured, envPath, ...defaults]
117
+ .filter((value, index, list) => typeof value === 'string' && value !== '' && list.indexOf(value) === index)
118
+ }
119
+
120
+ /** @returns {string[]} */
121
+ colimaCandidates() {
122
+ const configured = typeof this.config.colimaPath === 'string' && this.config.colimaPath.trim() !== '' ? this.config.colimaPath.trim() : null
123
+ return [
124
+ configured,
125
+ '/opt/homebrew/bin/colima',
126
+ '/usr/local/bin/colima',
127
+ join(this.home, 'go/bin/colima'),
128
+ ].filter((value, index, list) => typeof value === 'string' && value !== '' && list.indexOf(value) === index)
129
+ }
130
+
131
+ /** @param {string} command @param {AbortSignal | undefined} signal */
132
+ async resolveOnPath(command, signal) {
133
+ if (typeof this.subprocess.resolveExecutable !== 'function') return undefined
134
+ try {
135
+ return await this.subprocess.resolveExecutable(command, undefined, signal)
136
+ } catch (error) {
137
+ if (error?.name === 'SubprocessExecutableNotFoundError' || codeOf(error) === 'ENOENT') return undefined
138
+ throw error
139
+ }
140
+ }
141
+
142
+ /**
143
+ * @param {{signal?: AbortSignal, force?: boolean}} [options]
144
+ * @returns {Promise<string>}
145
+ */
146
+ async ensureDocker(options = {}) {
147
+ if (this.dockerPath !== undefined) return this.dockerPath
148
+ const now = Date.now()
149
+ if (!options.force && now - this.lastDockerAttempt < RESOLVE_RETRY_MS && this.dockerError !== undefined) throw this.dockerError
150
+ this.lastDockerAttempt = now
151
+ const configured = typeof this.config.dockerPath === 'string' && this.config.dockerPath.trim() !== '' ? this.config.dockerPath.trim() : null
152
+ if (configured !== null) {
153
+ const path = isAbsolute(configured) ? configured : resolve(this.home, configured)
154
+ if (executable(path, this.platform)) {
155
+ this.dockerPath = path
156
+ this.dockerError = undefined
157
+ return path
158
+ }
159
+ const error = new DockerCliError(
160
+ `配置的 dockerPath 不可执行: ${configured}`,
161
+ 'docker/cli-missing',
162
+ { candidates: [configured] },
163
+ )
164
+ this.dockerError = error
165
+ throw error
166
+ }
167
+ for (const candidate of this.dockerCandidates()) {
168
+ if (candidate === configured) continue
169
+ const path = isAbsolute(candidate) ? candidate : resolve(this.home, candidate)
170
+ if (executable(path, this.platform)) {
171
+ this.dockerPath = path
172
+ this.dockerError = undefined
173
+ return path
174
+ }
175
+ }
176
+ const commands = this.platform === 'win32' ? ['docker', 'docker.exe'] : ['docker']
177
+ for (const command of commands) {
178
+ const onPath = await this.resolveOnPath(command, options.signal)
179
+ if (onPath !== undefined && executable(onPath, this.platform)) {
180
+ this.dockerPath = onPath
181
+ this.dockerError = undefined
182
+ return onPath
183
+ }
184
+ }
185
+ const error = new DockerCliError(
186
+ this.platform === 'win32'
187
+ ? '未找到 docker.exe。请安装 Docker Desktop for Windows,并确认安装目录已加入 PATH。'
188
+ : '未找到 docker 命令。请安装 Docker Desktop,或安装 colima 并启动运行时。',
189
+ 'docker/cli-missing',
190
+ { candidates: this.dockerCandidates() },
191
+ )
192
+ this.dockerError = error
193
+ throw error
194
+ }
195
+
196
+ /**
197
+ * @param {{signal?: AbortSignal, force?: boolean}} [options]
198
+ * @returns {Promise<string | null>}
199
+ */
200
+ async ensureColima(options = {}) {
201
+ if (this.colimaPath !== undefined) return this.colimaPath
202
+ const now = Date.now()
203
+ if (!options.force && now - this.lastColimaAttempt < RESOLVE_RETRY_MS && this.colimaPath === null) return null
204
+ this.lastColimaAttempt = now
205
+ const configured = typeof this.config.colimaPath === 'string' && this.config.colimaPath.trim() !== '' ? this.config.colimaPath.trim() : null
206
+ if (configured !== null) {
207
+ const path = isAbsolute(configured) ? configured : resolve(this.home, configured)
208
+ if (executable(path, this.platform)) {
209
+ this.colimaPath = path
210
+ return path
211
+ }
212
+ this.colimaPath = null
213
+ return null
214
+ }
215
+ for (const candidate of this.colimaCandidates()) {
216
+ const path = isAbsolute(candidate) ? candidate : resolve(this.home, candidate)
217
+ if (executable(path, this.platform)) {
218
+ this.colimaPath = path
219
+ return path
220
+ }
221
+ }
222
+ const onPath = await this.resolveOnPath('colima', options.signal)
223
+ if (onPath !== undefined && executable(onPath, this.platform)) {
224
+ this.colimaPath = onPath
225
+ return onPath
226
+ }
227
+ this.colimaPath = null
228
+ return null
229
+ }
230
+
231
+ /** @param {string} path */
232
+ markDockerMissing(path) {
233
+ if (this.dockerPath === path) {
234
+ this.dockerPath = undefined
235
+ this.dockerError = undefined
236
+ this.lastDockerAttempt = 0
237
+ }
238
+ }
239
+
240
+ /** @returns {NodeJS.ProcessEnv} */
241
+ childEnv() {
242
+ const windows = this.platform === 'win32'
243
+ const separator = windows ? delimiter : ':'
244
+ const result = {}
245
+ const inherited = windows
246
+ ? [
247
+ 'SystemRoot', 'WINDIR', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',
248
+ 'ProgramFiles', 'ProgramFiles(X86)', 'CommonProgramFiles', 'TEMP', 'TMP',
249
+ 'COMSPEC', 'PATHEXT', 'COMPUTERNAME', 'HOMEDRIVE', 'HOMEPATH',
250
+ 'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'OS',
251
+ ]
252
+ : ['HOME', 'TMPDIR']
253
+ const dockerVars = [
254
+ 'DOCKER_HOST', 'DOCKER_CONTEXT', 'DOCKER_CONFIG', 'DOCKER_CERT_PATH',
255
+ 'DOCKER_TLS_VERIFY', 'DOCKER_BUILDKIT', 'COMPOSE_PROJECT_NAME', 'COMPOSE_FILE',
256
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
257
+ 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy',
258
+ ]
259
+ for (const name of [...inherited, ...dockerVars]) {
260
+ const value = this.envValue(name)
261
+ if (value !== undefined && value !== '') result[name] = value
262
+ }
263
+
264
+ const pathParts = []
265
+ if (this.dockerPath !== undefined) pathParts.push(dirname(this.dockerPath))
266
+ if (typeof this.colimaPath === 'string') pathParts.push(dirname(this.colimaPath))
267
+ if (windows) {
268
+ const root = this.envValue('SystemRoot') ?? this.envValue('WINDIR') ?? 'C:\\Windows'
269
+ pathParts.push(join(root, 'System32'), join(root, 'System32', 'WindowsPowerShell', 'v1.0'))
270
+ for (const name of ['ProgramFiles', 'ProgramFiles(X86)', 'LOCALAPPDATA']) {
271
+ const base = this.envValue(name)
272
+ if (base !== undefined && base !== '') pathParts.push(join(base, 'Docker', 'Docker', 'resources', 'bin'))
273
+ }
274
+ } else {
275
+ pathParts.push('/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin')
276
+ }
277
+ const ambientPath = this.envValue('PATH')
278
+ if (typeof ambientPath === 'string' && ambientPath !== '') pathParts.push(...ambientPath.split(separator))
279
+ const PATH = [...new Set(pathParts.filter(Boolean))].join(separator)
280
+ result.PATH = PATH
281
+ // Node treats env keys case-insensitively on Windows, but some subprocess
282
+ // wrappers look up `Path` literally; set both to the same value.
283
+ if (windows) result.Path = PATH
284
+ if (windows && (result.PATHEXT === undefined || result.PATHEXT === '')) result.PATHEXT = '.COM;.EXE;.BAT;.CMD'
285
+ result.NO_COLOR = '1'
286
+ result.CLICOLOR = '0'
287
+ result.TERM = 'dumb'
288
+ result.DOCKER_CLI_HINTS = 'false'
289
+ result.DOCKER_CLIENT_TIMEOUT = String(this.config.dockerClientTimeoutSec ?? 10)
290
+ result.COMPOSE_HTTP_TIMEOUT = String(this.config.composeHttpTimeoutSec ?? 20)
291
+ return result
292
+ }
293
+
294
+ /**
295
+ * @param {string[]} subargv
296
+ * @param {{context?: string | null, cwd?: string, timeoutMs?: number, signal?: AbortSignal, maxBytes?: number}} [options]
297
+ */
298
+ argvFor(subargv, options = {}) {
299
+ const path = this.dockerPath
300
+ if (path === undefined) throw new DockerCliError('docker 尚未解析', 'docker/cli-missing')
301
+ return [path, ...(options.context ? ['--context', options.context] : []), ...subargv]
302
+ }
303
+
304
+ /**
305
+ * Execute one Docker command and collect bounded stdout/stderr.
306
+ * @param {string[]} argv fully-resolved argv including the docker path
307
+ * @param {{cwd?: string, timeoutMs?: number, signal?: AbortSignal, maxBytes?: number}} [options]
308
+ */
309
+ async exec(argv, options = {}) {
310
+ const maxBytes = clampBytes(options.maxBytes ?? this.maxOutput)
311
+ const timeoutMs = Math.min(Math.max(Number(options.timeoutMs ?? this.queryTimeoutMs), 1000), 10 * 60_000)
312
+ const abort = new AbortController()
313
+ let timedOut = false
314
+ const onAbort = () => abort.abort(options.signal?.reason)
315
+ options.signal?.addEventListener('abort', onAbort, { once: true })
316
+ if (options.signal?.aborted === true) abort.abort(options.signal.reason)
317
+ const timeout = setTimeout(() => {
318
+ timedOut = true
319
+ abort.abort(new Error('docker command timed out'))
320
+ }, timeoutMs)
321
+ timeout.unref?.()
322
+
323
+ let handle
324
+ try {
325
+ handle = this.subprocess.spawn({
326
+ argv,
327
+ cwd: options.cwd ?? this.home,
328
+ stdio: { stdin: 'ignore', stdout: { maxBytes }, stderr: { maxBytes } },
329
+ graceMs: 2000,
330
+ env: this.childEnv(),
331
+ signal: abort.signal,
332
+ })
333
+ } catch (error) {
334
+ clearTimeout(timeout)
335
+ options.signal?.removeEventListener('abort', onAbort)
336
+ throw new DockerCommandError(`无法启动 docker: ${messageOf(error)}`, { code: 'docker/exec-failed' })
337
+ }
338
+
339
+ let outcome
340
+ try {
341
+ outcome = await handle.done
342
+ } catch (error) {
343
+ clearTimeout(timeout)
344
+ options.signal?.removeEventListener('abort', onAbort)
345
+ this.markDockerMissing(argv[0])
346
+ throw new DockerCommandError(`docker 进程失败: ${messageOf(error)}`, { code: 'docker/exec-failed' })
347
+ }
348
+ clearTimeout(timeout)
349
+ options.signal?.removeEventListener('abort', onAbort)
350
+
351
+ const read = (reader) => {
352
+ if (reader === undefined) return { text: '', truncated: false }
353
+ const value = reader.readFrom(0)
354
+ return { text: value.text, truncated: value.lossy === true, nextOffset: value.nextOffset }
355
+ }
356
+ const stdout = read(handle.collected?.stdout)
357
+ const stderr = read(handle.collected?.stderr)
358
+ return {
359
+ exitCode: outcome.exitCode,
360
+ signal: outcome.signal,
361
+ stdout: stdout.text,
362
+ stderr: stderr.text,
363
+ truncated: stdout.truncated || stderr.truncated,
364
+ timedOut,
365
+ argv,
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Execute a Docker subcommand with the selected context and parse-friendly
371
+ * error reporting.
372
+ * @param {string[]} subargv
373
+ * @param {{context?: string | null, cwd?: string, timeoutMs?: number, signal?: AbortSignal, maxBytes?: number}} [options]
374
+ */
375
+ async docker(subargv, options = {}) {
376
+ const path = await this.ensureDocker({ signal: options.signal })
377
+ const argv = this.argvFor(subargv, options)
378
+ const result = await this.exec(argv, { ...options, cwd: options.cwd ?? this.home })
379
+ if (result.timedOut || result.exitCode !== 0) {
380
+ const detail = summarizeStderr(result.stderr)
381
+ throw new DockerCommandError(
382
+ result.timedOut
383
+ ? `docker 命令超时(${subargv[0] ?? ''})`
384
+ : detail.trim() === ''
385
+ ? `docker ${subargv[0] ?? ''} 退出码 ${String(result.exitCode)}`
386
+ : detail,
387
+ {
388
+ code: result.timedOut ? 'docker/timeout' : 'docker/exec-failed',
389
+ stderr: result.stderr,
390
+ details: {
391
+ exitCode: result.exitCode,
392
+ signal: result.signal,
393
+ timedOut: result.timedOut,
394
+ argv,
395
+ },
396
+ },
397
+ )
398
+ }
399
+ return { ...result, path }
400
+ }
401
+
402
+ /**
403
+ * Execute a non-docker helper (colima/open/osascript) and collect output.
404
+ * @param {string} command absolute path or PATH name
405
+ * @param {string[]} args
406
+ * @param {{timeoutMs?: number, signal?: AbortSignal, maxBytes?: number, cwd?: string}} [options]
407
+ */
408
+ async program(command, args, options = {}) {
409
+ const maxBytes = clampBytes(options.maxBytes ?? this.maxOutput)
410
+ const timeoutMs = Math.min(Math.max(Number(options.timeoutMs ?? this.queryTimeoutMs), 1000), 30 * 60_000)
411
+ const abort = new AbortController()
412
+ let timedOut = false
413
+ const onAbort = () => abort.abort(options.signal?.reason)
414
+ options.signal?.addEventListener('abort', onAbort, { once: true })
415
+ if (options.signal?.aborted === true) abort.abort(options.signal.reason)
416
+ const timeout = setTimeout(() => {
417
+ timedOut = true
418
+ abort.abort(new Error('command timed out'))
419
+ }, timeoutMs)
420
+ timeout.unref?.()
421
+ let handle
422
+ try {
423
+ handle = this.subprocess.spawn({
424
+ argv: [command, ...args],
425
+ cwd: options.cwd ?? this.home,
426
+ stdio: { stdin: 'ignore', stdout: { maxBytes }, stderr: { maxBytes } },
427
+ graceMs: 2000,
428
+ env: this.childEnv(),
429
+ signal: abort.signal,
430
+ })
431
+ } catch (error) {
432
+ clearTimeout(timeout)
433
+ options.signal?.removeEventListener('abort', onAbort)
434
+ throw new DockerCommandError(`无法启动 ${basename(command)}: ${messageOf(error)}`, { code: 'docker/exec-failed' })
435
+ }
436
+ let outcome
437
+ try {
438
+ outcome = await handle.done
439
+ } catch (error) {
440
+ clearTimeout(timeout)
441
+ options.signal?.removeEventListener('abort', onAbort)
442
+ throw new DockerCommandError(`${basename(command)} 进程失败: ${messageOf(error)}`, { code: 'docker/exec-failed' })
443
+ }
444
+ clearTimeout(timeout)
445
+ options.signal?.removeEventListener('abort', onAbort)
446
+ const stdout = handle.collected?.stdout?.readFrom(0)?.text ?? ''
447
+ const stderr = handle.collected?.stderr?.readFrom(0)?.text ?? ''
448
+ if (timedOut || outcome.exitCode !== 0) {
449
+ throw new DockerCommandError(
450
+ timedOut ? `${basename(command)} 超时` : summarizeStderr(stderr) || `${basename(command)} 退出码 ${String(outcome.exitCode)}`, {
451
+ code: timedOut ? 'docker/timeout' : 'docker/exec-failed',
452
+ stderr,
453
+ details: { command, args, exitCode: outcome.exitCode, timedOut },
454
+ })
455
+ }
456
+ return { stdout, stderr, exitCode: outcome.exitCode, signal: outcome.signal, timedOut }
457
+ }
458
+
459
+ /** @param {string} endpoint */
460
+ static isLocalEndpoint(endpoint) {
461
+ return /^(?:unix|npipe):/iu.test(String(endpoint ?? ''))
462
+ }
463
+
464
+ /** @param {string} path */
465
+ static commandName(path) {
466
+ return basename(path)
467
+ }
468
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Shared validation for image push and build, used by the Docker and Apple
3
+ * providers. Everything here produces argv arrays; nothing touches a shell.
4
+ */
5
+ import { readdirSync, statSync } from 'node:fs'
6
+ import { basename, isAbsolute, join, resolve, sep } from 'node:path'
7
+
8
+ import { CommandError } from './commands.js'
9
+ import { requireString } from './util.js'
10
+
11
+ const IMAGE_REF = /^[A-Za-z0-9][A-Za-z0-9_.:/@-]*$/u
12
+ const PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9]+)?$/u
13
+ const BUILD_ARG = /^[A-Za-z_][A-Za-z0-9_]*=[^\r\n]*$/u
14
+ const DOCKERFILE_NAME = /^(?:Dockerfile|Containerfile)(?:\..+)?$|\.(?:Dockerfile|Containerfile)$/u
15
+
16
+ export const LONG_JOB_MS = 30 * 60_000
17
+
18
+ /** @param {unknown} value @param {string} field */
19
+ export function imageRef(value, field) {
20
+ const reference = requireString(value, field, { max: 512 })
21
+ if (!IMAGE_REF.test(reference)) throw new CommandError(`镜像名不合法: ${reference}`)
22
+ return reference
23
+ }
24
+
25
+ /**
26
+ * Docker rejects uppercase in the repository part; say so before running.
27
+ * @param {string} reference
28
+ */
29
+ function assertLowercaseRepository(reference) {
30
+ const withoutDigest = reference.split('@')[0]
31
+ const lastSlash = withoutDigest.lastIndexOf('/')
32
+ const lastColon = withoutDigest.lastIndexOf(':')
33
+ const repository = lastColon > lastSlash ? withoutDigest.slice(0, lastColon) : withoutDigest
34
+ if (/[A-Z]/u.test(repository)) throw new CommandError(`镜像名的仓库部分必须是小写: ${repository}`)
35
+ }
36
+
37
+ /**
38
+ * Optional `--platform` value shared by pull and build.
39
+ * @param {unknown} value
40
+ * @returns {string | undefined}
41
+ */
42
+ export function platformOf(value) {
43
+ if (value === undefined || value === null || String(value).trim() === '') return undefined
44
+ const platform = String(value).trim()
45
+ if (!PLATFORM.test(platform)) throw new CommandError(`平台格式不合法: ${platform}(示例 linux/arm64)`)
46
+ return platform
47
+ }
48
+
49
+ /** @param {Record<string, any>} payload */
50
+ export function pushSpec(payload) {
51
+ const source = imageRef(payload.id ?? payload.reference, 'id')
52
+ const target = payload.target === undefined || payload.target === null || String(payload.target).trim() === ''
53
+ ? source
54
+ : imageRef(String(payload.target).trim(), 'target')
55
+ assertLowercaseRepository(target)
56
+ return { source, target }
57
+ }
58
+
59
+ /** @param {unknown} value @param {string} field */
60
+ function list(value, field) {
61
+ if (value === undefined || value === null) return []
62
+ if (!Array.isArray(value)) throw new CommandError(`${field} 必须是字符串数组`)
63
+ if (value.length > 64) throw new CommandError(`${field} 数量过多`)
64
+ return value.map((entry, index) => requireString(entry, `${field}[${String(index)}]`, { max: 1024 }))
65
+ }
66
+
67
+ /** @param {unknown} value */
68
+ function statOrNull(value) {
69
+ try {
70
+ return statSync(value)
71
+ } catch {
72
+ return null
73
+ }
74
+ }
75
+
76
+ /** @param {Record<string, any>} payload */
77
+ export function buildSpec(payload) {
78
+ const tag = imageRef(payload.tag, 'tag')
79
+ assertLowercaseRepository(tag)
80
+ const rawDir = requireString(payload.contextDir, 'contextDir', { max: 4096 })
81
+ if (!isAbsolute(rawDir) || rawDir.includes('\0')) throw new CommandError('构建目录必须是绝对路径')
82
+ // Normalise so `/a/b/` and `/a/b/./` compare equal to the resolved Dockerfile path below.
83
+ const contextDir = resolve(rawDir)
84
+ const dirStat = statOrNull(contextDir)
85
+ if (dirStat === null) throw new CommandError(`构建目录不存在: ${contextDir}`)
86
+ if (!dirStat.isDirectory()) throw new CommandError(`不是目录: ${contextDir}`)
87
+
88
+ let file
89
+ if (payload.file !== undefined && payload.file !== null && String(payload.file).trim() !== '') {
90
+ const name = requireString(String(payload.file).trim(), 'file', { max: 1024 })
91
+ const resolved = resolve(contextDir, name)
92
+ const prefix = contextDir.endsWith(sep) ? contextDir : `${contextDir}${sep}`
93
+ if (resolved !== contextDir && !resolved.startsWith(prefix)) throw new CommandError('Dockerfile 必须位于构建目录内')
94
+ const fileStat = statOrNull(resolved)
95
+ if (fileStat === null || !fileStat.isFile()) throw new CommandError(`找不到 Dockerfile: ${name}`)
96
+ file = resolved
97
+ } else if (statOrNull(join(contextDir, 'Dockerfile')) === null && statOrNull(join(contextDir, 'Containerfile')) === null) {
98
+ throw new CommandError('构建目录里没有 Dockerfile 或 Containerfile,请选择其他目录或指定文件')
99
+ }
100
+
101
+ const platform = platformOf(payload.platform)
102
+ const buildArgs = list(payload.buildArgs, 'buildArgs').map((entry) => {
103
+ if (!BUILD_ARG.test(entry)) throw new CommandError(`构建参数格式不合法: ${entry}(示例 KEY=VALUE)`)
104
+ return entry
105
+ })
106
+ return { tag, contextDir, file, platform, noCache: payload.noCache === true, buildArgs }
107
+ }
108
+
109
+ /** Both `docker build` and `container build` accept this flag set. */
110
+ export function buildArgv(spec) {
111
+ return [
112
+ 'build',
113
+ '-t',
114
+ spec.tag,
115
+ ...(spec.file === undefined ? [] : ['-f', spec.file]),
116
+ ...(spec.platform === undefined ? [] : ['--platform', spec.platform]),
117
+ ...(spec.noCache ? ['--no-cache'] : []),
118
+ ...spec.buildArgs.flatMap((entry) => ['--build-arg', entry]),
119
+ spec.contextDir,
120
+ ]
121
+ }
122
+
123
+ /**
124
+ * Describe a candidate build directory so the form can validate before running.
125
+ * @param {unknown} value
126
+ */
127
+ export function inspectBuildContext(value) {
128
+ const path = typeof value === 'string' ? value.trim() : ''
129
+ const empty = { path, exists: false, isDirectory: false, dockerfiles: [], suggestedTag: '' }
130
+ if (path === '' || !isAbsolute(path) || path.includes('\0') || path.length > 4096) return empty
131
+ const stat = statOrNull(path)
132
+ if (stat === null) return empty
133
+ if (!stat.isDirectory()) return { ...empty, exists: true }
134
+ let names = []
135
+ try {
136
+ names = readdirSync(path).filter((name) => DOCKERFILE_NAME.test(name) && statOrNull(join(path, name))?.isFile())
137
+ } catch {
138
+ names = []
139
+ }
140
+ names.sort((a, b) => Number(b === 'Dockerfile') - Number(a === 'Dockerfile') || a.localeCompare(b))
141
+ const slug = basename(path).toLowerCase().replace(/[^a-z0-9._-]+/gu, '-').replace(/^[^a-z0-9]+|[^a-z0-9]+$/gu, '')
142
+ return { path, exists: true, isDirectory: true, dockerfiles: names.slice(0, 20), suggestedTag: slug === '' ? '' : `${slug}:latest` }
143
+ }