@happyvertical/garrula 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +71 -0
- package/CLAUDE.md +1 -0
- package/README.md +117 -2
- package/dist/Garrula.d.ts +240 -0
- package/dist/config.d.ts +49 -0
- package/dist/credentials.d.ts +57 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +2135 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest.json +2217 -0
- package/dist/outbound/drafting.d.ts +23 -0
- package/dist/outbound/models.d.ts +108 -0
- package/dist/outbound/rates.d.ts +35 -0
- package/dist/outbound/service.d.ts +127 -0
- package/dist/outbound/sources.d.ts +20 -0
- package/dist/outbound/state.d.ts +6 -0
- package/dist/outbound/types.d.ts +165 -0
- package/dist/smrt-knowledge.json +1161 -0
- package/dist/types.d.ts +199 -0
- package/dist/ui/admin/ActivitySpendPanel.svelte +340 -0
- package/dist/ui/admin/ActivitySpendPanel.svelte.d.ts +3 -0
- package/dist/ui/admin/AdminRoot.svelte +70 -0
- package/dist/ui/admin/AdminRoot.svelte.d.ts +9 -0
- package/dist/ui/admin/DraftCard.svelte +359 -0
- package/dist/ui/admin/DraftCard.svelte.d.ts +17 -0
- package/dist/ui/admin/PersonaPolicyPanel.svelte +177 -0
- package/dist/ui/admin/PersonaPolicyPanel.svelte.d.ts +3 -0
- package/dist/ui/admin/QueuePanel.svelte +192 -0
- package/dist/ui/admin/QueuePanel.svelte.d.ts +3 -0
- package/dist/ui/admin/SettingsPanel.svelte +338 -0
- package/dist/ui/admin/SettingsPanel.svelte.d.ts +4 -0
- package/dist/ui/admin/SourcesPanel.svelte +196 -0
- package/dist/ui/admin/SourcesPanel.svelte.d.ts +3 -0
- package/dist/ui/admin/StatusRegion.svelte +41 -0
- package/dist/ui/admin/StatusRegion.svelte.d.ts +7 -0
- package/dist/ui/admin/access.d.ts +23 -0
- package/dist/ui/admin/access.js +30 -0
- package/dist/ui/admin/format.d.ts +9 -0
- package/dist/ui/admin/format.js +39 -0
- package/dist/ui/admin/index.d.ts +12 -0
- package/dist/ui/admin/index.js +17 -0
- package/dist/ui/admin/nav.d.ts +2 -0
- package/dist/ui/admin/nav.js +7 -0
- package/dist/ui/types.d.ts +86 -0
- package/dist/ui/types.js +63 -0
- package/docs/manifest-routing.md +41 -0
- package/package.json +111 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2135 @@
|
|
|
1
|
+
import { Agent } from "@happyvertical/smrt-agents";
|
|
2
|
+
import { SmrtCollection, SmrtObject, smrt } from "@happyvertical/smrt-core";
|
|
3
|
+
import { SocialAccountCollection, SocialPostAnalyticsSnapshotCollection, SocialPostCollection } from "@happyvertical/smrt-social";
|
|
4
|
+
import { TenantScoped, getTenantId, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
|
|
5
|
+
import { SocialError, getSocial } from "@happyvertical/social";
|
|
6
|
+
//#region src/credentials.ts
|
|
7
|
+
/**
|
|
8
|
+
* Social OAuth token upkeep for Garrula's publisher.
|
|
9
|
+
*
|
|
10
|
+
* TODO(happyvertical/sdk#1376): `@happyvertical/social` adapters should
|
|
11
|
+
* refresh expired tokens themselves (expiry margin, retry after a 401) and
|
|
12
|
+
* hand the refreshed token set to a callback for the caller to persist,
|
|
13
|
+
* Threads included. Until then Garrula decides when to refresh, refreshes
|
|
14
|
+
* Threads tokens itself, and persists every refreshed token set. Drop this
|
|
15
|
+
* module's refresh logic when that ships.
|
|
16
|
+
*/
|
|
17
|
+
/** Default for how long before expiry an access token is refreshed. */
|
|
18
|
+
var ACCESS_TOKEN_REFRESH_MARGIN_MS = 300 * 1e3;
|
|
19
|
+
/**
|
|
20
|
+
* Default window in which a Threads long-lived token (60 days) is refreshed:
|
|
21
|
+
* once it is this close to lapsing. Meta refuses to refresh a token younger than 24 hours, so a
|
|
22
|
+
* publish soon after connecting keeps the token it has.
|
|
23
|
+
*/
|
|
24
|
+
var THREADS_REFRESH_WINDOW_MS = 10080 * 60 * 1e3;
|
|
25
|
+
var THREADS_REFRESH_URL = "https://graph.threads.net/refresh_access_token";
|
|
26
|
+
var PLATFORM_LABELS = {
|
|
27
|
+
youtube: "YouTube",
|
|
28
|
+
x: "X",
|
|
29
|
+
threads: "Threads",
|
|
30
|
+
facebook: "Facebook",
|
|
31
|
+
bluesky: "Bluesky"
|
|
32
|
+
};
|
|
33
|
+
function platformLabel(platform) {
|
|
34
|
+
return PLATFORM_LABELS[platform] ?? platform;
|
|
35
|
+
}
|
|
36
|
+
/** Where a person reconnects an account, unless the host says otherwise. */
|
|
37
|
+
var DEFAULT_SOCIAL_SETTINGS_LOCATION = "Settings → Social";
|
|
38
|
+
/** What the poster sees when an account has to be connected again. */
|
|
39
|
+
function reconnectMessage(platform, settingsLocation = DEFAULT_SOCIAL_SETTINGS_LOCATION) {
|
|
40
|
+
const label = platformLabel(platform);
|
|
41
|
+
return `The ${label} account's sign-in has expired or was revoked, so nothing was posted. Reconnect ${label} in ${settingsLocation}, then try again.`;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The account's sign-in can no longer be used or refreshed; a person has to
|
|
45
|
+
* reconnect it. The message is safe to show and never carries provider text.
|
|
46
|
+
*/
|
|
47
|
+
var GarrulaReconnectError = class extends Error {
|
|
48
|
+
platform;
|
|
49
|
+
code = "RECONNECT_REQUIRED";
|
|
50
|
+
constructor(platform, settingsLocation) {
|
|
51
|
+
super(reconnectMessage(platform, settingsLocation));
|
|
52
|
+
this.platform = platform;
|
|
53
|
+
this.name = "GarrulaReconnectError";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
/** The provider rejected the sign-in (HTTP 401 or an auth error code). */
|
|
57
|
+
function isAuthError(error) {
|
|
58
|
+
if (error instanceof GarrulaReconnectError) return false;
|
|
59
|
+
if (!(error instanceof SocialError)) return false;
|
|
60
|
+
return error.code === "AUTH_ERROR" || error.statusCode === 401;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The provider refused the refresh grant itself (revoked consent,
|
|
64
|
+
* `invalid_grant`, a rotated-away X refresh token), as opposed to a network
|
|
65
|
+
* failure or an outage worth retrying later.
|
|
66
|
+
*/
|
|
67
|
+
function isRefreshRejected(error) {
|
|
68
|
+
if (!(error instanceof SocialError)) return false;
|
|
69
|
+
if (error.code === "AUTH_ERROR") {
|
|
70
|
+
if (error.platform === "youtube") return OAUTH_GRANT_REFUSED.test(error.message);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
const status = error.statusCode;
|
|
74
|
+
return status === 400 || status === 401 || status === 403;
|
|
75
|
+
}
|
|
76
|
+
var OAUTH_GRANT_REFUSED = /\b(invalid_grant|invalid_client|unauthorized_client|invalid_scope)\b/;
|
|
77
|
+
function parseExpiry(value) {
|
|
78
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
|
79
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
80
|
+
const date = new Date(value);
|
|
81
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
function refreshKind(platform, credentials) {
|
|
86
|
+
const has = (name) => typeof credentials[name] === "string" && credentials[name].length > 0;
|
|
87
|
+
switch (platform) {
|
|
88
|
+
case "youtube": return has("refreshToken") && has("clientId") && has("clientSecret") ? "oauth2" : null;
|
|
89
|
+
case "x": return (credentials.authType === "oauth2" || !credentials.accessSecret) && has("refreshToken") && has("clientId") && has("clientSecret") ? "oauth2" : null;
|
|
90
|
+
case "threads": return has("accessToken") ? "threads" : null;
|
|
91
|
+
default: return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The stored credentials with a refreshed token set merged in. Every other
|
|
96
|
+
* stored field (client id/secret, user id, auth type, scopes) is kept.
|
|
97
|
+
*/
|
|
98
|
+
function mergeRefreshedCredentials(credentials, auth) {
|
|
99
|
+
const next = {
|
|
100
|
+
...credentials,
|
|
101
|
+
accessToken: auth.accessToken
|
|
102
|
+
};
|
|
103
|
+
if (auth.refreshToken) next.refreshToken = auth.refreshToken;
|
|
104
|
+
if (auth.expiresAt) next.expiresAt = auth.expiresAt.toISOString();
|
|
105
|
+
else delete next.expiresAt;
|
|
106
|
+
if (auth.tokenType) next.tokenType = auth.tokenType;
|
|
107
|
+
if (auth.scopes?.length) next.scopes = auth.scopes;
|
|
108
|
+
return next;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Refresh a Threads long-lived token. The upstream Threads adapter does not
|
|
112
|
+
* implement `refreshToken()` (TODO(happyvertical/sdk#1376)).
|
|
113
|
+
*/
|
|
114
|
+
async function refreshThreadsToken(accessToken, fetchImpl = fetch) {
|
|
115
|
+
const url = new URL(THREADS_REFRESH_URL);
|
|
116
|
+
url.searchParams.set("grant_type", "th_refresh_token");
|
|
117
|
+
url.searchParams.set("access_token", accessToken);
|
|
118
|
+
const response = await fetchImpl(url);
|
|
119
|
+
const body = await response.json().catch(() => null);
|
|
120
|
+
if (!response.ok || typeof body?.access_token !== "string" || !body.access_token) {
|
|
121
|
+
const code = body?.error?.code;
|
|
122
|
+
const status = response.ok ? 400 : response.status;
|
|
123
|
+
throw new SocialError("Threads token refresh failed", code === 190 ? "AUTH_ERROR" : "REFRESH_FAILED", "threads", code === 190 ? 401 : status);
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
accessToken: body.access_token,
|
|
127
|
+
tokenType: typeof body.token_type === "string" ? body.token_type : void 0,
|
|
128
|
+
expiresAt: typeof body.expires_in === "number" ? new Date(Date.now() + body.expires_in * 1e3) : void 0
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/outbound/rates.ts
|
|
133
|
+
var FALLBACK_X_RATES = Object.freeze({
|
|
134
|
+
post: .015,
|
|
135
|
+
postWithUrl: .2,
|
|
136
|
+
reply: .01
|
|
137
|
+
});
|
|
138
|
+
var DEFAULT_OUTBOUND_RATES = Object.freeze({ x: FALLBACK_X_RATES });
|
|
139
|
+
var MICROS_PER_USD = 1e6;
|
|
140
|
+
function usdToMicros(usd) {
|
|
141
|
+
return Math.round(usd * MICROS_PER_USD);
|
|
142
|
+
}
|
|
143
|
+
/** Estimate a publish from the rate table; unknown platforms are unpriced (0). */
|
|
144
|
+
function estimateCost(rates, platform, hasUrl) {
|
|
145
|
+
const table = rates[platform];
|
|
146
|
+
if (!table) return {
|
|
147
|
+
micros: 0,
|
|
148
|
+
source: "unpriced"
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
micros: usdToMicros(hasUrl ? table.postWithUrl : table.post),
|
|
152
|
+
source: "rate-table"
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Read a cost the adapter reported on its publish result. The social SDK does
|
|
157
|
+
* not report one yet (happyvertical.com#518); this accepts the shapes it is
|
|
158
|
+
* expected to use: `cost` as USD number, or `{ usd }` / `{ amountUsd }`.
|
|
159
|
+
*/
|
|
160
|
+
function adapterCostMicros(result) {
|
|
161
|
+
if (!result || typeof result !== "object") return null;
|
|
162
|
+
const cost = result.cost;
|
|
163
|
+
let usd = cost;
|
|
164
|
+
if (cost && typeof cost === "object") {
|
|
165
|
+
const c = cost;
|
|
166
|
+
usd = c.usd ?? c.amountUsd;
|
|
167
|
+
}
|
|
168
|
+
return typeof usd === "number" && Number.isFinite(usd) && usd >= 0 ? usdToMicros(usd) : null;
|
|
169
|
+
}
|
|
170
|
+
/** `YYYY-MM` in UTC. */
|
|
171
|
+
function monthKey(date) {
|
|
172
|
+
return date.toISOString().slice(0, 7);
|
|
173
|
+
}
|
|
174
|
+
//#endregion
|
|
175
|
+
//#region src/config.ts
|
|
176
|
+
var DEFAULT_GARRULA_CONFIG = Object.freeze({
|
|
177
|
+
storyLinkTargets: [
|
|
178
|
+
"facebook",
|
|
179
|
+
"x",
|
|
180
|
+
"threads"
|
|
181
|
+
],
|
|
182
|
+
articleVideoTargets: [
|
|
183
|
+
"youtube",
|
|
184
|
+
"x",
|
|
185
|
+
"threads",
|
|
186
|
+
"facebook"
|
|
187
|
+
],
|
|
188
|
+
defaultPublishMode: "dry_run",
|
|
189
|
+
tenantLabel: "organization",
|
|
190
|
+
socialSettingsLocation: "Settings → Social",
|
|
191
|
+
accessTokenRefreshMarginMs: ACCESS_TOKEN_REFRESH_MARGIN_MS,
|
|
192
|
+
threadsRefreshWindowMs: THREADS_REFRESH_WINDOW_MS,
|
|
193
|
+
outboundRates: DEFAULT_OUTBOUND_RATES,
|
|
194
|
+
outboundDefaultMonthlyCapUsd: 5,
|
|
195
|
+
outboundMaxLength: 280
|
|
196
|
+
});
|
|
197
|
+
/** Overlay the host's partial configuration on the neutral defaults. */
|
|
198
|
+
function resolveGarrulaConfig(overrides = {}) {
|
|
199
|
+
const config = { ...DEFAULT_GARRULA_CONFIG };
|
|
200
|
+
for (const key of Object.keys(overrides)) {
|
|
201
|
+
const value = overrides[key];
|
|
202
|
+
if (value !== void 0) config[key] = value;
|
|
203
|
+
}
|
|
204
|
+
config.storyLinkTargets = [...config.storyLinkTargets];
|
|
205
|
+
config.articleVideoTargets = [...config.articleVideoTargets];
|
|
206
|
+
config.outboundRates = { ...config.outboundRates };
|
|
207
|
+
return config;
|
|
208
|
+
}
|
|
209
|
+
/** Why a post was not sent because its tenant may not publish. */
|
|
210
|
+
function tenantBlockedMessage(config) {
|
|
211
|
+
return `Posting is paused for this ${config.tenantLabel}, so nothing was posted.`;
|
|
212
|
+
}
|
|
213
|
+
/** What the caller is told when no tenant can be resolved. */
|
|
214
|
+
function tenantRequiredMessage(config) {
|
|
215
|
+
return `Social publishing requires an ${config.tenantLabel} (tenantId).`;
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/outbound/drafting.ts
|
|
219
|
+
var DraftingError = class extends Error {
|
|
220
|
+
constructor(message) {
|
|
221
|
+
super(message);
|
|
222
|
+
this.name = "DraftingError";
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
/** Every reference the drafter may cite for an event, nothing else. */
|
|
226
|
+
function allowedEvidence(event) {
|
|
227
|
+
return {
|
|
228
|
+
urls: new Set([event.url, ...event.evidenceUrls ?? []].filter(Boolean)),
|
|
229
|
+
lines: new Set([event.changelogLine, ...event.changelog ?? []].filter((line) => typeof line === "string").map((line) => line.trim()).filter(Boolean))
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
function buildDraftPrompt(persona, kind, event, maxLength) {
|
|
233
|
+
const { urls, lines } = allowedEvidence(event);
|
|
234
|
+
return [
|
|
235
|
+
"You write one short social media post announcing a software change.",
|
|
236
|
+
`Write in this voice: ${persona.trim() || "plain, factual, friendly"}.`,
|
|
237
|
+
`Post type: ${kind}. At most ${maxLength} characters. Do not include any URL in the text.`,
|
|
238
|
+
"State only facts supported by the event below. Do not invent features, numbers or dates.",
|
|
239
|
+
"Reply with JSON only: {\"text\": string, \"claims\": [{\"text\": string, \"evidence\": string[]}]}.",
|
|
240
|
+
"Every factual statement in the post must appear in `claims`, and every claim must cite",
|
|
241
|
+
"evidence copied exactly from the allowed evidence lists (a URL or a changelog line).",
|
|
242
|
+
"",
|
|
243
|
+
`Event kind: ${event.kind}`,
|
|
244
|
+
`Title: ${event.title}`,
|
|
245
|
+
event.version ? `Version: ${event.version}` : "",
|
|
246
|
+
event.repo ? `Repository: ${event.repo}` : "",
|
|
247
|
+
event.summary ? `Summary: ${event.summary}` : "",
|
|
248
|
+
`Allowed evidence URLs: ${JSON.stringify([...urls])}`,
|
|
249
|
+
`Allowed evidence changelog lines: ${JSON.stringify([...lines])}`
|
|
250
|
+
].filter(Boolean).join("\n");
|
|
251
|
+
}
|
|
252
|
+
function extractJson(raw) {
|
|
253
|
+
const body = (raw.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1] ?? raw).trim();
|
|
254
|
+
const start = body.indexOf("{");
|
|
255
|
+
const end = body.lastIndexOf("}");
|
|
256
|
+
if (start < 0 || end < start) throw new DraftingError("The drafter did not return JSON.");
|
|
257
|
+
try {
|
|
258
|
+
return JSON.parse(body.slice(start, end + 1));
|
|
259
|
+
} catch {
|
|
260
|
+
throw new DraftingError("The drafter returned malformed JSON.");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Parse a model reply into a draft. Evidence that is not one of the event's
|
|
265
|
+
* own URLs or changelog lines is dropped, so a made-up citation leaves the
|
|
266
|
+
* claim uncited (and the draft unpublishable) rather than looking supported.
|
|
267
|
+
*/
|
|
268
|
+
function parseDraft(raw, event) {
|
|
269
|
+
const data = extractJson(raw);
|
|
270
|
+
const text = typeof data.text === "string" ? data.text.trim() : "";
|
|
271
|
+
if (!text) throw new DraftingError("The drafter returned no post text.");
|
|
272
|
+
const { urls, lines } = allowedEvidence(event);
|
|
273
|
+
const claims = [];
|
|
274
|
+
for (const entry of Array.isArray(data.claims) ? data.claims : []) {
|
|
275
|
+
if (!entry || typeof entry !== "object") continue;
|
|
276
|
+
const claimText = entry.text;
|
|
277
|
+
if (typeof claimText !== "string" || !claimText.trim()) continue;
|
|
278
|
+
const evidence = [];
|
|
279
|
+
const refs = entry.evidence;
|
|
280
|
+
for (const ref of Array.isArray(refs) ? refs : []) {
|
|
281
|
+
if (typeof ref !== "string") continue;
|
|
282
|
+
const value = ref.trim();
|
|
283
|
+
if (urls.has(value)) evidence.push({
|
|
284
|
+
type: "url",
|
|
285
|
+
ref: value
|
|
286
|
+
});
|
|
287
|
+
else if (lines.has(value)) evidence.push({
|
|
288
|
+
type: "changelog",
|
|
289
|
+
ref: value
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
claims.push({
|
|
293
|
+
text: claimText.trim(),
|
|
294
|
+
evidence
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
return {
|
|
298
|
+
text,
|
|
299
|
+
claims
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
async function draftPost(ai, persona, kind, event, maxLength) {
|
|
303
|
+
let raw;
|
|
304
|
+
try {
|
|
305
|
+
raw = await ai.message(buildDraftPrompt(persona, kind, event, maxLength));
|
|
306
|
+
} catch (error) {
|
|
307
|
+
throw new DraftingError(`Drafting failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
308
|
+
}
|
|
309
|
+
const draft = parseDraft(raw, event);
|
|
310
|
+
if (draft.text.length > maxLength) throw new DraftingError(`The draft is longer than ${maxLength} characters.`);
|
|
311
|
+
return draft;
|
|
312
|
+
}
|
|
313
|
+
/** A post is publishable only with at least one claim, every claim with evidence. */
|
|
314
|
+
function isFullyCited(claims) {
|
|
315
|
+
if (!claims || claims.length === 0) return false;
|
|
316
|
+
return claims.every((claim) => claim.text?.trim() && Array.isArray(claim.evidence) && claim.evidence.length > 0 && claim.evidence.every((item) => typeof item.ref === "string" && item.ref.trim().length > 0));
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorateMetadata.js
|
|
320
|
+
function __decorateMetadata(k, v) {
|
|
321
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
322
|
+
}
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorate.js
|
|
325
|
+
function __decorate(decorators, target, key, desc) {
|
|
326
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
327
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
328
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
329
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
330
|
+
}
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/outbound/models.ts
|
|
333
|
+
var GarrulaOutboundSettings = class GarrulaOutboundSettings extends SmrtObject {
|
|
334
|
+
static __smrtPackage__ = "@happyvertical/garrula";
|
|
335
|
+
tenantId = null;
|
|
336
|
+
paused = false;
|
|
337
|
+
monthlyCapMicros = 0;
|
|
338
|
+
persona = "";
|
|
339
|
+
sources = [];
|
|
340
|
+
autonomy = {};
|
|
341
|
+
linkPolicy = {};
|
|
342
|
+
defaultLinkPolicy = "none";
|
|
343
|
+
accountIds = [];
|
|
344
|
+
deferTopics = [];
|
|
345
|
+
constructor(options = {}) {
|
|
346
|
+
super(options);
|
|
347
|
+
if (options.tenantId !== void 0) this.tenantId = options.tenantId;
|
|
348
|
+
if (options.paused !== void 0) this.paused = options.paused;
|
|
349
|
+
if (options.monthlyCapMicros !== void 0) this.monthlyCapMicros = options.monthlyCapMicros;
|
|
350
|
+
if (options.persona !== void 0) this.persona = options.persona;
|
|
351
|
+
if (options.sources !== void 0) this.sources = options.sources;
|
|
352
|
+
if (options.autonomy !== void 0) this.autonomy = options.autonomy;
|
|
353
|
+
if (options.linkPolicy !== void 0) this.linkPolicy = options.linkPolicy;
|
|
354
|
+
if (options.defaultLinkPolicy !== void 0) this.defaultLinkPolicy = options.defaultLinkPolicy;
|
|
355
|
+
if (options.accountIds !== void 0) this.accountIds = options.accountIds;
|
|
356
|
+
if (options.deferTopics !== void 0) this.deferTopics = options.deferTopics;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
__decorate([tenantId({ nullable: false }), __decorateMetadata("design:type", Object)], GarrulaOutboundSettings.prototype, "tenantId", void 0);
|
|
360
|
+
GarrulaOutboundSettings = __decorate([
|
|
361
|
+
TenantScoped({ mode: "required" }),
|
|
362
|
+
smrt({
|
|
363
|
+
tableStrategy: "sti",
|
|
364
|
+
api: false,
|
|
365
|
+
mcp: false,
|
|
366
|
+
cli: false
|
|
367
|
+
}),
|
|
368
|
+
__decorateMetadata("design:paramtypes", [Object])
|
|
369
|
+
], GarrulaOutboundSettings);
|
|
370
|
+
var GarrulaOutboundSettingsCollection = class extends SmrtCollection {
|
|
371
|
+
static _itemClass = GarrulaOutboundSettings;
|
|
372
|
+
};
|
|
373
|
+
var GarrulaOutboundPost = class GarrulaOutboundPost extends SmrtObject {
|
|
374
|
+
static __smrtPackage__ = "@happyvertical/garrula";
|
|
375
|
+
tenantId = null;
|
|
376
|
+
socialPostId = null;
|
|
377
|
+
state = "draft";
|
|
378
|
+
kind = "release";
|
|
379
|
+
sourceEventId = "";
|
|
380
|
+
sourceKind = "package-publish";
|
|
381
|
+
sourceUrl = null;
|
|
382
|
+
claims = [];
|
|
383
|
+
approvedBy = null;
|
|
384
|
+
rejectedReason = null;
|
|
385
|
+
constructor(options = {}) {
|
|
386
|
+
super(options);
|
|
387
|
+
if (options.tenantId !== void 0) this.tenantId = options.tenantId;
|
|
388
|
+
if (options.socialPostId !== void 0) this.socialPostId = options.socialPostId;
|
|
389
|
+
if (options.state !== void 0) this.state = options.state;
|
|
390
|
+
if (options.kind !== void 0) this.kind = options.kind;
|
|
391
|
+
if (options.sourceEventId !== void 0) this.sourceEventId = options.sourceEventId;
|
|
392
|
+
if (options.sourceKind !== void 0) this.sourceKind = options.sourceKind;
|
|
393
|
+
if (options.sourceUrl !== void 0) this.sourceUrl = options.sourceUrl;
|
|
394
|
+
if (options.claims !== void 0) this.claims = options.claims;
|
|
395
|
+
if (options.approvedBy !== void 0) this.approvedBy = options.approvedBy;
|
|
396
|
+
if (options.rejectedReason !== void 0) this.rejectedReason = options.rejectedReason;
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
__decorate([tenantId({ nullable: false }), __decorateMetadata("design:type", Object)], GarrulaOutboundPost.prototype, "tenantId", void 0);
|
|
400
|
+
GarrulaOutboundPost = __decorate([
|
|
401
|
+
TenantScoped({ mode: "required" }),
|
|
402
|
+
smrt({
|
|
403
|
+
tableStrategy: "sti",
|
|
404
|
+
api: false,
|
|
405
|
+
mcp: false,
|
|
406
|
+
cli: false
|
|
407
|
+
}),
|
|
408
|
+
__decorateMetadata("design:paramtypes", [Object])
|
|
409
|
+
], GarrulaOutboundPost);
|
|
410
|
+
var GarrulaOutboundPostCollection = class extends SmrtCollection {
|
|
411
|
+
static _itemClass = GarrulaOutboundPost;
|
|
412
|
+
};
|
|
413
|
+
var GarrulaSpendEntry = class GarrulaSpendEntry extends SmrtObject {
|
|
414
|
+
static __smrtPackage__ = "@happyvertical/garrula";
|
|
415
|
+
tenantId = null;
|
|
416
|
+
month = "";
|
|
417
|
+
socialPostId = null;
|
|
418
|
+
costMicros = 0;
|
|
419
|
+
/** `adapter` | `rate-table` | `unpriced` */
|
|
420
|
+
source = "rate-table";
|
|
421
|
+
/** `reserved` | `recorded` | `released` */
|
|
422
|
+
status = "reserved";
|
|
423
|
+
constructor(options = {}) {
|
|
424
|
+
super(options);
|
|
425
|
+
if (options.tenantId !== void 0) this.tenantId = options.tenantId;
|
|
426
|
+
if (options.month !== void 0) this.month = options.month;
|
|
427
|
+
if (options.socialPostId !== void 0) this.socialPostId = options.socialPostId;
|
|
428
|
+
if (options.costMicros !== void 0) this.costMicros = options.costMicros;
|
|
429
|
+
if (options.source !== void 0) this.source = options.source;
|
|
430
|
+
if (options.status !== void 0) this.status = options.status;
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
__decorate([tenantId({ nullable: false }), __decorateMetadata("design:type", Object)], GarrulaSpendEntry.prototype, "tenantId", void 0);
|
|
434
|
+
GarrulaSpendEntry = __decorate([
|
|
435
|
+
TenantScoped({ mode: "required" }),
|
|
436
|
+
smrt({
|
|
437
|
+
tableStrategy: "sti",
|
|
438
|
+
api: false,
|
|
439
|
+
mcp: false,
|
|
440
|
+
cli: false
|
|
441
|
+
}),
|
|
442
|
+
__decorateMetadata("design:paramtypes", [Object])
|
|
443
|
+
], GarrulaSpendEntry);
|
|
444
|
+
var GarrulaSpendEntryCollection = class extends SmrtCollection {
|
|
445
|
+
static _itemClass = GarrulaSpendEntry;
|
|
446
|
+
};
|
|
447
|
+
var GarrulaSourceEvent = class GarrulaSourceEvent extends SmrtObject {
|
|
448
|
+
static __smrtPackage__ = "@happyvertical/garrula";
|
|
449
|
+
tenantId = null;
|
|
450
|
+
/** `<kind>:<id>` */
|
|
451
|
+
eventKey = "";
|
|
452
|
+
/** `drafted` | `ignored` */
|
|
453
|
+
outcome = "ignored";
|
|
454
|
+
outboundPostIds = [];
|
|
455
|
+
constructor(options = {}) {
|
|
456
|
+
super(options);
|
|
457
|
+
if (options.tenantId !== void 0) this.tenantId = options.tenantId;
|
|
458
|
+
if (options.eventKey !== void 0) this.eventKey = options.eventKey;
|
|
459
|
+
if (options.outcome !== void 0) this.outcome = options.outcome;
|
|
460
|
+
if (options.outboundPostIds !== void 0) this.outboundPostIds = options.outboundPostIds;
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
__decorate([tenantId({ nullable: false }), __decorateMetadata("design:type", Object)], GarrulaSourceEvent.prototype, "tenantId", void 0);
|
|
464
|
+
GarrulaSourceEvent = __decorate([
|
|
465
|
+
TenantScoped({ mode: "required" }),
|
|
466
|
+
smrt({
|
|
467
|
+
tableStrategy: "sti",
|
|
468
|
+
api: false,
|
|
469
|
+
mcp: false,
|
|
470
|
+
cli: false
|
|
471
|
+
}),
|
|
472
|
+
__decorateMetadata("design:paramtypes", [Object])
|
|
473
|
+
], GarrulaSourceEvent);
|
|
474
|
+
var GarrulaSourceEventCollection = class extends SmrtCollection {
|
|
475
|
+
static _itemClass = GarrulaSourceEvent;
|
|
476
|
+
};
|
|
477
|
+
//#endregion
|
|
478
|
+
//#region src/outbound/sources.ts
|
|
479
|
+
/**
|
|
480
|
+
* Default source rules: package publishes always post, merged pull requests
|
|
481
|
+
* only when they are a `feat`/`perf` change, docs changes are off. Chores,
|
|
482
|
+
* dependency bumps and internal work never produce a candidate.
|
|
483
|
+
*/
|
|
484
|
+
var DEFAULT_SOURCE_RULES = Object.freeze([
|
|
485
|
+
{
|
|
486
|
+
kind: "package-publish",
|
|
487
|
+
postKind: "release",
|
|
488
|
+
excludeLabels: ["internal", "skip-social"]
|
|
489
|
+
},
|
|
490
|
+
{
|
|
491
|
+
kind: "merged-pr",
|
|
492
|
+
postKind: "feature",
|
|
493
|
+
includeTitle: ["^(feat|perf)(\\(|:|!)"],
|
|
494
|
+
excludeTitle: ["\\b(deps?|dependenc(y|ies)|internal)\\b"],
|
|
495
|
+
excludeLabels: [
|
|
496
|
+
"internal",
|
|
497
|
+
"dependencies",
|
|
498
|
+
"skip-social"
|
|
499
|
+
]
|
|
500
|
+
},
|
|
501
|
+
{
|
|
502
|
+
kind: "docs-change",
|
|
503
|
+
postKind: "docs",
|
|
504
|
+
enabled: false,
|
|
505
|
+
excludeLabels: ["internal", "skip-social"]
|
|
506
|
+
}
|
|
507
|
+
]);
|
|
508
|
+
var DEFAULT_AUTONOMY = Object.freeze({
|
|
509
|
+
release: "require-approval",
|
|
510
|
+
feature: "require-approval",
|
|
511
|
+
docs: "require-approval"
|
|
512
|
+
});
|
|
513
|
+
function anyMatches(patterns, value) {
|
|
514
|
+
return (patterns ?? []).some((pattern) => {
|
|
515
|
+
try {
|
|
516
|
+
return new RegExp(pattern, "i").test(value);
|
|
517
|
+
} catch {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
function lower(values) {
|
|
523
|
+
return (values ?? []).map((value) => value.toLowerCase());
|
|
524
|
+
}
|
|
525
|
+
/** Decide whether an event produces a candidate under the tenant's rules. */
|
|
526
|
+
function evaluateSourceEvent(settings, event) {
|
|
527
|
+
const rules = settings.sources.filter((candidate) => candidate.kind === event.kind);
|
|
528
|
+
if (rules.length === 0) return {
|
|
529
|
+
match: false,
|
|
530
|
+
reason: "no-rule"
|
|
531
|
+
};
|
|
532
|
+
const enabled = rules.filter((candidate) => candidate.enabled !== false);
|
|
533
|
+
if (enabled.length === 0) return {
|
|
534
|
+
match: false,
|
|
535
|
+
reason: "rule-disabled"
|
|
536
|
+
};
|
|
537
|
+
const labels = lower(event.labels);
|
|
538
|
+
for (const rule of enabled) {
|
|
539
|
+
if (rule.includeTitle?.length && !anyMatches(rule.includeTitle, event.title)) continue;
|
|
540
|
+
if (anyMatches(rule.excludeTitle, event.title)) continue;
|
|
541
|
+
const include = lower(rule.includeLabels);
|
|
542
|
+
if (include.length > 0 && !include.some((label) => labels.includes(label))) continue;
|
|
543
|
+
if (lower(rule.excludeLabels).some((label) => labels.includes(label))) continue;
|
|
544
|
+
return {
|
|
545
|
+
match: true,
|
|
546
|
+
rule
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
return {
|
|
550
|
+
match: false,
|
|
551
|
+
reason: "filtered"
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
function eventKey(event) {
|
|
555
|
+
return `${event.kind}:${event.id}`;
|
|
556
|
+
}
|
|
557
|
+
/** True when the event mentions a topic the tenant leaves to a person. */
|
|
558
|
+
function isDeferred(topics, event) {
|
|
559
|
+
const haystack = [
|
|
560
|
+
event.title,
|
|
561
|
+
event.summary ?? "",
|
|
562
|
+
...event.labels ?? []
|
|
563
|
+
].join("\n").toLowerCase();
|
|
564
|
+
return topics.some((topic) => topic.trim() !== "" && haystack.includes(topic.toLowerCase()));
|
|
565
|
+
}
|
|
566
|
+
//#endregion
|
|
567
|
+
//#region src/outbound/state.ts
|
|
568
|
+
/** Legal outbound transitions. Anything else is refused. */
|
|
569
|
+
var OUTBOUND_TRANSITIONS = {
|
|
570
|
+
draft: ["approved", "rejected"],
|
|
571
|
+
approved: [
|
|
572
|
+
"scheduled",
|
|
573
|
+
"published",
|
|
574
|
+
"failed",
|
|
575
|
+
"rejected",
|
|
576
|
+
"draft"
|
|
577
|
+
],
|
|
578
|
+
scheduled: [
|
|
579
|
+
"approved",
|
|
580
|
+
"published",
|
|
581
|
+
"failed",
|
|
582
|
+
"rejected",
|
|
583
|
+
"draft"
|
|
584
|
+
],
|
|
585
|
+
failed: [
|
|
586
|
+
"approved",
|
|
587
|
+
"rejected",
|
|
588
|
+
"draft"
|
|
589
|
+
],
|
|
590
|
+
published: [],
|
|
591
|
+
rejected: []
|
|
592
|
+
};
|
|
593
|
+
function canTransition(from, to) {
|
|
594
|
+
return OUTBOUND_TRANSITIONS[from].includes(to);
|
|
595
|
+
}
|
|
596
|
+
/** The `smrt-social` post status that mirrors an outbound state. */
|
|
597
|
+
function socialStatusFor(state) {
|
|
598
|
+
switch (state) {
|
|
599
|
+
case "draft": return "draft";
|
|
600
|
+
case "approved": return "approved";
|
|
601
|
+
case "scheduled": return "scheduled";
|
|
602
|
+
case "published": return "published";
|
|
603
|
+
case "failed": return "failed";
|
|
604
|
+
case "rejected": return "cancelled";
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/outbound/types.ts
|
|
609
|
+
var OUTBOUND_POST_KINDS = [
|
|
610
|
+
"release",
|
|
611
|
+
"feature",
|
|
612
|
+
"docs"
|
|
613
|
+
];
|
|
614
|
+
var OUTBOUND_STATES = [
|
|
615
|
+
"draft",
|
|
616
|
+
"approved",
|
|
617
|
+
"scheduled",
|
|
618
|
+
"published",
|
|
619
|
+
"failed",
|
|
620
|
+
"rejected"
|
|
621
|
+
];
|
|
622
|
+
/** Thrown by the public API for refused changes (never for a publish). */
|
|
623
|
+
var OutboundError = class extends Error {
|
|
624
|
+
code;
|
|
625
|
+
constructor(code, message) {
|
|
626
|
+
super(message);
|
|
627
|
+
this.name = "OutboundError";
|
|
628
|
+
this.code = code;
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
//#endregion
|
|
632
|
+
//#region src/outbound/service.ts
|
|
633
|
+
async function createOutboundStores(options) {
|
|
634
|
+
const opts = options;
|
|
635
|
+
return {
|
|
636
|
+
settings: await GarrulaOutboundSettingsCollection.create(opts),
|
|
637
|
+
posts: await GarrulaOutboundPostCollection.create(opts),
|
|
638
|
+
spend: await GarrulaSpendEntryCollection.create(opts),
|
|
639
|
+
events: await GarrulaSourceEventCollection.create(opts)
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
var locks = /* @__PURE__ */ new Map();
|
|
643
|
+
function withLock(tenantId, fn) {
|
|
644
|
+
const run = (locks.get(tenantId) ?? Promise.resolve()).then(fn, fn);
|
|
645
|
+
const tail = run.catch(() => void 0);
|
|
646
|
+
locks.set(tenantId, tail);
|
|
647
|
+
tail.then(() => {
|
|
648
|
+
if (locks.get(tenantId) === tail) locks.delete(tenantId);
|
|
649
|
+
});
|
|
650
|
+
return run;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Public entry points act for one tenant. When a tenant context is active it
|
|
654
|
+
* must be that tenant: another tenant's records are reported as not found,
|
|
655
|
+
* never touched.
|
|
656
|
+
*/
|
|
657
|
+
function assertAmbientTenant(tenantId) {
|
|
658
|
+
const ambient = getTenantId()?.trim();
|
|
659
|
+
if (ambient && ambient !== tenantId) throw new OutboundError("not-found", "No such record for the current tenant.");
|
|
660
|
+
}
|
|
661
|
+
/** Title prefix on social posts created by outbound drafting. */
|
|
662
|
+
var OUTBOUND_POST_MARKER = "garrula-outbound:";
|
|
663
|
+
/** True for a social post that outbound drafting created. */
|
|
664
|
+
function isOutboundMarked(post) {
|
|
665
|
+
return typeof post.title === "string" && post.title.startsWith("garrula-outbound:");
|
|
666
|
+
}
|
|
667
|
+
var OutboundService = class {
|
|
668
|
+
stores;
|
|
669
|
+
social;
|
|
670
|
+
configFn;
|
|
671
|
+
aiFn;
|
|
672
|
+
nowFn;
|
|
673
|
+
constructor(options) {
|
|
674
|
+
this.stores = options.stores;
|
|
675
|
+
this.social = options.social;
|
|
676
|
+
this.configFn = options.config;
|
|
677
|
+
this.aiFn = options.ai;
|
|
678
|
+
this.nowFn = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
679
|
+
}
|
|
680
|
+
/** The default cap; a non-finite or negative configured value falls back to the shipped default. */
|
|
681
|
+
defaultCapMicros() {
|
|
682
|
+
const configured = this.configFn().outboundDefaultMonthlyCapUsd;
|
|
683
|
+
return usdToMicros(typeof configured === "number" && Number.isFinite(configured) && configured >= 0 ? configured : 5);
|
|
684
|
+
}
|
|
685
|
+
defaults(tenantId) {
|
|
686
|
+
return {
|
|
687
|
+
tenantId,
|
|
688
|
+
paused: false,
|
|
689
|
+
monthlyCapMicros: this.defaultCapMicros(),
|
|
690
|
+
persona: "",
|
|
691
|
+
sources: DEFAULT_SOURCE_RULES.map((rule) => ({ ...rule })),
|
|
692
|
+
autonomy: { ...DEFAULT_AUTONOMY },
|
|
693
|
+
linkPolicy: {},
|
|
694
|
+
defaultLinkPolicy: "none",
|
|
695
|
+
accountIds: [],
|
|
696
|
+
deferTopics: []
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
async findSettingsRow(tenantId) {
|
|
700
|
+
return (await this.stores.settings.list({ where: { tenantId } })).find((row) => row.tenantId === tenantId) ?? null;
|
|
701
|
+
}
|
|
702
|
+
toSettings(tenantId, row) {
|
|
703
|
+
const base = this.defaults(tenantId);
|
|
704
|
+
if (!row) return base;
|
|
705
|
+
const rule = (value) => !!value && typeof value === "object";
|
|
706
|
+
return {
|
|
707
|
+
tenantId,
|
|
708
|
+
paused: row.paused === true,
|
|
709
|
+
monthlyCapMicros: Number.isFinite(row.monthlyCapMicros) && row.monthlyCapMicros >= 0 ? row.monthlyCapMicros : base.monthlyCapMicros,
|
|
710
|
+
persona: row.persona ?? "",
|
|
711
|
+
sources: Array.isArray(row.sources) ? row.sources : base.sources,
|
|
712
|
+
autonomy: {
|
|
713
|
+
...base.autonomy,
|
|
714
|
+
...rule(row.autonomy) ? row.autonomy : {}
|
|
715
|
+
},
|
|
716
|
+
linkPolicy: rule(row.linkPolicy) ? row.linkPolicy : {},
|
|
717
|
+
defaultLinkPolicy: row.defaultLinkPolicy === "include" ? "include" : "none",
|
|
718
|
+
accountIds: Array.isArray(row.accountIds) ? row.accountIds : [],
|
|
719
|
+
deferTopics: Array.isArray(row.deferTopics) ? row.deferTopics.map(String) : []
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
/** Read fresh settings (never cached), defaults when the tenant has none. */
|
|
723
|
+
getSettings(tenantId) {
|
|
724
|
+
assertAmbientTenant(tenantId);
|
|
725
|
+
return withTenant({ tenantId }, async () => this.toSettings(tenantId, await this.findSettingsRow(tenantId)));
|
|
726
|
+
}
|
|
727
|
+
updateSettings(tenantId, patch) {
|
|
728
|
+
assertAmbientTenant(tenantId);
|
|
729
|
+
return withLock(tenantId, () => withTenant({ tenantId }, async () => {
|
|
730
|
+
const next = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
|
|
731
|
+
if (patch.paused !== void 0) next.paused = patch.paused === true;
|
|
732
|
+
if (patch.monthlyCapMicros !== void 0) {
|
|
733
|
+
const cap = patch.monthlyCapMicros;
|
|
734
|
+
if (!Number.isFinite(cap) || cap < 0) throw new OutboundError("invalid", "The monthly cap must be zero or more.");
|
|
735
|
+
next.monthlyCapMicros = Math.round(cap);
|
|
736
|
+
}
|
|
737
|
+
if (patch.persona !== void 0) next.persona = String(patch.persona);
|
|
738
|
+
if (patch.sources !== void 0) next.sources = patch.sources;
|
|
739
|
+
if (patch.autonomy) for (const [kind, mode] of Object.entries(patch.autonomy)) {
|
|
740
|
+
if (!OUTBOUND_POST_KINDS.includes(kind)) throw new OutboundError("invalid", `Unknown post type: ${kind}`);
|
|
741
|
+
if (mode !== "auto" && mode !== "require-approval") throw new OutboundError("invalid", `Unknown autonomy mode: ${String(mode)}`);
|
|
742
|
+
next.autonomy[kind] = mode;
|
|
743
|
+
}
|
|
744
|
+
if (patch.linkPolicy) next.linkPolicy = {
|
|
745
|
+
...next.linkPolicy,
|
|
746
|
+
...patch.linkPolicy
|
|
747
|
+
};
|
|
748
|
+
if (patch.defaultLinkPolicy !== void 0) next.defaultLinkPolicy = patch.defaultLinkPolicy;
|
|
749
|
+
if (patch.accountIds !== void 0) next.accountIds = [...patch.accountIds];
|
|
750
|
+
if (patch.deferTopics !== void 0) next.deferTopics = [...new Set(patch.deferTopics.map((topic) => String(topic).trim()).filter(Boolean))];
|
|
751
|
+
for (const policy of [next.defaultLinkPolicy, ...Object.values(next.linkPolicy)]) if (policy !== "none" && policy !== "include") throw new OutboundError("invalid", `Unknown link policy: ${String(policy)}`);
|
|
752
|
+
const row = await this.findSettingsRow(tenantId);
|
|
753
|
+
const data = {
|
|
754
|
+
paused: next.paused,
|
|
755
|
+
monthlyCapMicros: next.monthlyCapMicros,
|
|
756
|
+
persona: next.persona,
|
|
757
|
+
sources: next.sources,
|
|
758
|
+
autonomy: next.autonomy,
|
|
759
|
+
linkPolicy: next.linkPolicy,
|
|
760
|
+
defaultLinkPolicy: next.defaultLinkPolicy,
|
|
761
|
+
accountIds: next.accountIds,
|
|
762
|
+
deferTopics: next.deferTopics
|
|
763
|
+
};
|
|
764
|
+
if (row) {
|
|
765
|
+
Object.assign(row, data);
|
|
766
|
+
await row.save();
|
|
767
|
+
} else await this.stores.settings.create({
|
|
768
|
+
tenantId,
|
|
769
|
+
...data
|
|
770
|
+
});
|
|
771
|
+
return next;
|
|
772
|
+
}));
|
|
773
|
+
}
|
|
774
|
+
ingestSourceEvent(tenantId, event) {
|
|
775
|
+
assertAmbientTenant(tenantId);
|
|
776
|
+
if (!event || ![
|
|
777
|
+
"package-publish",
|
|
778
|
+
"merged-pr",
|
|
779
|
+
"docs-change"
|
|
780
|
+
].includes(event.kind) || !String(event.id ?? "").trim() || !String(event.title ?? "").trim() || !String(event.url ?? "").trim()) throw new OutboundError("invalid", "A source event needs a kind, id, title and url.");
|
|
781
|
+
return withLock(tenantId, () => withTenant({ tenantId }, async () => {
|
|
782
|
+
const key = eventKey(event);
|
|
783
|
+
if ((await this.stores.events.list({ where: {
|
|
784
|
+
tenantId,
|
|
785
|
+
eventKey: key
|
|
786
|
+
} })).some((row) => row.tenantId === tenantId)) return { outcome: "duplicate" };
|
|
787
|
+
const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
|
|
788
|
+
const decision = evaluateSourceEvent(settings, event);
|
|
789
|
+
if (!decision.match) {
|
|
790
|
+
await this.stores.events.create({
|
|
791
|
+
tenantId,
|
|
792
|
+
eventKey: key,
|
|
793
|
+
outcome: "ignored"
|
|
794
|
+
});
|
|
795
|
+
return {
|
|
796
|
+
outcome: "ignored",
|
|
797
|
+
reason: decision.reason
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
const accounts = await this.targetAccounts(tenantId, settings);
|
|
801
|
+
if (accounts.length === 0) return {
|
|
802
|
+
outcome: "ignored",
|
|
803
|
+
reason: "no-accounts"
|
|
804
|
+
};
|
|
805
|
+
const kind = decision.rule.postKind;
|
|
806
|
+
let draft;
|
|
807
|
+
try {
|
|
808
|
+
draft = await draftPost(this.aiFn(), settings.persona, kind, event, this.configFn().outboundMaxLength);
|
|
809
|
+
} catch (error) {
|
|
810
|
+
if (error instanceof DraftingError) return {
|
|
811
|
+
outcome: "draft-failed",
|
|
812
|
+
error: error.message
|
|
813
|
+
};
|
|
814
|
+
return {
|
|
815
|
+
outcome: "draft-failed",
|
|
816
|
+
error: error instanceof Error ? error.message : String(error)
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
const drafts = [];
|
|
820
|
+
const ids = [];
|
|
821
|
+
for (const account of accounts) {
|
|
822
|
+
const post = await this.social.socialPosts.createDraft({
|
|
823
|
+
socialAccountId: account.id,
|
|
824
|
+
postType: "text",
|
|
825
|
+
title: `${OUTBOUND_POST_MARKER}${event.id}`,
|
|
826
|
+
description: draft.text,
|
|
827
|
+
linkUrl: event.url,
|
|
828
|
+
tenantId
|
|
829
|
+
});
|
|
830
|
+
let row;
|
|
831
|
+
try {
|
|
832
|
+
row = await this.stores.posts.create({
|
|
833
|
+
tenantId,
|
|
834
|
+
socialPostId: post.id,
|
|
835
|
+
state: "draft",
|
|
836
|
+
kind,
|
|
837
|
+
sourceEventId: event.id,
|
|
838
|
+
sourceKind: event.kind,
|
|
839
|
+
sourceUrl: event.url,
|
|
840
|
+
claims: draft.claims
|
|
841
|
+
});
|
|
842
|
+
} catch (error) {
|
|
843
|
+
await this.discardSocialDraft(post);
|
|
844
|
+
throw error;
|
|
845
|
+
}
|
|
846
|
+
ids.push(row.id);
|
|
847
|
+
if (settings.autonomy[kind] === "auto" && isFullyCited(draft.claims) && !isDeferred(settings.deferTopics, event)) await this.transition(tenantId, row, "approved", { approvedBy: "autonomy" });
|
|
848
|
+
drafts.push(await this.view(tenantId, row, settings));
|
|
849
|
+
}
|
|
850
|
+
await this.stores.events.create({
|
|
851
|
+
tenantId,
|
|
852
|
+
eventKey: key,
|
|
853
|
+
outcome: "drafted",
|
|
854
|
+
outboundPostIds: ids
|
|
855
|
+
});
|
|
856
|
+
return {
|
|
857
|
+
outcome: "drafted",
|
|
858
|
+
drafts
|
|
859
|
+
};
|
|
860
|
+
}));
|
|
861
|
+
}
|
|
862
|
+
async targetAccounts(tenantId, settings) {
|
|
863
|
+
return (await this.social.socialAccounts.findReady()).filter((account) => account.id && account.tenantId === tenantId && (settings.accountIds.length === 0 || settings.accountIds.includes(account.id)));
|
|
864
|
+
}
|
|
865
|
+
async requireRow(tenantId, id) {
|
|
866
|
+
const row = (await this.stores.posts.list({ where: {
|
|
867
|
+
id,
|
|
868
|
+
tenantId
|
|
869
|
+
} })).find((item) => item.id === id && item.tenantId === tenantId);
|
|
870
|
+
if (!row) throw new OutboundError("not-found", "No such outbound post for this tenant.");
|
|
871
|
+
return row;
|
|
872
|
+
}
|
|
873
|
+
async loadPost(tenantId, row) {
|
|
874
|
+
if (!row.socialPostId) return null;
|
|
875
|
+
const post = await this.social.socialPosts.get({ id: row.socialPostId }, { cache: false });
|
|
876
|
+
return post && post.tenantId === tenantId ? post : null;
|
|
877
|
+
}
|
|
878
|
+
async view(tenantId, row, settings, known) {
|
|
879
|
+
const post = known === void 0 ? await this.loadPost(tenantId, row) : known;
|
|
880
|
+
const accountId = post?.socialAccountId ?? null;
|
|
881
|
+
const policy = accountId && settings.linkPolicy[accountId] || settings.defaultLinkPolicy;
|
|
882
|
+
return {
|
|
883
|
+
id: row.id,
|
|
884
|
+
tenantId,
|
|
885
|
+
socialPostId: row.socialPostId,
|
|
886
|
+
accountId,
|
|
887
|
+
state: row.state,
|
|
888
|
+
kind: row.kind,
|
|
889
|
+
text: post?.description ?? "",
|
|
890
|
+
hashtags: post?.hashtags ?? [],
|
|
891
|
+
claims: row.claims ?? [],
|
|
892
|
+
linkUrl: policy === "include" ? post?.linkUrl ?? row.sourceUrl ?? null : null,
|
|
893
|
+
sourceEventId: row.sourceEventId,
|
|
894
|
+
sourceKind: row.sourceKind,
|
|
895
|
+
scheduledAt: post?.scheduledAt ? new Date(post.scheduledAt) : null,
|
|
896
|
+
publishedUrl: post?.platformUrl ?? null,
|
|
897
|
+
error: post?.errorMessage ?? null,
|
|
898
|
+
rejectedReason: row.rejectedReason ?? null,
|
|
899
|
+
approvedBy: row.approvedBy ?? null,
|
|
900
|
+
publishable: isFullyCited(row.claims),
|
|
901
|
+
createdAt: row.created_at ?? null
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
listDrafts(tenantId, filter = {}) {
|
|
905
|
+
assertAmbientTenant(tenantId);
|
|
906
|
+
return withTenant({ tenantId }, async () => {
|
|
907
|
+
const where = { tenantId };
|
|
908
|
+
if (filter.state) where.state = filter.state;
|
|
909
|
+
if (filter.kind) where.kind = filter.kind;
|
|
910
|
+
const rows = (await this.stores.posts.list({
|
|
911
|
+
where,
|
|
912
|
+
orderBy: "created_at DESC",
|
|
913
|
+
limit: filter.limit
|
|
914
|
+
})).filter((row) => row.tenantId === tenantId);
|
|
915
|
+
const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
|
|
916
|
+
return Promise.all(rows.map((row) => this.view(tenantId, row, settings)));
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
getDraft(tenantId, id) {
|
|
920
|
+
assertAmbientTenant(tenantId);
|
|
921
|
+
return withTenant({ tenantId }, async () => {
|
|
922
|
+
const row = await this.requireRow(tenantId, id);
|
|
923
|
+
const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
|
|
924
|
+
return this.view(tenantId, row, settings);
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
editDraft(tenantId, id, patch) {
|
|
928
|
+
assertAmbientTenant(tenantId);
|
|
929
|
+
return withTenant({ tenantId }, async () => {
|
|
930
|
+
const row = await this.requireRow(tenantId, id);
|
|
931
|
+
const state = row.state;
|
|
932
|
+
if (state === "published" || state === "rejected") throw new OutboundError("illegal-transition", `A ${state} post cannot be edited.`);
|
|
933
|
+
const social = {};
|
|
934
|
+
if (patch.text !== void 0) {
|
|
935
|
+
const text = String(patch.text).trim();
|
|
936
|
+
const max = this.configFn().outboundMaxLength;
|
|
937
|
+
if (!text) throw new OutboundError("invalid", "The post text cannot be empty.");
|
|
938
|
+
if (text.length > max) throw new OutboundError("invalid", `The post text is longer than ${max} characters.`);
|
|
939
|
+
social.description = text;
|
|
940
|
+
}
|
|
941
|
+
if (patch.linkUrl !== void 0) social.link_url = patch.linkUrl;
|
|
942
|
+
if (patch.claims !== void 0) {
|
|
943
|
+
if (!Array.isArray(patch.claims)) throw new OutboundError("invalid", "Claims must be a list.");
|
|
944
|
+
row.claims = patch.claims.map((claim) => ({
|
|
945
|
+
text: String(claim.text ?? "").trim(),
|
|
946
|
+
evidence: (claim.evidence ?? []).map((item) => ({
|
|
947
|
+
type: item.type === "changelog" ? "changelog" : "url",
|
|
948
|
+
ref: String(item.ref ?? "").trim()
|
|
949
|
+
}))
|
|
950
|
+
}));
|
|
951
|
+
}
|
|
952
|
+
const back = state !== "draft";
|
|
953
|
+
await this.updateSocialPost(tenantId, row, {
|
|
954
|
+
...social,
|
|
955
|
+
...back ? {
|
|
956
|
+
status: socialStatusFor("draft"),
|
|
957
|
+
scheduled_at: null
|
|
958
|
+
} : {}
|
|
959
|
+
});
|
|
960
|
+
if (back) row.state = "draft";
|
|
961
|
+
await row.save();
|
|
962
|
+
return this.getDraft(tenantId, id);
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
approve(tenantId, id, approvedBy = "user") {
|
|
966
|
+
assertAmbientTenant(tenantId);
|
|
967
|
+
return withTenant({ tenantId }, async () => {
|
|
968
|
+
const row = await this.requireRow(tenantId, id);
|
|
969
|
+
if (!isFullyCited(row.claims)) throw new OutboundError("uncited", "Every claim needs evidence before a post is approved.");
|
|
970
|
+
await this.transition(tenantId, row, "approved", { approvedBy });
|
|
971
|
+
return this.getDraft(tenantId, id);
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
reject(tenantId, id, reason = "") {
|
|
975
|
+
assertAmbientTenant(tenantId);
|
|
976
|
+
return withTenant({ tenantId }, async () => {
|
|
977
|
+
const row = await this.requireRow(tenantId, id);
|
|
978
|
+
await this.transition(tenantId, row, "rejected", { rejectedReason: reason || null });
|
|
979
|
+
return this.getDraft(tenantId, id);
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
/** A failed post goes back to approved so the next run publishes it again. */
|
|
983
|
+
retry(tenantId, id) {
|
|
984
|
+
assertAmbientTenant(tenantId);
|
|
985
|
+
return withTenant({ tenantId }, async () => {
|
|
986
|
+
const row = await this.requireRow(tenantId, id);
|
|
987
|
+
if (row.state !== "failed") throw new OutboundError("illegal-transition", "Only a failed post can be retried.");
|
|
988
|
+
if (!isFullyCited(row.claims)) throw new OutboundError("uncited", "Every claim needs evidence before a post is retried.");
|
|
989
|
+
await this.transition(tenantId, row, "approved", {});
|
|
990
|
+
return this.getDraft(tenantId, id);
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
schedule(tenantId, id, at) {
|
|
994
|
+
assertAmbientTenant(tenantId);
|
|
995
|
+
return withTenant({ tenantId }, async () => {
|
|
996
|
+
if (!(at instanceof Date) || Number.isNaN(at.getTime())) throw new OutboundError("invalid", "A schedule needs a valid date.");
|
|
997
|
+
const row = await this.requireRow(tenantId, id);
|
|
998
|
+
if (!isFullyCited(row.claims)) throw new OutboundError("uncited", "Every claim needs evidence before a post is scheduled.");
|
|
999
|
+
await this.transition(tenantId, row, "scheduled", {}, { scheduled_at: at });
|
|
1000
|
+
return this.getDraft(tenantId, id);
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
/** Approved or scheduled posts of the tenant whose time has come. */
|
|
1004
|
+
async dueForPublish(tenantId, now) {
|
|
1005
|
+
assertAmbientTenant(tenantId);
|
|
1006
|
+
return withTenant({ tenantId }, async () => {
|
|
1007
|
+
const rows = (await this.stores.posts.list({
|
|
1008
|
+
where: { tenantId },
|
|
1009
|
+
orderBy: "created_at ASC"
|
|
1010
|
+
})).filter((row) => row.tenantId === tenantId && (row.state === "approved" || row.state === "scheduled"));
|
|
1011
|
+
const due = [];
|
|
1012
|
+
for (const row of rows) {
|
|
1013
|
+
const post = await this.loadPost(tenantId, row);
|
|
1014
|
+
if (!post) continue;
|
|
1015
|
+
const at = post.scheduledAt ? new Date(post.scheduledAt) : null;
|
|
1016
|
+
if (!at || at.getTime() <= now.getTime()) due.push(post);
|
|
1017
|
+
}
|
|
1018
|
+
return due;
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
/** The tenant's post to publish now: it must be approved or scheduled. */
|
|
1022
|
+
async postForPublish(tenantId, id) {
|
|
1023
|
+
assertAmbientTenant(tenantId);
|
|
1024
|
+
return withTenant({ tenantId }, async () => {
|
|
1025
|
+
const row = await this.requireRow(tenantId, id);
|
|
1026
|
+
if (row.state !== "approved" && row.state !== "scheduled") throw new OutboundError("not-approved", "Only an approved or scheduled post can be published.");
|
|
1027
|
+
const post = await this.loadPost(tenantId, row);
|
|
1028
|
+
if (!post) throw new OutboundError("not-found", "The social post is missing.");
|
|
1029
|
+
return post;
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
outboundIdForPost(tenantId, socialPostId) {
|
|
1033
|
+
assertAmbientTenant(tenantId);
|
|
1034
|
+
return withTenant({ tenantId }, async () => {
|
|
1035
|
+
return (await this.findRowForPost(tenantId, socialPostId))?.id ?? null;
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
async discardSocialDraft(post) {
|
|
1039
|
+
try {
|
|
1040
|
+
await post.delete();
|
|
1041
|
+
} catch {}
|
|
1042
|
+
}
|
|
1043
|
+
async findRowForPost(tenantId, socialPostId) {
|
|
1044
|
+
return (await this.stores.posts.list({ where: {
|
|
1045
|
+
tenantId,
|
|
1046
|
+
socialPostId
|
|
1047
|
+
} })).find((row) => row.tenantId === tenantId && row.socialPostId === socialPostId) ?? null;
|
|
1048
|
+
}
|
|
1049
|
+
async transition(tenantId, row, to, extra, social = {}) {
|
|
1050
|
+
const from = row.state;
|
|
1051
|
+
if (!OUTBOUND_STATES.includes(from) || !canTransition(from, to)) throw new OutboundError("illegal-transition", `A ${from} post cannot become ${to}.`);
|
|
1052
|
+
await this.updateSocialPost(tenantId, row, {
|
|
1053
|
+
status: socialStatusFor(to),
|
|
1054
|
+
...social
|
|
1055
|
+
});
|
|
1056
|
+
row.state = to;
|
|
1057
|
+
if (extra.approvedBy !== void 0) row.approvedBy = extra.approvedBy;
|
|
1058
|
+
if (extra.rejectedReason !== void 0) row.rejectedReason = extra.rejectedReason;
|
|
1059
|
+
try {
|
|
1060
|
+
await row.save();
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
row.state = from;
|
|
1063
|
+
await this.updateSocialPost(tenantId, row, { status: socialStatusFor(from) }).catch(() => void 0);
|
|
1064
|
+
throw error;
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Mirror onto the SocialPost with a conditional update: it never overwrites
|
|
1069
|
+
* a post a publisher has claimed (`publishing`). A refused write throws
|
|
1070
|
+
* `in-flight` (claimed) or `not-found` (missing) and changes nothing.
|
|
1071
|
+
*/
|
|
1072
|
+
async updateSocialPost(tenantId, row, data) {
|
|
1073
|
+
if (!row.socialPostId || Object.keys(data).length === 0) return;
|
|
1074
|
+
const { socialPosts } = this.social;
|
|
1075
|
+
if ((await socialPosts.db.update(socialPosts.tableName, {
|
|
1076
|
+
id: row.socialPostId,
|
|
1077
|
+
tenant_id: tenantId,
|
|
1078
|
+
"status not in": ["publishing"]
|
|
1079
|
+
}, {
|
|
1080
|
+
...data,
|
|
1081
|
+
updated_at: /* @__PURE__ */ new Date()
|
|
1082
|
+
})).affected === 1) return;
|
|
1083
|
+
const current = await this.loadPost(tenantId, row);
|
|
1084
|
+
if (current && current.status === "publishing") throw new OutboundError("in-flight", "This post is being published right now, so it was not changed.");
|
|
1085
|
+
throw new OutboundError("not-found", "The social post for this draft is missing.");
|
|
1086
|
+
}
|
|
1087
|
+
/**
|
|
1088
|
+
* Record a publish that failed before the gate (account, credentials, token
|
|
1089
|
+
* refresh, media) so no spend reservation exists to settle it: the approved
|
|
1090
|
+
* or scheduled post becomes `failed` and can be retried after repair.
|
|
1091
|
+
*/
|
|
1092
|
+
failUnreserved(tenantId, socialPostId) {
|
|
1093
|
+
return withLock(tenantId, () => withTenant({ tenantId }, async () => {
|
|
1094
|
+
const row = await this.findRowForPost(tenantId, socialPostId);
|
|
1095
|
+
if (row && (row.state === "approved" || row.state === "scheduled")) {
|
|
1096
|
+
row.state = "failed";
|
|
1097
|
+
await row.save();
|
|
1098
|
+
}
|
|
1099
|
+
}));
|
|
1100
|
+
}
|
|
1101
|
+
async monthEntries(tenantId, month) {
|
|
1102
|
+
return (await this.stores.spend.list({ where: {
|
|
1103
|
+
tenantId,
|
|
1104
|
+
month
|
|
1105
|
+
} })).filter((entry) => entry.tenantId === tenantId && entry.month === month);
|
|
1106
|
+
}
|
|
1107
|
+
getSpend(tenantId, month) {
|
|
1108
|
+
assertAmbientTenant(tenantId);
|
|
1109
|
+
return withTenant({ tenantId }, async () => {
|
|
1110
|
+
const key = month ?? monthKey(this.nowFn());
|
|
1111
|
+
const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
|
|
1112
|
+
const entries = await this.monthEntries(tenantId, key);
|
|
1113
|
+
const spent = entries.filter((entry) => entry.status !== "released").reduce((sum, entry) => sum + entry.costMicros, 0);
|
|
1114
|
+
return {
|
|
1115
|
+
tenantId,
|
|
1116
|
+
month: key,
|
|
1117
|
+
capMicros: settings.monthlyCapMicros,
|
|
1118
|
+
spentMicros: spent,
|
|
1119
|
+
remainingMicros: Math.max(0, settings.monthlyCapMicros - spent),
|
|
1120
|
+
paused: settings.paused,
|
|
1121
|
+
entries: entries.map((entry) => ({
|
|
1122
|
+
id: entry.id,
|
|
1123
|
+
month: entry.month,
|
|
1124
|
+
postId: entry.socialPostId,
|
|
1125
|
+
costMicros: entry.costMicros,
|
|
1126
|
+
source: entry.source,
|
|
1127
|
+
status: entry.status,
|
|
1128
|
+
createdAt: entry.created_at ?? null
|
|
1129
|
+
}))
|
|
1130
|
+
};
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* The server-side checks every publish passes immediately before the
|
|
1135
|
+
* adapter call: tenant, approval state, evidence, pause, link policy and
|
|
1136
|
+
* the monthly cap. On success a spend reservation is held (atomically with
|
|
1137
|
+
* the cap check) until {@link finish}.
|
|
1138
|
+
*/
|
|
1139
|
+
beforeSend(post, platform) {
|
|
1140
|
+
const tenantId = post.tenantId?.trim();
|
|
1141
|
+
const refuse = (code, message) => ({
|
|
1142
|
+
ok: false,
|
|
1143
|
+
refusal: {
|
|
1144
|
+
code,
|
|
1145
|
+
message
|
|
1146
|
+
}
|
|
1147
|
+
});
|
|
1148
|
+
if (!tenantId) return Promise.resolve(refuse("invalid", "The post has no tenant."));
|
|
1149
|
+
const ambient = getTenantId()?.trim();
|
|
1150
|
+
if (ambient && ambient !== tenantId) return Promise.resolve(refuse("invalid", "The post belongs to another tenant."));
|
|
1151
|
+
return withLock(tenantId, () => withTenant({ tenantId }, async () => {
|
|
1152
|
+
const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
|
|
1153
|
+
if (settings.paused) return refuse("paused", "Posting is paused for this tenant, so nothing was posted.");
|
|
1154
|
+
const row = post.id ? await this.findRowForPost(tenantId, post.id) : null;
|
|
1155
|
+
let linkUrl = post.linkUrl ?? null;
|
|
1156
|
+
if (row) {
|
|
1157
|
+
if (row.state !== "approved" && row.state !== "scheduled") return refuse("not-approved", `This post is ${row.state}, not approved.`);
|
|
1158
|
+
if (!isFullyCited(row.claims)) return refuse("uncited", "A claim in this post has no evidence, so it was not posted.");
|
|
1159
|
+
const accountId = post.socialAccountId ?? "";
|
|
1160
|
+
linkUrl = (settings.linkPolicy[accountId] ?? settings.defaultLinkPolicy) === "include" ? post.linkUrl ?? row.sourceUrl ?? null : null;
|
|
1161
|
+
} else if (isOutboundMarked(post)) return refuse("not-approved", "This post was drafted by the outbound pipeline but has no approval record, so it was not posted.");
|
|
1162
|
+
const estimate = estimateCost(this.configFn().outboundRates, platform, linkUrl !== null);
|
|
1163
|
+
const month = monthKey(this.nowFn());
|
|
1164
|
+
const spent = (await this.monthEntries(tenantId, month)).filter((entry) => entry.status !== "released").reduce((sum, entry) => sum + entry.costMicros, 0);
|
|
1165
|
+
const valid = (n) => Number.isFinite(n) && n >= 0;
|
|
1166
|
+
if (!valid(estimate.micros) || !valid(settings.monthlyCapMicros) || !valid(spent)) return refuse("invalid", "The cost estimate or spend cap is not a valid amount, so nothing was posted.");
|
|
1167
|
+
if (spent >= settings.monthlyCapMicros || spent + estimate.micros > settings.monthlyCapMicros) return refuse("cap-reached", "The monthly posting spend cap is reached, so nothing was posted.");
|
|
1168
|
+
const entry = await this.stores.spend.create({
|
|
1169
|
+
tenantId,
|
|
1170
|
+
month,
|
|
1171
|
+
socialPostId: post.id ?? null,
|
|
1172
|
+
costMicros: estimate.micros,
|
|
1173
|
+
source: estimate.source,
|
|
1174
|
+
status: "reserved"
|
|
1175
|
+
});
|
|
1176
|
+
return {
|
|
1177
|
+
ok: true,
|
|
1178
|
+
linkUrl,
|
|
1179
|
+
reservation: {
|
|
1180
|
+
tenantId,
|
|
1181
|
+
entryId: entry.id,
|
|
1182
|
+
month,
|
|
1183
|
+
estimateMicros: estimate.micros,
|
|
1184
|
+
estimateSource: estimate.source,
|
|
1185
|
+
outboundId: row?.id ?? null
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
}));
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Settle a reservation after the publish. Spend is recorded whenever the
|
|
1192
|
+
* platform was reached (adapter cost, else the rate table; a dry run costs
|
|
1193
|
+
* nothing) and released otherwise; the outbound state follows the outcome.
|
|
1194
|
+
*/
|
|
1195
|
+
finish(reservation, outcome) {
|
|
1196
|
+
const { tenantId } = reservation;
|
|
1197
|
+
assertAmbientTenant(tenantId);
|
|
1198
|
+
return withLock(tenantId, () => withTenant({ tenantId }, async () => {
|
|
1199
|
+
const entry = (await this.monthEntries(tenantId, reservation.month)).find((item) => item.id === reservation.entryId);
|
|
1200
|
+
if (entry) {
|
|
1201
|
+
const result = outcome.result;
|
|
1202
|
+
if (!result) {
|
|
1203
|
+
entry.status = "released";
|
|
1204
|
+
entry.costMicros = 0;
|
|
1205
|
+
} else if (result.status === "dry_run" || result.status === "staged") {
|
|
1206
|
+
entry.status = "recorded";
|
|
1207
|
+
entry.costMicros = 0;
|
|
1208
|
+
entry.source = "unpriced";
|
|
1209
|
+
} else {
|
|
1210
|
+
const reported = adapterCostMicros(result);
|
|
1211
|
+
entry.status = "recorded";
|
|
1212
|
+
entry.costMicros = reported ?? reservation.estimateMicros;
|
|
1213
|
+
entry.source = reported !== null ? "adapter" : reservation.estimateSource;
|
|
1214
|
+
}
|
|
1215
|
+
await entry.save();
|
|
1216
|
+
}
|
|
1217
|
+
if (reservation.outboundId) {
|
|
1218
|
+
const row = await this.requireRow(tenantId, reservation.outboundId).catch(() => null);
|
|
1219
|
+
if (row && (row.state === "approved" || row.state === "scheduled")) {
|
|
1220
|
+
row.state = outcome.result || outcome.success ? "published" : "failed";
|
|
1221
|
+
await row.save();
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
}));
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
//#endregion
|
|
1228
|
+
//#region src/Garrula.ts
|
|
1229
|
+
/**
|
|
1230
|
+
* Host hooks shared by every Garrula instance in this process, including the
|
|
1231
|
+
* ones the job runner constructs for scheduled posts. The host application
|
|
1232
|
+
* registers them once at startup with {@link setGarrulaHost}.
|
|
1233
|
+
*/
|
|
1234
|
+
var registeredHost = {};
|
|
1235
|
+
function setGarrulaHost(host) {
|
|
1236
|
+
registeredHost = host;
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Configuration shared by every Garrula instance in this process, registered
|
|
1240
|
+
* once at startup like the host hooks. Unset keys keep the neutral defaults.
|
|
1241
|
+
*/
|
|
1242
|
+
var registeredConfig = {};
|
|
1243
|
+
function setGarrulaConfig(config) {
|
|
1244
|
+
registeredConfig = config;
|
|
1245
|
+
}
|
|
1246
|
+
/** Why a post was not sent because its tenant may not publish (default wording). */
|
|
1247
|
+
var GARRULA_TENANT_BLOCKED_MESSAGE = tenantBlockedMessage(DEFAULT_GARRULA_CONFIG);
|
|
1248
|
+
/** Why a post was not sent because another publish already has it. */
|
|
1249
|
+
var GARRULA_POST_BUSY_MESSAGE = "This post is already being posted or is no longer waiting to be posted.";
|
|
1250
|
+
/** Why a post was not sent because its account is switched off. */
|
|
1251
|
+
var GARRULA_ACCOUNT_INACTIVE_MESSAGE = "This social account is switched off, so nothing was posted.";
|
|
1252
|
+
/** Every status a post may be published from. */
|
|
1253
|
+
var PUBLISHABLE_STATUSES = [
|
|
1254
|
+
"draft",
|
|
1255
|
+
"approved",
|
|
1256
|
+
"scheduled",
|
|
1257
|
+
"failed"
|
|
1258
|
+
];
|
|
1259
|
+
/** Statuses of posts that {@link Garrula.run} publishes when due. */
|
|
1260
|
+
var DUE_STATUSES = ["approved", "scheduled"];
|
|
1261
|
+
var Garrula = class Garrula extends Agent {
|
|
1262
|
+
static __smrtPackage__ = "@happyvertical/garrula";
|
|
1263
|
+
static uiSlots = {
|
|
1264
|
+
queue: {
|
|
1265
|
+
id: "queue",
|
|
1266
|
+
label: "Dashboard",
|
|
1267
|
+
description: "Review social posts, status, and latest stats",
|
|
1268
|
+
icon: "list-checks",
|
|
1269
|
+
order: 1
|
|
1270
|
+
},
|
|
1271
|
+
settings: {
|
|
1272
|
+
id: "settings",
|
|
1273
|
+
label: "Settings",
|
|
1274
|
+
description: "Connect and manage social accounts",
|
|
1275
|
+
icon: "settings",
|
|
1276
|
+
order: 2
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
static adminRoutes = [{
|
|
1280
|
+
path: "queue",
|
|
1281
|
+
component: "QueuePanel"
|
|
1282
|
+
}, {
|
|
1283
|
+
path: "settings",
|
|
1284
|
+
component: "SettingsPanel"
|
|
1285
|
+
}];
|
|
1286
|
+
socialAccounts;
|
|
1287
|
+
socialPosts;
|
|
1288
|
+
analyticsSnapshots;
|
|
1289
|
+
socialFactory;
|
|
1290
|
+
hostOverride;
|
|
1291
|
+
configOverride;
|
|
1292
|
+
draftingAI;
|
|
1293
|
+
outboundStores;
|
|
1294
|
+
unsafeDisableOutboundGate = false;
|
|
1295
|
+
outbound;
|
|
1296
|
+
nowFn = () => /* @__PURE__ */ new Date();
|
|
1297
|
+
/** The Agent base's persisted config; Garrula's own settings are {@link garrulaConfig}. */
|
|
1298
|
+
config = {};
|
|
1299
|
+
constructor(options = {}) {
|
|
1300
|
+
super(options);
|
|
1301
|
+
this.socialFactory = options.socialFactory;
|
|
1302
|
+
this.hostOverride = options.host;
|
|
1303
|
+
this.configOverride = options.garrula;
|
|
1304
|
+
this.draftingAI = options.draftingAI;
|
|
1305
|
+
this.outboundStores = options.outboundStores;
|
|
1306
|
+
this.unsafeDisableOutboundGate = options.unsafeDisableOutboundGate === true;
|
|
1307
|
+
if (options.now) this.nowFn = options.now;
|
|
1308
|
+
if (options.collections) {
|
|
1309
|
+
this.socialAccounts = options.collections.socialAccounts;
|
|
1310
|
+
this.socialPosts = options.collections.socialPosts;
|
|
1311
|
+
this.analyticsSnapshots = options.collections.analyticsSnapshots;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
async initialize() {
|
|
1315
|
+
await super.initialize();
|
|
1316
|
+
let ownCollections = false;
|
|
1317
|
+
if (!this.socialAccounts || !this.socialPosts || !this.analyticsSnapshots) {
|
|
1318
|
+
const opts = {
|
|
1319
|
+
db: this.options.db,
|
|
1320
|
+
ai: this.options.ai
|
|
1321
|
+
};
|
|
1322
|
+
this.socialAccounts = await SocialAccountCollection.create(opts);
|
|
1323
|
+
this.socialPosts = await SocialPostCollection.create(opts);
|
|
1324
|
+
this.analyticsSnapshots = await SocialPostAnalyticsSnapshotCollection.create(opts);
|
|
1325
|
+
ownCollections = true;
|
|
1326
|
+
}
|
|
1327
|
+
if (!this.outbound && (ownCollections || this.outboundStores)) {
|
|
1328
|
+
this.outboundStores ??= await createOutboundStores({
|
|
1329
|
+
db: this.options.db,
|
|
1330
|
+
ai: this.options.ai
|
|
1331
|
+
});
|
|
1332
|
+
this.outbound = new OutboundService({
|
|
1333
|
+
stores: this.outboundStores,
|
|
1334
|
+
social: {
|
|
1335
|
+
socialAccounts: this.socialAccounts,
|
|
1336
|
+
socialPosts: this.socialPosts
|
|
1337
|
+
},
|
|
1338
|
+
config: () => this.garrulaConfig,
|
|
1339
|
+
ai: () => this.draftingAI ?? this.ai,
|
|
1340
|
+
now: () => this.nowFn()
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
if (!this.outbound && !this.unsafeDisableOutboundGate) throw new Error("Garrula has no outbound gate: pass `outboundStores` (or let it use its own database). `unsafeDisableOutboundGate: true` disables it and is for tests only.");
|
|
1344
|
+
return this;
|
|
1345
|
+
}
|
|
1346
|
+
get hostHooks() {
|
|
1347
|
+
return this.hostOverride ?? registeredHost;
|
|
1348
|
+
}
|
|
1349
|
+
/** The host's configuration over the neutral defaults. */
|
|
1350
|
+
get garrulaConfig() {
|
|
1351
|
+
return resolveGarrulaConfig({
|
|
1352
|
+
...registeredConfig,
|
|
1353
|
+
...this.configOverride
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Publish every post that is due (scheduled time reached, or approved).
|
|
1358
|
+
* Posts of an organization that may not publish right now are left as they
|
|
1359
|
+
* are and picked up by a later run.
|
|
1360
|
+
*/
|
|
1361
|
+
async run() {
|
|
1362
|
+
const duePosts = await this.socialPosts.findDueForPublish(/* @__PURE__ */ new Date());
|
|
1363
|
+
let published = 0;
|
|
1364
|
+
let failed = 0;
|
|
1365
|
+
let skipped = 0;
|
|
1366
|
+
for (const post of duePosts) {
|
|
1367
|
+
const result = await this.publishClaimed(post, { claimFrom: DUE_STATUSES });
|
|
1368
|
+
if (result.success) published++;
|
|
1369
|
+
else if (result.skipped) skipped++;
|
|
1370
|
+
else failed++;
|
|
1371
|
+
}
|
|
1372
|
+
if (duePosts.length > 0) this.logger.info("Published due social posts", {
|
|
1373
|
+
due: duePosts.length,
|
|
1374
|
+
published,
|
|
1375
|
+
failed,
|
|
1376
|
+
skipped
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
async createStoryLinkPosts(request) {
|
|
1380
|
+
const tenantId = this.resolveRequestTenantId(request.tenantId);
|
|
1381
|
+
return withTenant({ tenantId }, async () => {
|
|
1382
|
+
const accounts = await this.resolveTargetAccounts(request.targets ?? this.garrulaConfig.storyLinkTargets, tenantId);
|
|
1383
|
+
return Promise.all(accounts.map((account) => this.socialPosts.createDraft({
|
|
1384
|
+
socialAccountId: this.requireAccountId(account),
|
|
1385
|
+
contentId: request.contentId,
|
|
1386
|
+
postType: "link",
|
|
1387
|
+
title: request.title,
|
|
1388
|
+
description: request.excerpt ?? request.title,
|
|
1389
|
+
hashtags: this.mergeHashtags(account, request.hashtags),
|
|
1390
|
+
linkUrl: request.url,
|
|
1391
|
+
scheduledAt: request.scheduledAt ?? null,
|
|
1392
|
+
createdByUserId: request.createdByUserId ?? null,
|
|
1393
|
+
tenantId
|
|
1394
|
+
})));
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
async createArticleVideoPosts(request) {
|
|
1398
|
+
const tenantId = this.resolveRequestTenantId(request.tenantId);
|
|
1399
|
+
return withTenant({ tenantId }, async () => {
|
|
1400
|
+
const readyAccounts = await this.resolveTargetAccounts(request.targets ?? this.garrulaConfig.articleVideoTargets, tenantId);
|
|
1401
|
+
const accounts = this.selectAccounts(readyAccounts, request.accountIds);
|
|
1402
|
+
return Promise.all(accounts.map((account) => this.socialPosts.createDraft({
|
|
1403
|
+
socialAccountId: this.requireAccountId(account),
|
|
1404
|
+
contentId: request.contentId,
|
|
1405
|
+
videoContentId: request.videoContentId ?? null,
|
|
1406
|
+
postType: "video",
|
|
1407
|
+
title: request.title,
|
|
1408
|
+
description: request.description ?? request.title,
|
|
1409
|
+
hashtags: this.mergeHashtags(account, request.hashtags),
|
|
1410
|
+
linkUrl: request.url ?? null,
|
|
1411
|
+
mediaUrl: request.mediaUrl,
|
|
1412
|
+
scheduledAt: request.scheduledAt ?? null,
|
|
1413
|
+
createdByUserId: request.createdByUserId ?? null,
|
|
1414
|
+
tenantId
|
|
1415
|
+
})));
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
outboundFor(options) {
|
|
1419
|
+
if (!this.outbound) throw new Error("The outbound pipeline is not initialized; call initialize() first.");
|
|
1420
|
+
return {
|
|
1421
|
+
service: this.outbound,
|
|
1422
|
+
tenantId: this.resolveRequestTenantId(options?.tenantId)
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Offer a release/changelog event as a post candidate. Events that match no
|
|
1427
|
+
* enabled source rule, or were seen before, produce nothing; a match is
|
|
1428
|
+
* drafted in the tenant's persona with a cited claim list.
|
|
1429
|
+
*/
|
|
1430
|
+
async ingestSourceEvent(event, options) {
|
|
1431
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1432
|
+
return service.ingestSourceEvent(tenantId, event);
|
|
1433
|
+
}
|
|
1434
|
+
async listDrafts(filter = {}, options) {
|
|
1435
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1436
|
+
return service.listDrafts(tenantId, filter);
|
|
1437
|
+
}
|
|
1438
|
+
/** Edit text, claims or link. An edit withdraws approval (back to draft). */
|
|
1439
|
+
async editDraft(id, patch, options) {
|
|
1440
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1441
|
+
return service.editDraft(tenantId, id, patch);
|
|
1442
|
+
}
|
|
1443
|
+
async approve(id, options) {
|
|
1444
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1445
|
+
return service.approve(tenantId, id, options?.approvedBy);
|
|
1446
|
+
}
|
|
1447
|
+
async reject(id, reason, options) {
|
|
1448
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1449
|
+
return service.reject(tenantId, id, reason);
|
|
1450
|
+
}
|
|
1451
|
+
/** Send a failed post back to approved so the next run publishes it again. */
|
|
1452
|
+
async retry(id, options) {
|
|
1453
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1454
|
+
return service.retry(tenantId, id);
|
|
1455
|
+
}
|
|
1456
|
+
async schedule(id, at, options) {
|
|
1457
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1458
|
+
return service.schedule(tenantId, id, at);
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Publish the tenant's approved posts whose time has come (scheduled time
|
|
1462
|
+
* reached, or approved without one). Each goes through the same gate as any
|
|
1463
|
+
* publish: a pause or spend cap refuses it without calling the platform.
|
|
1464
|
+
*/
|
|
1465
|
+
async publishDue(options) {
|
|
1466
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1467
|
+
const due = await service.dueForPublish(tenantId, options?.now ?? this.nowFn());
|
|
1468
|
+
const results = [];
|
|
1469
|
+
for (const post of due) results.push(await this.publishOutboundPost(service, tenantId, post));
|
|
1470
|
+
return results;
|
|
1471
|
+
}
|
|
1472
|
+
/** Publish one approved or scheduled draft now. */
|
|
1473
|
+
async publishNow(id, options) {
|
|
1474
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1475
|
+
const post = await service.postForPublish(tenantId, id);
|
|
1476
|
+
return this.publishOutboundPost(service, tenantId, post);
|
|
1477
|
+
}
|
|
1478
|
+
async publishOutboundPost(service, tenantId, post) {
|
|
1479
|
+
const outboundId = await service.outboundIdForPost(tenantId, post.id ?? "");
|
|
1480
|
+
const result = await this.publishClaimed(post, { claimFrom: DUE_STATUSES });
|
|
1481
|
+
return {
|
|
1482
|
+
postId: result.postId,
|
|
1483
|
+
outboundId,
|
|
1484
|
+
success: result.success,
|
|
1485
|
+
skipped: result.skipped,
|
|
1486
|
+
refusal: result.refusal,
|
|
1487
|
+
error: result.error
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
async getSettings(options) {
|
|
1491
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1492
|
+
return service.getSettings(tenantId);
|
|
1493
|
+
}
|
|
1494
|
+
async updateSettings(patch, options) {
|
|
1495
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1496
|
+
return service.updateSettings(tenantId, patch);
|
|
1497
|
+
}
|
|
1498
|
+
/** Stop all publishing for the tenant, effective on the very next publish. */
|
|
1499
|
+
async pause(options) {
|
|
1500
|
+
return this.updateSettings({ paused: true }, options);
|
|
1501
|
+
}
|
|
1502
|
+
async resume(options) {
|
|
1503
|
+
return this.updateSettings({ paused: false }, options);
|
|
1504
|
+
}
|
|
1505
|
+
/** Spend ledger and cap for a month (`YYYY-MM`, default: this month, UTC). */
|
|
1506
|
+
async getSpend(options) {
|
|
1507
|
+
const { service, tenantId } = this.outboundFor(options);
|
|
1508
|
+
return service.getSpend(tenantId, options?.month);
|
|
1509
|
+
}
|
|
1510
|
+
/** Record the failure on the post, then let the host tell the poster. */
|
|
1511
|
+
async recordFailure(post, error) {
|
|
1512
|
+
await this.socialPosts.recordPublishFailure(post, error);
|
|
1513
|
+
const onPublishFailed = this.hostHooks.onPublishFailed;
|
|
1514
|
+
if (!onPublishFailed) return;
|
|
1515
|
+
try {
|
|
1516
|
+
await onPublishFailed(post, error instanceof Error ? error.message : error);
|
|
1517
|
+
} catch (hookError) {
|
|
1518
|
+
this.logger.warn("Social publish failure hook failed", {
|
|
1519
|
+
postId: post.id,
|
|
1520
|
+
error: hookError
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Publish one post. The post is first claimed with a single conditional
|
|
1526
|
+
* update (`status` → `publishing`, only from `options.claimFrom`), so
|
|
1527
|
+
* overlapping runs or a double-clicked retry never send it twice. A post
|
|
1528
|
+
* of an organization that may not publish is left as it is; after the
|
|
1529
|
+
* claim, every failure is recorded on the post (never left `publishing`).
|
|
1530
|
+
*/
|
|
1531
|
+
async publishPost(post, options = {}) {
|
|
1532
|
+
const postTenant = this.normalizeTenantId(post.tenantId);
|
|
1533
|
+
if (postTenant) this.resolveRequestTenantId(postTenant);
|
|
1534
|
+
return this.publishClaimed(post, options);
|
|
1535
|
+
}
|
|
1536
|
+
/** The trusted publish path: enters the post's own tenant (see {@link publishPost}). */
|
|
1537
|
+
async publishClaimed(post, options = {}) {
|
|
1538
|
+
const tenantId = this.normalizeTenantId(post.tenantId);
|
|
1539
|
+
const postId = post.id ?? "";
|
|
1540
|
+
const previousStatus = post.status;
|
|
1541
|
+
if (!tenantId) {
|
|
1542
|
+
const error = /* @__PURE__ */ new Error("Cannot publish social post without tenant context");
|
|
1543
|
+
await this.recordFailure(post, error);
|
|
1544
|
+
return {
|
|
1545
|
+
postId,
|
|
1546
|
+
platform: "unknown",
|
|
1547
|
+
success: false,
|
|
1548
|
+
error: error.message
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1551
|
+
if (this.hostHooks.canPublish && !await this.hostHooks.canPublish(tenantId)) return {
|
|
1552
|
+
postId,
|
|
1553
|
+
platform: "unknown",
|
|
1554
|
+
success: false,
|
|
1555
|
+
error: tenantBlockedMessage(this.garrulaConfig),
|
|
1556
|
+
skipped: "tenant-blocked"
|
|
1557
|
+
};
|
|
1558
|
+
if (!await this.claimForPublish(post, tenantId, options.claimFrom ?? PUBLISHABLE_STATUSES)) return {
|
|
1559
|
+
postId,
|
|
1560
|
+
platform: "unknown",
|
|
1561
|
+
success: false,
|
|
1562
|
+
error: GARRULA_POST_BUSY_MESSAGE,
|
|
1563
|
+
skipped: "post-busy"
|
|
1564
|
+
};
|
|
1565
|
+
const context = {};
|
|
1566
|
+
let result;
|
|
1567
|
+
try {
|
|
1568
|
+
result = await withTenant({ tenantId }, () => this.publishPostInTenant(post, context, previousStatus));
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
await this.settleOutbound(tenantId, postId, context, false, errorMessage(error));
|
|
1571
|
+
throw error;
|
|
1572
|
+
}
|
|
1573
|
+
await this.settleOutbound(tenantId, postId, context, result.success, result.error, result.skipped !== void 0);
|
|
1574
|
+
return result;
|
|
1575
|
+
}
|
|
1576
|
+
/** Record spend and the outbound state once a publish attempt is over. */
|
|
1577
|
+
async settleOutbound(tenantId, postId, context, success, error, skipped = false) {
|
|
1578
|
+
if (!this.outbound) return;
|
|
1579
|
+
try {
|
|
1580
|
+
await withTenant({ tenantId }, async () => {
|
|
1581
|
+
if (context.reservation) await this.outbound?.finish(context.reservation, {
|
|
1582
|
+
result: context.sent ?? null,
|
|
1583
|
+
success,
|
|
1584
|
+
error
|
|
1585
|
+
});
|
|
1586
|
+
else if (!success && !skipped && postId) await this.outbound?.failUnreserved(tenantId, postId);
|
|
1587
|
+
});
|
|
1588
|
+
} catch (settleError) {
|
|
1589
|
+
this.logger.error("Could not settle the outcome of a publish", {
|
|
1590
|
+
entryId: context.reservation?.entryId,
|
|
1591
|
+
postId,
|
|
1592
|
+
error: errorMessage(settleError)
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
/** Put a refused post back where it was, so a later run can try again. */
|
|
1597
|
+
async releaseClaim(post, status) {
|
|
1598
|
+
if (!post.id || !status) return;
|
|
1599
|
+
await this.socialPosts.db.update(this.socialPosts.tableName, {
|
|
1600
|
+
id: post.id,
|
|
1601
|
+
tenant_id: post.tenantId,
|
|
1602
|
+
status: "publishing"
|
|
1603
|
+
}, {
|
|
1604
|
+
status,
|
|
1605
|
+
updated_at: /* @__PURE__ */ new Date()
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Atomically move the post to `publishing` if it is still in one of
|
|
1610
|
+
* `from`. Returns false when another publisher got there first.
|
|
1611
|
+
*
|
|
1612
|
+
* The claim writes the row directly, so the caller's copy of the post keeps
|
|
1613
|
+
* the old revision; {@link loadClaimedPost} re-reads it before anything is
|
|
1614
|
+
* saved.
|
|
1615
|
+
*
|
|
1616
|
+
* TODO(happyvertical/smrt#3300): a `SocialPostCollection.claimForPublish`
|
|
1617
|
+
* that returns the claimed post belongs next to
|
|
1618
|
+
* `recordPublishSuccess`/`recordPublishFailure`; adopt it and drop the
|
|
1619
|
+
* re-read.
|
|
1620
|
+
*/
|
|
1621
|
+
async claimForPublish(post, tenantId, from) {
|
|
1622
|
+
if (!post.id || from.length === 0) return false;
|
|
1623
|
+
if ((await this.socialPosts.db.update(this.socialPosts.tableName, {
|
|
1624
|
+
id: post.id,
|
|
1625
|
+
tenant_id: tenantId,
|
|
1626
|
+
"status in": from
|
|
1627
|
+
}, {
|
|
1628
|
+
status: "publishing",
|
|
1629
|
+
error_message: null,
|
|
1630
|
+
updated_at: /* @__PURE__ */ new Date()
|
|
1631
|
+
})).affected !== 1) return false;
|
|
1632
|
+
post.status = "publishing";
|
|
1633
|
+
post.errorMessage = null;
|
|
1634
|
+
return true;
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Re-read a post the claim just moved to `publishing`, so the revision the
|
|
1638
|
+
* outcome is saved against is the one the claim wrote. Saving the caller's
|
|
1639
|
+
* copy instead always fails with `RUNTIME_REVISION_CONFLICT`.
|
|
1640
|
+
*/
|
|
1641
|
+
async loadClaimedPost(post) {
|
|
1642
|
+
const claimed = post.id ? await this.socialPosts.get({ id: post.id }, { cache: false }) : null;
|
|
1643
|
+
if (!claimed) throw new Error("This post could not be read back after it was claimed.");
|
|
1644
|
+
return claimed;
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Runs after the claim: every outcome is recorded on the post, and a
|
|
1648
|
+
* failure to record never hides why the publish itself failed.
|
|
1649
|
+
*/
|
|
1650
|
+
async publishPostInTenant(claimedPost, context, previousStatus) {
|
|
1651
|
+
const postId = claimedPost.id ?? "";
|
|
1652
|
+
let post = null;
|
|
1653
|
+
let platform = "unknown";
|
|
1654
|
+
let accountPlatform;
|
|
1655
|
+
let adapter;
|
|
1656
|
+
let result;
|
|
1657
|
+
try {
|
|
1658
|
+
post = await this.loadClaimedPost(claimedPost);
|
|
1659
|
+
const account = await this.getPostAccount(post);
|
|
1660
|
+
if (!account) throw new Error("Social account not found");
|
|
1661
|
+
platform = accountPlatform = account.platform;
|
|
1662
|
+
if (account.isActive === false) throw new Error(GARRULA_ACCOUNT_INACTIVE_MESSAGE);
|
|
1663
|
+
const credentials = await account.getCredentials();
|
|
1664
|
+
if (!credentials) throw new Error(`No credentials configured for ${account.name}`);
|
|
1665
|
+
let session = await this.openAdapter(account, credentials);
|
|
1666
|
+
const mediaUrl = post.postType === "video" ? await this.hostHooks.resolveMediaUrl?.(post) || post.mediaUrl : post.mediaUrl;
|
|
1667
|
+
let sendPost = post;
|
|
1668
|
+
if (this.outbound) {
|
|
1669
|
+
const gate = await this.outbound.beforeSend(post, account.platform);
|
|
1670
|
+
if (!gate.ok) {
|
|
1671
|
+
await this.releaseClaim(post, previousStatus);
|
|
1672
|
+
return {
|
|
1673
|
+
postId,
|
|
1674
|
+
platform,
|
|
1675
|
+
success: false,
|
|
1676
|
+
error: gate.refusal.message,
|
|
1677
|
+
skipped: "refused",
|
|
1678
|
+
refusal: gate.refusal
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
context.reservation = gate.reservation;
|
|
1682
|
+
sendPost = {
|
|
1683
|
+
...post,
|
|
1684
|
+
linkUrl: gate.linkUrl,
|
|
1685
|
+
...isOutboundMarked(post) ? { title: null } : {}
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
try {
|
|
1689
|
+
result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);
|
|
1690
|
+
} catch (publishError) {
|
|
1691
|
+
if (!isAuthError(publishError)) throw publishError;
|
|
1692
|
+
session = await this.openAdapter(account, session.credentials, { force: true });
|
|
1693
|
+
try {
|
|
1694
|
+
result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);
|
|
1695
|
+
} catch (retryError) {
|
|
1696
|
+
if (!isAuthError(retryError)) throw retryError;
|
|
1697
|
+
throw await this.requireReconnect(account, "publish rejected after refresh");
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
adapter = session.adapter;
|
|
1701
|
+
context.sent = result;
|
|
1702
|
+
} catch (error) {
|
|
1703
|
+
return this.failClaimedPost(post ?? claimedPost, post !== null, platform, error);
|
|
1704
|
+
}
|
|
1705
|
+
let publishedPost;
|
|
1706
|
+
try {
|
|
1707
|
+
publishedPost = await this.socialPosts.recordPublishSuccess(post, {
|
|
1708
|
+
platformPostId: result.id,
|
|
1709
|
+
platformUrl: result.url,
|
|
1710
|
+
publishedAt: result.publishedAt,
|
|
1711
|
+
status: result.status === "dry_run" || result.status === "staged" ? result.status : "published"
|
|
1712
|
+
});
|
|
1713
|
+
} catch (recordError) {
|
|
1714
|
+
if (result.status === "dry_run") return this.failClaimedPost(post, false, platform, recordError);
|
|
1715
|
+
this.logger.error("Social post was sent but its result could not be saved", {
|
|
1716
|
+
postId,
|
|
1717
|
+
platform,
|
|
1718
|
+
platformPostId: result.id,
|
|
1719
|
+
platformUrl: result.url,
|
|
1720
|
+
error: errorMessage(recordError)
|
|
1721
|
+
});
|
|
1722
|
+
return {
|
|
1723
|
+
postId,
|
|
1724
|
+
platform,
|
|
1725
|
+
success: false,
|
|
1726
|
+
platformPostId: result.id,
|
|
1727
|
+
platformUrl: result.url,
|
|
1728
|
+
error: `Posted (${result.url || result.id}), but the result could not be saved. Do not post it again.`
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
if (result.status === "published" || result.status === "processing") try {
|
|
1732
|
+
await this.syncAnalyticsForPost(publishedPost, adapter, accountPlatform);
|
|
1733
|
+
} catch (analyticsError) {
|
|
1734
|
+
this.logger.warn("Unable to sync analytics after social publish", {
|
|
1735
|
+
postId,
|
|
1736
|
+
platform,
|
|
1737
|
+
error: errorMessage(analyticsError)
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
return {
|
|
1741
|
+
postId,
|
|
1742
|
+
platform,
|
|
1743
|
+
success: true,
|
|
1744
|
+
platformPostId: result.id,
|
|
1745
|
+
platformUrl: result.url
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* Record why a claimed post was not published and return that reason. The
|
|
1750
|
+
* reason is logged first, so it survives even when recording it fails.
|
|
1751
|
+
*/
|
|
1752
|
+
async failClaimedPost(post, isFresh, platform, error) {
|
|
1753
|
+
const postId = post.id ?? "";
|
|
1754
|
+
const reason = errorMessage(error);
|
|
1755
|
+
this.logger.error("Social publish failed", {
|
|
1756
|
+
postId,
|
|
1757
|
+
platform,
|
|
1758
|
+
error: reason
|
|
1759
|
+
});
|
|
1760
|
+
try {
|
|
1761
|
+
const current = isFresh ? post : await this.loadClaimedPost(post);
|
|
1762
|
+
await this.recordFailure(current, error instanceof Error ? error : reason);
|
|
1763
|
+
} catch (recordError) {
|
|
1764
|
+
this.logger.error("Could not record a failed social publish; the post is still marked publishing", {
|
|
1765
|
+
postId,
|
|
1766
|
+
platform,
|
|
1767
|
+
publishError: reason,
|
|
1768
|
+
error: errorMessage(recordError)
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
return {
|
|
1772
|
+
postId,
|
|
1773
|
+
platform,
|
|
1774
|
+
success: false,
|
|
1775
|
+
error: reason
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* Refresh the stats of published posts. With `options.tenantId`, only that
|
|
1780
|
+
* organization's posts are read; organizations that may not publish right
|
|
1781
|
+
* now (see {@link GarrulaHost.canPublish}) are skipped.
|
|
1782
|
+
*/
|
|
1783
|
+
async syncAnalytics(postIds, options = {}) {
|
|
1784
|
+
const where = { status: "published" };
|
|
1785
|
+
const scopeTenantId = this.normalizeTenantId(options.tenantId) || this.normalizeTenantId(getTenantId()) ? this.resolveRequestTenantId(options.tenantId) : null;
|
|
1786
|
+
if (scopeTenantId) where.tenantId = scopeTenantId;
|
|
1787
|
+
if (postIds?.length) where["id in"] = postIds;
|
|
1788
|
+
const selected = (await this.socialPosts.list({
|
|
1789
|
+
where,
|
|
1790
|
+
orderBy: "publishedAt DESC"
|
|
1791
|
+
})).filter((post) => (!postIds?.length || post.id && postIds.includes(post.id)) && (!scopeTenantId || this.normalizeTenantId(post.tenantId) === scopeTenantId));
|
|
1792
|
+
const mayPublish = /* @__PURE__ */ new Map();
|
|
1793
|
+
const tenantMayPublish = async (tenantId) => {
|
|
1794
|
+
const canPublish = this.hostHooks.canPublish;
|
|
1795
|
+
if (!canPublish) return true;
|
|
1796
|
+
if (!mayPublish.has(tenantId)) mayPublish.set(tenantId, await canPublish(tenantId));
|
|
1797
|
+
return mayPublish.get(tenantId);
|
|
1798
|
+
};
|
|
1799
|
+
const result = {
|
|
1800
|
+
checked: selected.length,
|
|
1801
|
+
updated: 0,
|
|
1802
|
+
failed: 0,
|
|
1803
|
+
skipped: 0,
|
|
1804
|
+
errors: []
|
|
1805
|
+
};
|
|
1806
|
+
for (const post of selected) {
|
|
1807
|
+
const tenantId = this.normalizeTenantId(post.tenantId);
|
|
1808
|
+
if (!tenantId || !await tenantMayPublish(tenantId)) {
|
|
1809
|
+
result.skipped++;
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
try {
|
|
1813
|
+
await withTenant({ tenantId }, async () => {
|
|
1814
|
+
const account = await this.getPostAccount(post);
|
|
1815
|
+
if (!account || account.isActive === false || !post.platformPostId) {
|
|
1816
|
+
result.skipped++;
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
const credentials = await account.getCredentials();
|
|
1820
|
+
if (!credentials) {
|
|
1821
|
+
result.skipped++;
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
const { adapter } = await this.openAdapter(account, credentials);
|
|
1825
|
+
await this.syncAnalyticsForPost(post, adapter, account.platform);
|
|
1826
|
+
result.updated++;
|
|
1827
|
+
});
|
|
1828
|
+
} catch (error) {
|
|
1829
|
+
result.failed++;
|
|
1830
|
+
result.errors.push(error instanceof Error ? error.message : String(error));
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
return result;
|
|
1834
|
+
}
|
|
1835
|
+
async resolveTargetAccounts(targets, tenantId) {
|
|
1836
|
+
return (await Promise.all(targets.map((platform) => this.socialAccounts.findReady(platform)))).flat().filter((account) => account.tenantId === tenantId);
|
|
1837
|
+
}
|
|
1838
|
+
/**
|
|
1839
|
+
* Narrow ready accounts to the requested ids. Every requested id must be one
|
|
1840
|
+
* of the ready accounts, so a stale or foreign id is refused, not skipped.
|
|
1841
|
+
*/
|
|
1842
|
+
selectAccounts(readyAccounts, accountIds) {
|
|
1843
|
+
if (!accountIds) return readyAccounts;
|
|
1844
|
+
const requested = new Set(accountIds.map((id) => id.trim()).filter(Boolean));
|
|
1845
|
+
const selected = readyAccounts.filter((account) => account.id && requested.has(account.id));
|
|
1846
|
+
if (requested.size === 0 || selected.length !== requested.size) throw new Error("One or more selected social accounts are not ready to post.");
|
|
1847
|
+
return selected;
|
|
1848
|
+
}
|
|
1849
|
+
mergeHashtags(account, requested) {
|
|
1850
|
+
return Array.from(/* @__PURE__ */ new Set([...account.defaultHashtags ?? [], ...requested ?? []]));
|
|
1851
|
+
}
|
|
1852
|
+
requireAccountId(account) {
|
|
1853
|
+
if (!account.id) throw new Error(`Ready social account is missing an id: ${account.name}`);
|
|
1854
|
+
return account.id;
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* The tenant a request acts for: its own `tenantId`, else the tenant of the
|
|
1858
|
+
* current context. A request naming a different tenant than the active
|
|
1859
|
+
* context is refused rather than silently crossing tenants.
|
|
1860
|
+
*/
|
|
1861
|
+
resolveRequestTenantId(value) {
|
|
1862
|
+
const requested = this.normalizeTenantId(value);
|
|
1863
|
+
const ambient = this.normalizeTenantId(getTenantId());
|
|
1864
|
+
if (requested && ambient && requested !== ambient) throw new Error("The request names a different tenant than the current tenant context.");
|
|
1865
|
+
const tenantId = requested ?? ambient;
|
|
1866
|
+
if (!tenantId) throw new Error(tenantRequiredMessage(this.garrulaConfig));
|
|
1867
|
+
return tenantId;
|
|
1868
|
+
}
|
|
1869
|
+
normalizeTenantId(value) {
|
|
1870
|
+
const tenantId = value?.trim();
|
|
1871
|
+
return tenantId ? tenantId : null;
|
|
1872
|
+
}
|
|
1873
|
+
async getPostAccount(post) {
|
|
1874
|
+
if (!post.socialAccountId) return null;
|
|
1875
|
+
const account = await this.socialAccounts.get({ id: post.socialAccountId });
|
|
1876
|
+
if (account && this.normalizeTenantId(account.tenantId) !== this.normalizeTenantId(post.tenantId)) return null;
|
|
1877
|
+
return account;
|
|
1878
|
+
}
|
|
1879
|
+
/**
|
|
1880
|
+
* Build the account's adapter with a usable access token. A token that is
|
|
1881
|
+
* expired or close to it (or of unknown age) is refreshed first and the new
|
|
1882
|
+
* token set is saved on the account, so the next publish starts from it.
|
|
1883
|
+
* With `force`, the token is refreshed even if it looks valid (the platform
|
|
1884
|
+
* just rejected it); a token that cannot be refreshed then needs a
|
|
1885
|
+
* reconnect.
|
|
1886
|
+
*/
|
|
1887
|
+
async openAdapter(account, credentials, options = {}) {
|
|
1888
|
+
const adapter = await this.createAdapter(account, credentials);
|
|
1889
|
+
const fresh = await this.ensureFreshCredentials(account, credentials, adapter, options);
|
|
1890
|
+
if (fresh === credentials) return {
|
|
1891
|
+
adapter,
|
|
1892
|
+
credentials
|
|
1893
|
+
};
|
|
1894
|
+
return {
|
|
1895
|
+
adapter: await this.createAdapter(account, fresh),
|
|
1896
|
+
credentials: fresh
|
|
1897
|
+
};
|
|
1898
|
+
}
|
|
1899
|
+
/**
|
|
1900
|
+
* Return credentials whose access token can be used now: the stored ones,
|
|
1901
|
+
* or a refreshed set that has been saved on the account.
|
|
1902
|
+
*/
|
|
1903
|
+
async ensureFreshCredentials(account, credentials, adapter, options) {
|
|
1904
|
+
const kind = refreshKind(account.platform, credentials);
|
|
1905
|
+
const force = options.force === true;
|
|
1906
|
+
if (!kind) {
|
|
1907
|
+
if (force) throw await this.requireReconnect(account, "token rejected and not refreshable");
|
|
1908
|
+
return credentials;
|
|
1909
|
+
}
|
|
1910
|
+
const { accessTokenRefreshMarginMs, threadsRefreshWindowMs } = this.garrulaConfig;
|
|
1911
|
+
const now = Date.now();
|
|
1912
|
+
if (kind === "threads") {
|
|
1913
|
+
const expiresAt = parseExpiry(credentials.expiresAt) ?? parseExpiry(account.tokenExpiresAt);
|
|
1914
|
+
if (expiresAt && expiresAt.getTime() <= now) throw await this.requireReconnect(account, "long-lived token expired");
|
|
1915
|
+
if (!force && (!expiresAt || expiresAt.getTime() - now > threadsRefreshWindowMs)) return credentials;
|
|
1916
|
+
return this.refreshCredentials(account, credentials, adapter, kind, { force });
|
|
1917
|
+
}
|
|
1918
|
+
const expiresAt = parseExpiry(credentials.expiresAt);
|
|
1919
|
+
if (!force && expiresAt && expiresAt.getTime() - now > accessTokenRefreshMarginMs) return credentials;
|
|
1920
|
+
return this.refreshCredentials(account, credentials, adapter, kind, { force: true });
|
|
1921
|
+
}
|
|
1922
|
+
async refreshCredentials(account, credentials, adapter, kind, options) {
|
|
1923
|
+
let auth;
|
|
1924
|
+
try {
|
|
1925
|
+
auth = kind === "threads" ? await refreshThreadsToken(String(credentials.accessToken)) : await adapter.refreshToken(String(credentials.refreshToken));
|
|
1926
|
+
} catch (error) {
|
|
1927
|
+
const stored = await account.getCredentials().catch(() => null);
|
|
1928
|
+
if (stored && stored.accessToken !== credentials.accessToken) return stored;
|
|
1929
|
+
if (isRefreshRejected(error)) throw await this.requireReconnect(account, "refresh rejected");
|
|
1930
|
+
if (!options.force && kind === "threads") {
|
|
1931
|
+
this.logger.warn("Could not refresh a Threads token early; using the current one", {
|
|
1932
|
+
accountId: account.id,
|
|
1933
|
+
error: errorMessage(error)
|
|
1934
|
+
});
|
|
1935
|
+
return credentials;
|
|
1936
|
+
}
|
|
1937
|
+
this.logger.warn("Social token refresh failed", {
|
|
1938
|
+
accountId: account.id,
|
|
1939
|
+
platform: account.platform,
|
|
1940
|
+
error: errorMessage(error)
|
|
1941
|
+
});
|
|
1942
|
+
throw new Error(`Could not renew the ${platformLabel(account.platform)} sign-in right now. Try again in a few minutes.`);
|
|
1943
|
+
}
|
|
1944
|
+
const next = mergeRefreshedCredentials(credentials, auth);
|
|
1945
|
+
await this.saveRefreshedCredentials(account, next, kind === "threads" ? auth.expiresAt ?? null : null);
|
|
1946
|
+
return next;
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* Save a refreshed token set on the account (encrypted, tenant-scoped).
|
|
1950
|
+
* `tokenExpiresAt` on the account means "the connection lapses then", so it
|
|
1951
|
+
* is cleared for refreshable OAuth 2 tokens and moved forward for Threads.
|
|
1952
|
+
* A failed save is logged and the fresh token is still used for this
|
|
1953
|
+
* publish.
|
|
1954
|
+
*/
|
|
1955
|
+
async saveRefreshedCredentials(account, credentials, connectionExpiresAt) {
|
|
1956
|
+
try {
|
|
1957
|
+
account.tokenExpiresAt = connectionExpiresAt;
|
|
1958
|
+
if (account.status !== "connected") {
|
|
1959
|
+
account.status = "connected";
|
|
1960
|
+
account.errorMessage = null;
|
|
1961
|
+
}
|
|
1962
|
+
await account.setCredentials(credentials);
|
|
1963
|
+
this.logger.info("Refreshed social account token", {
|
|
1964
|
+
accountId: account.id,
|
|
1965
|
+
platform: account.platform
|
|
1966
|
+
});
|
|
1967
|
+
} catch (error) {
|
|
1968
|
+
this.logger.error("Could not save a refreshed social account token", {
|
|
1969
|
+
accountId: account.id,
|
|
1970
|
+
platform: account.platform,
|
|
1971
|
+
error: errorMessage(error)
|
|
1972
|
+
});
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
/**
|
|
1976
|
+
* Mark the account as needing a reconnect and return the error to throw.
|
|
1977
|
+
* Provider error text is never shown: it can be cryptic, and the message
|
|
1978
|
+
* says what to do.
|
|
1979
|
+
*/
|
|
1980
|
+
async requireReconnect(account, reason) {
|
|
1981
|
+
const error = new GarrulaReconnectError(account.platform, this.garrulaConfig.socialSettingsLocation);
|
|
1982
|
+
this.logger.warn("Social account needs to be reconnected", {
|
|
1983
|
+
accountId: account.id,
|
|
1984
|
+
platform: account.platform,
|
|
1985
|
+
reason
|
|
1986
|
+
});
|
|
1987
|
+
try {
|
|
1988
|
+
account.status = "expired";
|
|
1989
|
+
account.errorMessage = error.message;
|
|
1990
|
+
await account.save();
|
|
1991
|
+
} catch (saveError) {
|
|
1992
|
+
this.logger.error("Could not mark a social account as needing reconnection", {
|
|
1993
|
+
accountId: account.id,
|
|
1994
|
+
platform: account.platform,
|
|
1995
|
+
error: errorMessage(saveError)
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
return error;
|
|
1999
|
+
}
|
|
2000
|
+
async createAdapter(account, credentials) {
|
|
2001
|
+
if (this.socialFactory) return this.socialFactory(account, credentials);
|
|
2002
|
+
return await getSocial(this.buildSocialConfig(account, credentials));
|
|
2003
|
+
}
|
|
2004
|
+
buildSocialConfig(account, credentials) {
|
|
2005
|
+
const required = (name) => {
|
|
2006
|
+
const value = credentials[name];
|
|
2007
|
+
if (typeof value !== "string" || value.length === 0) throw new Error(`Missing ${name} for ${account.platform}`);
|
|
2008
|
+
return value;
|
|
2009
|
+
};
|
|
2010
|
+
const optional = (name) => {
|
|
2011
|
+
const value = credentials[name];
|
|
2012
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2013
|
+
};
|
|
2014
|
+
const publishMode = account.effectivePublishMode ?? account.publishMode ?? this.garrulaConfig.defaultPublishMode;
|
|
2015
|
+
switch (account.platform) {
|
|
2016
|
+
case "youtube": return {
|
|
2017
|
+
type: "youtube",
|
|
2018
|
+
clientId: required("clientId"),
|
|
2019
|
+
clientSecret: required("clientSecret"),
|
|
2020
|
+
accessToken: required("accessToken"),
|
|
2021
|
+
refreshToken: optional("refreshToken"),
|
|
2022
|
+
publishMode
|
|
2023
|
+
};
|
|
2024
|
+
case "facebook": return {
|
|
2025
|
+
type: "facebook",
|
|
2026
|
+
accessToken: required("accessToken"),
|
|
2027
|
+
pageId: typeof credentials.pageId === "string" ? credentials.pageId : account.platformUserId ?? required("pageId"),
|
|
2028
|
+
publishMode
|
|
2029
|
+
};
|
|
2030
|
+
case "threads": return {
|
|
2031
|
+
type: "threads",
|
|
2032
|
+
accessToken: required("accessToken"),
|
|
2033
|
+
userId: typeof credentials.userId === "string" ? credentials.userId : account.platformUserId ?? required("userId"),
|
|
2034
|
+
publishMode
|
|
2035
|
+
};
|
|
2036
|
+
case "x": {
|
|
2037
|
+
const linkBehavior = account.linkBehavior === "reply" || account.linkBehavior === "none" ? account.linkBehavior : "inline";
|
|
2038
|
+
if ((credentials.authType === "oauth2" || !credentials.accessSecret ? "oauth2" : "oauth1") === "oauth2") return {
|
|
2039
|
+
type: "x",
|
|
2040
|
+
authType: "oauth2",
|
|
2041
|
+
clientId: optional("clientId"),
|
|
2042
|
+
clientSecret: optional("clientSecret"),
|
|
2043
|
+
accessToken: required("accessToken"),
|
|
2044
|
+
refreshToken: optional("refreshToken"),
|
|
2045
|
+
linkBehavior,
|
|
2046
|
+
publishMode
|
|
2047
|
+
};
|
|
2048
|
+
return {
|
|
2049
|
+
type: "x",
|
|
2050
|
+
apiKey: required("apiKey"),
|
|
2051
|
+
apiSecret: required("apiSecret"),
|
|
2052
|
+
accessToken: required("accessToken"),
|
|
2053
|
+
accessSecret: required("accessSecret"),
|
|
2054
|
+
linkBehavior,
|
|
2055
|
+
publishMode
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
case "bluesky": throw new SocialError("Posting to Bluesky is not available yet.", "UNSUPPORTED_PLATFORM", "bluesky");
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
publishWithAdapter(adapter, post, mediaUrl) {
|
|
2062
|
+
if (post.postType === "link") {
|
|
2063
|
+
if (!post.linkUrl) throw new SocialError("Link URL is required", "MISSING_LINK_URL");
|
|
2064
|
+
return adapter.publishLink({
|
|
2065
|
+
url: post.linkUrl,
|
|
2066
|
+
text: post.description,
|
|
2067
|
+
title: post.title ?? void 0,
|
|
2068
|
+
tags: post.hashtags
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
if (post.postType === "video") {
|
|
2072
|
+
if (!mediaUrl) throw new SocialError("Media URL is required", "MISSING_MEDIA_URL");
|
|
2073
|
+
return adapter.publishVideo({
|
|
2074
|
+
file: mediaUrl,
|
|
2075
|
+
title: post.title ?? void 0,
|
|
2076
|
+
description: post.description,
|
|
2077
|
+
tags: post.hashtags,
|
|
2078
|
+
linkUrl: post.linkUrl ?? void 0,
|
|
2079
|
+
isShort: adapter.platform === "youtube"
|
|
2080
|
+
});
|
|
2081
|
+
}
|
|
2082
|
+
if (post.postType === "image") {
|
|
2083
|
+
if (!mediaUrl) throw new SocialError("A picture is required for a picture post", "MISSING_MEDIA_URL");
|
|
2084
|
+
return adapter.publishImage({
|
|
2085
|
+
file: mediaUrl,
|
|
2086
|
+
description: post.description,
|
|
2087
|
+
altText: post.title ?? void 0,
|
|
2088
|
+
tags: post.hashtags,
|
|
2089
|
+
linkUrl: post.linkUrl ?? void 0
|
|
2090
|
+
});
|
|
2091
|
+
}
|
|
2092
|
+
return adapter.publishText({
|
|
2093
|
+
text: post.description,
|
|
2094
|
+
tags: post.hashtags,
|
|
2095
|
+
linkUrl: post.linkUrl ?? void 0
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
async syncAnalyticsForPost(post, adapter, platform) {
|
|
2099
|
+
if (!post.platformPostId) return;
|
|
2100
|
+
const analytics = await adapter.getAnalytics(post.platformPostId);
|
|
2101
|
+
const capturedAt = analytics.lastUpdated ?? /* @__PURE__ */ new Date();
|
|
2102
|
+
await this.socialPosts.updateLatestAnalytics(post, analytics, capturedAt);
|
|
2103
|
+
await this.analyticsSnapshots.recordSnapshot({
|
|
2104
|
+
socialPostId: post.id ?? "",
|
|
2105
|
+
platform,
|
|
2106
|
+
metrics: analytics,
|
|
2107
|
+
raw: toRawAnalyticsPayload(analytics.raw),
|
|
2108
|
+
capturedAt,
|
|
2109
|
+
tenantId: post.tenantId ?? null
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
};
|
|
2113
|
+
Garrula = __decorate([smrt({
|
|
2114
|
+
agent: {
|
|
2115
|
+
icon: "share-2",
|
|
2116
|
+
tier: "standard",
|
|
2117
|
+
description: "Social media publishing, account health, and post analytics"
|
|
2118
|
+
},
|
|
2119
|
+
cli: {
|
|
2120
|
+
include: ["run", "syncAnalytics"],
|
|
2121
|
+
skipApiCheck: ["run", "syncAnalytics"]
|
|
2122
|
+
},
|
|
2123
|
+
mcp: { include: ["createStoryLinkPosts", "createArticleVideoPosts"] }
|
|
2124
|
+
}), __decorateMetadata("design:paramtypes", [Object])], Garrula);
|
|
2125
|
+
function toRawAnalyticsPayload(value) {
|
|
2126
|
+
if (value === null || Array.isArray(value)) return value;
|
|
2127
|
+
return typeof value === "object" ? value : void 0;
|
|
2128
|
+
}
|
|
2129
|
+
function errorMessage(error) {
|
|
2130
|
+
return error instanceof Error ? error.message : String(error);
|
|
2131
|
+
}
|
|
2132
|
+
//#endregion
|
|
2133
|
+
export { DEFAULT_AUTONOMY, DEFAULT_GARRULA_CONFIG, DEFAULT_OUTBOUND_RATES, DEFAULT_SOURCE_RULES, FALLBACK_X_RATES, GARRULA_ACCOUNT_INACTIVE_MESSAGE, GARRULA_POST_BUSY_MESSAGE, GARRULA_TENANT_BLOCKED_MESSAGE, Garrula, GarrulaOutboundPost, GarrulaOutboundPostCollection, GarrulaOutboundSettings, GarrulaOutboundSettingsCollection, GarrulaReconnectError, GarrulaSourceEvent, GarrulaSourceEventCollection, GarrulaSpendEntry, GarrulaSpendEntryCollection, OUTBOUND_TRANSITIONS, OutboundError, OutboundService, canTransition, createOutboundStores, reconnectMessage, resolveGarrulaConfig, setGarrulaConfig, setGarrulaHost };
|
|
2134
|
+
|
|
2135
|
+
//# sourceMappingURL=index.js.map
|