@ever-works/mastodon-connector-plugin 1.0.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.
@@ -0,0 +1,154 @@
1
+ import { IConnectorPlugin, IEventSourcePlugin, PluginCategory, ConnectorMetadata, JsonSchema, ChannelTargetConfig, ConnectorCallOptions, ChannelVerification, ChannelSendInput, ChannelSendResult, EventSourcePullInput, EventSourcePullResult } from '@ever-works/plugin';
2
+
3
+ /**
4
+ * Payload text cap for ingested envelopes. Envelope payloads are
5
+ * size-capped platform-side (32 KB serialized); a status body never
6
+ * needs more than this to be useful in Memory/Activities.
7
+ */
8
+ declare const MASTODON_EVENT_TEXT_MAX_CHARS = 4000;
9
+ /** Items requested per Mastodon page (notifications and statuses alike). */
10
+ declare const MASTODON_PULL_PAGE_SIZE = 40;
11
+ /**
12
+ * Historical backfill bound: at most this many pages per phase
13
+ * (notifications, then the account's own statuses) during the opt-in
14
+ * first-pull backfill, so a busy account can never turn activation
15
+ * into an unbounded crawl.
16
+ */
17
+ declare const MASTODON_BACKFILL_MAX_PAGES = 10;
18
+ /** Visibilities Mastodon accepts for an outbound status. */
19
+ declare const MASTODON_VISIBILITIES: readonly ["public", "unlisted", "private", "direct"];
20
+ type MastodonVisibility = (typeof MASTODON_VISIBILITIES)[number];
21
+ /** Clamp the opt-in backfill window to the supported 0–90 day range. */
22
+ declare function clampBackfillDays(value: unknown): number;
23
+ /**
24
+ * Mastodon status bodies are HTML. Envelopes carry plain text (Memory
25
+ * observations and Activity rows are text surfaces), so block-level
26
+ * markup becomes newlines, remaining tags are dropped and the handful
27
+ * of entities Mastodon actually emits are decoded.
28
+ */
29
+ declare function stripStatusHtml(html: string | undefined): string | undefined;
30
+ /** Normalize the configured visibility, defaulting to `public`. */
31
+ declare function resolveVisibility(value: unknown): MastodonVisibility;
32
+ /** Minimal shape of an account we consume. */
33
+ interface MastodonAccount {
34
+ id?: string;
35
+ username?: string;
36
+ acct?: string;
37
+ displayName?: string;
38
+ url?: string;
39
+ }
40
+ /** Minimal shape of a status we consume. */
41
+ interface MastodonStatus {
42
+ id?: string;
43
+ uri?: string;
44
+ url?: string;
45
+ content?: string;
46
+ createdAt?: string;
47
+ repliesCount?: number;
48
+ reblogsCount?: number;
49
+ favouritesCount?: number;
50
+ visibility?: string;
51
+ account?: MastodonAccount;
52
+ }
53
+ /** Minimal shape of a notification we consume. */
54
+ interface MastodonNotification {
55
+ id?: string;
56
+ type?: string;
57
+ createdAt?: string;
58
+ account?: MastodonAccount;
59
+ status?: MastodonStatus;
60
+ }
61
+ /** The subset of the `masto` REST surface this plugin calls. */
62
+ interface MastodonClientLike {
63
+ v1: {
64
+ accounts: {
65
+ verifyCredentials(): Promise<MastodonAccount>;
66
+ $select(id: string): {
67
+ statuses: {
68
+ list(params: Record<string, unknown>): Promise<MastodonStatus[]>;
69
+ };
70
+ };
71
+ };
72
+ statuses: {
73
+ create(params: Record<string, unknown>): Promise<MastodonStatus>;
74
+ };
75
+ notifications: {
76
+ list(params: Record<string, unknown>): Promise<MastodonNotification[]>;
77
+ };
78
+ };
79
+ }
80
+ /** Resolved credentials for one call. */
81
+ interface MastodonCredentials {
82
+ instanceUrl: string;
83
+ accessToken: string;
84
+ }
85
+ /**
86
+ * Resolve credentials from the per-connection target config, falling
87
+ * back to the resolved plugin settings. Returns undefined (never a
88
+ * partial) so callers fail loudly with one clear message.
89
+ */
90
+ declare function resolveCredentials(config: ChannelTargetConfig, options: ConnectorCallOptions): MastodonCredentials | undefined;
91
+ /**
92
+ * Mastodon social connector — first-party native connector.
93
+ *
94
+ * Outbound: `send` publishes a status — or a threaded reply when the
95
+ * target config carries `inReplyToId` — through the `masto` SDK against
96
+ * the operator's own instance. The instance URL is operator-supplied,
97
+ * so it passes the shared SSRF guard before any request is issued.
98
+ *
99
+ * Event source: `pullEvents` sweeps notifications (mentions, favourites,
100
+ * boosts, follows) then the connected account's own statuses since the
101
+ * watermark, normalized into `IngestedEventEnvelope`s
102
+ * (`mastodon.notification` / `mastodon.status`, the status permalink as
103
+ * `sourceUrl`) for the platform's event-ingest spine. Mastodon paginates
104
+ * by id rather than time, so each phase walks `max_id` newest-first and
105
+ * stops at the first item older than the watermark. The opt-in
106
+ * historical backfill (`backfillDays`, default 0 = off, max 90) widens
107
+ * the FIRST pull's window only, with a per-phase page bound.
108
+ * Re-delivery across overlapping windows is fine — the ingest pipeline
109
+ * dedupes on `(source, sourceEventId)`.
110
+ *
111
+ * Unconfigured is always LOUD: `verifyConnection` reports the missing
112
+ * credentials, `send` throws, and `pullEvents` throws
113
+ * `EventSourceNotConfiguredError`. Nothing silently no-ops.
114
+ */
115
+ declare class MastodonConnectorPlugin implements IConnectorPlugin, IEventSourcePlugin {
116
+ readonly id = "mastodon-connector";
117
+ readonly name = "Mastodon Connector";
118
+ readonly version = "1.0.0";
119
+ readonly category: PluginCategory;
120
+ readonly capabilities: readonly ["connector", "connector-mastodon", "event-source"];
121
+ readonly providerName = "mastodon";
122
+ readonly connector: ConnectorMetadata;
123
+ readonly settingsSchema: JsonSchema;
124
+ private readonly idempotencyCache;
125
+ onLoad(): Promise<void>;
126
+ onUnload(): Promise<void>;
127
+ /** Testable seam — specs stub this; production uses the real SDK. */
128
+ protected createClient(instanceUrl: string, accessToken: string): MastodonClientLike;
129
+ /**
130
+ * Build a client for the operator's instance. The instance URL is
131
+ * user-supplied, so it passes the shared SSRF guard before any
132
+ * request is issued.
133
+ */
134
+ private connect;
135
+ verifyConnection(config: ChannelTargetConfig, options: ConnectorCallOptions): Promise<ChannelVerification>;
136
+ /** Outbound leg — publish a status (or a threaded reply). */
137
+ send(payload: ChannelSendInput, options: ConnectorCallOptions): Promise<ChannelSendResult>;
138
+ /**
139
+ * Pull one page of the current sweep phase (notifications → own
140
+ * statuses) since the effective watermark, normalized to envelopes.
141
+ * The returned cursor resumes the same phase (Mastodon `max_id`) or
142
+ * advances to the next; no cursor means the sweep is done.
143
+ *
144
+ * First pull (epoch/absent watermark, no cursor): the window is
145
+ * `now - backfillDays` when the opt-in backfill is on, otherwise
146
+ * `now` — history stays untouched unless the user asked for it.
147
+ */
148
+ pullEvents(input: EventSourcePullInput): Promise<EventSourcePullResult>;
149
+ private normalizeNotification;
150
+ private normalizeStatus;
151
+ }
152
+ declare const mastodonConnectorPlugin: MastodonConnectorPlugin;
153
+
154
+ export { MASTODON_BACKFILL_MAX_PAGES, MASTODON_EVENT_TEXT_MAX_CHARS, MASTODON_PULL_PAGE_SIZE, MASTODON_VISIBILITIES, MastodonConnectorPlugin, type MastodonVisibility, clampBackfillDays, MastodonConnectorPlugin as default, mastodonConnectorPlugin, resolveCredentials, resolveVisibility, stripStatusHtml };
package/dist/index.js ADDED
@@ -0,0 +1,466 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { createRestAPIClient } from 'masto';
3
+ import '@ever-works/contracts';
4
+ import { isIP } from 'net';
5
+
6
+ // src/mastodon-connector-plugin.ts
7
+ var EventSourceNotConfiguredError = class extends Error {
8
+ constructor(message) {
9
+ super(message ?? "Event-source plugin is not configured in this runtime.");
10
+ this.name = "EventSourceNotConfiguredError";
11
+ }
12
+ };
13
+ var PLUGIN_CAPABILITIES = {
14
+ // Connectors ("Connector fabric") — first-party BIDIRECTIONAL
15
+ // communication-channel plugins. Each connector declares `CONNECTOR`
16
+ // (umbrella, for discovery/grouping) plus its `CONNECTOR_<provider>`
17
+ // constant. Superset of the outbound-only notification channels; see
18
+ // `capabilities/connector.interface.ts`.
19
+ CONNECTOR: "connector",
20
+ CONNECTOR_MASTODON: "connector-mastodon",
21
+ // Event-ingest spine (Wave 6) — plugins that pull/push normalized
22
+ // external events into the platform ingest pipeline. See
23
+ // capabilities/event-source.interface.ts.
24
+ EVENT_SOURCE: "event-source"};
25
+ function isSafeWebhookUrl(rawUrl) {
26
+ let url;
27
+ try {
28
+ url = new URL(rawUrl);
29
+ } catch {
30
+ return false;
31
+ }
32
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
33
+ return false;
34
+ }
35
+ let host = url.hostname.toLowerCase();
36
+ if (host.startsWith("[") && host.endsWith("]")) {
37
+ host = host.slice(1, -1);
38
+ }
39
+ if (CLOUD_METADATA_HOSTNAMES.has(host)) {
40
+ return false;
41
+ }
42
+ const ipKind = isIP(host);
43
+ if (ipKind === 4 && isPrivateIPv4(host)) return false;
44
+ if (ipKind === 6 && isPrivateIPv6(host)) return false;
45
+ return true;
46
+ }
47
+ var CLOUD_METADATA_HOSTNAMES = /* @__PURE__ */ new Set([
48
+ // GCP
49
+ "metadata.google.internal",
50
+ "metadata.goog",
51
+ // AWS
52
+ "instance-data",
53
+ "instance-data.ec2.internal",
54
+ // Azure
55
+ "metadata.azure.internal"
56
+ ]);
57
+ function isPrivateIPv4(ip) {
58
+ const parts = ip.split(".").map((p) => Number(p));
59
+ if (parts.length !== 4 || parts.some((n) => Number.isNaN(n))) return false;
60
+ const [a, b] = parts;
61
+ if (a === 10) return true;
62
+ if (a === 127) return true;
63
+ if (a === 0) return true;
64
+ if (a === 169 && b === 254) return true;
65
+ if (a === 172 && b >= 16 && b <= 31) return true;
66
+ if (a === 192 && b === 168) return true;
67
+ if (a === 192 && b === 0 && parts[2] === 0) return true;
68
+ if (a === 100 && b >= 64 && b <= 127) return true;
69
+ if (a >= 224) return true;
70
+ return false;
71
+ }
72
+ function isPrivateIPv6(ip) {
73
+ const lower = ip.toLowerCase();
74
+ if (lower === "::1" || lower === "::") return true;
75
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
76
+ const firstHextet = lower.split(":", 1)[0];
77
+ if (/^[0-9a-f]{1,4}$/.test(firstHextet)) {
78
+ const group0 = parseInt(firstHextet, 16);
79
+ if ((group0 & 65472) === 65152) return true;
80
+ }
81
+ if (lower.startsWith("::ffff:")) {
82
+ const v4 = lower.slice("::ffff:".length);
83
+ if (isIP(v4) === 4) return isPrivateIPv4(v4);
84
+ }
85
+ return false;
86
+ }
87
+
88
+ // src/mastodon-connector-plugin.ts
89
+ var MASTODON_EVENT_TEXT_MAX_CHARS = 4e3;
90
+ var MASTODON_PULL_PAGE_SIZE = 40;
91
+ var MASTODON_BACKFILL_MAX_PAGES = 10;
92
+ var MASTODON_VISIBILITIES = ["public", "unlisted", "private", "direct"];
93
+ function clampBackfillDays(value) {
94
+ const num = typeof value === "number" ? value : Number(value);
95
+ if (!Number.isFinite(num) || num <= 0) return 0;
96
+ return Math.min(Math.floor(num), 90);
97
+ }
98
+ function truncateText(text) {
99
+ return text.length > MASTODON_EVENT_TEXT_MAX_CHARS ? text.slice(0, MASTODON_EVENT_TEXT_MAX_CHARS) : text;
100
+ }
101
+ function stripStatusHtml(html) {
102
+ if (typeof html !== "string" || html.length === 0) return void 0;
103
+ const text = html.replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n\n").replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").trim();
104
+ return text.length > 0 ? text : void 0;
105
+ }
106
+ function resolveVisibility(value) {
107
+ if (typeof value === "string") {
108
+ const candidate = value.trim().toLowerCase();
109
+ if (MASTODON_VISIBILITIES.includes(candidate)) {
110
+ return candidate;
111
+ }
112
+ }
113
+ return "public";
114
+ }
115
+ function mastodonErrorMessage(err) {
116
+ const e = err;
117
+ return e.message ?? e.error ?? (typeof e.statusCode === "number" ? `HTTP ${e.statusCode}` : "unknown error");
118
+ }
119
+ function toIso(value) {
120
+ if (value instanceof Date) return value.toISOString();
121
+ if (typeof value === "string") {
122
+ const ms = Date.parse(value);
123
+ if (Number.isFinite(ms)) return new Date(ms).toISOString();
124
+ }
125
+ return (/* @__PURE__ */ new Date(0)).toISOString();
126
+ }
127
+ function parsePullCursor(cursor) {
128
+ if (!cursor) return void 0;
129
+ try {
130
+ const parsed = JSON.parse(cursor);
131
+ if (parsed && (parsed.p === "notifications" || parsed.p === "statuses") && typeof parsed.s === "string") {
132
+ return parsed;
133
+ }
134
+ } catch {
135
+ }
136
+ return void 0;
137
+ }
138
+ function firstString(candidates) {
139
+ for (const c of candidates) {
140
+ if (typeof c === "string" && c.trim().length > 0) return c.trim();
141
+ }
142
+ return void 0;
143
+ }
144
+ function resolveCredentials(config, options) {
145
+ const instanceUrl = firstString([config.instanceUrl, options.settings?.instanceUrl]);
146
+ const accessToken = firstString([config.accessToken, options.settings?.accessToken]);
147
+ if (!instanceUrl || !accessToken) return void 0;
148
+ return { instanceUrl, accessToken };
149
+ }
150
+ var MastodonConnectorPlugin = class {
151
+ constructor() {
152
+ this.id = "mastodon-connector";
153
+ this.name = "Mastodon Connector";
154
+ this.version = "1.0.0";
155
+ this.category = "connector";
156
+ this.capabilities = [
157
+ PLUGIN_CAPABILITIES.CONNECTOR,
158
+ PLUGIN_CAPABILITIES.CONNECTOR_MASTODON,
159
+ PLUGIN_CAPABILITIES.EVENT_SOURCE
160
+ ];
161
+ this.providerName = "mastodon";
162
+ this.connector = {
163
+ direction: "outbound",
164
+ transport: "poll",
165
+ flags: {
166
+ outboundMessage: true,
167
+ outboundRecord: false,
168
+ inbound: false,
169
+ reply: false,
170
+ pairing: false,
171
+ richOutbound: false
172
+ }
173
+ };
174
+ this.settingsSchema = {
175
+ type: "object",
176
+ required: ["instanceUrl", "accessToken"],
177
+ properties: {
178
+ instanceUrl: {
179
+ type: "string",
180
+ title: "Mastodon instance URL (e.g. https://mastodon.social)"
181
+ },
182
+ accessToken: {
183
+ type: "string",
184
+ title: "Mastodon application access token",
185
+ "x-secret": true,
186
+ "x-envVar": "MASTODON_ACCESS_TOKEN"
187
+ },
188
+ defaultVisibility: {
189
+ type: "string",
190
+ title: "Visibility applied to outbound statuses",
191
+ default: "public",
192
+ enum: [...MASTODON_VISIBILITIES]
193
+ },
194
+ backfillDays: {
195
+ type: "number",
196
+ title: "Historical backfill window in days on first pull (0 = off, max 90)",
197
+ default: 0,
198
+ minimum: 0,
199
+ maximum: 90
200
+ }
201
+ }
202
+ };
203
+ this.idempotencyCache = /* @__PURE__ */ new Map();
204
+ }
205
+ async onLoad() {
206
+ }
207
+ async onUnload() {
208
+ this.idempotencyCache.clear();
209
+ }
210
+ /** Testable seam — specs stub this; production uses the real SDK. */
211
+ createClient(instanceUrl, accessToken) {
212
+ return createRestAPIClient({ url: instanceUrl, accessToken });
213
+ }
214
+ /**
215
+ * Build a client for the operator's instance. The instance URL is
216
+ * user-supplied, so it passes the shared SSRF guard before any
217
+ * request is issued.
218
+ */
219
+ connect(credentials) {
220
+ if (!isSafeWebhookUrl(credentials.instanceUrl)) {
221
+ throw new Error(`mastodon-connector: refusing to use an unsafe instance URL '${credentials.instanceUrl}'`);
222
+ }
223
+ return this.createClient(credentials.instanceUrl, credentials.accessToken);
224
+ }
225
+ async verifyConnection(config, options) {
226
+ const credentials = resolveCredentials(config, options);
227
+ if (!credentials) {
228
+ return { valid: false, message: "instanceUrl and accessToken are required" };
229
+ }
230
+ try {
231
+ const account = await this.connect(credentials).v1.accounts.verifyCredentials();
232
+ return {
233
+ valid: true,
234
+ details: {
235
+ instanceUrl: credentials.instanceUrl,
236
+ ...account?.id ? { accountId: account.id } : {},
237
+ ...account?.acct ? { acct: account.acct } : {},
238
+ ...account?.displayName ? { displayName: account.displayName } : {}
239
+ }
240
+ };
241
+ } catch (err) {
242
+ return { valid: false, message: `Mastodon verifyCredentials failed: ${mastodonErrorMessage(err)}` };
243
+ }
244
+ }
245
+ /** Outbound leg — publish a status (or a threaded reply). */
246
+ async send(payload, options) {
247
+ const config = payload.target ?? options.target ?? {};
248
+ const credentials = resolveCredentials(config, options);
249
+ if (!credentials) {
250
+ throw new Error(
251
+ "mastodon-connector: instanceUrl and accessToken are required (targetConfig.instanceUrl/accessToken or settings.instanceUrl/accessToken)"
252
+ );
253
+ }
254
+ const inReplyToId = firstString([config.inReplyToId]);
255
+ const visibility = resolveVisibility(config.visibility ?? options.settings?.defaultVisibility);
256
+ const cacheKey = `${options.connectorId ?? ""}\0${inReplyToId ?? ""}\0${payload.messageRef}`;
257
+ const cached = this.idempotencyCache.get(cacheKey);
258
+ if (cached) return cached;
259
+ let statusId;
260
+ try {
261
+ const status = await this.connect(credentials).v1.statuses.create({
262
+ status: payload.text,
263
+ visibility,
264
+ ...inReplyToId ? { inReplyToId } : {}
265
+ });
266
+ statusId = typeof status?.id === "string" ? status.id : void 0;
267
+ } catch (err) {
268
+ throw new Error(`Mastodon status create failed: ${mastodonErrorMessage(err)}`);
269
+ }
270
+ const result = {
271
+ provider: this.id,
272
+ providerMessageId: statusId ?? `mastodon-${payload.messageRef}`,
273
+ deliveredAt: /* @__PURE__ */ new Date()
274
+ };
275
+ this.idempotencyCache.set(cacheKey, result);
276
+ if (this.idempotencyCache.size > 500) {
277
+ const firstKey = this.idempotencyCache.keys().next().value;
278
+ if (firstKey) this.idempotencyCache.delete(firstKey);
279
+ }
280
+ return result;
281
+ }
282
+ // ── Event source (pull) ─────────────────────────────────────────────
283
+ /**
284
+ * Pull one page of the current sweep phase (notifications → own
285
+ * statuses) since the effective watermark, normalized to envelopes.
286
+ * The returned cursor resumes the same phase (Mastodon `max_id`) or
287
+ * advances to the next; no cursor means the sweep is done.
288
+ *
289
+ * First pull (epoch/absent watermark, no cursor): the window is
290
+ * `now - backfillDays` when the opt-in backfill is on, otherwise
291
+ * `now` — history stays untouched unless the user asked for it.
292
+ */
293
+ async pullEvents(input) {
294
+ const instanceUrl = input.settings?.instanceUrl;
295
+ const accessToken = input.settings?.accessToken;
296
+ if (typeof instanceUrl !== "string" || instanceUrl.length === 0) {
297
+ throw new EventSourceNotConfiguredError(
298
+ "mastodon-connector: settings.instanceUrl is required to pull events"
299
+ );
300
+ }
301
+ if (typeof accessToken !== "string" || accessToken.length === 0) {
302
+ throw new EventSourceNotConfiguredError(
303
+ "mastodon-connector: settings.accessToken is required to pull events"
304
+ );
305
+ }
306
+ const cursor = parsePullCursor(input.cursor);
307
+ let phase;
308
+ let maxId;
309
+ let since;
310
+ let backfill;
311
+ let pagesUsed;
312
+ if (cursor) {
313
+ phase = cursor.p;
314
+ maxId = cursor.n;
315
+ since = cursor.s;
316
+ backfill = cursor.f === 1;
317
+ pagesUsed = cursor.b ?? 0;
318
+ } else {
319
+ const sinceMs2 = Date.parse(input.since);
320
+ const firstPull = !Number.isFinite(sinceMs2) || sinceMs2 <= 0;
321
+ const backfillDays = clampBackfillDays(input.settings?.backfillDays);
322
+ if (firstPull) {
323
+ const start = backfillDays > 0 ? Date.now() - backfillDays * 864e5 : Date.now();
324
+ since = new Date(start).toISOString();
325
+ backfill = backfillDays > 0;
326
+ } else {
327
+ since = new Date(sinceMs2).toISOString();
328
+ backfill = false;
329
+ }
330
+ phase = "notifications";
331
+ maxId = void 0;
332
+ pagesUsed = 0;
333
+ }
334
+ const client = this.connect({ instanceUrl, accessToken });
335
+ const sinceMs = Date.parse(since);
336
+ const events = [];
337
+ let lastId;
338
+ let pageSize = 0;
339
+ let stopSweep = false;
340
+ if (phase === "notifications") {
341
+ const notifications = await client.v1.notifications.list({
342
+ limit: MASTODON_PULL_PAGE_SIZE,
343
+ ...maxId ? { maxId } : {}
344
+ });
345
+ pageSize = notifications.length;
346
+ for (const notification of notifications) {
347
+ lastId = notification.id ?? lastId;
348
+ const createdMs = Date.parse(notification.createdAt ?? "");
349
+ if (Number.isFinite(createdMs) && createdMs < sinceMs) {
350
+ stopSweep = true;
351
+ break;
352
+ }
353
+ const envelope = this.normalizeNotification(notification);
354
+ if (envelope) events.push(envelope);
355
+ }
356
+ } else {
357
+ const account = await client.v1.accounts.verifyCredentials();
358
+ const accountId = account?.id;
359
+ if (!accountId) {
360
+ throw new EventSourceNotConfiguredError(
361
+ "mastodon-connector: the access token resolved to no account \u2014 re-authorize the application"
362
+ );
363
+ }
364
+ const statuses = await client.v1.accounts.$select(accountId).statuses.list({
365
+ limit: MASTODON_PULL_PAGE_SIZE,
366
+ ...maxId ? { maxId } : {}
367
+ });
368
+ pageSize = statuses.length;
369
+ for (const status of statuses) {
370
+ lastId = status.id ?? lastId;
371
+ const createdMs = Date.parse(status.createdAt ?? "");
372
+ if (Number.isFinite(createdMs) && createdMs < sinceMs) {
373
+ stopSweep = true;
374
+ break;
375
+ }
376
+ const envelope = this.normalizeStatus(status);
377
+ if (envelope) events.push(envelope);
378
+ }
379
+ }
380
+ pagesUsed += 1;
381
+ const pageBudgetExhausted = backfill && pagesUsed >= MASTODON_BACKFILL_MAX_PAGES;
382
+ const mayHaveMore = pageSize >= MASTODON_PULL_PAGE_SIZE && lastId !== void 0;
383
+ let next;
384
+ if (!stopSweep && mayHaveMore && !pageBudgetExhausted) {
385
+ next = { p: phase, n: lastId, s: since, ...backfill ? { f: 1 } : {}, b: pagesUsed };
386
+ } else if (phase === "notifications") {
387
+ next = { p: "statuses", s: since, ...backfill ? { f: 1 } : {}, b: 0 };
388
+ }
389
+ return next ? { events, nextCursor: JSON.stringify(next) } : { events };
390
+ }
391
+ normalizeNotification(notification) {
392
+ if (!notification.id) return null;
393
+ const occurredAt = toIso(notification.createdAt);
394
+ const type = notification.type ?? "unknown";
395
+ const account = notification.account ?? {};
396
+ const text = stripStatusHtml(notification.status?.content);
397
+ const sourceUrl = notification.status?.url ?? account.url;
398
+ return {
399
+ id: randomUUID(),
400
+ source: this.id,
401
+ sourceEventId: `notification:${notification.id}`,
402
+ kind: "mastodon.notification",
403
+ occurredAt,
404
+ ...account.acct || account.displayName ? {
405
+ actor: {
406
+ name: account.displayName ?? account.acct ?? "unknown",
407
+ ...account.id ? { externalId: account.id } : {}
408
+ }
409
+ } : {},
410
+ subject: {
411
+ type: notification.status?.id ? "status" : "account",
412
+ externalId: notification.status?.id ?? account.id ?? notification.id,
413
+ ...text ? { title: truncateText(text) } : {}
414
+ },
415
+ ...sourceUrl ? { sourceUrl } : {},
416
+ payload: {
417
+ notificationType: type,
418
+ notificationId: notification.id,
419
+ ...notification.status?.id ? { statusId: notification.status.id } : {},
420
+ ...account.id ? { accountId: account.id } : {},
421
+ ...account.acct ? { acct: account.acct } : {},
422
+ ...text ? { text: truncateText(text) } : {},
423
+ createdAt: occurredAt
424
+ }
425
+ };
426
+ }
427
+ normalizeStatus(status) {
428
+ if (!status.id) return null;
429
+ const occurredAt = toIso(status.createdAt);
430
+ const account = status.account ?? {};
431
+ const text = stripStatusHtml(status.content);
432
+ return {
433
+ id: randomUUID(),
434
+ source: this.id,
435
+ sourceEventId: `status:${status.id}`,
436
+ kind: "mastodon.status",
437
+ occurredAt,
438
+ ...account.acct || account.displayName ? {
439
+ actor: {
440
+ name: account.displayName ?? account.acct ?? "unknown",
441
+ ...account.id ? { externalId: account.id } : {}
442
+ }
443
+ } : {},
444
+ subject: {
445
+ type: "status",
446
+ externalId: status.id,
447
+ ...text ? { title: truncateText(text) } : {}
448
+ },
449
+ ...status.url ? { sourceUrl: status.url } : {},
450
+ payload: {
451
+ statusId: status.id,
452
+ ...status.uri ? { uri: status.uri } : {},
453
+ ...status.visibility ? { visibility: status.visibility } : {},
454
+ ...account.acct ? { acct: account.acct } : {},
455
+ ...text ? { text: truncateText(text) } : {},
456
+ ...typeof status.repliesCount === "number" ? { repliesCount: status.repliesCount } : {},
457
+ ...typeof status.reblogsCount === "number" ? { reblogsCount: status.reblogsCount } : {},
458
+ ...typeof status.favouritesCount === "number" ? { favouritesCount: status.favouritesCount } : {},
459
+ createdAt: occurredAt
460
+ }
461
+ };
462
+ }
463
+ };
464
+ var mastodonConnectorPlugin = new MastodonConnectorPlugin();
465
+
466
+ export { MASTODON_BACKFILL_MAX_PAGES, MASTODON_EVENT_TEXT_MAX_CHARS, MASTODON_PULL_PAGE_SIZE, MASTODON_VISIBILITIES, MastodonConnectorPlugin, clampBackfillDays, MastodonConnectorPlugin as default, mastodonConnectorPlugin, resolveCredentials, resolveVisibility, stripStatusHtml };