loopzero-gateway-imessage 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/LICENSE +201 -0
- package/README.md +123 -2
- package/dist/index.cjs +364 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +183 -0
- package/dist/index.d.ts +183 -0
- package/dist/index.js +360 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var child_process = require('child_process');
|
|
4
|
+
var loopzeroGateway = require('loopzero-gateway');
|
|
5
|
+
|
|
6
|
+
// src/adapter.ts
|
|
7
|
+
|
|
8
|
+
// src/errors.ts
|
|
9
|
+
var OUTCOME_UNCERTAIN = -32001;
|
|
10
|
+
var SEND_LANE_BLOCKED = -32004;
|
|
11
|
+
function mapSendError(code, message2, data) {
|
|
12
|
+
if (code === SEND_LANE_BLOCKED) {
|
|
13
|
+
return { result: failure("imsg_send_lane_blocked", message2), endChild: true };
|
|
14
|
+
}
|
|
15
|
+
if (wasNotStarted(data)) return refused("imsg_not_sent", message2);
|
|
16
|
+
if (code === OUTCOME_UNCERTAIN) return refused("imsg_outcome_uncertain", message2);
|
|
17
|
+
return refused("imsg_error", message2);
|
|
18
|
+
}
|
|
19
|
+
function wasNotStarted(data) {
|
|
20
|
+
if (typeof data !== "object" || data === null) return false;
|
|
21
|
+
const fields = data;
|
|
22
|
+
return fields.state === "not_started" && fields.retry_safe === true;
|
|
23
|
+
}
|
|
24
|
+
function refused(code, message2) {
|
|
25
|
+
return { result: failure(code, message2), endChild: false };
|
|
26
|
+
}
|
|
27
|
+
function failure(code, message2) {
|
|
28
|
+
return { ok: false, error: { code, message: message2 } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/normalize.ts
|
|
32
|
+
function imessageRowToMessageEvent(row, receivedAt) {
|
|
33
|
+
if (row.is_from_me !== false) return void 0;
|
|
34
|
+
const { text, chat_id: chatId, guid, sender } = row;
|
|
35
|
+
if (typeof text !== "string" || text === "") return void 0;
|
|
36
|
+
if (typeof chatId !== "number" || typeof guid !== "string" || typeof sender !== "string") {
|
|
37
|
+
return void 0;
|
|
38
|
+
}
|
|
39
|
+
const isGroup = row.is_group === true;
|
|
40
|
+
return {
|
|
41
|
+
id: guid,
|
|
42
|
+
platform: "imessage",
|
|
43
|
+
sender: { id: sender },
|
|
44
|
+
channel: { id: String(chatId), type: isGroup ? "group" : "dm" },
|
|
45
|
+
text,
|
|
46
|
+
receivedAt,
|
|
47
|
+
imessage: { chatId, guid, isGroup, participants: row.participants ?? [], raw: row }
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/refuse-attachments.ts
|
|
52
|
+
function refuseAttachments(out) {
|
|
53
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
54
|
+
return {
|
|
55
|
+
ok: false,
|
|
56
|
+
error: { code: "attachments_unsupported", message: "imessage adapter cannot send attachments" }
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/adapter.ts
|
|
61
|
+
var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
|
|
62
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
63
|
+
var EXIT_GRACE_MS = 2e3;
|
|
64
|
+
var CHAT_ID = /^[1-9]\d*$/;
|
|
65
|
+
var LABEL = "gateway-imessage";
|
|
66
|
+
var defaultSpawn = (command, args) => child_process.spawn(command, [...args], { stdio: ["pipe", "pipe", "pipe"] });
|
|
67
|
+
var IMessageAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
68
|
+
platform = "imessage";
|
|
69
|
+
opts;
|
|
70
|
+
session;
|
|
71
|
+
handler;
|
|
72
|
+
connected = false;
|
|
73
|
+
warnedAboutHtml = false;
|
|
74
|
+
connecting;
|
|
75
|
+
/** The last row whose turn finished; a new subscription resumes after it. */
|
|
76
|
+
lastRowId;
|
|
77
|
+
/**
|
|
78
|
+
* Rows wait here for the one before them, across sessions: a row replayed by a new child waits
|
|
79
|
+
* for the old child's row still in its handler, then finds the cursor past it.
|
|
80
|
+
*/
|
|
81
|
+
rows = Promise.resolve();
|
|
82
|
+
constructor(opts) {
|
|
83
|
+
super();
|
|
84
|
+
this.opts = opts;
|
|
85
|
+
}
|
|
86
|
+
async connect() {
|
|
87
|
+
if (this.connected) return true;
|
|
88
|
+
this.connecting ??= this.openSession().finally(() => {
|
|
89
|
+
this.connecting = void 0;
|
|
90
|
+
});
|
|
91
|
+
return this.connecting;
|
|
92
|
+
}
|
|
93
|
+
async disconnect() {
|
|
94
|
+
const session = this.session;
|
|
95
|
+
if (session === void 0) return;
|
|
96
|
+
this.endSession(session);
|
|
97
|
+
await session.ended;
|
|
98
|
+
}
|
|
99
|
+
async sendMessage(out) {
|
|
100
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
101
|
+
}
|
|
102
|
+
async sendText(out) {
|
|
103
|
+
if (out.text.length === 0) {
|
|
104
|
+
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
105
|
+
}
|
|
106
|
+
const chatId = toChatId(out.channel.id);
|
|
107
|
+
if (chatId === void 0) {
|
|
108
|
+
return {
|
|
109
|
+
ok: false,
|
|
110
|
+
error: {
|
|
111
|
+
code: "invalid_chat_id",
|
|
112
|
+
message: `channel.id must be imsg's chat id, a positive integer, got "${out.channel.id}"`
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const session = this.session;
|
|
117
|
+
if (!this.connected || session === void 0) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
error: { code: "not_connected", message: "IMessageAdapter.connect() has not succeeded" }
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const outcome = await session.rpc.request(
|
|
124
|
+
"send",
|
|
125
|
+
{ chat_id: chatId, text: this.textFor(out) },
|
|
126
|
+
this.opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
|
|
127
|
+
);
|
|
128
|
+
return this.toSendResult(outcome, session);
|
|
129
|
+
}
|
|
130
|
+
onInbound(handler) {
|
|
131
|
+
this.handler = handler;
|
|
132
|
+
return () => {
|
|
133
|
+
if (this.handler === handler) {
|
|
134
|
+
this.handler = void 0;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Deliver an event that arrived out of band. One line over `runHandler`, which owns the
|
|
140
|
+
* containment of a throwing handler.
|
|
141
|
+
*/
|
|
142
|
+
async deliver(event) {
|
|
143
|
+
return this.runHandler(this.handler, event);
|
|
144
|
+
}
|
|
145
|
+
/** The text to send: markdown loses its markers, html goes as is with one warning. */
|
|
146
|
+
textFor(out) {
|
|
147
|
+
if (out.format === "markdown") return loopzeroGateway.channelRendering(this.platform).translate(out.text);
|
|
148
|
+
if (out.format === "html" && !this.warnedAboutHtml) {
|
|
149
|
+
this.warnedAboutHtml = true;
|
|
150
|
+
process.stderr.write(
|
|
151
|
+
`[${LABEL}] format="html" was declared and iMessage has no html mode; sending the text unchanged. Logged once.
|
|
152
|
+
`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
return out.text;
|
|
156
|
+
}
|
|
157
|
+
toSendResult(outcome, session) {
|
|
158
|
+
switch (outcome.kind) {
|
|
159
|
+
case "result":
|
|
160
|
+
return sentResult(outcome.result);
|
|
161
|
+
case "error": {
|
|
162
|
+
const mapped = mapSendError(outcome.code, outcome.message, outcome.data);
|
|
163
|
+
if (mapped.endChild) this.endSession(session);
|
|
164
|
+
return mapped.result;
|
|
165
|
+
}
|
|
166
|
+
case "timeout":
|
|
167
|
+
return {
|
|
168
|
+
ok: false,
|
|
169
|
+
error: { code: "timeout", message: "imsg did not answer the send in time" }
|
|
170
|
+
};
|
|
171
|
+
case "disconnected":
|
|
172
|
+
return {
|
|
173
|
+
ok: false,
|
|
174
|
+
error: { code: "transport_closed", message: "imsg ended before answering the send" }
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** Start imsg and subscribe; on any failure the child is ended and `false` returned. */
|
|
179
|
+
async openSession() {
|
|
180
|
+
const session = this.startChild();
|
|
181
|
+
if (session === void 0) return false;
|
|
182
|
+
const outcome = await session.rpc.request(
|
|
183
|
+
"watch.subscribe",
|
|
184
|
+
this.lastRowId === void 0 ? {} : { since_rowid: this.lastRowId },
|
|
185
|
+
this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS
|
|
186
|
+
);
|
|
187
|
+
if (outcome.kind === "result" && this.session === session) {
|
|
188
|
+
this.connected = true;
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
process.stderr.write(`[${LABEL}] connect failed: ${describe(outcome)}
|
|
192
|
+
`);
|
|
193
|
+
if (this.session === session) this.endSession(session);
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
/** Start imsg and attach the line client, or `undefined` when it cannot be started. */
|
|
197
|
+
startChild() {
|
|
198
|
+
const args = ["rpc", ...this.opts.dbPath === void 0 ? [] : ["--db", this.opts.dbPath]];
|
|
199
|
+
let child;
|
|
200
|
+
try {
|
|
201
|
+
child = (this.opts.spawn ?? defaultSpawn)(this.opts.cliPath ?? "imsg", args);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
process.stderr.write(`[${LABEL}] connect failed: could not start imsg: ${message(err)}
|
|
204
|
+
`);
|
|
205
|
+
return void 0;
|
|
206
|
+
}
|
|
207
|
+
const rpc = new loopzeroGateway.JsonRpcLineClient(
|
|
208
|
+
child,
|
|
209
|
+
LABEL,
|
|
210
|
+
(notification) => this.onNotification(session, notification),
|
|
211
|
+
(reason) => this.onChildClosed(session, reason)
|
|
212
|
+
);
|
|
213
|
+
const session = { child, rpc };
|
|
214
|
+
this.session = session;
|
|
215
|
+
return session;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* End a session: settle its pending requests, close imsg's stdin and give it `EXIT_GRACE_MS`
|
|
219
|
+
* to exit before `SIGTERM`. `session.ended` resolves once the child closed or was signalled.
|
|
220
|
+
* Idempotent.
|
|
221
|
+
*/
|
|
222
|
+
endSession(session) {
|
|
223
|
+
if (this.session === session) {
|
|
224
|
+
this.session = void 0;
|
|
225
|
+
this.connected = false;
|
|
226
|
+
}
|
|
227
|
+
if (session.ended !== void 0) return;
|
|
228
|
+
session.rpc.close("disconnected");
|
|
229
|
+
session.ended = new Promise((resolve) => {
|
|
230
|
+
const timer = setTimeout(() => {
|
|
231
|
+
session.child.kill("SIGTERM");
|
|
232
|
+
resolve();
|
|
233
|
+
}, EXIT_GRACE_MS);
|
|
234
|
+
timer.unref?.();
|
|
235
|
+
session.child.on("close", (code, signal) => {
|
|
236
|
+
clearTimeout(timer);
|
|
237
|
+
process.stderr.write(`[${LABEL}] imsg exited with ${signal ?? `code ${code}`}
|
|
238
|
+
`);
|
|
239
|
+
resolve();
|
|
240
|
+
});
|
|
241
|
+
session.child.stdin.end();
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
onChildClosed(session, reason) {
|
|
245
|
+
if (this.session !== session) return;
|
|
246
|
+
process.stderr.write(`[${LABEL}] imsg ${reason}
|
|
247
|
+
`);
|
|
248
|
+
this.session = void 0;
|
|
249
|
+
this.connected = false;
|
|
250
|
+
}
|
|
251
|
+
onNotification(session, notification) {
|
|
252
|
+
if (notification.method !== "message") return;
|
|
253
|
+
const row = notification.params?.message;
|
|
254
|
+
if (row === void 0) return;
|
|
255
|
+
this.rows = this.rows.then(() => this.handleRow(session, row)).catch((err) => {
|
|
256
|
+
process.stderr.write(`[${LABEL}] handler threw: ${message(err)}
|
|
257
|
+
`);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Hand one row to the handler, then move the cursor past it. A row that found no handler does
|
|
262
|
+
* not move the cursor; the next subscription asks for it again unless a later row of the same
|
|
263
|
+
* session was handled first and moved the cursor past both.
|
|
264
|
+
*/
|
|
265
|
+
async handleRow(session, row) {
|
|
266
|
+
if (this.session !== session) return;
|
|
267
|
+
const rowId = typeof row.id === "number" ? row.id : void 0;
|
|
268
|
+
if (rowId !== void 0 && this.lastRowId !== void 0 && rowId <= this.lastRowId) return;
|
|
269
|
+
const event = imessageRowToMessageEvent(row, Date.now());
|
|
270
|
+
const outcome = event === void 0 ? "ok" : await this.runHandler(this.handler, event);
|
|
271
|
+
if (rowId !== void 0 && outcome !== "no_handler") {
|
|
272
|
+
this.lastRowId = Math.max(rowId, this.lastRowId ?? rowId);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
function sentResult(result) {
|
|
277
|
+
const fields = typeof result === "object" && result !== null ? result : {};
|
|
278
|
+
if (typeof fields.guid === "string") return { ok: true, messageId: fields.guid };
|
|
279
|
+
if (typeof fields.id === "number") return { ok: true, messageId: String(fields.id) };
|
|
280
|
+
return { ok: true };
|
|
281
|
+
}
|
|
282
|
+
function toChatId(id) {
|
|
283
|
+
if (!CHAT_ID.test(id)) return void 0;
|
|
284
|
+
const chatId = Number(id);
|
|
285
|
+
return Number.isSafeInteger(chatId) ? chatId : void 0;
|
|
286
|
+
}
|
|
287
|
+
function describe(outcome) {
|
|
288
|
+
if (outcome.kind === "error")
|
|
289
|
+
return `watch.subscribe answered ${outcome.code}: ${outcome.message}`;
|
|
290
|
+
if (outcome.kind === "timeout") return "watch.subscribe was not answered in time";
|
|
291
|
+
return "imsg ended before answering watch.subscribe";
|
|
292
|
+
}
|
|
293
|
+
function message(err) {
|
|
294
|
+
return err instanceof Error ? err.message : String(err);
|
|
295
|
+
}
|
|
296
|
+
var { invalid, isAbsent, readString } = loopzeroGateway.channelConfigReaders("gateway-imessage");
|
|
297
|
+
function readNumber(config, key) {
|
|
298
|
+
const raw = config[key];
|
|
299
|
+
if (isAbsent(raw)) return void 0;
|
|
300
|
+
const value = typeof raw === "string" && /^\d+$/.test(raw.trim()) ? Number(raw) : raw;
|
|
301
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
302
|
+
throw invalid(key, "a number or a string of digits");
|
|
303
|
+
}
|
|
304
|
+
var CONFIG = [
|
|
305
|
+
{
|
|
306
|
+
key: "cliPath",
|
|
307
|
+
required: false,
|
|
308
|
+
secret: false,
|
|
309
|
+
env: "IMESSAGE_CLI_PATH",
|
|
310
|
+
description: "Path or name of the `imsg` binary; default `imsg` on PATH."
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
key: "dbPath",
|
|
314
|
+
required: false,
|
|
315
|
+
secret: false,
|
|
316
|
+
env: "IMESSAGE_DB_PATH",
|
|
317
|
+
description: "Messages database to read; default is `imsg`'s own."
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
key: "connectTimeoutMs",
|
|
321
|
+
required: false,
|
|
322
|
+
secret: false,
|
|
323
|
+
env: "IMESSAGE_CONNECT_TIMEOUT_MS",
|
|
324
|
+
description: "Milliseconds `connect()` waits for `imsg`; default 10000."
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
key: "requestTimeoutMs",
|
|
328
|
+
required: false,
|
|
329
|
+
secret: false,
|
|
330
|
+
env: "IMESSAGE_REQUEST_TIMEOUT_MS",
|
|
331
|
+
description: "Milliseconds a send may stay unanswered; default 30000."
|
|
332
|
+
}
|
|
333
|
+
];
|
|
334
|
+
var imessageChannel = {
|
|
335
|
+
platform: "imessage",
|
|
336
|
+
transport: "socket",
|
|
337
|
+
config: CONFIG,
|
|
338
|
+
create(config) {
|
|
339
|
+
if (process.platform !== "darwin") {
|
|
340
|
+
throw new loopzeroGateway.GatewayConfigurationError("gateway-imessage", {
|
|
341
|
+
code: "invalid_config",
|
|
342
|
+
message: `gateway-imessage: iMessage needs macOS (darwin); this platform is ${process.platform}`,
|
|
343
|
+
detail: "platform"
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
const cliPath = readString(config, "cliPath");
|
|
347
|
+
const dbPath = readString(config, "dbPath");
|
|
348
|
+
const connectTimeoutMs = readNumber(config, "connectTimeoutMs");
|
|
349
|
+
const requestTimeoutMs = readNumber(config, "requestTimeoutMs");
|
|
350
|
+
const options = {
|
|
351
|
+
...cliPath === void 0 ? {} : { cliPath },
|
|
352
|
+
...dbPath === void 0 ? {} : { dbPath },
|
|
353
|
+
...connectTimeoutMs === void 0 ? {} : { connectTimeoutMs },
|
|
354
|
+
...requestTimeoutMs === void 0 ? {} : { requestTimeoutMs }
|
|
355
|
+
};
|
|
356
|
+
return new IMessageAdapter(options);
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
exports.IMessageAdapter = IMessageAdapter;
|
|
361
|
+
exports.imessageChannel = imessageChannel;
|
|
362
|
+
exports.imessageRowToMessageEvent = imessageRowToMessageEvent;
|
|
363
|
+
//# sourceMappingURL=index.cjs.map
|
|
364
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/adapter.ts","../src/channel.ts"],"names":["message","nodeSpawn","BasePlatformAdapter","channelRendering","JsonRpcLineClient","channelConfigReaders","GatewayConfigurationError"],"mappings":";;;;;;;;AAaA,IAAM,iBAAA,GAAoB,MAAA;AAE1B,IAAM,iBAAA,GAAoB,MAAA;AAUnB,SAAS,YAAA,CAAa,IAAA,EAAcA,QAAAA,EAAiB,IAAA,EAAgC;AAE1F,EAAA,IAAI,SAAS,iBAAA,EAAmB;AAC9B,IAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,CAAQ,0BAA0BA,QAAO,CAAA,EAAG,UAAU,IAAA,EAAK;AAAA,EAC9E;AACA,EAAA,IAAI,cAAc,IAAI,CAAA,EAAG,OAAO,OAAA,CAAQ,iBAAiBA,QAAO,CAAA;AAChE,EAAA,IAAI,IAAA,KAAS,iBAAA,EAAm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AAAA,IACL,WAAA,EAAa;AAAA;AAEjB,CAAA;AAWO,IAAM,eAAA,GAAkB;AAAA,EAC7B,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAAiC;AACtC,IAAA,IAAI,OAAA,CAAQ,aAAa,QAAA,EAAU;AACjC,MAAA,MAAM,IAAIC,0CAA0B,kBAAA,EAAoB;AAAA,QACtD,IAAA,EAAM,gBAAA;AAAA,QACN,OAAA,EAAS,CAAA,kEAAA,EAAqE,OAAA,CAAQ,QAAQ,CAAA,CAAA;AAAA,QAC9F,MAAA,EAAQ;AAAA,OACT,CAAA;AAAA,IACH;AACA,IAAA,MAAM,OAAA,GAAU,UAAA,CAAW,MAAA,EAAQ,SAAS,CAAA;AAC5C,IAAA,MAAM,MAAA,GAAS,UAAA,CAAW,MAAA,EAAQ,QAAQ,CAAA;AAC1C,IAAA,MAAM,gBAAA,GAAmB,UAAA,CAAW,MAAA,EAAQ,kBAAkB,CAAA;AAC9D,IAAA,MAAM,gBAAA,GAAmB,UAAA,CAAW,MAAA,EAAQ,kBAAkB,CAAA;AAC9D,IAAA,MAAM,OAAA,GAAkC;AAAA,MACtC,GAAI,OAAA,KAAY,MAAA,GAAY,EAAC,GAAI,EAAE,OAAA,EAAQ;AAAA,MAC3C,GAAI,MAAA,KAAW,MAAA,GAAY,EAAC,GAAI,EAAE,MAAA,EAAO;AAAA,MACzC,GAAI,gBAAA,KAAqB,MAAA,GAAY,EAAC,GAAI,EAAE,gBAAA,EAAiB;AAAA,MAC7D,GAAI,gBAAA,KAAqB,MAAA,GAAY,EAAC,GAAI,EAAE,gBAAA;AAAiB,KAC/D;AACA,IAAA,OAAO,IAAI,gBAAgB,OAAO,CAAA;AAAA,EACpC;AACF","file":"index.cjs","sourcesContent":["/**\n * `imsg` send errors → `SendResult`, keeping what each one says about the message.\n *\n * The codes and the `data` shape are `imsg`'s own (its `docs/rpc.md` at `e07f914`, relayed by the\n * B-355 discovery). None of them is retried here: an uncertain send may already be on the\n * recipient's phone, and only the caller can decide whether a second copy is acceptable.\n *\n * @internal\n */\n\nimport type { SendResult } from \"loopzero-gateway\";\n\n/** The send may have completed; its receipt is missing. */\nconst OUTCOME_UNCERTAIN = -32001;\n/** The send lane is blocked after an earlier send stayed in flight; only a new child clears it. */\nconst SEND_LANE_BLOCKED = -32004;\n\n/** What the adapter must do after an error, beyond returning its result. */\nexport interface MappedSendError {\n readonly result: SendResult;\n /** True when the child can no longer send and must be ended. */\n readonly endChild: boolean;\n}\n\n/** Map one JSON-RPC error of a `send` request. */\nexport function mapSendError(code: number, message: string, data: unknown): MappedSendError {\n // A blocked lane comes first whatever its data says: the child must end either way.\n if (code === SEND_LANE_BLOCKED) {\n return { result: failure(\"imsg_send_lane_blocked\", message), endChild: true };\n }\n if (wasNotStarted(data)) return refused(\"imsg_not_sent\", message);\n if (code === OUTCOME_UNCERTAIN) return refused(\"imsg_outcome_uncertain\", message);\n return refused(\"imsg_error\", message);\n}\n\n/** `data: { state: \"not_started\", retry_safe: true }`: nothing was sent, so a retry is safe. */\nfunction wasNotStarted(data: unknown): boolean {\n if (typeof data !== \"object\" || data === null) return false;\n const fields = data as { state?: unknown; retry_safe?: unknown };\n return fields.state === \"not_started\" && fields.retry_safe === true;\n}\n\nfunction refused(code: string, message: string): MappedSendError {\n return { result: failure(code, message), endChild: false };\n}\n\nfunction failure(code: string, message: string): SendResult {\n return { ok: false, error: { code, message } };\n}\n","/**\n * `imsg` `message` notification → `IMessageMessageEvent`.\n *\n * @public\n */\n\nimport type { IMessageMessageEvent } from \"loopzero-gateway\";\n\n/** The fields of an `imsg` message row this package reads. Everything else stays in `raw`. */\nexport interface IMessageRow {\n /** The row id in the Messages database; the cursor `since_rowid` resumes after. */\n readonly id?: number;\n readonly chat_id?: number;\n readonly guid?: string;\n readonly sender?: string;\n readonly is_from_me?: boolean;\n readonly text?: string | null;\n readonly is_group?: boolean;\n readonly participants?: readonly string[];\n}\n\n/**\n * Build the event for one row, or `undefined` when the handler must not see it.\n *\n * A row the signed-in account sent (`is_from_me`), including the adapter's own replies, gives no\n * event, and neither does a row with no text (an attachment, a tapback) or with no chat or guid.\n *\n * @param row - the `params.message` of an `imsg` `message` notification\n * @param receivedAt - when the adapter read it, in ms since the epoch\n */\nexport function imessageRowToMessageEvent(\n row: IMessageRow,\n receivedAt: number,\n): IMessageMessageEvent | undefined {\n if (row.is_from_me !== false) return undefined;\n const { text, chat_id: chatId, guid, sender } = row;\n if (typeof text !== \"string\" || text === \"\") return undefined;\n if (typeof chatId !== \"number\" || typeof guid !== \"string\" || typeof sender !== \"string\") {\n return undefined;\n }\n const isGroup = row.is_group === true;\n return {\n id: guid,\n platform: \"imessage\",\n sender: { id: sender },\n channel: { id: String(chatId), type: isGroup ? \"group\" : \"dm\" },\n text,\n receivedAt,\n imessage: { chatId, guid, isGroup, participants: row.participants ?? [], raw: row },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `loopzero-gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"loopzero-gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"imessage adapter cannot send attachments\" },\n };\n}\n","/**\n * `IMessageAdapter` — `BasePlatformAdapter` over `imsg rpc`.\n *\n * The adapter owns one `imsg` child. Requests go out on its stdin, and responses and `message`\n * notifications come back on its stdout, one JSON line each. `imsg` sends as the account signed\n * in to Messages on its Mac, so the adapter carries no secret.\n *\n * @public\n */\n\nimport { spawn as nodeSpawn } from \"node:child_process\";\n\nimport {\n BasePlatformAdapter,\n channelRendering,\n type MessageEvent as GatewayMessageEvent,\n JsonRpcLineClient,\n type OutboundMessage,\n type RpcNotification,\n type RpcOutcome,\n type SendResult,\n} from \"loopzero-gateway\";\n\nimport { mapSendError } from \"./errors.js\";\nimport { type IMessageRow, imessageRowToMessageEvent } from \"./normalize.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport type { ChildLike, IMessageAdapterOptions, SpawnLike } from \"./types.js\";\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n/** How long `disconnect()` lets `imsg` end on its own after stdin closes, before `SIGTERM`. */\nconst EXIT_GRACE_MS = 2_000;\nconst CHAT_ID = /^[1-9]\\d*$/;\nconst LABEL = \"gateway-imessage\";\n\nconst defaultSpawn: SpawnLike = (command, args) =>\n nodeSpawn(command, [...args], { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\n/** One running `imsg rpc`. */\ninterface Session {\n readonly child: ChildLike;\n readonly rpc: JsonRpcLineClient;\n /** Set once the session is ended: resolves when the child closed or was signalled. */\n ended?: Promise<void>;\n}\n\n/**\n * iMessage adapter over one `imsg rpc` child.\n *\n * `connect()` starts `imsg rpc` and answers `true` once it accepts `watch.subscribe`. Each\n * `message` notification from someone else, with text, becomes an `IMessageMessageEvent`;\n * `sendMessage` writes one `send` request and maps its answer to a `SendResult`.\n *\n * @public\n */\nexport class IMessageAdapter extends BasePlatformAdapter {\n readonly platform = \"imessage\" as const;\n private readonly opts: IMessageAdapterOptions;\n private session: Session | undefined;\n private handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private warnedAboutHtml = false;\n private connecting: Promise<boolean> | undefined;\n /** The last row whose turn finished; a new subscription resumes after it. */\n private lastRowId: number | undefined;\n /**\n * Rows wait here for the one before them, across sessions: a row replayed by a new child waits\n * for the old child's row still in its handler, then finds the cursor past it.\n */\n private rows: Promise<void> = Promise.resolve();\n\n constructor(opts: IMessageAdapterOptions) {\n super();\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n // A second caller while the first waits for watch.subscribe shares its answer instead of\n // starting a second imsg, which would deliver every message twice.\n this.connecting ??= this.openSession().finally(() => {\n this.connecting = undefined;\n });\n return this.connecting;\n }\n\n async disconnect(): Promise<void> {\n const session = this.session;\n if (session === undefined) return;\n this.endSession(session);\n await session.ended;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n const chatId = toChatId(out.channel.id);\n if (chatId === undefined) {\n return {\n ok: false,\n error: {\n code: \"invalid_chat_id\",\n message: `channel.id must be imsg's chat id, a positive integer, got \"${out.channel.id}\"`,\n },\n };\n }\n const session = this.session;\n if (!this.connected || session === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"IMessageAdapter.connect() has not succeeded\" },\n };\n }\n const outcome = await session.rpc.request(\n \"send\",\n { chat_id: chatId, text: this.textFor(out) },\n this.opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n );\n return this.toSendResult(outcome, session);\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // Replace, not stack.\n this.handler = handler;\n return () => {\n if (this.handler === handler) {\n this.handler = undefined;\n }\n };\n }\n\n /**\n * Deliver an event that arrived out of band. One line over `runHandler`, which owns the\n * containment of a throwing handler.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n\n /** The text to send: markdown loses its markers, html goes as is with one warning. */\n private textFor(out: OutboundMessage): string {\n if (out.format === \"markdown\") return channelRendering(this.platform).translate(out.text);\n if (out.format === \"html\" && !this.warnedAboutHtml) {\n this.warnedAboutHtml = true;\n process.stderr.write(\n `[${LABEL}] format=\"html\" was declared and iMessage has no html mode; sending the text unchanged. Logged once.\\n`,\n );\n }\n return out.text;\n }\n\n private toSendResult(outcome: RpcOutcome, session: Session): SendResult {\n switch (outcome.kind) {\n case \"result\":\n return sentResult(outcome.result);\n case \"error\": {\n const mapped = mapSendError(outcome.code, outcome.message, outcome.data);\n if (mapped.endChild) this.endSession(session);\n return mapped.result;\n }\n case \"timeout\":\n return {\n ok: false,\n error: { code: \"timeout\", message: \"imsg did not answer the send in time\" },\n };\n case \"disconnected\":\n return {\n ok: false,\n error: { code: \"transport_closed\", message: \"imsg ended before answering the send\" },\n };\n }\n }\n\n /** Start imsg and subscribe; on any failure the child is ended and `false` returned. */\n private async openSession(): Promise<boolean> {\n const session = this.startChild();\n if (session === undefined) return false;\n const outcome = await session.rpc.request(\n \"watch.subscribe\",\n this.lastRowId === undefined ? {} : { since_rowid: this.lastRowId },\n this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,\n );\n if (outcome.kind === \"result\" && this.session === session) {\n this.connected = true;\n return true;\n }\n process.stderr.write(`[${LABEL}] connect failed: ${describe(outcome)}\\n`);\n // The answer is false now; the child's grace period runs on its own.\n if (this.session === session) this.endSession(session);\n return false;\n }\n\n /** Start imsg and attach the line client, or `undefined` when it cannot be started. */\n private startChild(): Session | undefined {\n const args = [\"rpc\", ...(this.opts.dbPath === undefined ? [] : [\"--db\", this.opts.dbPath])];\n let child: ChildLike;\n try {\n child = (this.opts.spawn ?? defaultSpawn)(this.opts.cliPath ?? \"imsg\", args);\n } catch (err) {\n process.stderr.write(`[${LABEL}] connect failed: could not start imsg: ${message(err)}\\n`);\n return undefined;\n }\n const rpc: JsonRpcLineClient = new JsonRpcLineClient(\n child,\n LABEL,\n (notification) => this.onNotification(session, notification),\n (reason) => this.onChildClosed(session, reason),\n );\n const session: Session = { child, rpc };\n this.session = session;\n return session;\n }\n\n /**\n * End a session: settle its pending requests, close imsg's stdin and give it `EXIT_GRACE_MS`\n * to exit before `SIGTERM`. `session.ended` resolves once the child closed or was signalled.\n * Idempotent.\n */\n private endSession(session: Session): void {\n if (this.session === session) {\n this.session = undefined;\n this.connected = false;\n }\n if (session.ended !== undefined) return;\n session.rpc.close(\"disconnected\");\n session.ended = new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n session.child.kill(\"SIGTERM\");\n resolve();\n }, EXIT_GRACE_MS);\n timer.unref?.();\n session.child.on(\"close\", (code, signal) => {\n clearTimeout(timer);\n process.stderr.write(`[${LABEL}] imsg exited with ${signal ?? `code ${code}`}\\n`);\n resolve();\n });\n session.child.stdin.end();\n });\n }\n\n private onChildClosed(session: Session, reason: string): void {\n if (this.session !== session) return;\n process.stderr.write(`[${LABEL}] imsg ${reason}\\n`);\n this.session = undefined;\n this.connected = false;\n }\n\n private onNotification(session: Session, notification: RpcNotification): void {\n if (notification.method !== \"message\") return;\n const row = (notification.params as { message?: IMessageRow } | undefined)?.message;\n if (row === undefined) return;\n // One row at a time, in the order imsg wrote them, so the cursor only ever covers rows\n // whose turn has finished.\n this.rows = this.rows\n .then(() => this.handleRow(session, row))\n .catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] handler threw: ${message(err)}\\n`);\n });\n }\n\n /**\n * Hand one row to the handler, then move the cursor past it. A row that found no handler does\n * not move the cursor; the next subscription asks for it again unless a later row of the same\n * session was handled first and moved the cursor past both.\n */\n private async handleRow(session: Session, row: IMessageRow): Promise<void> {\n // A row queued behind one that was running when imsg died is not started: the next\n // subscription replays it from the cursor.\n if (this.session !== session) return;\n const rowId = typeof row.id === \"number\" ? row.id : undefined;\n if (rowId !== undefined && this.lastRowId !== undefined && rowId <= this.lastRowId) return;\n const event = imessageRowToMessageEvent(row, Date.now());\n const outcome = event === undefined ? \"ok\" : await this.runHandler(this.handler, event);\n if (rowId !== undefined && outcome !== \"no_handler\") {\n this.lastRowId = Math.max(rowId, this.lastRowId ?? rowId);\n }\n }\n}\n\n/** A successful send: the guid, else the numeric row id, else no `messageId` at all. */\nfunction sentResult(result: unknown): SendResult {\n const fields = (typeof result === \"object\" && result !== null ? result : {}) as {\n guid?: unknown;\n id?: unknown;\n };\n if (typeof fields.guid === \"string\") return { ok: true, messageId: fields.guid };\n if (typeof fields.id === \"number\") return { ok: true, messageId: String(fields.id) };\n return { ok: true };\n}\n\n/** `imsg`'s chat id from a `channel.id`, or `undefined` when it is not a positive integer. */\nfunction toChatId(id: string): number | undefined {\n if (!CHAT_ID.test(id)) return undefined;\n const chatId = Number(id);\n return Number.isSafeInteger(chatId) ? chatId : undefined;\n}\n\nfunction describe(outcome: RpcOutcome): string {\n if (outcome.kind === \"error\")\n return `watch.subscribe answered ${outcome.code}: ${outcome.message}`;\n if (outcome.kind === \"timeout\") return \"watch.subscribe was not answered in time\";\n return \"imsg ended before answering watch.subscribe\";\n}\n\nfunction message(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * `imessageChannel` — the iMessage channel described as data, with an environment variable bound\n * to each option so `configFromEnv` can read it.\n *\n * Typed locally on purpose, like `telegramChannel`. `create` validates every value before the\n * constructor runs and starts no process (`imsg` starts in `connect()`).\n */\n\nimport {\n type ChannelConfigField,\n channelConfigReaders,\n GatewayConfigurationError,\n} from \"loopzero-gateway\";\n\nimport { IMessageAdapter } from \"./adapter.js\";\nimport type { IMessageAdapterOptions } from \"./types.js\";\n\ntype Config = Readonly<Record<string, unknown>>;\n\nconst { invalid, isAbsent, readString } = channelConfigReaders(\"gateway-imessage\");\n\n/** A number or digit string; a digit string past ~308 digits is Infinity and is rejected. */\nfunction readNumber(config: Config, key: string): number | undefined {\n const raw = config[key];\n if (isAbsent(raw)) return undefined;\n const value = typeof raw === \"string\" && /^\\d+$/.test(raw.trim()) ? Number(raw) : raw;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw invalid(key, \"a number or a string of digits\");\n}\n\nconst CONFIG: ReadonlyArray<ChannelConfigField> = [\n {\n key: \"cliPath\",\n required: false,\n secret: false,\n env: \"IMESSAGE_CLI_PATH\",\n description: \"Path or name of the `imsg` binary; default `imsg` on PATH.\",\n },\n {\n key: \"dbPath\",\n required: false,\n secret: false,\n env: \"IMESSAGE_DB_PATH\",\n description: \"Messages database to read; default is `imsg`'s own.\",\n },\n {\n key: \"connectTimeoutMs\",\n required: false,\n secret: false,\n env: \"IMESSAGE_CONNECT_TIMEOUT_MS\",\n description: \"Milliseconds `connect()` waits for `imsg`; default 10000.\",\n },\n {\n key: \"requestTimeoutMs\",\n required: false,\n secret: false,\n env: \"IMESSAGE_REQUEST_TIMEOUT_MS\",\n description: \"Milliseconds a send may stay unanswered; default 30000.\",\n },\n];\n\n/**\n * The iMessage channel: `imsg` runs as a child process, so it needs no webhook route.\n *\n * `create` throws `invalid_config` when `process.platform` is not `darwin`, so the channel is\n * rejected instead of looping on a missing `imsg`. Build `IMessageAdapter` directly to drive a\n * Mac over an ssh wrapper script from another system.\n *\n * @public\n */\nexport const imessageChannel = {\n platform: \"imessage\" as const,\n transport: \"socket\" as const,\n config: CONFIG,\n create(config: Config): IMessageAdapter {\n if (process.platform !== \"darwin\") {\n throw new GatewayConfigurationError(\"gateway-imessage\", {\n code: \"invalid_config\",\n message: `gateway-imessage: iMessage needs macOS (darwin); this platform is ${process.platform}`,\n detail: \"platform\",\n });\n }\n const cliPath = readString(config, \"cliPath\");\n const dbPath = readString(config, \"dbPath\");\n const connectTimeoutMs = readNumber(config, \"connectTimeoutMs\");\n const requestTimeoutMs = readNumber(config, \"requestTimeoutMs\");\n const options: IMessageAdapterOptions = {\n ...(cliPath === undefined ? {} : { cliPath }),\n ...(dbPath === undefined ? {} : { dbPath }),\n ...(connectTimeoutMs === undefined ? {} : { connectTimeoutMs }),\n ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),\n };\n return new IMessageAdapter(options);\n },\n};\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, ChannelConfigField, IMessageMessageEvent } from 'loopzero-gateway';
|
|
2
|
+
import { Writable, Readable } from 'node:stream';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Options and seams for `IMessageAdapter`.
|
|
6
|
+
*
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The part of a child process the adapter uses: its three pipes, `kill`, and the `close` and
|
|
12
|
+
* `error` events. `node:child_process` `spawn` returns a superset of it.
|
|
13
|
+
*
|
|
14
|
+
* @public
|
|
15
|
+
*/
|
|
16
|
+
interface ChildLike {
|
|
17
|
+
/** The child's standard input; the adapter writes one JSON-RPC request per line. */
|
|
18
|
+
readonly stdin: Writable;
|
|
19
|
+
/** The child's standard output; one JSON-RPC message per line. */
|
|
20
|
+
readonly stdout: Readable;
|
|
21
|
+
/** The child's standard error; drained so the pipe never fills. */
|
|
22
|
+
readonly stderr: Readable;
|
|
23
|
+
/** Signal the child to end. */
|
|
24
|
+
kill(signal?: NodeJS.Signals | number): boolean;
|
|
25
|
+
/** Fires once the child has ended and its pipes are closed, with its exit code or signal. */
|
|
26
|
+
on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
|
27
|
+
/** Fires when the child cannot be started or signalled (`ENOENT` for a missing binary). */
|
|
28
|
+
on(event: "error", listener: (err: Error) => void): this;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Starts a child process. The default is `node:child_process` `spawn` with all three pipes;
|
|
32
|
+
* tests pass a scripted child instead.
|
|
33
|
+
*
|
|
34
|
+
* @public
|
|
35
|
+
*/
|
|
36
|
+
type SpawnLike = (command: string, args: readonly string[]) => ChildLike;
|
|
37
|
+
/**
|
|
38
|
+
* Construction options for `IMessageAdapter`.
|
|
39
|
+
*
|
|
40
|
+
* The adapter holds no secret: `imsg` reads the Messages database and sends as the account
|
|
41
|
+
* signed in to Messages on its Mac, which is why there is no credential field here.
|
|
42
|
+
*
|
|
43
|
+
* @public
|
|
44
|
+
*/
|
|
45
|
+
interface IMessageAdapterOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Path or name of the `imsg` binary, or of a script that runs `imsg rpc` on a Mac over ssh.
|
|
48
|
+
* Default `"imsg"`, looked up on `PATH`.
|
|
49
|
+
*/
|
|
50
|
+
readonly cliPath?: string;
|
|
51
|
+
/** Messages database to read, passed as `--db <dbPath>`. Default: `imsg`'s own. */
|
|
52
|
+
readonly dbPath?: string;
|
|
53
|
+
/** How long `connect()` waits for `imsg` to answer `watch.subscribe`. Default 10000 ms. */
|
|
54
|
+
readonly connectTimeoutMs?: number;
|
|
55
|
+
/** How long a `send` may stay unanswered before it fails with `timeout`. Default 30000 ms. */
|
|
56
|
+
readonly requestTimeoutMs?: number;
|
|
57
|
+
/** Test seam: starts the child. Default `node:child_process` `spawn`. */
|
|
58
|
+
readonly spawn?: SpawnLike;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* `IMessageAdapter` — `BasePlatformAdapter` over `imsg rpc`.
|
|
63
|
+
*
|
|
64
|
+
* The adapter owns one `imsg` child. Requests go out on its stdin, and responses and `message`
|
|
65
|
+
* notifications come back on its stdout, one JSON line each. `imsg` sends as the account signed
|
|
66
|
+
* in to Messages on its Mac, so the adapter carries no secret.
|
|
67
|
+
*
|
|
68
|
+
* @public
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* iMessage adapter over one `imsg rpc` child.
|
|
73
|
+
*
|
|
74
|
+
* `connect()` starts `imsg rpc` and answers `true` once it accepts `watch.subscribe`. Each
|
|
75
|
+
* `message` notification from someone else, with text, becomes an `IMessageMessageEvent`;
|
|
76
|
+
* `sendMessage` writes one `send` request and maps its answer to a `SendResult`.
|
|
77
|
+
*
|
|
78
|
+
* @public
|
|
79
|
+
*/
|
|
80
|
+
declare class IMessageAdapter extends BasePlatformAdapter {
|
|
81
|
+
readonly platform: "imessage";
|
|
82
|
+
private readonly opts;
|
|
83
|
+
private session;
|
|
84
|
+
private handler;
|
|
85
|
+
private connected;
|
|
86
|
+
private warnedAboutHtml;
|
|
87
|
+
private connecting;
|
|
88
|
+
/** The last row whose turn finished; a new subscription resumes after it. */
|
|
89
|
+
private lastRowId;
|
|
90
|
+
/**
|
|
91
|
+
* Rows wait here for the one before them, across sessions: a row replayed by a new child waits
|
|
92
|
+
* for the old child's row still in its handler, then finds the cursor past it.
|
|
93
|
+
*/
|
|
94
|
+
private rows;
|
|
95
|
+
constructor(opts: IMessageAdapterOptions);
|
|
96
|
+
connect(): Promise<boolean>;
|
|
97
|
+
disconnect(): Promise<void>;
|
|
98
|
+
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
99
|
+
private sendText;
|
|
100
|
+
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
101
|
+
/**
|
|
102
|
+
* Deliver an event that arrived out of band. One line over `runHandler`, which owns the
|
|
103
|
+
* containment of a throwing handler.
|
|
104
|
+
*/
|
|
105
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
106
|
+
/** The text to send: markdown loses its markers, html goes as is with one warning. */
|
|
107
|
+
private textFor;
|
|
108
|
+
private toSendResult;
|
|
109
|
+
/** Start imsg and subscribe; on any failure the child is ended and `false` returned. */
|
|
110
|
+
private openSession;
|
|
111
|
+
/** Start imsg and attach the line client, or `undefined` when it cannot be started. */
|
|
112
|
+
private startChild;
|
|
113
|
+
/**
|
|
114
|
+
* End a session: settle its pending requests, close imsg's stdin and give it `EXIT_GRACE_MS`
|
|
115
|
+
* to exit before `SIGTERM`. `session.ended` resolves once the child closed or was signalled.
|
|
116
|
+
* Idempotent.
|
|
117
|
+
*/
|
|
118
|
+
private endSession;
|
|
119
|
+
private onChildClosed;
|
|
120
|
+
private onNotification;
|
|
121
|
+
/**
|
|
122
|
+
* Hand one row to the handler, then move the cursor past it. A row that found no handler does
|
|
123
|
+
* not move the cursor; the next subscription asks for it again unless a later row of the same
|
|
124
|
+
* session was handled first and moved the cursor past both.
|
|
125
|
+
*/
|
|
126
|
+
private handleRow;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* `imessageChannel` — the iMessage channel described as data, with an environment variable bound
|
|
131
|
+
* to each option so `configFromEnv` can read it.
|
|
132
|
+
*
|
|
133
|
+
* Typed locally on purpose, like `telegramChannel`. `create` validates every value before the
|
|
134
|
+
* constructor runs and starts no process (`imsg` starts in `connect()`).
|
|
135
|
+
*/
|
|
136
|
+
|
|
137
|
+
type Config = Readonly<Record<string, unknown>>;
|
|
138
|
+
/**
|
|
139
|
+
* The iMessage channel: `imsg` runs as a child process, so it needs no webhook route.
|
|
140
|
+
*
|
|
141
|
+
* `create` throws `invalid_config` when `process.platform` is not `darwin`, so the channel is
|
|
142
|
+
* rejected instead of looping on a missing `imsg`. Build `IMessageAdapter` directly to drive a
|
|
143
|
+
* Mac over an ssh wrapper script from another system.
|
|
144
|
+
*
|
|
145
|
+
* @public
|
|
146
|
+
*/
|
|
147
|
+
declare const imessageChannel: {
|
|
148
|
+
platform: "imessage";
|
|
149
|
+
transport: "socket";
|
|
150
|
+
config: readonly ChannelConfigField[];
|
|
151
|
+
create(config: Config): IMessageAdapter;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* `imsg` `message` notification → `IMessageMessageEvent`.
|
|
156
|
+
*
|
|
157
|
+
* @public
|
|
158
|
+
*/
|
|
159
|
+
|
|
160
|
+
/** The fields of an `imsg` message row this package reads. Everything else stays in `raw`. */
|
|
161
|
+
interface IMessageRow {
|
|
162
|
+
/** The row id in the Messages database; the cursor `since_rowid` resumes after. */
|
|
163
|
+
readonly id?: number;
|
|
164
|
+
readonly chat_id?: number;
|
|
165
|
+
readonly guid?: string;
|
|
166
|
+
readonly sender?: string;
|
|
167
|
+
readonly is_from_me?: boolean;
|
|
168
|
+
readonly text?: string | null;
|
|
169
|
+
readonly is_group?: boolean;
|
|
170
|
+
readonly participants?: readonly string[];
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Build the event for one row, or `undefined` when the handler must not see it.
|
|
174
|
+
*
|
|
175
|
+
* A row the signed-in account sent (`is_from_me`), including the adapter's own replies, gives no
|
|
176
|
+
* event, and neither does a row with no text (an attachment, a tapback) or with no chat or guid.
|
|
177
|
+
*
|
|
178
|
+
* @param row - the `params.message` of an `imsg` `message` notification
|
|
179
|
+
* @param receivedAt - when the adapter read it, in ms since the epoch
|
|
180
|
+
*/
|
|
181
|
+
declare function imessageRowToMessageEvent(row: IMessageRow, receivedAt: number): IMessageMessageEvent | undefined;
|
|
182
|
+
|
|
183
|
+
export { type ChildLike, IMessageAdapter, type IMessageAdapterOptions, type IMessageRow, type SpawnLike, imessageChannel, imessageRowToMessageEvent };
|