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