cmd-op-sdk 0.0.0-stage → 1.3.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.
- package/README.md +116 -2
- package/dist/index.d.ts +109 -0
- package/dist/index.js +673 -0
- package/package.json +66 -4
package/README.md
CHANGED
|
@@ -1,3 +1,117 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cmd-op-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A thin **async** Node.js client over [cmd_op](https://github.com/karlmoriaty/office-command-operate)'s
|
|
4
|
+
resident pipe. It does one thing: forward a command to the running resident and
|
|
5
|
+
hand back the response. There is no second vocabulary to learn — a command is the
|
|
6
|
+
same object you'd put in a cmd_op `batch` list.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install cmd-op-sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The CLI is installed separately — the one-line installer, or the npm wrapper
|
|
13
|
+
(`npm i -g cmd_op`) — and the SDK provisions it on first use if it is missing
|
|
14
|
+
(downloads the signed release binary, or falls back to the official installer).
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
const oc = require('cmd-op-sdk');
|
|
20
|
+
|
|
21
|
+
const doc = await oc.create('report.xlsx', ['--force']);
|
|
22
|
+
try {
|
|
23
|
+
await doc.send({ command: 'set', path: '/Sheet1/A1', props: { text: 'Hello' } });
|
|
24
|
+
const a1 = await doc.send({ command: 'get', path: '/Sheet1/A1' }); // → envelope object
|
|
25
|
+
console.log(a1);
|
|
26
|
+
|
|
27
|
+
// Many writes in one round-trip:
|
|
28
|
+
await doc.batch([
|
|
29
|
+
{ command: 'set', path: '/Sheet1/B1', props: { text: '42' } },
|
|
30
|
+
{ command: 'set', path: '/Sheet1/C1', props: { text: 'world' } },
|
|
31
|
+
]);
|
|
32
|
+
} finally {
|
|
33
|
+
await doc.close(); // flushes to disk
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
On Node ≥ 24 you can use `await using` and skip the explicit close:
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
await using doc = await oc.open('existing.xlsx');
|
|
41
|
+
await doc.send({ command: 'get', path: '/body/p[1]' });
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Two surfaces
|
|
45
|
+
|
|
46
|
+
- **bootstrap** (infrequent): `create()` / `open()` spawn one CLI process.
|
|
47
|
+
- **hot path**: `send()` / `batch()` are pure pipe round-trips, no per-command
|
|
48
|
+
process spawn.
|
|
49
|
+
|
|
50
|
+
## API
|
|
51
|
+
|
|
52
|
+
- `await create(path, args?, options?)` → `Document` — make a new file. Extra CLI
|
|
53
|
+
flags pass through verbatim (`['--force']`, `['--type', 'docx']`).
|
|
54
|
+
- `await open(path, options?)` → `Document` — open an existing file.
|
|
55
|
+
- `Document.send(item, asJson = true, timeoutMs?)` — forward one command.
|
|
56
|
+
`asJson = false` requests plain-text output (view/raw/dump).
|
|
57
|
+
- `Document.batch(items, { force = true, stopOnError = false, timeoutMs? })`.
|
|
58
|
+
- `Document.alive(timeoutMs?)` — is a resident serving this file?
|
|
59
|
+
- `Document.close()` — stop the resident (flushes to disk).
|
|
60
|
+
- `install()` — run the official installer (unix only).
|
|
61
|
+
|
|
62
|
+
`options`: `{ binary?, timeoutMs?, autoInstall? }`. Pass `binary` to point at a
|
|
63
|
+
specific cmd_op; `autoInstall: false` to disable provisioning a missing CLI.
|
|
64
|
+
|
|
65
|
+
## Errors vs business outcomes
|
|
66
|
+
|
|
67
|
+
Transport/process failures throw `CmdOpError`. Business outcomes are **not**
|
|
68
|
+
exceptions — they live in the returned envelope's `success` field, exactly like
|
|
69
|
+
the CLI's exit code. Check `result.success` yourself.
|
|
70
|
+
|
|
71
|
+
## Lifecycle
|
|
72
|
+
|
|
73
|
+
```js
|
|
74
|
+
// Owner — close on exit:
|
|
75
|
+
const d = await oc.open(f);
|
|
76
|
+
try { /* ... */ } finally { await d.close(); }
|
|
77
|
+
|
|
78
|
+
// Borrow — leave a resident another program owns running:
|
|
79
|
+
const d = await oc.open(f);
|
|
80
|
+
await d.send(/* ... */); // no close()
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
A dead resident is transparently restarted and the command retried once. An
|
|
84
|
+
alive-but-busy pipe raises `CmdOpError` (retry, or `close()` and reopen) —
|
|
85
|
+
the SDK never bypasses a live resident, which would race its save.
|
|
86
|
+
|
|
87
|
+
## Use it as an MCP server
|
|
88
|
+
|
|
89
|
+
The cmd_op CLI is also an MCP stdio server, so the same install also gives
|
|
90
|
+
Claude Code, Cursor, VS Code, LM Studio, or opencode direct document tools:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
npx cmd_op mcp claude # also: cursor, vscode, lmstudio, opencode
|
|
94
|
+
npx cmd_op mcp list
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Any other client can point at the stdio server:
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
{
|
|
101
|
+
"mcpServers": {
|
|
102
|
+
"cmd_op": {
|
|
103
|
+
"command": "npx",
|
|
104
|
+
"args": ["-y", "cmd_op", "mcp"]
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Development
|
|
111
|
+
|
|
112
|
+
Sources are TypeScript under `src/`; `npm run build` emits `dist/` (JS plus
|
|
113
|
+
`.d.ts`), and `dist/` is what gets published. `npm run smoke` does an end-to-end
|
|
114
|
+
round-trip (provisioning the CLI on first use), `npm run demo` walks through a
|
|
115
|
+
small create/write/read session.
|
|
116
|
+
|
|
117
|
+
Licensed under Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** A single command in cmd_op's batch-item shape. */
|
|
2
|
+
export interface BatchItem {
|
|
3
|
+
command?: string;
|
|
4
|
+
op?: string;
|
|
5
|
+
path?: string;
|
|
6
|
+
parent?: string;
|
|
7
|
+
type?: string;
|
|
8
|
+
index?: number | string;
|
|
9
|
+
after?: string;
|
|
10
|
+
before?: string;
|
|
11
|
+
to?: string;
|
|
12
|
+
selector?: string;
|
|
13
|
+
props?: Record<string, unknown>;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
/** Parsed result: the JSON envelope (object/array) for --json commands, or raw
|
|
17
|
+
* text for content commands (view/raw/dump). */
|
|
18
|
+
export type Result = Record<string, unknown> | unknown[] | string;
|
|
19
|
+
export interface OpenOptions {
|
|
20
|
+
/** CLI binary name or absolute path. Default "cmd_op". */
|
|
21
|
+
binary?: string;
|
|
22
|
+
/** Command-delivery timeout in ms (connect + retries); the reply read blocks. Default 30000. */
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
/** Actively install/download the CLI if missing (bundled binary, then install.sh). Default true. */
|
|
25
|
+
autoInstall?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface BatchOptions {
|
|
28
|
+
force?: boolean;
|
|
29
|
+
stopOnError?: boolean;
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Raised on transport/process failure (could not reach the resident). Business
|
|
34
|
+
* outcomes are NOT exceptions — they live in the returned envelope's `success`
|
|
35
|
+
* field, same as the CLI's exit code.
|
|
36
|
+
*/
|
|
37
|
+
export declare class CmdOpError extends Error {
|
|
38
|
+
code: number;
|
|
39
|
+
constructor(code: number, msg: string);
|
|
40
|
+
}
|
|
41
|
+
/** [main, ping] pipe addresses for a document path. Exposed for debugging. */
|
|
42
|
+
export declare function pipePaths(filePath: string): [string, string];
|
|
43
|
+
/** A live handle to a resident serving one document. */
|
|
44
|
+
export declare class Document {
|
|
45
|
+
readonly path: string;
|
|
46
|
+
private bin;
|
|
47
|
+
private timeout;
|
|
48
|
+
private _main;
|
|
49
|
+
private _ping;
|
|
50
|
+
private _restarting;
|
|
51
|
+
constructor(filePath: string, binary?: string, timeoutMs?: number);
|
|
52
|
+
private _cmd;
|
|
53
|
+
/**
|
|
54
|
+
* Forward ONE command in cmd_op's batch-item shape and return its parsed
|
|
55
|
+
* result (the JSON envelope, or raw text for content commands). `item` is
|
|
56
|
+
* exactly an object you'd put in a `batch` list:
|
|
57
|
+
* { command: 'set', path: '/Sheet1/A1', props: { text: 'hi' } }
|
|
58
|
+
* `command` (or `op`) picks the command, `props` becomes the property map, and
|
|
59
|
+
* every other key is forwarded verbatim as a command argument. asJson=false
|
|
60
|
+
* requests plain-text output (view/raw/dump), mirroring the CLI's --json.
|
|
61
|
+
*/
|
|
62
|
+
send(item: BatchItem, asJson?: boolean, timeoutMs?: number): Promise<Result>;
|
|
63
|
+
/**
|
|
64
|
+
* Forward cmd_op's `batch`: apply a LIST of the same item objects as send()
|
|
65
|
+
* in ONE round-trip — the fast path for many writes.
|
|
66
|
+
*/
|
|
67
|
+
batch(items: BatchItem[], { force, stopOnError, timeoutMs }?: BatchOptions): Promise<Result>;
|
|
68
|
+
/** True iff a resident is alive AND serving this file (probes the -ping pipe). */
|
|
69
|
+
alive(timeoutMs?: number): Promise<boolean>;
|
|
70
|
+
/**
|
|
71
|
+
* = `cmd_op close`: stop the resident. It flushes the in-memory doc to disk
|
|
72
|
+
* as it shuts down, so no separate save is needed. The resident acks AFTER
|
|
73
|
+
* shutting down, so a missing/empty ack still means "closed"; a real shutdown
|
|
74
|
+
* error is a non-empty response and surfaces through the return value.
|
|
75
|
+
*/
|
|
76
|
+
close(): Promise<Result>;
|
|
77
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Create a blank Office document and return a live Document handle. Extra CLI
|
|
81
|
+
* flags pass through verbatim:
|
|
82
|
+
* await create('report.xlsx', ['--force']);
|
|
83
|
+
* await create('doc', ['--type', 'docx']);
|
|
84
|
+
* One CLI spawn (`cmd_op create`), which auto-starts a resident; the handle
|
|
85
|
+
* binds to THAT resident (no second spawn). Inherits cmd_op's semantics —
|
|
86
|
+
* file_locked (close it first) / file_exists (pass '--force').
|
|
87
|
+
*/
|
|
88
|
+
export declare function create(filePath: string, args?: string[], { binary, timeoutMs, autoInstall }?: OpenOptions): Promise<Document>;
|
|
89
|
+
/**
|
|
90
|
+
* Open an EXISTING document and return a live Document handle. `cmd_op open`
|
|
91
|
+
* is idempotent: reuse a resident already serving this file or start one.
|
|
92
|
+
*
|
|
93
|
+
* Owner — `const d = await open(f); try { ... } finally { await d.close(); }`
|
|
94
|
+
* Borrow — `const d = await open(f); await d.send(...)` // leave it running
|
|
95
|
+
*
|
|
96
|
+
* Failure model (per send/batch): a DEAD resident is transparently restarted and
|
|
97
|
+
* the command retried once; an ALIVE-but-busy pipe raises CmdOpError (retry,
|
|
98
|
+
* or close() and reopen).
|
|
99
|
+
*/
|
|
100
|
+
export declare function open(filePath: string, { binary, timeoutMs, autoInstall }?: OpenOptions): Promise<Document>;
|
|
101
|
+
/**
|
|
102
|
+
* Install the cmd_op CLI binary via its OFFICIAL installer — explicit by
|
|
103
|
+
* design (this SDK never auto-downloads behind your back). Runs install.ps1 via
|
|
104
|
+
* PowerShell on Windows and install.sh via bash elsewhere. Note: when installed
|
|
105
|
+
* via npm, cmd_op already bundles an auto-updating binary, so this
|
|
106
|
+
* is only needed for a standalone (~/.local/bin or %LOCALAPPDATA%\cmd_op)
|
|
107
|
+
* install.
|
|
108
|
+
*/
|
|
109
|
+
export declare function install(): void;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* cmd_op — a thin Node.js shell over cmd_op's resident pipe.
|
|
4
|
+
*
|
|
5
|
+
* Node port of sdk/python/cmd_op.py. Same one job: forward a command to the
|
|
6
|
+
* running resident over its named pipe and hand back the response. There is NO
|
|
7
|
+
* second vocabulary: a command is the same object you'd put in an cmd_op
|
|
8
|
+
* `batch` list — e.g. {command:"set", path:"/Sheet1/A1", props:{text:"Hello"}}.
|
|
9
|
+
* `send` forwards one; `batch` forwards many in a single round-trip.
|
|
10
|
+
*
|
|
11
|
+
* Two surfaces, by design:
|
|
12
|
+
* - bootstrap (infrequent): create() / open() spawn ONE CLI process — a file
|
|
13
|
+
* that isn't open yet has no resident to talk to.
|
|
14
|
+
* - everything else (the hot path): send() / batch() are pure pipe
|
|
15
|
+
* round-trips, no per-command process spawn.
|
|
16
|
+
*
|
|
17
|
+
* const oc = require('cmd-op-sdk');
|
|
18
|
+
* const doc = await oc.create('report.xlsx', ['--force']);
|
|
19
|
+
* try {
|
|
20
|
+
* await doc.send({ command: 'set', path: '/Sheet1/A1', props: { text: 'Hello' } });
|
|
21
|
+
* console.log(await doc.send({ command: 'get', path: '/Sheet1/A1' }));
|
|
22
|
+
* } finally {
|
|
23
|
+
* await doc.close();
|
|
24
|
+
* }
|
|
25
|
+
* // or `await using doc = await oc.open('existing.xlsx')` on Node >= 24.
|
|
26
|
+
*
|
|
27
|
+
* Protocol (matches ResidentServer.cs / ResidentClient.cs):
|
|
28
|
+
* - pipe name : cmd_op-<SHA256(fullpath)[:16] uppercase>;
|
|
29
|
+
* fullpath upper-cased on macOS/Windows, left as-is on Linux.
|
|
30
|
+
* - unix path : $TMPDIR/CoreFxPipe_<name> (+ "-ping"); $TMPDIR else /tmp
|
|
31
|
+
* - win path : \\.\pipe\<name> (+ "-ping")
|
|
32
|
+
* - framing : one request line + one response line, UTF-8, '\n' terminated;
|
|
33
|
+
* one connection == one command. The reply may carry a UTF-8 BOM
|
|
34
|
+
* (unix StreamWriter) and a trailing '\r' — both stripped here.
|
|
35
|
+
* - request : PascalCase {"Command","Args","Props","Json"}
|
|
36
|
+
* - response : {"ExitCode","Stdout","Stderr"}
|
|
37
|
+
*/
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.Document = exports.CmdOpError = void 0;
|
|
40
|
+
exports.pipePaths = pipePaths;
|
|
41
|
+
exports.create = create;
|
|
42
|
+
exports.open = open;
|
|
43
|
+
exports.install = install;
|
|
44
|
+
const os = require("node:os");
|
|
45
|
+
const net = require("node:net");
|
|
46
|
+
const path = require("node:path");
|
|
47
|
+
const fs = require("node:fs");
|
|
48
|
+
const crypto = require("node:crypto");
|
|
49
|
+
const node_child_process_1 = require("node:child_process");
|
|
50
|
+
const IS_WIN = process.platform === 'win32';
|
|
51
|
+
const IS_MAC = process.platform === 'darwin';
|
|
52
|
+
// Mirror cmd_op's TryResident busy-delivery policy (CommandBuilder.cs): a
|
|
53
|
+
// generous connect timeout + a few retries with backoff, applied identically to
|
|
54
|
+
// every command. The reply read itself blocks (no timeout) — like cmd_op's
|
|
55
|
+
// PipeReadLine — trusting the resident to answer once our turn comes up in its
|
|
56
|
+
// serialized queue. Retries only re-attempt the CONNECT (before the command
|
|
57
|
+
// executes), so re-sending is safe even for mutations: there is no "read timed
|
|
58
|
+
// out, resend" path that could double-apply.
|
|
59
|
+
const BUSY_CONNECT_TIMEOUT_MS = 30000; // = ResidentBusyConnectTimeoutMs
|
|
60
|
+
const BUSY_MAX_RETRIES = 3; // = ResidentBusyMaxRetries
|
|
61
|
+
// = CommandBuilder's DefaultOpenIdleSeconds. open() upgrades a reused resident
|
|
62
|
+
// (which create() may have auto-started with a short 60s timeout) to the 12min
|
|
63
|
+
// interactive window, so a long session over an SDK handle isn't cut short.
|
|
64
|
+
const OPEN_IDLE_SECONDS = 12 * 60;
|
|
65
|
+
// Installer scripts: GitHub raw is the only source. There is no project
|
|
66
|
+
// mirror — install.sh and the npm installer both resolve releases from the
|
|
67
|
+
// same repository, so there is nothing else to fall back to.
|
|
68
|
+
const INSTALL_SH_URL = 'https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh';
|
|
69
|
+
const INSTALL_PS1_URL = 'https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1';
|
|
70
|
+
const MISSING_CLI = "cmd_op CLI not found: {bin} is not on PATH nor in the default install " +
|
|
71
|
+
'location (~/.local/bin, or %LOCALAPPDATA%\\cmd_op on Windows). This SDK only ' +
|
|
72
|
+
'forwards commands to the cmd_op binary, which must be installed separately. Install it:\n' +
|
|
73
|
+
' node -e "require(\'cmd-op-sdk\').install()" # runs the official installer\n' +
|
|
74
|
+
' # or: curl -fsSL ' + INSTALL_SH_URL + ' | bash\n' +
|
|
75
|
+
' # or install the npm wrapper: npm i -g cmd_op\n' +
|
|
76
|
+
'Already installed elsewhere? pass { binary: "/path/to/cmd_op" }.';
|
|
77
|
+
/**
|
|
78
|
+
* Raised on transport/process failure (could not reach the resident). Business
|
|
79
|
+
* outcomes are NOT exceptions — they live in the returned envelope's `success`
|
|
80
|
+
* field, same as the CLI's exit code.
|
|
81
|
+
*/
|
|
82
|
+
class CmdOpError extends Error {
|
|
83
|
+
code;
|
|
84
|
+
constructor(code, msg) {
|
|
85
|
+
super(`[exit ${code}] ${msg}`);
|
|
86
|
+
this.name = 'CmdOpError';
|
|
87
|
+
this.code = code;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
exports.CmdOpError = CmdOpError;
|
|
91
|
+
function errMessage(e) {
|
|
92
|
+
return e instanceof Error ? e.message : String(e);
|
|
93
|
+
}
|
|
94
|
+
// ---------------------------------------------------------------- pipe address
|
|
95
|
+
function dotnetTempDir() {
|
|
96
|
+
// Mirror .NET Path.GetTempPath() on Unix exactly: $TMPDIR else /tmp.
|
|
97
|
+
return process.env.TMPDIR || '/tmp';
|
|
98
|
+
}
|
|
99
|
+
// Match the path cmd_op's resident hashes into the pipe name. On Windows it
|
|
100
|
+
// derives the name from GetFullPath, which expands 8.3 short components (e.g.
|
|
101
|
+
// RUNNER~1, or any user name > 8 chars under %TEMP%) to their long form.
|
|
102
|
+
// path.resolve does NOT expand 8.3, so a short path would hash to a different
|
|
103
|
+
// pipe and every connect fails with ENOENT — hence realpath, which does expand
|
|
104
|
+
// it. realpath needs the file to exist; fall back to the resolved path when it
|
|
105
|
+
// doesn't (e.g. pre-create). realpath ALSO resolves symlinks/junctions, which
|
|
106
|
+
// GetFullPath does not; harmless here because we hand this resolved path to the
|
|
107
|
+
// resident, so the server's GetFullPath sees the already-resolved string and
|
|
108
|
+
// both sides hash the same thing. Windows only — on Linux/macOS cmd_op uses
|
|
109
|
+
// GetFullPath (no symlink resolution), so realpath would diverge there
|
|
110
|
+
// (e.g. /tmp → /private/tmp on macOS).
|
|
111
|
+
function canonicalPath(filePath) {
|
|
112
|
+
const resolved = path.resolve(filePath);
|
|
113
|
+
if (IS_WIN) {
|
|
114
|
+
try {
|
|
115
|
+
return fs.realpathSync.native(resolved);
|
|
116
|
+
}
|
|
117
|
+
catch { /* not there yet */ }
|
|
118
|
+
}
|
|
119
|
+
return resolved;
|
|
120
|
+
}
|
|
121
|
+
/** [main, ping] pipe addresses for a document path. Exposed for debugging. */
|
|
122
|
+
function pipePaths(filePath) {
|
|
123
|
+
let full = canonicalPath(filePath);
|
|
124
|
+
if (IS_MAC || IS_WIN)
|
|
125
|
+
full = full.toUpperCase(); // Linux: case-sensitive, no upper
|
|
126
|
+
const h = crypto.createHash('sha256').update(full, 'utf8').digest('hex').toUpperCase().slice(0, 16);
|
|
127
|
+
const name = `cmd_op-${h}`;
|
|
128
|
+
if (IS_WIN)
|
|
129
|
+
return [`\\\\.\\pipe\\${name}`, `\\\\.\\pipe\\${name}-ping`];
|
|
130
|
+
const base = path.join(dotnetTempDir(), `CoreFxPipe_${name}`);
|
|
131
|
+
return [base, base + '-ping'];
|
|
132
|
+
}
|
|
133
|
+
// ---------------------------------------------------------------- transport
|
|
134
|
+
function sleep(ms) {
|
|
135
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
136
|
+
}
|
|
137
|
+
// One attempt: bound the CONNECT, then block on the reply (no read timeout) —
|
|
138
|
+
// exactly like cmd_op's TrySend (Connect(timeout) + blocking PipeReadLine).
|
|
139
|
+
function sendOnce(sockPath, line, connectTimeoutMs) {
|
|
140
|
+
return new Promise((resolve, reject) => {
|
|
141
|
+
let settled = false;
|
|
142
|
+
const chunks = [];
|
|
143
|
+
const socket = net.createConnection(sockPath);
|
|
144
|
+
const connTimer = setTimeout(() => {
|
|
145
|
+
if (settled)
|
|
146
|
+
return;
|
|
147
|
+
settled = true;
|
|
148
|
+
socket.destroy();
|
|
149
|
+
reject(new Error(`connect timed out after ${connectTimeoutMs}ms`));
|
|
150
|
+
}, connectTimeoutMs);
|
|
151
|
+
const fail = (err) => {
|
|
152
|
+
if (settled)
|
|
153
|
+
return;
|
|
154
|
+
settled = true;
|
|
155
|
+
clearTimeout(connTimer);
|
|
156
|
+
socket.destroy();
|
|
157
|
+
reject(err);
|
|
158
|
+
};
|
|
159
|
+
socket.once('connect', () => {
|
|
160
|
+
clearTimeout(connTimer); // connected: stop bounding; reply read blocks
|
|
161
|
+
socket.write(line);
|
|
162
|
+
});
|
|
163
|
+
socket.on('data', (d) => {
|
|
164
|
+
chunks.push(d);
|
|
165
|
+
// Line protocol: the reply is one '\n'-terminated line.
|
|
166
|
+
if (d.length && d[d.length - 1] === 0x0a) {
|
|
167
|
+
if (settled)
|
|
168
|
+
return;
|
|
169
|
+
settled = true;
|
|
170
|
+
clearTimeout(connTimer);
|
|
171
|
+
socket.end();
|
|
172
|
+
resolve(Buffer.concat(chunks));
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
socket.once('end', () => {
|
|
176
|
+
if (settled)
|
|
177
|
+
return;
|
|
178
|
+
settled = true;
|
|
179
|
+
clearTimeout(connTimer);
|
|
180
|
+
resolve(Buffer.concat(chunks));
|
|
181
|
+
});
|
|
182
|
+
socket.once('error', fail);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
function decodeLine(raw) {
|
|
186
|
+
let text = raw.toString('utf8');
|
|
187
|
+
if (text.charCodeAt(0) === 0xfeff)
|
|
188
|
+
text = text.slice(1); // strip UTF-8 BOM (unix StreamWriter)
|
|
189
|
+
if (text.charCodeAt(text.length - 1) === 0x0a)
|
|
190
|
+
text = text.slice(0, -1); // drop the '\n' terminator
|
|
191
|
+
if (text.charCodeAt(text.length - 1) === 0x0d)
|
|
192
|
+
text = text.slice(0, -1); // and a trailing '\r'
|
|
193
|
+
return text;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Forward one request, mirroring cmd_op's TrySend: bounded connect + a few
|
|
197
|
+
* retries with backoff, then a blocking read. A retry only re-attempts the
|
|
198
|
+
* connect (before the command runs), so it never double-applies a mutation. If
|
|
199
|
+
* the command still can't be delivered, raise a busy/unresponsive error — never
|
|
200
|
+
* fall back to touching the file directly (that would race the resident).
|
|
201
|
+
*
|
|
202
|
+
* `maxRetries` overrides the busy-retry count. Liveness probes (serves) pass 0
|
|
203
|
+
* so a missing/stale pipe fails FAST instead of sleeping through the backoff.
|
|
204
|
+
*/
|
|
205
|
+
async function rpc(sockPath, req, connectTimeoutMs = BUSY_CONNECT_TIMEOUT_MS, maxRetries = BUSY_MAX_RETRIES) {
|
|
206
|
+
const line = Buffer.from(JSON.stringify(req) + '\n', 'utf8');
|
|
207
|
+
let raw = null;
|
|
208
|
+
for (let attempt = 0;; attempt++) {
|
|
209
|
+
try {
|
|
210
|
+
raw = await sendOnce(sockPath, line, connectTimeoutMs);
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
catch (e) {
|
|
214
|
+
// Connect/socket error only — the command never ran, so a retry is safe.
|
|
215
|
+
if (attempt >= maxRetries) {
|
|
216
|
+
throw new CmdOpError(-1, 'resident is running but the command could not be delivered ' +
|
|
217
|
+
`(pipe busy or unresponsive); retry, or close and reopen [${errMessage(e)}]`);
|
|
218
|
+
}
|
|
219
|
+
await sleep(50 * (attempt + 1)); // = TrySend's 50*(n+1)ms backoff
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const text = decodeLine(raw);
|
|
223
|
+
if (!text.trim()) {
|
|
224
|
+
// Empty/closed reply: the resident accepted the connection but closed
|
|
225
|
+
// without a complete response (e.g. crashed mid-serve). We refuse to
|
|
226
|
+
// re-send — the command may already have been APPLIED before the resident
|
|
227
|
+
// died, so re-sending would double-apply a non-idempotent op — and raise
|
|
228
|
+
// instead. _cmd's recovery then restarts a dead resident and retries once.
|
|
229
|
+
throw new CmdOpError(-1, 'resident closed the connection without a response ' +
|
|
230
|
+
'(it may have crashed mid-command); retry, or close and reopen');
|
|
231
|
+
}
|
|
232
|
+
return JSON.parse(text);
|
|
233
|
+
}
|
|
234
|
+
function parseEnvelope(resp) {
|
|
235
|
+
// Return the useful payload: the parsed JSON envelope (object/array) if Stdout
|
|
236
|
+
// is JSON, otherwise the raw Stdout text ("" when empty). Accept ONLY
|
|
237
|
+
// object/array — a bare JSON scalar ("42", "true", "null", a quoted string)
|
|
238
|
+
// stays text, or the caller can't tell literal text "42" from the number 42.
|
|
239
|
+
const out = resp.Stdout || '';
|
|
240
|
+
let v;
|
|
241
|
+
try {
|
|
242
|
+
v = JSON.parse(out);
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
247
|
+
return typeof v === 'object' && v !== null ? v : out;
|
|
248
|
+
}
|
|
249
|
+
function strMap(o) {
|
|
250
|
+
// Drop null/undefined values (omit), and stringify the rest — the resident's
|
|
251
|
+
// Args/Props are Dictionary<string,string>. A value set to null means "don't
|
|
252
|
+
// send it", not "send empty string"; pass "" for an explicit empty value.
|
|
253
|
+
const r = {};
|
|
254
|
+
for (const k of Object.keys(o)) {
|
|
255
|
+
const v = o[k];
|
|
256
|
+
if (v !== null && v !== undefined)
|
|
257
|
+
r[k] = String(v);
|
|
258
|
+
}
|
|
259
|
+
return r;
|
|
260
|
+
}
|
|
261
|
+
async function serves(pingPath, fullPath, timeoutMs = 1000) {
|
|
262
|
+
// Is a resident alive on `pingPath` AND serving `fullPath`? Probes the
|
|
263
|
+
// always-responsive `-ping` pipe (cmd_op's TryConnect): it answers even
|
|
264
|
+
// while the MAIN pipe is busy. Single-shot (maxRetries=0): a probe should fail
|
|
265
|
+
// fast, not sit through the busy-retry backoff.
|
|
266
|
+
let resp;
|
|
267
|
+
try {
|
|
268
|
+
resp = await rpc(pingPath, { Command: '__ping__' }, timeoutMs, 0);
|
|
269
|
+
}
|
|
270
|
+
catch (e) {
|
|
271
|
+
if (e instanceof CmdOpError)
|
|
272
|
+
return false;
|
|
273
|
+
throw e;
|
|
274
|
+
}
|
|
275
|
+
const served = (resp.Stdout || '').trim(); // ping echoes the served path
|
|
276
|
+
if (!served)
|
|
277
|
+
return false;
|
|
278
|
+
const a = path.resolve(served);
|
|
279
|
+
return a === fullPath || ((IS_MAC || IS_WIN) && a.toLowerCase() === fullPath.toLowerCase());
|
|
280
|
+
}
|
|
281
|
+
// ---------------------------------------------------------------- binary resolution
|
|
282
|
+
function installDirCandidate(name) {
|
|
283
|
+
// Where install.sh / install.ps1 drop the binary: ~/.local/bin on macOS/Linux,
|
|
284
|
+
// %LOCALAPPDATA%\cmd_op on Windows. PATH-miss fallback only.
|
|
285
|
+
if (IS_WIN) {
|
|
286
|
+
const base = process.env.LOCALAPPDATA;
|
|
287
|
+
if (!base)
|
|
288
|
+
return null;
|
|
289
|
+
const exe = name.toLowerCase().endsWith('.exe') ? name : name + '.exe';
|
|
290
|
+
return path.join(base, 'cmd_op', exe);
|
|
291
|
+
}
|
|
292
|
+
return path.join(os.homedir(), '.local', 'bin', name);
|
|
293
|
+
}
|
|
294
|
+
function whichOnPath(name) {
|
|
295
|
+
const dirs = (process.env.PATH || '').split(path.delimiter);
|
|
296
|
+
const cands = IS_WIN ? [name, name + '.exe', name + '.cmd'] : [name];
|
|
297
|
+
for (const dir of dirs) {
|
|
298
|
+
if (!dir)
|
|
299
|
+
continue;
|
|
300
|
+
for (const c of cands) {
|
|
301
|
+
const p = path.join(dir, c);
|
|
302
|
+
try {
|
|
303
|
+
fs.accessSync(p, fs.constants.X_OK);
|
|
304
|
+
return p;
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
/* keep looking */
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
function loadInstaller() {
|
|
314
|
+
try {
|
|
315
|
+
return require('cmd_op');
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function bundledBinary() {
|
|
322
|
+
// If the cmd_op installer package is installed (it is a
|
|
323
|
+
// dependency), prefer its vendored, auto-updating binary. Returns the path if
|
|
324
|
+
// it is present on disk, else null. require is wrapped so the SDK still works
|
|
325
|
+
// as a pure thin client when the dependency was omitted.
|
|
326
|
+
try {
|
|
327
|
+
const cli = loadInstaller();
|
|
328
|
+
if (!cli)
|
|
329
|
+
return null;
|
|
330
|
+
const p = cli.binaryPath();
|
|
331
|
+
return fs.existsSync(p) ? p : null;
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function resolveBinary(binary) {
|
|
338
|
+
// Order: explicit path (has a separator) is trusted as-is; then the bundled
|
|
339
|
+
// installer-package binary; then PATH; then the official installer's known
|
|
340
|
+
// location. Idempotent — an already-resolved absolute path passes through.
|
|
341
|
+
if (binary.includes(path.sep) || binary.includes('/'))
|
|
342
|
+
return binary;
|
|
343
|
+
if (binary === 'cmd_op') {
|
|
344
|
+
const bundled = bundledBinary();
|
|
345
|
+
if (bundled)
|
|
346
|
+
return bundled;
|
|
347
|
+
}
|
|
348
|
+
const found = whichOnPath(binary);
|
|
349
|
+
if (found)
|
|
350
|
+
return found;
|
|
351
|
+
const cand = installDirCandidate(binary);
|
|
352
|
+
if (cand) {
|
|
353
|
+
try {
|
|
354
|
+
fs.accessSync(cand, fs.constants.X_OK);
|
|
355
|
+
return cand;
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
/* fall through */
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return binary; // give up; runCli raises the helpful error
|
|
362
|
+
}
|
|
363
|
+
async function ensureCliBinary(binary, autoInstall) {
|
|
364
|
+
// Async binary resolution for the entry points (open/create), able to ACTIVELY
|
|
365
|
+
// provision a missing CLI. Order: explicit path is trusted as-is; then the
|
|
366
|
+
// bundled installer package (download its binary if not yet present — this is
|
|
367
|
+
// the package's own signed download, not a surprise); then PATH; then the
|
|
368
|
+
// installer's known location; finally, if autoInstall, run the official
|
|
369
|
+
// install.sh. Returns the resolved path (or the bare name, so runCli raises
|
|
370
|
+
// the helpful MISSING_CLI error if everything failed).
|
|
371
|
+
if (binary.includes(path.sep) || binary.includes('/'))
|
|
372
|
+
return binary; // explicit: trust caller
|
|
373
|
+
// Accept the first candidate that actually RUNS (`--version` exit 0), in
|
|
374
|
+
// priority order: the bundled (auto-updating) binary, then PATH, then the
|
|
375
|
+
// installer's known location. Probing — not mere file existence — means a
|
|
376
|
+
// present-but-broken binary is skipped, and a working cmd_op is never
|
|
377
|
+
// shadowed by a needless install.
|
|
378
|
+
const candidates = [];
|
|
379
|
+
if (binary === 'cmd_op') {
|
|
380
|
+
try {
|
|
381
|
+
const cli = loadInstaller();
|
|
382
|
+
if (cli) {
|
|
383
|
+
const p = cli.binaryPath();
|
|
384
|
+
if (fs.existsSync(p))
|
|
385
|
+
candidates.push(p);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
catch { /* dependency absent */ }
|
|
389
|
+
}
|
|
390
|
+
const onPath = whichOnPath(binary);
|
|
391
|
+
if (onPath)
|
|
392
|
+
candidates.push(onPath);
|
|
393
|
+
const cand = installDirCandidate(binary);
|
|
394
|
+
if (cand)
|
|
395
|
+
candidates.push(cand);
|
|
396
|
+
for (const c of candidates) {
|
|
397
|
+
if (probeVersion(c))
|
|
398
|
+
return c;
|
|
399
|
+
}
|
|
400
|
+
// Nothing usable found anywhere — provision it (only for the default name).
|
|
401
|
+
if (autoInstall && binary === 'cmd_op') {
|
|
402
|
+
process.stderr.write('[cmd_op] CLI not found — installing from GitHub …\n');
|
|
403
|
+
try {
|
|
404
|
+
const cli = loadInstaller();
|
|
405
|
+
if (cli) {
|
|
406
|
+
await cli.ensureBinary(); // bundled package's own signed download
|
|
407
|
+
const p = cli.binaryPath();
|
|
408
|
+
if (probeVersion(p))
|
|
409
|
+
return p;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
catch { /* fall through to the official installer */ }
|
|
413
|
+
install(); // install.sh (unix) / install.ps1 (Windows)
|
|
414
|
+
const after = installDirCandidate('cmd_op');
|
|
415
|
+
if (after && probeVersion(after))
|
|
416
|
+
return after;
|
|
417
|
+
}
|
|
418
|
+
return binary; // give up → runCli raises the helpful MISSING_CLI
|
|
419
|
+
}
|
|
420
|
+
// Quote one token for a cmd.exe command line: ALWAYS wrap in double quotes,
|
|
421
|
+
// doubling any embedded quote. Unconditional quoting (rather than "only when it
|
|
422
|
+
// looks dangerous") is deliberate — it removes any reliance on enumerating every
|
|
423
|
+
// cmd metacharacter. A double-quoted token cannot be re-tokenized by cmd.exe, so
|
|
424
|
+
// & | < > ^ ( ) " are inert, and a %VAR% expansion stays *inside* the quotes and
|
|
425
|
+
// thus can never inject a command separator (at worst the argument is mangled —
|
|
426
|
+
// there is no command-line escape for %, a documented cmd.exe limitation). This
|
|
427
|
+
// matters because the binary path / args may be untrusted when the SDK is driven
|
|
428
|
+
// by a server. cmd /s strips the outer wrapper, leaving these per-token quotes.
|
|
429
|
+
function quoteForCmd(s) {
|
|
430
|
+
return `"${String(s).replace(/"/g, '""')}"`;
|
|
431
|
+
}
|
|
432
|
+
function spawnCli(binary, argv, extraOpts = {}) {
|
|
433
|
+
let cmd = binary;
|
|
434
|
+
let args = argv;
|
|
435
|
+
const opts = { encoding: 'utf8', ...extraOpts };
|
|
436
|
+
if (IS_WIN && /\.(cmd|bat)$/i.test(binary)) {
|
|
437
|
+
// Node refuses to spawn a .cmd/.bat directly without a shell since
|
|
438
|
+
// CVE-2024-27980 (raises EINVAL). Run it through cmd.exe ourselves,
|
|
439
|
+
// quoting each token so paths with spaces survive — shell:true would
|
|
440
|
+
// join the args unquoted and break on the first space. Mirrors Node's
|
|
441
|
+
// own shell idiom (cmd /d /s /c "<line>" + windowsVerbatimArguments)
|
|
442
|
+
// but with the per-token quoting shell:true omits.
|
|
443
|
+
const line = [binary, ...argv].map(quoteForCmd).join(' ');
|
|
444
|
+
cmd = process.env.ComSpec || 'cmd.exe';
|
|
445
|
+
args = ['/d', '/s', '/c', `"${line}"`];
|
|
446
|
+
opts.windowsVerbatimArguments = true;
|
|
447
|
+
}
|
|
448
|
+
return (0, node_child_process_1.spawnSync)(cmd, args, opts);
|
|
449
|
+
}
|
|
450
|
+
function runCli(binary, argv) {
|
|
451
|
+
const r = spawnCli(binary, argv);
|
|
452
|
+
if (r.error && r.error.code === 'ENOENT') {
|
|
453
|
+
throw new CmdOpError(127, MISSING_CLI.replace('{bin}', JSON.stringify(binary)));
|
|
454
|
+
}
|
|
455
|
+
if (r.error)
|
|
456
|
+
throw new CmdOpError(-1, r.error.message);
|
|
457
|
+
return r;
|
|
458
|
+
}
|
|
459
|
+
// Probe a resolved binary by running `<binary> --version`: true iff it actually
|
|
460
|
+
// runs and exits 0. We accept only a WORKING cmd_op — a present-but-broken
|
|
461
|
+
// file (wrong arch, stale/again-renamed shim, corrupt download) must not be
|
|
462
|
+
// used, and conversely a working cmd_op on PATH must not be shadowed by a
|
|
463
|
+
// needless auto-install. Output is discarded.
|
|
464
|
+
function probeVersion(binPath) {
|
|
465
|
+
const r = spawnCli(binPath, ['--version'], { stdio: ['ignore', 'ignore', 'ignore'] });
|
|
466
|
+
return !r.error && r.status === 0;
|
|
467
|
+
}
|
|
468
|
+
// ---------------------------------------------------------------- the shell
|
|
469
|
+
/** A live handle to a resident serving one document. */
|
|
470
|
+
class Document {
|
|
471
|
+
path;
|
|
472
|
+
bin;
|
|
473
|
+
timeout;
|
|
474
|
+
_main;
|
|
475
|
+
_ping;
|
|
476
|
+
_restarting;
|
|
477
|
+
constructor(filePath, binary = 'cmd_op', timeoutMs = 30000) {
|
|
478
|
+
// Canonical (Windows 8.3-expanded) so the pipe name AND the serves() path
|
|
479
|
+
// comparison both match what the resident reports.
|
|
480
|
+
this.path = canonicalPath(filePath);
|
|
481
|
+
this.bin = resolveBinary(binary);
|
|
482
|
+
this.timeout = timeoutMs; // connect timeout (ms); the reply read blocks
|
|
483
|
+
const [main, ping] = pipePaths(this.path);
|
|
484
|
+
this._main = main;
|
|
485
|
+
this._ping = ping;
|
|
486
|
+
this._restarting = null; // in-flight dead-resident restart (serializes callers)
|
|
487
|
+
}
|
|
488
|
+
/** @internal */
|
|
489
|
+
async _start() {
|
|
490
|
+
// Reuse a resident already serving this file (no spawn). serves() is a real
|
|
491
|
+
// liveness probe (ping + path match), so a stale/dead socket falls through
|
|
492
|
+
// to `cmd_op open`, which replaces it via TryConnect.
|
|
493
|
+
if (await serves(this._ping, this.path))
|
|
494
|
+
return;
|
|
495
|
+
const r = runCli(this.bin, ['open', this.path]);
|
|
496
|
+
if (r.status !== 0)
|
|
497
|
+
throw new CmdOpError(r.status == null ? -1 : r.status, r.stderr || r.stdout);
|
|
498
|
+
}
|
|
499
|
+
async _cmd(command, args, props, asJson = true, timeoutMs) {
|
|
500
|
+
const req = { Command: command, Json: asJson };
|
|
501
|
+
if (args)
|
|
502
|
+
req.Args = strMap(args);
|
|
503
|
+
if (props !== null && props !== undefined)
|
|
504
|
+
req.Props = strMap(props);
|
|
505
|
+
const t = timeoutMs == null ? this.timeout : timeoutMs;
|
|
506
|
+
try {
|
|
507
|
+
return await rpc(this._main, req, t, BUSY_MAX_RETRIES);
|
|
508
|
+
}
|
|
509
|
+
catch (e) {
|
|
510
|
+
if (!(e instanceof CmdOpError))
|
|
511
|
+
throw e;
|
|
512
|
+
// Delivery failed. Use the -ping pipe to tell DEAD from BUSY:
|
|
513
|
+
// • ALIVE but main pipe unresponsive → do NOT bypass it (a second writer
|
|
514
|
+
// racing the live resident loses data on its save). Re-raise.
|
|
515
|
+
// • DEAD (crashed / stale socket) → restart with one `cmd_op open`
|
|
516
|
+
// and retry ONCE. Safe across reads and mutations.
|
|
517
|
+
if (await this.alive())
|
|
518
|
+
throw e;
|
|
519
|
+
// Serialize the restart across concurrent callers sharing this Document so
|
|
520
|
+
// only one spawns `cmd_op open` (else N-1 orphaned residents race saves).
|
|
521
|
+
if (!this._restarting) {
|
|
522
|
+
this._restarting = (async () => {
|
|
523
|
+
if (!(await this.alive()))
|
|
524
|
+
await this._start();
|
|
525
|
+
})().finally(() => {
|
|
526
|
+
this._restarting = null;
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
await this._restarting;
|
|
530
|
+
return await rpc(this._main, req, t, BUSY_MAX_RETRIES);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Forward ONE command in cmd_op's batch-item shape and return its parsed
|
|
535
|
+
* result (the JSON envelope, or raw text for content commands). `item` is
|
|
536
|
+
* exactly an object you'd put in a `batch` list:
|
|
537
|
+
* { command: 'set', path: '/Sheet1/A1', props: { text: 'hi' } }
|
|
538
|
+
* `command` (or `op`) picks the command, `props` becomes the property map, and
|
|
539
|
+
* every other key is forwarded verbatim as a command argument. asJson=false
|
|
540
|
+
* requests plain-text output (view/raw/dump), mirroring the CLI's --json.
|
|
541
|
+
*/
|
|
542
|
+
async send(item, asJson = true, timeoutMs) {
|
|
543
|
+
const command = item.command || item.op;
|
|
544
|
+
if (!command)
|
|
545
|
+
throw new CmdOpError(-1, "send(item): item needs a 'command' (or 'op') key");
|
|
546
|
+
const args = {};
|
|
547
|
+
for (const k of Object.keys(item)) {
|
|
548
|
+
if (k !== 'command' && k !== 'op' && k !== 'props')
|
|
549
|
+
args[k] = item[k];
|
|
550
|
+
}
|
|
551
|
+
return parseEnvelope(await this._cmd(command, args, item.props, asJson, timeoutMs));
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Forward cmd_op's `batch`: apply a LIST of the same item objects as send()
|
|
555
|
+
* in ONE round-trip — the fast path for many writes.
|
|
556
|
+
*/
|
|
557
|
+
async batch(items, { force = true, stopOnError = false, timeoutMs } = {}) {
|
|
558
|
+
const args = { batchJson: JSON.stringify(items), force, stopOnError };
|
|
559
|
+
return parseEnvelope(await this._cmd('batch', args, undefined, true, timeoutMs));
|
|
560
|
+
}
|
|
561
|
+
// Best-effort idle-timeout upgrade over the always-responsive ping pipe.
|
|
562
|
+
// Mirrors ResidentClient.SendSetIdleTimeout: a failure is non-fatal — the
|
|
563
|
+
// resident keeps its original idle schedule. Single-shot (maxRetries=0).
|
|
564
|
+
/** @internal */
|
|
565
|
+
async _setIdleTimeout(seconds) {
|
|
566
|
+
try {
|
|
567
|
+
await rpc(this._ping, { Command: '__set-idle-timeout__', Args: { seconds: String(seconds) } }, this.timeout, 0);
|
|
568
|
+
}
|
|
569
|
+
catch (e) {
|
|
570
|
+
if (!(e instanceof CmdOpError))
|
|
571
|
+
throw e;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/** True iff a resident is alive AND serving this file (probes the -ping pipe). */
|
|
575
|
+
async alive(timeoutMs = 1000) {
|
|
576
|
+
return serves(this._ping, this.path, timeoutMs);
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* = `cmd_op close`: stop the resident. It flushes the in-memory doc to disk
|
|
580
|
+
* as it shuts down, so no separate save is needed. The resident acks AFTER
|
|
581
|
+
* shutting down, so a missing/empty ack still means "closed"; a real shutdown
|
|
582
|
+
* error is a non-empty response and surfaces through the return value.
|
|
583
|
+
*/
|
|
584
|
+
async close() {
|
|
585
|
+
try {
|
|
586
|
+
return parseEnvelope(await rpc(this._ping, { Command: '__close__' }, this.timeout));
|
|
587
|
+
}
|
|
588
|
+
catch (e) {
|
|
589
|
+
if (!(e instanceof CmdOpError))
|
|
590
|
+
throw e;
|
|
591
|
+
// Only swallow if the resident is actually gone. If it's still alive (ping
|
|
592
|
+
// momentarily unreachable), the close did NOT take effect — re-raise, or
|
|
593
|
+
// the caller wrongly believes the file is released.
|
|
594
|
+
if (await this.alive())
|
|
595
|
+
throw e;
|
|
596
|
+
return ''; // resident gone / ack lost — end state is "closed"
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async [Symbol.asyncDispose]() {
|
|
600
|
+
await this.close();
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
exports.Document = Document;
|
|
604
|
+
/**
|
|
605
|
+
* Create a blank Office document and return a live Document handle. Extra CLI
|
|
606
|
+
* flags pass through verbatim:
|
|
607
|
+
* await create('report.xlsx', ['--force']);
|
|
608
|
+
* await create('doc', ['--type', 'docx']);
|
|
609
|
+
* One CLI spawn (`cmd_op create`), which auto-starts a resident; the handle
|
|
610
|
+
* binds to THAT resident (no second spawn). Inherits cmd_op's semantics —
|
|
611
|
+
* file_locked (close it first) / file_exists (pass '--force').
|
|
612
|
+
*/
|
|
613
|
+
async function create(filePath, args = [], { binary = 'cmd_op', timeoutMs = 30000, autoInstall = true } = {}) {
|
|
614
|
+
const full = path.resolve(filePath);
|
|
615
|
+
const bin = await ensureCliBinary(binary, autoInstall);
|
|
616
|
+
const r = runCli(bin, ['create', full, ...args]);
|
|
617
|
+
if (r.status !== 0)
|
|
618
|
+
throw new CmdOpError(r.status == null ? -1 : r.status, r.stderr || r.stdout);
|
|
619
|
+
const doc = new Document(full, bin, timeoutMs);
|
|
620
|
+
await doc._start(); // create auto-started a resident; this finds it alive (no extra spawn)
|
|
621
|
+
return doc;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Open an EXISTING document and return a live Document handle. `cmd_op open`
|
|
625
|
+
* is idempotent: reuse a resident already serving this file or start one.
|
|
626
|
+
*
|
|
627
|
+
* Owner — `const d = await open(f); try { ... } finally { await d.close(); }`
|
|
628
|
+
* Borrow — `const d = await open(f); await d.send(...)` // leave it running
|
|
629
|
+
*
|
|
630
|
+
* Failure model (per send/batch): a DEAD resident is transparently restarted and
|
|
631
|
+
* the command retried once; an ALIVE-but-busy pipe raises CmdOpError (retry,
|
|
632
|
+
* or close() and reopen).
|
|
633
|
+
*/
|
|
634
|
+
async function open(filePath, { binary = 'cmd_op', timeoutMs = 30000, autoInstall = true } = {}) {
|
|
635
|
+
const bin = await ensureCliBinary(binary, autoInstall);
|
|
636
|
+
const doc = new Document(filePath, bin, timeoutMs);
|
|
637
|
+
await doc._start();
|
|
638
|
+
// Mirror CLI `open`: when reusing a resident create() auto-started with a
|
|
639
|
+
// short 60s timeout, upgrade it to the 12min interactive window. (If _start
|
|
640
|
+
// spawned `cmd_op open` instead, that path already set 12min; re-sending
|
|
641
|
+
// is idempotent.)
|
|
642
|
+
await doc._setIdleTimeout(OPEN_IDLE_SECONDS);
|
|
643
|
+
return doc;
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Install the cmd_op CLI binary via its OFFICIAL installer — explicit by
|
|
647
|
+
* design (this SDK never auto-downloads behind your back). Runs install.ps1 via
|
|
648
|
+
* PowerShell on Windows and install.sh via bash elsewhere. Note: when installed
|
|
649
|
+
* via npm, cmd_op already bundles an auto-updating binary, so this
|
|
650
|
+
* is only needed for a standalone (~/.local/bin or %LOCALAPPDATA%\cmd_op)
|
|
651
|
+
* install.
|
|
652
|
+
*/
|
|
653
|
+
function install() {
|
|
654
|
+
if (IS_WIN) {
|
|
655
|
+
process.stderr.write(`Installing cmd_op via ${INSTALL_PS1_URL} ...\n`);
|
|
656
|
+
// Fetch the script, then run it.
|
|
657
|
+
const ps = `$s = irm '${INSTALL_PS1_URL}'; $s | iex`;
|
|
658
|
+
const r = (0, node_child_process_1.spawnSync)('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ps], {
|
|
659
|
+
stdio: 'inherit',
|
|
660
|
+
});
|
|
661
|
+
if (r.status !== 0) {
|
|
662
|
+
throw new CmdOpError(r.status == null ? -1 : r.status, `cmd_op install failed. Run manually:\n irm ${INSTALL_PS1_URL} | iex`);
|
|
663
|
+
}
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
process.stderr.write(`Installing cmd_op via ${INSTALL_SH_URL} ...\n`);
|
|
667
|
+
// curl | bash — the script is the only source, no retry layer.
|
|
668
|
+
const sh = `curl -fsSL ${INSTALL_SH_URL} | bash`;
|
|
669
|
+
const r = (0, node_child_process_1.spawnSync)('bash', ['-c', sh], { stdio: 'inherit' });
|
|
670
|
+
if (r.status !== 0) {
|
|
671
|
+
throw new CmdOpError(r.status == null ? -1 : r.status, `cmd_op install failed. Run manually:\n curl -fsSL ${INSTALL_SH_URL} | bash`);
|
|
672
|
+
}
|
|
673
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cmd-op-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.3.2",
|
|
4
|
+
"description": "Node.js SDK for cmd_op — a thin async client over the cmd_op resident pipe (read/write .docx/.xlsx/.pptx).",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "karlmoriaty",
|
|
7
|
+
"homepage": "https://github.com/karlmoriaty/office-command-operate/tree/main/sdk/node",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/karlmoriaty/office-command-operate.git",
|
|
11
|
+
"directory": "sdk/node"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/karlmoriaty/office-command-operate/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"cmd_op",
|
|
18
|
+
"office",
|
|
19
|
+
"docx",
|
|
20
|
+
"xlsx",
|
|
21
|
+
"pptx",
|
|
22
|
+
"word",
|
|
23
|
+
"excel",
|
|
24
|
+
"powerpoint",
|
|
25
|
+
"ooxml",
|
|
26
|
+
"sdk",
|
|
27
|
+
"mcp",
|
|
28
|
+
"ai-agents",
|
|
29
|
+
"office-automation"
|
|
30
|
+
],
|
|
31
|
+
"main": "dist/index.js",
|
|
32
|
+
"types": "dist/index.d.ts",
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"require": "./dist/index.js",
|
|
37
|
+
"default": "./dist/index.js"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"dist/index.js",
|
|
42
|
+
"dist/index.d.ts",
|
|
43
|
+
"README.md"
|
|
44
|
+
],
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=18"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsc -p tsconfig.json",
|
|
50
|
+
"prepare": "npm run build",
|
|
51
|
+
"prepublishOnly": "npm run build",
|
|
52
|
+
"smoke": "node dist/smoke.js",
|
|
53
|
+
"demo": "node dist/demo.js"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"cmd_op": "^1.3.2"
|
|
58
|
+
},
|
|
59
|
+
"peerDependenciesMeta": {
|
|
60
|
+
"cmd_op": {
|
|
61
|
+
"optional": true
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"devDependencies": {
|
|
65
|
+
"@types/node": "^20.19.0",
|
|
66
|
+
"typescript": "^5.9.0"
|
|
67
|
+
}
|
|
68
|
+
}
|