@happyvertical/garrula 0.1.7 → 0.1.8

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/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
+ import { SocialError, getSocial } from "@happyvertical/social";
1
2
  import { Agent } from "@happyvertical/smrt-agents";
2
3
  import { SmrtCollection, SmrtObject, smrt } from "@happyvertical/smrt-core";
3
4
  import { SocialAccountCollection, SocialPostAnalyticsSnapshotCollection, SocialPostCollection } from "@happyvertical/smrt-social";
4
5
  import { TenantScoped, getTenantId, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
5
- import { SocialError, getSocial } from "@happyvertical/social";
6
6
  //#region src/credentials.ts
7
7
  /**
8
8
  * Social OAuth token upkeep for Garrula's publisher.
@@ -380,6 +380,13 @@ var GarrulaOutboundPost = class GarrulaOutboundPost extends SmrtObject {
380
380
  sourceKind = "package-publish";
381
381
  sourceUrl = null;
382
382
  claims = [];
383
+ media = null;
384
+ youtubeMetadata = null;
385
+ parentOutboundId = null;
386
+ xRepostMode = null;
387
+ requestedTargetAccountIds = null;
388
+ requestedXRepostMode = null;
389
+ utmCampaign = null;
383
390
  /** Who supplied a manual draft (`createDraft`); null for ingested drafts. */
384
391
  createdBy = null;
385
392
  approvedBy = null;
@@ -394,6 +401,13 @@ var GarrulaOutboundPost = class GarrulaOutboundPost extends SmrtObject {
394
401
  if (options.sourceKind !== void 0) this.sourceKind = options.sourceKind;
395
402
  if (options.sourceUrl !== void 0) this.sourceUrl = options.sourceUrl;
396
403
  if (options.claims !== void 0) this.claims = options.claims;
404
+ if (options.media !== void 0) this.media = options.media;
405
+ if (options.youtubeMetadata !== void 0) this.youtubeMetadata = options.youtubeMetadata;
406
+ if (options.parentOutboundId !== void 0) this.parentOutboundId = options.parentOutboundId;
407
+ if (options.xRepostMode !== void 0) this.xRepostMode = options.xRepostMode;
408
+ if (options.requestedTargetAccountIds !== void 0) this.requestedTargetAccountIds = options.requestedTargetAccountIds;
409
+ if (options.requestedXRepostMode !== void 0) this.requestedXRepostMode = options.requestedXRepostMode;
410
+ if (options.utmCampaign !== void 0) this.utmCampaign = options.utmCampaign;
397
411
  if (options.createdBy !== void 0) this.createdBy = options.createdBy;
398
412
  if (options.approvedBy !== void 0) this.approvedBy = options.approvedBy;
399
413
  if (options.rejectedReason !== void 0) this.rejectedReason = options.rejectedReason;
@@ -455,12 +469,16 @@ var GarrulaSourceEvent = class GarrulaSourceEvent extends SmrtObject {
455
469
  /** `drafted` | `ignored` */
456
470
  outcome = "ignored";
457
471
  outboundPostIds = [];
472
+ requestedTargetAccountIds = null;
473
+ requestedXRepostMode = null;
458
474
  constructor(options = {}) {
459
475
  super(options);
460
476
  if (options.tenantId !== void 0) this.tenantId = options.tenantId;
461
477
  if (options.eventKey !== void 0) this.eventKey = options.eventKey;
462
478
  if (options.outcome !== void 0) this.outcome = options.outcome;
463
479
  if (options.outboundPostIds !== void 0) this.outboundPostIds = options.outboundPostIds;
480
+ if (options.requestedTargetAccountIds !== void 0) this.requestedTargetAccountIds = options.requestedTargetAccountIds;
481
+ if (options.requestedXRepostMode !== void 0) this.requestedXRepostMode = options.requestedXRepostMode;
464
482
  }
465
483
  };
466
484
  __decorate([tenantId({ nullable: false }), __decorateMetadata("design:type", Object)], GarrulaSourceEvent.prototype, "tenantId", void 0);
@@ -624,6 +642,13 @@ var OUTBOUND_STATES = [
624
642
  "failed",
625
643
  "rejected"
626
644
  ];
645
+ var YOUTUBE_MAX_TITLE_LENGTH = 100;
646
+ var YOUTUBE_MAX_DESCRIPTION_LENGTH = 5e3;
647
+ var X_REPOST_MODES = [
648
+ "teaser_plus_link",
649
+ "full_video",
650
+ "link_only"
651
+ ];
627
652
  /** Thrown by the public API for refused changes (never for a publish). */
628
653
  var OutboundError = class extends Error {
629
654
  code;
@@ -673,6 +698,136 @@ var OUTBOUND_POST_MARKER = "garrula-outbound:";
673
698
  function isOutboundMarked(post) {
674
699
  return typeof post.title === "string" && post.title.startsWith("garrula-outbound:");
675
700
  }
701
+ var VALID_ASPECT_RATIOS = [
702
+ "16:9",
703
+ "9:16",
704
+ "1:1"
705
+ ];
706
+ function validateYouTubeMetadata(input) {
707
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new OutboundError("invalid", "YouTube metadata must be an object.");
708
+ const raw = input;
709
+ const title = typeof raw.title === "string" ? raw.title.trim() : "";
710
+ if (!title) throw new OutboundError("invalid", "YouTube metadata requires a non-empty title.");
711
+ if (title.length > 100) throw new OutboundError("invalid", `YouTube title must be at most 100 characters.`);
712
+ let description;
713
+ if (raw.description !== void 0 && raw.description !== null) {
714
+ if (typeof raw.description !== "string") throw new OutboundError("invalid", "YouTube description must be a string.");
715
+ if (raw.description.length > 5e3) throw new OutboundError("invalid", `YouTube description must be at most ${YOUTUBE_MAX_DESCRIPTION_LENGTH} characters.`);
716
+ description = raw.description;
717
+ }
718
+ let tags;
719
+ if (raw.tags !== void 0 && raw.tags !== null) {
720
+ if (!Array.isArray(raw.tags)) throw new OutboundError("invalid", "YouTube tags must be a list of strings.");
721
+ tags = [...new Set(raw.tags.map((item) => String(item ?? "").trim()).filter(Boolean))];
722
+ }
723
+ return {
724
+ title,
725
+ ...description !== void 0 ? { description } : {},
726
+ ...tags !== void 0 ? { tags } : {}
727
+ };
728
+ }
729
+ function normalizeAttachMedia(input) {
730
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new OutboundError("invalid", "Media attachment requires postType and videoContentId.");
731
+ if (input.postType !== "video" && input.postType !== "image") throw new OutboundError("invalid", "postType must be 'video' or 'image'.");
732
+ const videoContentId = typeof input.videoContentId === "string" ? input.videoContentId.trim() : "";
733
+ if (!videoContentId) throw new OutboundError("invalid", "videoContentId cannot be empty.");
734
+ let hasMediaUrl = false;
735
+ let mediaUrl;
736
+ if (input.mediaUrl !== void 0) {
737
+ hasMediaUrl = true;
738
+ if (input.mediaUrl === null) mediaUrl = null;
739
+ else if (typeof input.mediaUrl === "string") {
740
+ const trimmed = input.mediaUrl.trim();
741
+ if (!trimmed || /^(javascript|data):/i.test(trimmed)) throw new OutboundError("invalid", "mediaUrl must be a valid media URL.");
742
+ mediaUrl = trimmed;
743
+ } else throw new OutboundError("invalid", "mediaUrl must be a string or null.");
744
+ }
745
+ let variants;
746
+ if (input.variants !== void 0) {
747
+ if (!Array.isArray(input.variants)) throw new OutboundError("invalid", "variants must be a list.");
748
+ variants = input.variants.map((item) => {
749
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new OutboundError("invalid", "Each media variant must be an object.");
750
+ const vid = typeof item.videoContentId === "string" ? item.videoContentId.trim() : "";
751
+ if (!vid) throw new OutboundError("invalid", "Each media variant requires a non-empty videoContentId.");
752
+ if (item.aspectRatio !== void 0 && !VALID_ASPECT_RATIOS.includes(item.aspectRatio)) throw new OutboundError("invalid", `Unsupported aspectRatio: ${String(item.aspectRatio)}.`);
753
+ let outputId;
754
+ if (item.outputId !== void 0) {
755
+ const trimmedOut = typeof item.outputId === "string" ? item.outputId.trim() : "";
756
+ if (!trimmedOut) throw new OutboundError("invalid", "Variant outputId must be a non-empty string.");
757
+ outputId = trimmedOut;
758
+ }
759
+ if (item.isShort !== void 0 && typeof item.isShort !== "boolean") throw new OutboundError("invalid", "Variant isShort must be a boolean.");
760
+ if (item.role !== void 0 && item.role !== "primary" && item.role !== "teaser") throw new OutboundError("invalid", "Variant role must be 'primary' or 'teaser'.");
761
+ return {
762
+ ...outputId !== void 0 ? { outputId } : {},
763
+ ...item.aspectRatio !== void 0 ? { aspectRatio: item.aspectRatio } : {},
764
+ videoContentId: vid,
765
+ ...item.isShort !== void 0 ? { isShort: item.isShort } : {},
766
+ ...item.role !== void 0 ? { role: item.role } : {}
767
+ };
768
+ });
769
+ }
770
+ const youtube = input.youtube !== void 0 ? validateYouTubeMetadata(input.youtube) : void 0;
771
+ return {
772
+ media: {
773
+ postType: input.postType,
774
+ videoContentId,
775
+ ...variants !== void 0 ? { variants } : {},
776
+ ...youtube !== void 0 ? { youtube } : {}
777
+ },
778
+ hasMediaUrl,
779
+ mediaUrl
780
+ };
781
+ }
782
+ function selectMediaVariant(media, platform, postVideoContentId, xRepostMode) {
783
+ if (!media?.variants?.length) return null;
784
+ const { variants } = media;
785
+ if (platform === "youtube") return variants.find((v) => v.role === "primary") ?? variants.find((v) => v.aspectRatio === "16:9") ?? variants[0] ?? null;
786
+ if (platform === "x" && xRepostMode === "teaser_plus_link") return variants.find((v) => v.role === "teaser") ?? variants.find((v) => v.aspectRatio === "9:16") ?? variants.find((v) => v.aspectRatio === "1:1") ?? (postVideoContentId ? variants.find((v) => v.videoContentId === postVideoContentId) : void 0) ?? variants[0] ?? null;
787
+ if (platform === "x" && xRepostMode === "full_video") return variants.find((v) => v.role === "primary") ?? variants.find((v) => v.aspectRatio === "16:9") ?? (media.videoContentId ? variants.find((v) => v.videoContentId === media.videoContentId) : void 0) ?? null;
788
+ return (postVideoContentId ? variants.find((v) => v.videoContentId === postVideoContentId) : void 0) ?? variants.find((v) => v.aspectRatio === "9:16") ?? variants[0] ?? null;
789
+ }
790
+ function buildPairedYouTubeUrl(youtubeUrl, draftLinkUrl, configuredUtmCampaign) {
791
+ let utm = configuredUtmCampaign?.trim() || null;
792
+ if (!utm && draftLinkUrl) try {
793
+ utm = new URL(draftLinkUrl).searchParams.get("utm_campaign")?.trim() || null;
794
+ } catch {}
795
+ if (!utm) return youtubeUrl;
796
+ try {
797
+ const parsed = new URL(youtubeUrl);
798
+ if (!parsed.searchParams.has("utm_campaign")) parsed.searchParams.set("utm_campaign", utm);
799
+ return parsed.toString();
800
+ } catch {
801
+ return `${youtubeUrl}${youtubeUrl.includes("?") ? "&" : "?"}utm_campaign=${encodeURIComponent(utm)}`;
802
+ }
803
+ }
804
+ function stripUrlFromDescription(description, url) {
805
+ if (!url || !description.includes(url)) return description;
806
+ return description.replace(url, "").trim();
807
+ }
808
+ function computeXPostLength(text, hashtags, linkUrl, linkBehavior) {
809
+ const cleanText = linkUrl ? stripUrlFromDescription(text, linkUrl) : text;
810
+ const suffixParts = [];
811
+ if (linkUrl && linkBehavior !== "reply" && linkBehavior !== "none") suffixParts.push(linkUrl);
812
+ if (hashtags.length > 0) suffixParts.push(hashtags.map((tag) => tag.startsWith("#") ? tag : `#${tag}`).join(" "));
813
+ const suffix = suffixParts.join("\n\n");
814
+ if (!suffix) return cleanText.length;
815
+ const separator = cleanText.length > 0 ? "\n\n" : "";
816
+ return cleanText.length + separator.length + suffix.length;
817
+ }
818
+ function sameStringArray(a, b) {
819
+ const normA = a && a.length > 0 ? a : null;
820
+ const normB = b && b.length > 0 ? b : null;
821
+ if (normA === null && normB === null) return true;
822
+ if (normA === null || normB === null) return false;
823
+ if (normA.length !== normB.length) return false;
824
+ return normA.every((item, idx) => item === normB[idx]);
825
+ }
826
+ function fallbackMediaUrlForVariant(media, resolvedVideoContentId, hasMediaUrl, mediaUrl) {
827
+ if (!hasMediaUrl) return void 0;
828
+ if (resolvedVideoContentId && resolvedVideoContentId !== media.videoContentId) return null;
829
+ return mediaUrl ?? null;
830
+ }
676
831
  var OutboundService = class {
677
832
  stores;
678
833
  social;
@@ -899,6 +1054,34 @@ var OutboundService = class {
899
1054
  }));
900
1055
  const linkUrl = input.linkUrl?.trim() || null;
901
1056
  if (linkUrl && !/^https?:\/\/\S+$/i.test(linkUrl)) throw new OutboundError("invalid", "linkUrl must be an http(s) URL.");
1057
+ let requestedTargetAccountIds;
1058
+ let canonicalTargetAccountIds = null;
1059
+ if (input.targetAccountIds !== void 0) {
1060
+ if (!Array.isArray(input.targetAccountIds)) throw new OutboundError("invalid", "targetAccountIds must be a list of account IDs.");
1061
+ if (input.targetAccountIds.length === 0) throw new OutboundError("invalid", "targetAccountIds cannot be empty.");
1062
+ const trimmedIds = input.targetAccountIds.map((id) => typeof id === "string" ? id.trim() : "");
1063
+ if (trimmedIds.some((id) => !id)) throw new OutboundError("invalid", "targetAccountIds must contain non-empty account IDs.");
1064
+ requestedTargetAccountIds = [...new Set(trimmedIds)];
1065
+ canonicalTargetAccountIds = [...requestedTargetAccountIds].sort();
1066
+ }
1067
+ let xRepostMode = null;
1068
+ if (input.xRepostMode !== void 0) {
1069
+ if (!X_REPOST_MODES.includes(input.xRepostMode)) throw new OutboundError("invalid", `Unknown xRepostMode: ${String(input.xRepostMode)}.`);
1070
+ xRepostMode = input.xRepostMode;
1071
+ }
1072
+ let utmCampaign = null;
1073
+ if (input.utmCampaign !== void 0 && input.utmCampaign !== null) {
1074
+ if (typeof input.utmCampaign !== "string") throw new OutboundError("invalid", "utmCampaign must be a string or null.");
1075
+ utmCampaign = input.utmCampaign.trim() || null;
1076
+ }
1077
+ const normalizedMedia = input.media !== void 0 ? normalizeAttachMedia(input.media) : null;
1078
+ const validatedYoutube = input.youtube !== void 0 ? validateYouTubeMetadata(input.youtube) : null;
1079
+ if (normalizedMedia?.media.youtube && validatedYoutube && JSON.stringify(normalizedMedia.media.youtube) !== JSON.stringify(validatedYoutube)) throw new OutboundError("invalid", "Conflicting YouTube metadata was supplied.");
1080
+ const effectiveYoutube = normalizedMedia?.media.youtube ?? validatedYoutube ?? null;
1081
+ const effectiveMedia = normalizedMedia ? {
1082
+ ...normalizedMedia.media,
1083
+ ...effectiveYoutube ? { youtube: effectiveYoutube } : {}
1084
+ } : null;
902
1085
  return withLock(tenantId, () => withTenant({ tenantId }, async () => {
903
1086
  const ledgerKey = `manual:${key}`;
904
1087
  const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
@@ -907,6 +1090,7 @@ var OutboundService = class {
907
1090
  eventKey: ledgerKey
908
1091
  } })).find((row) => row.tenantId === tenantId);
909
1092
  if (seen) {
1093
+ if (!sameStringArray(seen.requestedTargetAccountIds ?? null, canonicalTargetAccountIds) || (seen.requestedXRepostMode ?? null) !== xRepostMode) throw new OutboundError("invalid", "Idempotency key replay conflicts with the original targetAccountIds or xRepostMode.");
910
1094
  const drafts = [];
911
1095
  for (const id of seen.outboundPostIds ?? []) drafts.push(await this.view(tenantId, await this.requireRow(tenantId, id), settings));
912
1096
  return {
@@ -914,8 +1098,21 @@ var OutboundService = class {
914
1098
  drafts
915
1099
  };
916
1100
  }
917
- const accounts = await this.targetAccounts(tenantId, settings);
1101
+ const accounts = requestedTargetAccountIds ? await this.resolveSelectedAccounts(tenantId, requestedTargetAccountIds) : await this.targetAccounts(tenantId, settings);
918
1102
  if (accounts.length === 0) return { outcome: "no-accounts" };
1103
+ let orderedAccounts = accounts;
1104
+ if (xRepostMode) {
1105
+ const ytAccounts = accounts.filter((a) => a.platform === "youtube");
1106
+ const xAccounts = accounts.filter((a) => a.platform === "x");
1107
+ if (ytAccounts.length !== 1) throw new OutboundError("invalid", "Paired YouTube-to-X publishing requires exactly one YouTube target account.");
1108
+ if (xAccounts.length === 0) throw new OutboundError("invalid", "Paired YouTube-to-X publishing requires at least one X target account.");
1109
+ const otherAccounts = accounts.filter((a) => a.platform !== "youtube" && a.platform !== "x");
1110
+ orderedAccounts = [
1111
+ ...ytAccounts,
1112
+ ...xAccounts,
1113
+ ...otherAccounts
1114
+ ];
1115
+ }
919
1116
  const drafts = [];
920
1117
  const ids = [];
921
1118
  const covered = /* @__PURE__ */ new Set();
@@ -924,17 +1121,45 @@ var OutboundService = class {
924
1121
  sourceKind: "manual",
925
1122
  sourceEventId: key
926
1123
  } })).filter((row) => row.tenantId === tenantId);
1124
+ let parentYoutubeRowId = null;
927
1125
  for (const row of earlier) {
928
1126
  const view = await this.view(tenantId, row, settings);
929
1127
  covered.add(view.accountId);
930
1128
  ids.push(row.id);
931
1129
  drafts.push(view);
1130
+ if (!row.parentOutboundId && view.accountId) {
1131
+ if (orderedAccounts.find((a) => a.id === view.accountId)?.platform === "youtube") parentYoutubeRowId = row.id;
1132
+ }
932
1133
  }
933
- for (const account of accounts) {
934
- if (covered.has(account.id)) continue;
1134
+ if (earlier.length > 0) {
1135
+ for (const row of earlier) if (!sameStringArray(row.requestedTargetAccountIds ?? null, canonicalTargetAccountIds) || (row.requestedXRepostMode ?? null) !== xRepostMode) throw new OutboundError("invalid", "Idempotency key retry conflicts with partially created targetAccountIds or xRepostMode.");
1136
+ }
1137
+ for (const account of orderedAccounts) {
1138
+ const accountId = account.id;
1139
+ if (covered.has(accountId)) continue;
1140
+ const isPairedYoutube = Boolean(xRepostMode && account.platform === "youtube");
1141
+ const isPairedX = Boolean(xRepostMode && account.platform === "x");
1142
+ let postType = "text";
1143
+ let videoContentId = null;
1144
+ let mediaUrl = null;
1145
+ let rowMedia = null;
1146
+ if (effectiveMedia) if (isPairedX && xRepostMode === "link_only") {
1147
+ postType = "text";
1148
+ videoContentId = null;
1149
+ mediaUrl = null;
1150
+ rowMedia = null;
1151
+ } else {
1152
+ const variant = selectMediaVariant(effectiveMedia, account.platform, null, isPairedX ? xRepostMode : null);
1153
+ postType = effectiveMedia.postType;
1154
+ videoContentId = variant?.videoContentId ?? effectiveMedia.videoContentId;
1155
+ mediaUrl = normalizedMedia?.hasMediaUrl ? fallbackMediaUrlForVariant(effectiveMedia, videoContentId, true, normalizedMedia.mediaUrl) ?? null : null;
1156
+ rowMedia = effectiveMedia;
1157
+ }
935
1158
  const post = await this.social.socialPosts.createDraft({
936
- socialAccountId: account.id,
937
- postType: "text",
1159
+ socialAccountId: accountId,
1160
+ postType,
1161
+ videoContentId,
1162
+ mediaUrl,
938
1163
  title: `${OUTBOUND_POST_MARKER}manual:${key}`,
939
1164
  description: text,
940
1165
  linkUrl,
@@ -951,12 +1176,20 @@ var OutboundService = class {
951
1176
  sourceKind: "manual",
952
1177
  sourceUrl: linkUrl,
953
1178
  claims,
1179
+ media: rowMedia,
1180
+ youtubeMetadata: isPairedYoutube || account.platform === "youtube" ? effectiveYoutube : null,
1181
+ parentOutboundId: isPairedX ? parentYoutubeRowId : null,
1182
+ xRepostMode: isPairedX ? xRepostMode : null,
1183
+ requestedTargetAccountIds: canonicalTargetAccountIds,
1184
+ requestedXRepostMode: xRepostMode,
1185
+ utmCampaign: isPairedYoutube || isPairedX ? utmCampaign : null,
954
1186
  createdBy
955
1187
  });
956
1188
  } catch (error) {
957
1189
  await this.discardSocialDraft(post);
958
1190
  throw error;
959
1191
  }
1192
+ if (isPairedYoutube) parentYoutubeRowId = row.id;
960
1193
  ids.push(row.id);
961
1194
  drafts.push(await this.view(tenantId, row, settings));
962
1195
  }
@@ -964,7 +1197,9 @@ var OutboundService = class {
964
1197
  tenantId,
965
1198
  eventKey: ledgerKey,
966
1199
  outcome: "drafted",
967
- outboundPostIds: ids
1200
+ outboundPostIds: ids,
1201
+ requestedTargetAccountIds: canonicalTargetAccountIds,
1202
+ requestedXRepostMode: xRepostMode
968
1203
  });
969
1204
  return {
970
1205
  outcome: "drafted",
@@ -972,6 +1207,35 @@ var OutboundService = class {
972
1207
  };
973
1208
  }));
974
1209
  }
1210
+ isAccountValidAndReady(account, tenantId) {
1211
+ return Boolean(account.id) && account.tenantId === tenantId && account.isActive !== false && account.status === "connected" && (account.missingPermissions?.length ?? 0) === 0 && account.isReady !== false;
1212
+ }
1213
+ async resolveSelectedAccounts(tenantId, requestedIds) {
1214
+ const readyById = /* @__PURE__ */ new Map();
1215
+ const ready = await this.social.socialAccounts.findReady();
1216
+ for (const account of ready) if (account.id && this.isAccountValidAndReady(account, tenantId)) readyById.set(account.id, account);
1217
+ const collection = this.social.socialAccounts;
1218
+ const missing = requestedIds.filter((id) => !readyById.has(id));
1219
+ if (missing.length > 0 && this.refreshAccount && typeof collection.findActive === "function") {
1220
+ const missingSet = new Set(missing);
1221
+ for (const account of await collection.findActive()) {
1222
+ if (!account.id || !missingSet.has(account.id) || account.tenantId !== tenantId || !isLapsedOnly(account)) continue;
1223
+ try {
1224
+ await this.refreshAccount(account);
1225
+ } catch {
1226
+ continue;
1227
+ }
1228
+ if (this.isAccountValidAndReady(account, tenantId)) readyById.set(account.id, account);
1229
+ }
1230
+ }
1231
+ const selected = [];
1232
+ for (const id of requestedIds) {
1233
+ const account = readyById.get(id);
1234
+ if (!account) throw new OutboundError("invalid", "One or more target accounts are invalid, inactive, or not ready for this tenant.");
1235
+ selected.push(account);
1236
+ }
1237
+ return selected;
1238
+ }
975
1239
  async targetAccounts(tenantId, settings) {
976
1240
  const wanted = (account) => Boolean(account.id) && account.tenantId === tenantId && (settings.accountIds.length === 0 || settings.accountIds.includes(account.id));
977
1241
  const ready = (await this.social.socialAccounts.findReady()).filter(wanted);
@@ -1007,6 +1271,17 @@ var OutboundService = class {
1007
1271
  const post = known === void 0 ? await this.loadPost(tenantId, row) : known;
1008
1272
  const accountId = post?.socialAccountId ?? null;
1009
1273
  const policy = accountId && settings.linkPolicy[accountId] || settings.defaultLinkPolicy;
1274
+ const media = row.media ?? (post && (post.postType === "video" || post.postType === "image") && post.videoContentId ? {
1275
+ postType: post.postType,
1276
+ videoContentId: post.videoContentId
1277
+ } : null);
1278
+ let linkUrl = policy === "include" ? post?.linkUrl ?? row.sourceUrl ?? null : null;
1279
+ if (row.parentOutboundId) {
1280
+ const parentRow = await this.requireRow(tenantId, row.parentOutboundId).catch(() => null);
1281
+ const parentPost = parentRow ? await this.loadPost(tenantId, parentRow) : null;
1282
+ const parentUrl = parentPost?.platformUrl?.trim() || "";
1283
+ if (parentPost?.status === "published" && parentUrl) linkUrl = buildPairedYouTubeUrl(parentUrl, post?.linkUrl ?? row.sourceUrl, row.utmCampaign);
1284
+ }
1010
1285
  return {
1011
1286
  id: row.id,
1012
1287
  tenantId,
@@ -1017,7 +1292,10 @@ var OutboundService = class {
1017
1292
  text: post?.description ?? "",
1018
1293
  hashtags: post?.hashtags ?? [],
1019
1294
  claims: row.claims ?? [],
1020
- linkUrl: policy === "include" ? post?.linkUrl ?? row.sourceUrl ?? null : null,
1295
+ linkUrl,
1296
+ media,
1297
+ parentOutboundId: row.parentOutboundId ?? null,
1298
+ xRepostMode: row.xRepostMode ?? null,
1021
1299
  sourceEventId: row.sourceEventId,
1022
1300
  sourceKind: row.sourceKind,
1023
1301
  createdBy: row.createdBy ?? null,
@@ -1078,18 +1356,210 @@ var OutboundService = class {
1078
1356
  }))
1079
1357
  }));
1080
1358
  }
1359
+ const post = await this.loadPost(tenantId, row);
1360
+ if (!post) throw new OutboundError("not-found", "The social post for this draft is missing.");
1361
+ const dependents = await this.findDependents(tenantId, row.id);
1362
+ await this.assertDependentsMutable(tenantId, dependents, "edited");
1363
+ const prevRowState = row.state;
1364
+ const prevRowApprovedBy = row.approvedBy;
1365
+ const prevRowClaims = row.claims;
1081
1366
  const back = state !== "draft";
1082
- await this.updateSocialPost(tenantId, row, {
1083
- ...social,
1367
+ const undoStack = [];
1368
+ try {
1369
+ for (const dep of dependents) {
1370
+ if (dep.state === "draft" || dep.state === "published" || dep.state === "rejected") continue;
1371
+ const depPost = await this.loadPost(tenantId, dep);
1372
+ if (!depPost) throw new OutboundError("not-found", "The social post for a dependent draft is missing.");
1373
+ const prevDepState = dep.state;
1374
+ const prevDepApprovedBy = dep.approvedBy;
1375
+ await this.updateSocialPost(tenantId, dep, {
1376
+ status: socialStatusFor("draft"),
1377
+ scheduled_at: null
1378
+ });
1379
+ undoStack.push(() => this.updateSocialPost(tenantId, dep, {
1380
+ status: socialStatusFor(prevDepState),
1381
+ scheduled_at: depPost.scheduledAt ?? null
1382
+ }));
1383
+ dep.state = "draft";
1384
+ dep.approvedBy = null;
1385
+ await dep.save();
1386
+ undoStack.push(async () => {
1387
+ dep.state = prevDepState;
1388
+ dep.approvedBy = prevDepApprovedBy;
1389
+ await dep.save();
1390
+ });
1391
+ }
1392
+ const rollbackParentSocial = {
1393
+ ...patch.text !== void 0 ? { description: post.description } : {},
1394
+ ...patch.linkUrl !== void 0 ? { link_url: post.linkUrl ?? null } : {},
1395
+ ...back ? {
1396
+ status: socialStatusFor(state),
1397
+ scheduled_at: post.scheduledAt ?? null
1398
+ } : {}
1399
+ };
1400
+ await this.updateSocialPost(tenantId, row, {
1401
+ ...social,
1402
+ ...back ? {
1403
+ status: socialStatusFor("draft"),
1404
+ scheduled_at: null
1405
+ } : {}
1406
+ });
1407
+ undoStack.push(() => this.updateSocialPost(tenantId, row, rollbackParentSocial));
1408
+ if (back) {
1409
+ row.state = "draft";
1410
+ row.approvedBy = null;
1411
+ }
1412
+ await row.save();
1413
+ undoStack.push(async () => {
1414
+ row.state = prevRowState;
1415
+ row.approvedBy = prevRowApprovedBy;
1416
+ row.claims = prevRowClaims;
1417
+ await row.save();
1418
+ });
1419
+ } catch (error) {
1420
+ for (const undo of undoStack.reverse()) await undo().catch(() => void 0);
1421
+ throw error;
1422
+ }
1423
+ return this.getDraft(tenantId, id);
1424
+ });
1425
+ }
1426
+ /**
1427
+ * Attach a video or image reference (with optional aspect-ratio variants and
1428
+ * YouTube metadata) to an outbound draft. Like `editDraft`, attaching media
1429
+ * withdraws any existing approval back to `draft` (and on any paired
1430
+ * dependent X draft) while keeping the outbound marker on `SocialPost.title`
1431
+ * intact.
1432
+ */
1433
+ attachMedia(tenantId, id, input) {
1434
+ assertAmbientTenant(tenantId);
1435
+ const { media, hasMediaUrl, mediaUrl } = normalizeAttachMedia(input);
1436
+ return withLock(tenantId, () => withTenant({ tenantId }, async () => {
1437
+ const row = await this.requireRow(tenantId, id);
1438
+ const state = row.state;
1439
+ if (state === "published" || state === "rejected") throw new OutboundError("illegal-transition", `A ${state} post cannot have media attached.`);
1440
+ const post = await this.loadPost(tenantId, row);
1441
+ if (!post) throw new OutboundError("not-found", "The social post for this draft is missing.");
1442
+ const dependents = await this.findDependents(tenantId, row.id);
1443
+ await this.assertDependentsMutable(tenantId, dependents, "updated with new media");
1444
+ const effectiveYoutube = media.youtube ?? row.youtubeMetadata ?? void 0;
1445
+ const effectiveMedia = {
1446
+ ...media,
1447
+ ...effectiveYoutube ? { youtube: effectiveYoutube } : {}
1448
+ };
1449
+ const account = post.socialAccountId ? await this.social.socialAccounts.get({ id: post.socialAccountId }) : null;
1450
+ const isLinkOnly = row.xRepostMode === "link_only";
1451
+ const resolvedVariant = selectMediaVariant(effectiveMedia, account?.platform ?? "", post.videoContentId, row.xRepostMode ?? null);
1452
+ const resolvedVideoContentId = isLinkOnly ? null : resolvedVariant?.videoContentId ?? effectiveMedia.videoContentId;
1453
+ const resolvedPostType = isLinkOnly ? "text" : effectiveMedia.postType;
1454
+ const parentAssignedMediaUrl = fallbackMediaUrlForVariant(effectiveMedia, resolvedVideoContentId, hasMediaUrl, mediaUrl);
1455
+ const parentAssetChanged = resolvedVideoContentId !== (post.videoContentId ?? null) || row.media !== null && row.media.videoContentId !== effectiveMedia.videoContentId;
1456
+ const clearParentMediaUrl = isLinkOnly || parentAssignedMediaUrl === null || !hasMediaUrl && parentAssetChanged;
1457
+ const prevRowMedia = row.media;
1458
+ const prevRowYoutube = row.youtubeMetadata;
1459
+ const prevRowState = row.state;
1460
+ const prevRowApprovedBy = row.approvedBy;
1461
+ const back = state !== "draft";
1462
+ const rollbackPost = {
1463
+ post_type: post.postType ?? "text",
1464
+ video_content_id: post.videoContentId ?? null,
1465
+ ...hasMediaUrl || clearParentMediaUrl ? { media_url: post.mediaUrl ?? null } : {},
1084
1466
  ...back ? {
1085
- status: socialStatusFor("draft"),
1086
- scheduled_at: null
1467
+ status: socialStatusFor(state),
1468
+ scheduled_at: post.scheduledAt ?? null
1087
1469
  } : {}
1088
- });
1089
- if (back) row.state = "draft";
1090
- await row.save();
1470
+ };
1471
+ const undoStack = [];
1472
+ try {
1473
+ for (const dep of dependents) {
1474
+ if (dep.state === "rejected") continue;
1475
+ const depPost = await this.loadPost(tenantId, dep);
1476
+ if (!depPost) throw new OutboundError("not-found", "The social post for a dependent draft is missing.");
1477
+ const depMode = dep.xRepostMode ?? null;
1478
+ const depLinkOnly = depMode === "link_only";
1479
+ const depVariant = depLinkOnly ? null : selectMediaVariant(effectiveMedia, "x", null, depMode);
1480
+ const depVideoId = depLinkOnly ? null : depVariant?.videoContentId ?? effectiveMedia.videoContentId;
1481
+ const depPostType = depLinkOnly ? "text" : effectiveMedia.postType;
1482
+ const depAssignedMediaUrl = fallbackMediaUrlForVariant(effectiveMedia, depVideoId, hasMediaUrl, mediaUrl);
1483
+ const depAssetChanged = depVideoId !== (depPost.videoContentId ?? null) || dep.media !== null && dep.media.videoContentId !== effectiveMedia.videoContentId;
1484
+ const clearDepMediaUrl = depLinkOnly || depAssignedMediaUrl === null || !hasMediaUrl && depAssetChanged;
1485
+ const depBack = dep.state !== "draft";
1486
+ const prevDepState = dep.state;
1487
+ const prevDepApprovedBy = dep.approvedBy;
1488
+ const prevDepMedia = dep.media;
1489
+ const depRollbackSocial = {
1490
+ post_type: depPost.postType ?? "text",
1491
+ video_content_id: depPost.videoContentId ?? null,
1492
+ ...hasMediaUrl || clearDepMediaUrl ? { media_url: depPost.mediaUrl ?? null } : {},
1493
+ ...depBack ? {
1494
+ status: socialStatusFor(prevDepState),
1495
+ scheduled_at: depPost.scheduledAt ?? null
1496
+ } : {}
1497
+ };
1498
+ await this.updateSocialPost(tenantId, dep, {
1499
+ post_type: depPostType,
1500
+ video_content_id: depVideoId,
1501
+ ...clearDepMediaUrl ? { media_url: null } : hasMediaUrl ? { media_url: mediaUrl ?? null } : {},
1502
+ ...depBack ? {
1503
+ status: socialStatusFor("draft"),
1504
+ scheduled_at: null
1505
+ } : {}
1506
+ });
1507
+ undoStack.push(() => this.updateSocialPost(tenantId, dep, depRollbackSocial));
1508
+ dep.media = depLinkOnly ? null : effectiveMedia;
1509
+ if (depBack) {
1510
+ dep.state = "draft";
1511
+ dep.approvedBy = null;
1512
+ }
1513
+ await dep.save();
1514
+ undoStack.push(async () => {
1515
+ dep.media = prevDepMedia;
1516
+ dep.state = prevDepState;
1517
+ dep.approvedBy = prevDepApprovedBy;
1518
+ await dep.save();
1519
+ });
1520
+ }
1521
+ await this.updateSocialPost(tenantId, row, {
1522
+ post_type: resolvedPostType,
1523
+ video_content_id: resolvedVideoContentId,
1524
+ ...clearParentMediaUrl ? { media_url: null } : hasMediaUrl ? { media_url: mediaUrl ?? null } : {},
1525
+ ...back ? {
1526
+ status: socialStatusFor("draft"),
1527
+ scheduled_at: null
1528
+ } : {}
1529
+ });
1530
+ undoStack.push(() => this.updateSocialPost(tenantId, row, rollbackPost));
1531
+ row.media = isLinkOnly ? null : effectiveMedia;
1532
+ if (effectiveYoutube) row.youtubeMetadata = effectiveYoutube;
1533
+ if (back) {
1534
+ row.state = "draft";
1535
+ row.approvedBy = null;
1536
+ }
1537
+ await row.save();
1538
+ undoStack.push(async () => {
1539
+ row.media = prevRowMedia;
1540
+ row.youtubeMetadata = prevRowYoutube;
1541
+ row.state = prevRowState;
1542
+ row.approvedBy = prevRowApprovedBy;
1543
+ await row.save();
1544
+ });
1545
+ } catch (error) {
1546
+ for (const undo of undoStack.reverse()) await undo().catch(() => void 0);
1547
+ throw error;
1548
+ }
1091
1549
  return this.getDraft(tenantId, id);
1092
- });
1550
+ }));
1551
+ }
1552
+ async findDependents(tenantId, parentOutboundId) {
1553
+ return (await this.stores.posts.list({ where: {
1554
+ tenantId,
1555
+ parentOutboundId
1556
+ } })).filter((item) => item.tenantId === tenantId && item.parentOutboundId === parentOutboundId);
1557
+ }
1558
+ async assertDependentsMutable(tenantId, dependents, action) {
1559
+ for (const dep of dependents) {
1560
+ if (dep.state === "published") throw new OutboundError("illegal-transition", `A paired dependent post is already published, so this parent cannot be ${action}.`);
1561
+ if ((await this.loadPost(tenantId, dep))?.status === "publishing") throw new OutboundError("in-flight", "A paired dependent post is being published right now, so it was not changed.");
1562
+ }
1093
1563
  }
1094
1564
  approve(tenantId, id, approvedBy = "user") {
1095
1565
  assertAmbientTenant(tenantId);
@@ -1129,7 +1599,7 @@ var OutboundService = class {
1129
1599
  return this.getDraft(tenantId, id);
1130
1600
  });
1131
1601
  }
1132
- /** Approved or scheduled posts of the tenant whose time has come. */
1602
+ /** Approved or scheduled posts of the tenant whose time has come (parents before dependents). */
1133
1603
  async dueForPublish(tenantId, now) {
1134
1604
  assertAmbientTenant(tenantId);
1135
1605
  return withTenant({ tenantId }, async () => {
@@ -1137,8 +1607,10 @@ var OutboundService = class {
1137
1607
  where: { tenantId },
1138
1608
  orderBy: "created_at ASC"
1139
1609
  })).filter((row) => row.tenantId === tenantId && (row.state === "approved" || row.state === "scheduled"));
1610
+ const parents = rows.filter((row) => !row.parentOutboundId);
1611
+ const children = rows.filter((row) => Boolean(row.parentOutboundId));
1140
1612
  const due = [];
1141
- for (const row of rows) {
1613
+ for (const row of [...parents, ...children]) {
1142
1614
  const post = await this.loadPost(tenantId, row);
1143
1615
  if (!post) continue;
1144
1616
  const at = post.scheduledAt ? new Date(post.scheduledAt) : null;
@@ -1147,6 +1619,26 @@ var OutboundService = class {
1147
1619
  return due;
1148
1620
  });
1149
1621
  }
1622
+ /** Order social posts so parent YouTube posts run ahead of dependent X posts. */
1623
+ async orderSocialPostsForPublish(posts) {
1624
+ if (posts.length <= 1) return posts;
1625
+ const tagged = await Promise.all(posts.map(async (post, index) => {
1626
+ const tenantId = post.tenantId?.trim();
1627
+ if (!tenantId || !post.id) return {
1628
+ post,
1629
+ index,
1630
+ hasParent: false
1631
+ };
1632
+ const row = await withTenant({ tenantId }, () => this.findRowForPost(tenantId, post.id)).catch(() => null);
1633
+ return {
1634
+ post,
1635
+ index,
1636
+ hasParent: Boolean(row?.parentOutboundId)
1637
+ };
1638
+ }));
1639
+ tagged.sort((a, b) => Number(a.hasParent) - Number(b.hasParent) || a.index - b.index);
1640
+ return tagged.map((entry) => entry.post);
1641
+ }
1150
1642
  /** The tenant's post to publish now: it must be approved or scheduled. */
1151
1643
  async postForPublish(tenantId, id) {
1152
1644
  assertAmbientTenant(tenantId);
@@ -1265,7 +1757,7 @@ var OutboundService = class {
1265
1757
  * the monthly cap. On success a spend reservation is held (atomically with
1266
1758
  * the cap check) until {@link finish}.
1267
1759
  */
1268
- beforeSend(post, platform) {
1760
+ beforeSend(post, platform, linkBehavior) {
1269
1761
  const tenantId = post.tenantId?.trim();
1270
1762
  const refuse = (code, message) => ({
1271
1763
  ok: false,
@@ -1280,15 +1772,68 @@ var OutboundService = class {
1280
1772
  return withLock(tenantId, () => withTenant({ tenantId }, async () => {
1281
1773
  const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
1282
1774
  if (settings.paused) return refuse("paused", "Posting is paused for this tenant, so nothing was posted.");
1775
+ const config = this.configFn();
1283
1776
  const row = post.id ? await this.findRowForPost(tenantId, post.id) : null;
1284
1777
  let linkUrl = post.linkUrl ?? null;
1778
+ let resolved;
1285
1779
  if (row) {
1286
1780
  if (row.state !== "approved" && row.state !== "scheduled") return refuse("not-approved", `This post is ${row.state}, not approved.`);
1287
1781
  if (!isFullyCited(row.claims)) return refuse("uncited", "A claim in this post has no evidence, so it was not posted.");
1288
1782
  const accountId = post.socialAccountId ?? "";
1289
1783
  linkUrl = (settings.linkPolicy[accountId] ?? settings.defaultLinkPolicy) === "include" ? post.linkUrl ?? row.sourceUrl ?? null : null;
1784
+ let descriptionOverride;
1785
+ let postTypeOverride = row.media?.postType;
1786
+ let videoContentIdOverride;
1787
+ let mediaUrlOverride;
1788
+ let linkBehaviorOverride;
1789
+ const xRepostMode = row.xRepostMode ?? null;
1790
+ if (row.parentOutboundId) {
1791
+ const parentRow = await this.requireRow(tenantId, row.parentOutboundId).catch(() => null);
1792
+ const parentPost = parentRow ? await this.loadPost(tenantId, parentRow) : null;
1793
+ if (!parentRow || !parentPost) return refuse("dependency-not-ready", "The parent YouTube post is missing, so this dependent X post was not published.");
1794
+ if (parentRow.state === "failed" || parentPost.status === "failed") {
1795
+ const reason = parentPost.errorMessage ? `: ${parentPost.errorMessage}` : "";
1796
+ return refuse("dependency-not-ready", `The parent YouTube publish failed${reason}, so this dependent X post remains blocked.`);
1797
+ }
1798
+ if (parentRow.state === "rejected" || parentPost.status === "cancelled") return refuse("dependency-not-ready", "The parent YouTube post was rejected, so this dependent X post was not published.");
1799
+ const parentUrl = parentPost.platformUrl?.trim() || "";
1800
+ if (parentPost.status !== "published" || !parentUrl) return refuse("dependency-not-ready", `The parent YouTube post is ${parentPost.status} without a live URL, so this dependent X post is waiting.`);
1801
+ const liveYouTubeUrl = buildPairedYouTubeUrl(parentUrl, post.linkUrl ?? row.sourceUrl, row.utmCampaign);
1802
+ linkUrl = liveYouTubeUrl;
1803
+ descriptionOverride = stripUrlFromDescription(post.description, liveYouTubeUrl);
1804
+ if (linkBehavior === "none") linkBehaviorOverride = "inline";
1805
+ const maxLen = config.outboundMaxLength;
1806
+ const effectiveLen = linkBehavior === "reply" ? Math.max(computeXPostLength(descriptionOverride, post.hashtags ?? [], null, "reply"), liveYouTubeUrl.length) : computeXPostLength(descriptionOverride, post.hashtags ?? [], liveYouTubeUrl, "inline");
1807
+ if (effectiveLen > maxLen) return refuse("invalid", `The X repost text with YouTube URL exceeds ${maxLen} characters (${effectiveLen} > ${maxLen}).`);
1808
+ if (xRepostMode === "link_only") {
1809
+ postTypeOverride = "text";
1810
+ videoContentIdOverride = null;
1811
+ mediaUrlOverride = null;
1812
+ }
1813
+ }
1814
+ const variant = xRepostMode === "link_only" ? null : selectMediaVariant(row.media, platform, post.videoContentId, xRepostMode);
1815
+ const isShort = xRepostMode === "link_only" ? false : variant?.isShort === true || variant?.aspectRatio === "9:16";
1816
+ if (xRepostMode !== "link_only") {
1817
+ videoContentIdOverride = variant?.videoContentId ?? row.media?.videoContentId;
1818
+ if (videoContentIdOverride && post.videoContentId && videoContentIdOverride !== post.videoContentId) mediaUrlOverride = null;
1819
+ }
1820
+ const yt = platform === "youtube" ? row.media?.youtube ?? row.youtubeMetadata ?? void 0 : void 0;
1821
+ resolved = {
1822
+ linkUrl,
1823
+ ...postTypeOverride !== void 0 ? { postType: postTypeOverride } : {},
1824
+ ...videoContentIdOverride !== void 0 ? { videoContentId: videoContentIdOverride } : {},
1825
+ ...mediaUrlOverride !== void 0 ? { mediaUrl: mediaUrlOverride } : {},
1826
+ ...descriptionOverride !== void 0 ? { description: descriptionOverride } : {},
1827
+ ...linkBehaviorOverride !== void 0 ? { linkBehavior: linkBehaviorOverride } : {},
1828
+ ...yt ? {
1829
+ title: yt.title,
1830
+ ...yt.description !== void 0 ? { description: yt.description } : {},
1831
+ ...yt.tags !== void 0 ? { hashtags: yt.tags } : {}
1832
+ } : {},
1833
+ isShort
1834
+ };
1290
1835
  } 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.");
1291
- const estimate = estimateCost(this.configFn().outboundRates, platform, linkUrl !== null);
1836
+ const estimate = estimateCost(config.outboundRates, platform, linkUrl !== null);
1292
1837
  const month = monthKey(this.nowFn());
1293
1838
  const spent = (await this.monthEntries(tenantId, month)).filter((entry) => entry.status !== "released").reduce((sum, entry) => sum + entry.costMicros, 0);
1294
1839
  const valid = (n) => Number.isFinite(n) && n >= 0;
@@ -1305,6 +1850,7 @@ var OutboundService = class {
1305
1850
  return {
1306
1851
  ok: true,
1307
1852
  linkUrl,
1853
+ ...resolved ? { resolved } : {},
1308
1854
  reservation: {
1309
1855
  tenantId,
1310
1856
  entryId: entry.id,
@@ -1343,7 +1889,7 @@ var OutboundService = class {
1343
1889
  }
1344
1890
  await entry.save();
1345
1891
  }
1346
- if (reservation.outboundId) {
1892
+ if (reservation.outboundId && !outcome.skipped) {
1347
1893
  const row = await this.requireRow(tenantId, reservation.outboundId).catch(() => null);
1348
1894
  if (row && (row.state === "approved" || row.state === "scheduled")) {
1349
1895
  row.state = outcome.result || outcome.success ? "published" : "failed";
@@ -1489,7 +2035,8 @@ var Garrula = class Garrula extends Agent {
1489
2035
  * are and picked up by a later run.
1490
2036
  */
1491
2037
  async run() {
1492
- const duePosts = await this.socialPosts.findDueForPublish(/* @__PURE__ */ new Date());
2038
+ const rawDuePosts = await this.socialPosts.findDueForPublish(/* @__PURE__ */ new Date());
2039
+ const duePosts = this.outbound ? await this.outbound.orderSocialPostsForPublish(rawDuePosts) : rawDuePosts;
1493
2040
  let published = 0;
1494
2041
  let failed = 0;
1495
2042
  let skipped = 0;
@@ -1580,6 +2127,11 @@ var Garrula = class Garrula extends Agent {
1580
2127
  const { service, tenantId } = this.outboundFor(options);
1581
2128
  return service.editDraft(tenantId, id, patch);
1582
2129
  }
2130
+ /** Attach video/image media (and optional variants/YouTube metadata). Withdraws approval. */
2131
+ async attachMedia(id, media, options) {
2132
+ const { service, tenantId } = this.outboundFor(options);
2133
+ return service.attachMedia(tenantId, id, media);
2134
+ }
1583
2135
  async approve(id, options) {
1584
2136
  const { service, tenantId } = this.outboundFor(options);
1585
2137
  return service.approve(tenantId, id, options?.approvedBy);
@@ -1721,7 +2273,8 @@ var Garrula = class Garrula extends Agent {
1721
2273
  if (context.reservation) await this.outbound?.finish(context.reservation, {
1722
2274
  result: context.sent ?? null,
1723
2275
  success,
1724
- error
2276
+ error,
2277
+ skipped
1725
2278
  });
1726
2279
  else if (!success && !skipped && postId) await this.outbound?.failUnreserved(tenantId, postId);
1727
2280
  });
@@ -1803,10 +2356,9 @@ var Garrula = class Garrula extends Agent {
1803
2356
  const credentials = await account.getCredentials();
1804
2357
  if (!credentials) throw new Error(`No credentials configured for ${account.name}`);
1805
2358
  let session = await this.openAdapter(account, credentials);
1806
- const mediaUrl = post.postType === "video" ? await this.hostHooks.resolveMediaUrl?.(post) || post.mediaUrl : post.mediaUrl;
1807
2359
  let sendPost = post;
1808
2360
  if (this.outbound) {
1809
- const gate = await this.outbound.beforeSend(post, account.platform);
2361
+ const gate = await this.outbound.beforeSend(post, account.platform, account.linkBehavior);
1810
2362
  if (!gate.ok) {
1811
2363
  await this.releaseClaim(post, previousStatus);
1812
2364
  return {
@@ -1819,19 +2371,74 @@ var Garrula = class Garrula extends Agent {
1819
2371
  };
1820
2372
  }
1821
2373
  context.reservation = gate.reservation;
2374
+ context.isShort = gate.resolved?.isShort === true;
2375
+ context.linkBehavior = gate.resolved?.linkBehavior;
1822
2376
  sendPost = {
1823
2377
  ...post,
1824
2378
  linkUrl: gate.linkUrl,
1825
- ...isOutboundMarked(post) ? { title: null } : {}
2379
+ ...gate.resolved?.postType !== void 0 ? { postType: gate.resolved.postType } : {},
2380
+ ...gate.resolved?.videoContentId !== void 0 ? { videoContentId: gate.resolved.videoContentId } : {},
2381
+ ...gate.resolved?.mediaUrl !== void 0 ? { mediaUrl: gate.resolved.mediaUrl } : {},
2382
+ ...gate.resolved?.description !== void 0 ? { description: gate.resolved.description } : {},
2383
+ ...gate.resolved?.hashtags !== void 0 ? { hashtags: gate.resolved.hashtags } : {},
2384
+ ...gate.resolved?.title !== void 0 ? { title: gate.resolved.title } : isOutboundMarked(post) ? { title: null } : {}
1826
2385
  };
1827
2386
  }
2387
+ let mediaUrl = sendPost.mediaUrl;
2388
+ if (sendPost.postType === "video") {
2389
+ let resolvedUrl;
2390
+ try {
2391
+ resolvedUrl = await this.hostHooks.resolveMediaUrl?.(sendPost);
2392
+ } catch (mediaError) {
2393
+ if (isMediaUnavailableError(mediaError)) {
2394
+ const message = errorMessage(mediaError) || "Video post has no resolvable media URL.";
2395
+ await this.releaseClaim(post, previousStatus);
2396
+ return {
2397
+ postId,
2398
+ platform,
2399
+ success: false,
2400
+ error: message,
2401
+ skipped: "refused",
2402
+ refusal: {
2403
+ code: "media-unavailable",
2404
+ message
2405
+ }
2406
+ };
2407
+ }
2408
+ throw mediaError;
2409
+ }
2410
+ const trimmedResolved = typeof resolvedUrl === "string" ? resolvedUrl.trim() : "";
2411
+ const trimmedFallback = typeof sendPost.mediaUrl === "string" ? sendPost.mediaUrl.trim() : "";
2412
+ mediaUrl = trimmedResolved || trimmedFallback || null;
2413
+ if (!mediaUrl) {
2414
+ const message = "Video post has no resolvable media URL.";
2415
+ await this.releaseClaim(post, previousStatus);
2416
+ return {
2417
+ postId,
2418
+ platform,
2419
+ success: false,
2420
+ error: message,
2421
+ skipped: "refused",
2422
+ refusal: {
2423
+ code: "media-unavailable",
2424
+ message
2425
+ }
2426
+ };
2427
+ }
2428
+ }
1828
2429
  try {
1829
- result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);
2430
+ result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null, {
2431
+ isShort: context.isShort,
2432
+ linkBehavior: context.linkBehavior
2433
+ });
1830
2434
  } catch (publishError) {
1831
2435
  if (!isAuthError(publishError)) throw publishError;
1832
2436
  session = await this.openAdapter(account, session.credentials, { force: true });
1833
2437
  try {
1834
- result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);
2438
+ result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null, {
2439
+ isShort: context.isShort,
2440
+ linkBehavior: context.linkBehavior
2441
+ });
1835
2442
  } catch (retryError) {
1836
2443
  if (!isAuthError(retryError)) throw retryError;
1837
2444
  throw await this.requireReconnect(account, "publish rejected after refresh");
@@ -2218,14 +2825,16 @@ var Garrula = class Garrula extends Agent {
2218
2825
  case "bluesky": throw new SocialError("Posting to Bluesky is not available yet.", "UNSUPPORTED_PLATFORM", "bluesky");
2219
2826
  }
2220
2827
  }
2221
- publishWithAdapter(adapter, post, mediaUrl) {
2828
+ publishWithAdapter(adapter, post, mediaUrl, options = {}) {
2829
+ const linkBehaviorOpt = options.linkBehavior ? { linkBehavior: options.linkBehavior } : {};
2222
2830
  if (post.postType === "link") {
2223
2831
  if (!post.linkUrl) throw new SocialError("Link URL is required", "MISSING_LINK_URL");
2224
2832
  return adapter.publishLink({
2225
2833
  url: post.linkUrl,
2226
2834
  text: post.description,
2227
2835
  title: post.title ?? void 0,
2228
- tags: post.hashtags
2836
+ tags: post.hashtags,
2837
+ ...linkBehaviorOpt
2229
2838
  });
2230
2839
  }
2231
2840
  if (post.postType === "video") {
@@ -2236,7 +2845,8 @@ var Garrula = class Garrula extends Agent {
2236
2845
  description: post.description,
2237
2846
  tags: post.hashtags,
2238
2847
  linkUrl: post.linkUrl ?? void 0,
2239
- isShort: adapter.platform === "youtube"
2848
+ isShort: options.isShort === true,
2849
+ ...linkBehaviorOpt
2240
2850
  });
2241
2851
  }
2242
2852
  if (post.postType === "image") {
@@ -2246,13 +2856,15 @@ var Garrula = class Garrula extends Agent {
2246
2856
  description: post.description,
2247
2857
  altText: post.title ?? void 0,
2248
2858
  tags: post.hashtags,
2249
- linkUrl: post.linkUrl ?? void 0
2859
+ linkUrl: post.linkUrl ?? void 0,
2860
+ ...linkBehaviorOpt
2250
2861
  });
2251
2862
  }
2252
2863
  return adapter.publishText({
2253
2864
  text: post.description,
2254
2865
  tags: post.hashtags,
2255
- linkUrl: post.linkUrl ?? void 0
2866
+ linkUrl: post.linkUrl ?? void 0,
2867
+ ...linkBehaviorOpt
2256
2868
  });
2257
2869
  }
2258
2870
  async syncAnalyticsForPost(post, adapter, platform) {
@@ -2286,10 +2898,19 @@ function toRawAnalyticsPayload(value) {
2286
2898
  if (value === null || Array.isArray(value)) return value;
2287
2899
  return typeof value === "object" ? value : void 0;
2288
2900
  }
2901
+ function isMediaUnavailableError(error) {
2902
+ if (error instanceof OutboundError && error.code === "media-unavailable") return true;
2903
+ if (error instanceof SocialError && (error.code === "MEDIA_UNAVAILABLE" || error.code === "MISSING_MEDIA_URL")) return true;
2904
+ if (typeof error === "object" && error !== null && "code" in error) {
2905
+ const code = error.code;
2906
+ return code === "media-unavailable" || code === "MEDIA_UNAVAILABLE";
2907
+ }
2908
+ return false;
2909
+ }
2289
2910
  function errorMessage(error) {
2290
2911
  return error instanceof Error ? error.message : String(error);
2291
2912
  }
2292
2913
  //#endregion
2293
- 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 };
2914
+ 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, X_REPOST_MODES, YOUTUBE_MAX_DESCRIPTION_LENGTH, YOUTUBE_MAX_TITLE_LENGTH, canTransition, createOutboundStores, reconnectMessage, resolveGarrulaConfig, setGarrulaConfig, setGarrulaHost };
2294
2915
 
2295
2916
  //# sourceMappingURL=index.js.map