@usesocial/cli 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3478,7 +3478,7 @@ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9
3478
3478
  /** Returns a regex for validating an RFC 9562/4122 UUID.
3479
3479
  *
3480
3480
  * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
3481
- const uuid$1 = (version) => {
3481
+ const uuid$2 = (version) => {
3482
3482
  if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
3483
3483
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3484
3484
  };
@@ -4048,8 +4048,8 @@ const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
4048
4048
  v8: 8
4049
4049
  }[def.version];
4050
4050
  if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
4051
- def.pattern ?? (def.pattern = uuid$1(v));
4052
- } else def.pattern ?? (def.pattern = uuid$1());
4051
+ def.pattern ?? (def.pattern = uuid$2(v));
4052
+ } else def.pattern ?? (def.pattern = uuid$2());
4053
4053
  $ZodStringFormat.init(inst, def);
4054
4054
  });
4055
4055
  const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
@@ -6877,6 +6877,9 @@ const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
6877
6877
  $ZodUUID.init(inst, def);
6878
6878
  ZodStringFormat.init(inst, def);
6879
6879
  });
6880
+ function uuid$1(params) {
6881
+ return /* @__PURE__ */ _uuid(ZodUUID, params);
6882
+ }
6880
6883
  const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
6881
6884
  $ZodURL.init(inst, def);
6882
6885
  ZodStringFormat.init(inst, def);
@@ -11046,6 +11049,14 @@ const CONNECTED_ACCOUNT_STATUSES = [
11046
11049
  "disconnected",
11047
11050
  "error"
11048
11051
  ];
11052
+ const ACCOUNT_CONNECT_ATTEMPT_LANES = ["provider", "legacy"];
11053
+ const ACCOUNT_CONNECT_ATTEMPT_STATUSES = [
11054
+ "pending_billing",
11055
+ "pending_approval",
11056
+ "connected",
11057
+ "expired",
11058
+ "failed"
11059
+ ];
11049
11060
  const PROXY_SURFACES = [
11050
11061
  "cli",
11051
11062
  "mcp",
@@ -11102,6 +11113,8 @@ const WEBHOOK_OPERATION_STATES = [
11102
11113
  ];
11103
11114
  _enum(PLATFORMS);
11104
11115
  _enum(CONNECTED_ACCOUNT_STATUSES);
11116
+ _enum(ACCOUNT_CONNECT_ATTEMPT_LANES);
11117
+ _enum(ACCOUNT_CONNECT_ATTEMPT_STATUSES);
11105
11118
  _enum(PROXY_SURFACES);
11106
11119
  _enum(PROXY_CACHE_STATUSES);
11107
11120
  _enum(PROXY_CAPABILITIES);
@@ -11293,6 +11306,33 @@ const connectedAccounts = pgTable("connected_accounts", {
11293
11306
  check("connected_accounts_platform_check", sqlCheckIn(table.platform, PLATFORMS)),
11294
11307
  check("connected_accounts_status_check", sqlCheckIn(table.status, CONNECTED_ACCOUNT_STATUSES))
11295
11308
  ]);
11309
+ pgTable("account_connect_attempts", {
11310
+ id: text$1("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
11311
+ userId: text$1("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
11312
+ platform: text$1("platform", { enum: PLATFORMS }).notNull(),
11313
+ lane: text$1("lane", { enum: ACCOUNT_CONNECT_ATTEMPT_LANES }).notNull(),
11314
+ targetPaidSeats: integer("target_paid_seats").notNull(),
11315
+ status: text$1("status", { enum: ACCOUNT_CONNECT_ATTEMPT_STATUSES }).notNull().default("pending_billing"),
11316
+ connectedAccountId: text$1("connected_account_id").references(() => connectedAccounts.id, { onDelete: "set null" }),
11317
+ operationKey: text$1("operation_key").notNull(),
11318
+ billingPaymentURL: text$1("billing_payment_url"),
11319
+ billingRequiredAction: jsonb("billing_required_action").$type(),
11320
+ hostedAuthBindingId: text$1("hosted_auth_binding_id"),
11321
+ hostedAuthAccountId: text$1("hosted_auth_account_id"),
11322
+ hostedAuthBoundAt: timestamptz("hosted_auth_bound_at"),
11323
+ expiresAt: timestamptz("expires_at").notNull(),
11324
+ createdAt: timestamptz("created_at").notNull().defaultNow(),
11325
+ updatedAt: timestamptz("updated_at").notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
11326
+ }, (table) => [
11327
+ uniqueIndex("account_connect_attempts_operation_key_key").on(table.operationKey),
11328
+ uniqueIndex("account_connect_attempts_hosted_auth_binding_id_key").on(table.hostedAuthBindingId),
11329
+ uniqueIndex("account_connect_attempts_active_user_platform_key").on(table.userId, table.platform).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11330
+ index("account_connect_attempts_expiry_idx").on(table.expiresAt).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11331
+ check("account_connect_attempts_platform_check", sqlCheckIn(table.platform, PLATFORMS)),
11332
+ check("account_connect_attempts_lane_check", sqlCheckIn(table.lane, ACCOUNT_CONNECT_ATTEMPT_LANES)),
11333
+ check("account_connect_attempts_status_check", sqlCheckIn(table.status, ACCOUNT_CONNECT_ATTEMPT_STATUSES)),
11334
+ check("account_connect_attempts_target_paid_seats_check", sql`${table.targetPaidSeats} >= 0`)
11335
+ ]);
11296
11336
  pgTable("account_defaults", {
11297
11337
  userId: text$1("user_id").notNull(),
11298
11338
  platform: text$1("platform", { enum: PLATFORMS }).notNull(),
@@ -22674,11 +22714,6 @@ const LINKEDIN_CONNECTED_STATUS = "connected";
22674
22714
  var InvalidLinkedinLifecycleTarget = class extends h("InvalidLinkedinLifecycleTarget") {};
22675
22715
  var LinkedinLifecycleNoAccountMatch = class extends h("LinkedinLifecycleNoAccountMatch") {};
22676
22716
  var LinkedinLifecycleAmbiguousAccount = class extends h("LinkedinLifecycleAmbiguousAccount") {};
22677
- var LinkedinLifecycleSeatTimeout = class extends h("LinkedinLifecycleSeatTimeout") {
22678
- constructor() {
22679
- super({ message: "billing_seat_timed_out" });
22680
- }
22681
- };
22682
22717
  const accountUsername$1 = (account) => account.username.replace(/^@+/, "");
22683
22718
  const parseLinkedinReconnectTarget = (value) => {
22684
22719
  const trimmed = value.trim();
@@ -22739,41 +22774,16 @@ const resolveLinkedinDisconnectAccount = (accounts, identifier) => {
22739
22774
  const LINKEDIN_PLATFORM = "linkedin";
22740
22775
  const DEFAULT_POLL_INTERVAL_MS = 2e3;
22741
22776
  const DEFAULT_POLL_TIMEOUT_MS = 12e4;
22742
- const SEAT_POLL_TIMEOUT_MS$1 = 600 * 1e3;
22777
+ const CONNECT_POLL_TIMEOUT_MS = 600 * 1e3;
22743
22778
  const surfaceURL$1 = (deps, url, options = {}) => {
22744
22779
  const log = deps.log ?? console.error;
22745
22780
  if (options.log ?? true) log(`Open this URL: ${url}`);
22746
22781
  };
22747
- const pollForSeat$1 = async (deps) => {
22748
- const intervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
22749
- const sleep = deps.sleep ?? setTimeout$1;
22750
- const startedAt = Date.now();
22751
- while (Date.now() - startedAt < SEAT_POLL_TIMEOUT_MS$1) {
22752
- if ((await deps.client.billing.status()).canConnect) return;
22753
- await sleep(intervalMs);
22754
- }
22755
- throw new LinkedinLifecycleSeatTimeout();
22756
- };
22757
- const prepareAccountConnect$1 = async (deps) => {
22758
- if ((await deps.client.billing.status()).canConnect) return;
22759
- const status = await deps.client.billing.prepareAccountConnect();
22760
- if (status.canConnect) return;
22761
- if (status.paymentURL) surfaceURL$1(deps, status.paymentURL);
22762
- await pollForSeat$1(deps);
22763
- };
22764
22782
  const accountUsername = (account) => account.username.replace(/^@+/, "");
22765
22783
  const listLinkedinLifecycleAccounts = (deps, includeDisconnected = true) => deps.client.listAccounts({
22766
22784
  platform: LINKEDIN_PLATFORM,
22767
22785
  includeDisconnected
22768
22786
  });
22769
- /**
22770
- * Resolve the LinkedIn hosted-auth connect URL without opening a browser or
22771
- * polling. Lets a non-TTY caller advance a connect handshake one step at a time.
22772
- */
22773
- const createLinkedinConnectURL = async (deps) => (await deps.client.createHostedAuthURL({
22774
- platform: LINKEDIN_PLATFORM,
22775
- mode: "create"
22776
- })).url;
22777
22787
  const pollForAccount$1 = async (deps, predicate, errorMessage) => {
22778
22788
  const startedAt = Date.now();
22779
22789
  const timeoutMs = deps.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
@@ -22791,8 +22801,15 @@ const authURLFor$1 = async (deps, operation) => ({
22791
22801
  openingLogged: deps.handshakeAuthURL !== void 0
22792
22802
  });
22793
22803
  const reconnectAccountForIdentifier = async (deps, identifier) => {
22794
- const account = resolveLinkedinLifecycleAccount(await listLinkedinLifecycleAccounts(deps), identifier);
22795
- if (ae.isError(account)) throw account.error;
22804
+ const accounts = await listLinkedinLifecycleAccounts(deps);
22805
+ const account = resolveLinkedinLifecycleAccount(accounts.filter((candidate) => candidate.status !== "disconnected"), identifier);
22806
+ if (ae.isError(account)) {
22807
+ if (LinkedinLifecycleNoAccountMatch.is(account.error)) {
22808
+ const disconnected = resolveLinkedinLifecycleAccount(accounts.filter((candidate) => candidate.status === "disconnected"), identifier);
22809
+ if (ae.isOk(disconnected)) throw new Error(`LinkedIn account @${accountUsername(disconnected.value)} is disconnected and its seat was released. Run \`social account connect linkedin\` to connect it again.`);
22810
+ }
22811
+ throw account.error;
22812
+ }
22796
22813
  return account.value;
22797
22814
  };
22798
22815
  const resolveDisconnectTarget = async (deps, identifier) => {
@@ -22800,21 +22817,32 @@ const resolveDisconnectTarget = async (deps, identifier) => {
22800
22817
  if (ae.isError(account)) throw account.error;
22801
22818
  return account.value;
22802
22819
  };
22803
- const connectLinkedinAccount = async (deps) => {
22804
- await prepareAccountConnect$1(deps);
22805
- const before = await listLinkedinLifecycleAccounts(deps);
22806
- const existingProfileIds = new Set(before.map((account) => account.profileId));
22807
- const authURL = await authURLFor$1(deps, async () => (await deps.client.createHostedAuthURL({
22808
- platform: LINKEDIN_PLATFORM,
22809
- mode: "create"
22810
- })).url);
22811
- surfaceURL$1(deps, authURL.url, { log: !authURL.openingLogged });
22812
- const account = await pollForAccount$1(deps, (candidate) => candidate.status === "connected" && !existingProfileIds.has(candidate.profileId), "Timed out waiting for a new LinkedIn account connection.");
22813
- return {
22814
- platform: LINKEDIN_PLATFORM,
22815
- status: "connected",
22816
- account
22817
- };
22820
+ const connectLinkedinAccount = async (deps, attemptId) => {
22821
+ const intervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
22822
+ const sleep = deps.sleep ?? setTimeout$1;
22823
+ const startedAt = Date.now();
22824
+ let currentAttemptId = attemptId;
22825
+ const surfacedURLs = /* @__PURE__ */ new Set();
22826
+ while (Date.now() - startedAt < CONNECT_POLL_TIMEOUT_MS) {
22827
+ const state = await deps.client.connectStep({
22828
+ platform: LINKEDIN_PLATFORM,
22829
+ ...currentAttemptId ? { attemptId: currentAttemptId } : {}
22830
+ });
22831
+ currentAttemptId = state.attemptId;
22832
+ if (state.status === "connected") return {
22833
+ platform: LINKEDIN_PLATFORM,
22834
+ status: "connected",
22835
+ account: state.account
22836
+ };
22837
+ if (state.status === "expired" || state.status === "failed") throw new Error(state.code);
22838
+ const url = state.status === "pending_billing" ? state.paymentURL : state.status === "pending_approval" ? state.connectURL : null;
22839
+ if (url && !surfacedURLs.has(url)) {
22840
+ surfacedURLs.add(url);
22841
+ surfaceURL$1(deps, url);
22842
+ } else if (state.status === "pending_billing" && state.requiredAction) deps.log?.(state.requiredAction.reason);
22843
+ await sleep(intervalMs);
22844
+ }
22845
+ throw new Error("linkedin_connect_timed_out");
22818
22846
  };
22819
22847
  const reconnectLinkedinAccount = async (deps, identifier) => {
22820
22848
  const account = await reconnectAccountForIdentifier(deps, identifier);
@@ -22846,7 +22874,6 @@ const disconnectLinkedinAccount = async (deps, identifier) => {
22846
22874
  //#endregion
22847
22875
  //#region ../../packages/x/src/cli/lifecycle.ts
22848
22876
  const CONNECT_TIMEOUT_MS = 300 * 1e3;
22849
- const SEAT_POLL_TIMEOUT_MS = 600 * 1e3;
22850
22877
  const POLL_INTERVAL_MS = 2 * 1e3;
22851
22878
  var XConnectTimedOut = class extends h("XConnectTimedOut") {
22852
22879
  constructor(args) {
@@ -22857,14 +22884,14 @@ var XConnectTimedOut = class extends h("XConnectTimedOut") {
22857
22884
  this.name = "XConnectTimedOut";
22858
22885
  }
22859
22886
  };
22860
- var XBillingSeatTimedOut = class extends h("XBillingSeatTimedOut") {
22861
- constructor() {
22887
+ var XConnectStepFailed = class extends h("XConnectStepFailed") {
22888
+ constructor(args) {
22862
22889
  super({
22863
- operation: "prepareAccountConnect",
22864
- timeoutMS: SEAT_POLL_TIMEOUT_MS,
22865
- message: "billing_seat_timed_out"
22890
+ operation: "connect",
22891
+ ...args,
22892
+ message: args.code
22866
22893
  });
22867
- this.name = "XBillingSeatTimedOut";
22894
+ this.name = "XConnectStepFailed";
22868
22895
  }
22869
22896
  };
22870
22897
  var XAccountNotFound = class extends h("XAccountNotFound") {
@@ -22876,6 +22903,16 @@ var XAccountNotFound = class extends h("XAccountNotFound") {
22876
22903
  this.name = "XAccountNotFound";
22877
22904
  }
22878
22905
  };
22906
+ var XReconnectRequiresConnect = class extends h("XReconnectRequiresConnect") {
22907
+ constructor(account) {
22908
+ super({
22909
+ operation: "reconnect",
22910
+ account,
22911
+ message: `X account ${account} is disconnected and its seat was released. Run \`social account connect x\` to connect it again.`
22912
+ });
22913
+ this.name = "XReconnectRequiresConnect";
22914
+ }
22915
+ };
22879
22916
  var XInvalidSelector = class extends h("XInvalidSelector") {
22880
22917
  constructor(args) {
22881
22918
  super({
@@ -22895,11 +22932,11 @@ const throwXLifecycleError = (error) => {
22895
22932
  const defaultSleep = async (ms) => {
22896
22933
  await new Promise((resolve) => setTimeout(resolve, ms));
22897
22934
  };
22898
- const connectURLFor = async (deps, reconnectProfileId) => {
22935
+ const reconnectURLFor = async (deps, reconnectProfileId) => {
22899
22936
  return (await deps.client.accounts.reconnectURL({
22900
22937
  platform: "x",
22901
- mode: reconnectProfileId ? "reconnect" : "create",
22902
- ...reconnectProfileId ? { account: `profile_id:${reconnectProfileId}` } : {}
22938
+ mode: "reconnect",
22939
+ account: `profile_id:${reconnectProfileId}`
22903
22940
  })).url;
22904
22941
  };
22905
22942
  const surfaceURL = (deps, url, options = {}) => {
@@ -22927,25 +22964,6 @@ const authURLFor = async (deps, operation) => ({
22927
22964
  url: deps.handshakeAuthURL ? await deps.handshakeAuthURL(operation) : await operation(),
22928
22965
  openingLogged: deps.handshakeAuthURL !== void 0
22929
22966
  });
22930
- const pollForSeat = async (deps) => {
22931
- const sleep = deps.sleep ?? defaultSleep;
22932
- const now = deps.now ?? Date.now;
22933
- const startedAt = now();
22934
- while (now() - startedAt < SEAT_POLL_TIMEOUT_MS) {
22935
- if ((await deps.client.billing.status()).canConnect) return ae.ok();
22936
- await sleep(POLL_INTERVAL_MS);
22937
- }
22938
- return ae.err(new XBillingSeatTimedOut());
22939
- };
22940
- const prepareAccountConnect = async (deps) => {
22941
- if ((await deps.client.billing.status()).canConnect) return ae.ok();
22942
- const status = await deps.client.billing.prepareAccountConnect();
22943
- if (status.canConnect) return ae.ok();
22944
- if (status.paymentURL) surfaceURL(deps, status.paymentURL);
22945
- return pollForSeat(deps);
22946
- };
22947
- const accountKey = (account) => account.profileId;
22948
- const timestampMS = (value) => value instanceof Date ? value.getTime() : void 0;
22949
22967
  const normalizeIdentifier = (value) => value.trim().replace(/^@+/, "").toLowerCase();
22950
22968
  const accountSelectorFor$1 = (account) => account.username ? `@${account.username.replace(/^@+/, "")}` : `profile_id:${account.profileId}`;
22951
22969
  const parseXAccountSelector = (target, operation) => {
@@ -22976,34 +22994,35 @@ const listXLifecycleAccounts = async (deps, includeDisconnected) => ae.ok(await
22976
22994
  platform: "x",
22977
22995
  includeDisconnected
22978
22996
  }));
22979
- /**
22980
- * Resolve the X connect/reconnect URL without opening a browser or polling.
22981
- * Lets a non-TTY caller advance a connect handshake one step at a time.
22982
- */
22983
- const createXConnectURL = (deps, reconnectProfileId) => connectURLFor(deps, reconnectProfileId);
22984
- const connectXAccount = async (deps) => {
22985
- const beforeResult = await listXLifecycleAccounts(deps, true);
22986
- if (ae.isError(beforeResult)) return ae.err(beforeResult.error);
22987
- const before = beforeResult.value;
22988
- const connectedBefore = new Set(before.filter((account) => account.status === "connected").map(accountKey));
22989
- const lastSeenBefore = new Map(before.filter((account) => account.status === "connected").map((account) => [accountKey(account), timestampMS(account.lastSeenAt)]));
22990
- const prepared = await prepareAccountConnect(deps);
22991
- if (ae.isError(prepared)) return ae.err(prepared.error);
22992
- const authURL = await authURLFor(deps, () => connectURLFor(deps));
22993
- surfaceURL(deps, authURL.url, { log: !authURL.openingLogged });
22994
- const account = await pollForAccount(deps, "connect", (candidate) => {
22995
- if (candidate.status !== "connected") return false;
22996
- if (!connectedBefore.has(candidate.profileId)) return true;
22997
- const previousLastSeen = lastSeenBefore.get(candidate.profileId);
22998
- const currentLastSeen = timestampMS(candidate.lastSeenAt);
22999
- return previousLastSeen !== void 0 && currentLastSeen !== void 0 && currentLastSeen > previousLastSeen;
23000
- });
23001
- if (ae.isError(account)) return ae.err(account.error);
23002
- return ae.ok({
23003
- platform: "x",
23004
- status: "connected",
23005
- account: account.value
23006
- });
22997
+ const connectXAccount = async (deps, attemptId) => {
22998
+ const sleep = deps.sleep ?? defaultSleep;
22999
+ const now = deps.now ?? Date.now;
23000
+ const startedAt = now();
23001
+ let currentAttemptId = attemptId;
23002
+ const surfacedURLs = /* @__PURE__ */ new Set();
23003
+ while (now() - startedAt < CONNECT_TIMEOUT_MS) {
23004
+ const state = await deps.client.connectStep({
23005
+ platform: "x",
23006
+ ...currentAttemptId ? { attemptId: currentAttemptId } : {}
23007
+ });
23008
+ currentAttemptId = state.attemptId;
23009
+ if (state.status === "connected") return ae.ok({
23010
+ platform: "x",
23011
+ status: "connected",
23012
+ account: state.account
23013
+ });
23014
+ if (state.status === "expired" || state.status === "failed") return ae.err(new XConnectStepFailed(state));
23015
+ const url = state.status === "pending_billing" ? state.paymentURL : state.status === "pending_approval" ? state.connectURL : null;
23016
+ if (url && !surfacedURLs.has(url)) {
23017
+ surfacedURLs.add(url);
23018
+ surfaceURL(deps, url);
23019
+ } else if (state.status === "pending_billing" && state.requiredAction) deps.log?.(state.requiredAction.reason);
23020
+ await sleep(POLL_INTERVAL_MS);
23021
+ }
23022
+ return ae.err(new XConnectTimedOut({
23023
+ operation: "connect",
23024
+ timeoutMS: CONNECT_TIMEOUT_MS
23025
+ }));
23007
23026
  };
23008
23027
  const reconnectXAccount = async (deps, args) => {
23009
23028
  const selector = parseXAccountSelector(args.account, "reconnect");
@@ -23011,12 +23030,15 @@ const reconnectXAccount = async (deps, args) => {
23011
23030
  const accountsResult = await listXLifecycleAccounts(deps, true);
23012
23031
  if (ae.isError(accountsResult)) return ae.err(accountsResult.error);
23013
23032
  const accounts = accountsResult.value;
23014
- const existing = findXLifecycleAccount(accounts, selector.value);
23015
- if (!existing) return ae.err(new XAccountNotFound({
23016
- operation: "reconnect",
23017
- account: args.account
23018
- }));
23019
- const authURL = await authURLFor(deps, () => connectURLFor(deps, existing.profileId));
23033
+ const existing = findXLifecycleAccount(accounts.filter((account) => account.status !== "disconnected"), selector.value);
23034
+ if (!existing) {
23035
+ if (findXLifecycleAccount(accounts.filter((account) => account.status === "disconnected"), selector.value)) return ae.err(new XReconnectRequiresConnect(args.account));
23036
+ return ae.err(new XAccountNotFound({
23037
+ operation: "reconnect",
23038
+ account: args.account
23039
+ }));
23040
+ }
23041
+ const authURL = await authURLFor(deps, () => reconnectURLFor(deps, existing.profileId));
23020
23042
  surfaceURL(deps, authURL.url, { log: !authURL.openingLogged });
23021
23043
  const account = await pollForAccount(deps, "reconnect", (candidate) => candidate.profileId === existing.profileId && candidate.status === "connected");
23022
23044
  if (ae.isError(account)) return ae.err(account.error);
@@ -24448,7 +24470,7 @@ function createEnv(opts) {
24448
24470
  }
24449
24471
  //#endregion
24450
24472
  //#region package.json
24451
- var version$1 = "0.18.4";
24473
+ var version$1 = "0.19.0";
24452
24474
  //#endregion
24453
24475
  //#region src/lib/env.ts
24454
24476
  const URLWithTrailingSlash = url().transform(ensureTrailingSlash);
@@ -25575,23 +25597,39 @@ const configCommand = defineCommand({
25575
25597
  })
25576
25598
  }
25577
25599
  });
25578
- const BillingOutput = object({
25579
- seats: object({
25580
- total: number().int().nonnegative(),
25581
- used: number().int().nonnegative(),
25582
- available: number().int().nonnegative()
25583
- }),
25584
- subscription: object({
25585
- active: boolean$1(),
25586
- quantity: number().int().nonnegative(),
25587
- currentPeriodEnd: string().nullable()
25588
- }).nullable(),
25589
- usage: object({
25590
- calls: number().int().nonnegative(),
25591
- credit: number().nonnegative(),
25592
- cost: number().nonnegative()
25593
- })
25600
+ //#endregion
25601
+ //#region src/billing/index.ts
25602
+ const SeatsOutput = object({
25603
+ total: number().int().nonnegative(),
25604
+ used: number().int().nonnegative(),
25605
+ available: number().int().nonnegative()
25594
25606
  });
25607
+ const SubscriptionOutput = object({
25608
+ active: boolean$1(),
25609
+ quantity: number().int().nonnegative(),
25610
+ currentPeriodEnd: string().nullable(),
25611
+ canceling: boolean$1(),
25612
+ canceledAt: string().nullable()
25613
+ }).nullable();
25614
+ const UsageSummaryOutput$1 = object({
25615
+ calls: number().int().nonnegative(),
25616
+ credit: number().nonnegative(),
25617
+ cost: number().nonnegative()
25618
+ });
25619
+ const ProviderBillingOutput = object({
25620
+ platform: _enum(["linkedin", "x"]),
25621
+ plan: object({
25622
+ id: string(),
25623
+ name: string()
25624
+ }),
25625
+ seats: SeatsOutput,
25626
+ canConnect: boolean$1(),
25627
+ subscription: SubscriptionOutput
25628
+ });
25629
+ const BillingOutput = object({ providers: object({
25630
+ linkedin: ProviderBillingOutput,
25631
+ x: ProviderBillingOutput.extend({ usage: UsageSummaryOutput$1 })
25632
+ }) });
25595
25633
  const BillingPortalOutput = object({
25596
25634
  url: string(),
25597
25635
  opened: boolean$1()
@@ -25637,11 +25675,13 @@ const createBillingCommand = (deps = {}) => {
25637
25675
  run: async () => {
25638
25676
  const client = clientFrom(deps);
25639
25677
  const [status, usage] = await Promise.all([client.billing.status(), client.usage.summary({})]);
25640
- await writeOutput$2(deps, {
25641
- seats: status.seats,
25642
- subscription: status.subscription,
25643
- usage: usageSummaryForOutput(usage)
25644
- });
25678
+ await writeOutput$2(deps, { providers: {
25679
+ linkedin: status.providers.linkedin,
25680
+ x: {
25681
+ ...status.providers.x,
25682
+ usage: usageSummaryForOutput(usage)
25683
+ }
25684
+ } });
25645
25685
  }
25646
25686
  });
25647
25687
  };
@@ -33067,13 +33107,9 @@ const errorOutput = (error) => ({
33067
33107
  message: error instanceof Error ? error.message : String(error)
33068
33108
  });
33069
33109
  const nextCommands = ["social account connect linkedin", "social account connect x"];
33070
- const availableConnectCommands = (capabilities) => nextCommands.filter((command) => {
33071
- const platform = command.endsWith(" linkedin") ? "linkedin" : "x";
33072
- return capabilities.some((capability) => capability.startsWith(`${platform}:`));
33073
- });
33074
33110
  const setupOutputFor = (setup) => ({
33075
33111
  ...setup,
33076
- nextCommands: setup.status === "pending_billing" ? ["social account setup"] : availableConnectCommands(setup.capabilities)
33112
+ nextCommands: setup.status === "pending_billing" ? ["social account setup"] : nextCommands
33077
33113
  });
33078
33114
  const deviceExpiredMessage = "Sign-in expired before approval. Run `social account setup` again to restart.";
33079
33115
  const scopeUpgradeRequiresReauthorization = "Existing CLI session is read-only. Run `social account logout`, then `social account setup` to approve a new write-capable session.";
@@ -33160,7 +33196,7 @@ const createLoginCommand = (deps = {}) => {
33160
33196
  return defineCommand({
33161
33197
  meta: commandMeta({
33162
33198
  name: "setup",
33163
- description: "Authenticate Social and ensure billing is ready",
33199
+ description: "Authenticate Social and add a reusable payment method before connecting accounts",
33164
33200
  contract: localCLIContract({
33165
33201
  auth: {
33166
33202
  interactive: true,
@@ -33235,11 +33271,7 @@ const createLoginCommand = (deps = {}) => {
33235
33271
  }
33236
33272
  if (output.status === "ready") {
33237
33273
  analytics.identifyUser(output.user.id);
33238
- analytics.capture("login_completed", {
33239
- scope: output.scope,
33240
- seats_total: output.seats.total,
33241
- seats_available: output.seats.available
33242
- });
33274
+ analytics.capture("login_completed", { scope: output.scope });
33243
33275
  } else if (output.status === "expired") analytics.capture("login_failed", { code: "expired" });
33244
33276
  else if (output.status === "needs_input") analytics.capture("login_failed", {
33245
33277
  code: "needs_input",
@@ -33592,12 +33624,18 @@ const AccountDefaultSetInput = AccountDefaultGetInput.extend({ account: string()
33592
33624
  const AccountConnectStateOutput = discriminatedUnion("status", [
33593
33625
  object({
33594
33626
  status: literal("connected"),
33627
+ attemptId: uuid$1(),
33595
33628
  platform: _enum(["linkedin", "x"]),
33596
33629
  account: LifecycleAccountOutput
33597
33630
  }),
33598
33631
  object({
33599
33632
  status: literal("pending_billing"),
33633
+ attemptId: uuid$1(),
33600
33634
  platform: _enum(["linkedin", "x"]),
33635
+ plan: object({
33636
+ id: string(),
33637
+ name: string()
33638
+ }),
33601
33639
  paymentURL: string().nullable(),
33602
33640
  requiredAction: object({
33603
33641
  code: string(),
@@ -33611,8 +33649,17 @@ const AccountConnectStateOutput = discriminatedUnion("status", [
33611
33649
  }),
33612
33650
  object({
33613
33651
  status: literal("pending_approval"),
33652
+ attemptId: uuid$1(),
33653
+ platform: _enum(["linkedin", "x"]),
33654
+ connectURL: string().nullable(),
33655
+ expiresAt: string()
33656
+ }),
33657
+ object({
33658
+ status: _enum(["expired", "failed"]),
33659
+ attemptId: uuid$1(),
33614
33660
  platform: _enum(["linkedin", "x"]),
33615
- connectURL: string()
33661
+ code: string(),
33662
+ retryable: boolean$1()
33616
33663
  })
33617
33664
  ]);
33618
33665
  const AccountConnectOutput = union([string(), AccountConnectStateOutput]);
@@ -33702,7 +33749,15 @@ const platformLabel = (platform) => platform === "x" ? "X" : "LinkedIn";
33702
33749
  const lifecycleConnectContract = writeCLIContract({
33703
33750
  outputSchema: AccountConnectOutput,
33704
33751
  responseShaping: { supported: false },
33705
- idempotency: "non-idempotent"
33752
+ idempotency: {
33753
+ idempotent: false,
33754
+ retrySafeWith: "attemptId"
33755
+ },
33756
+ idField: "attemptId",
33757
+ hazards: [{
33758
+ code: "account_connect_billing",
33759
+ message: "The first call can start provider billing; pass the returned attemptId when polling so retries cannot start another charge."
33760
+ }]
33706
33761
  });
33707
33762
  const usernameLabelFor = (account) => account.username.startsWith("@") ? account.username : `@${account.username}`;
33708
33763
  const authHandshakeMessage = "Handshaking auth...";
@@ -33733,43 +33788,13 @@ const runConnectOutput = async (deps, connect) => {
33733
33788
  writeText(deps, `${usernameLabelFor(result.account)} connected!`);
33734
33789
  };
33735
33790
  const isInteractiveConnect = (deps) => deps.isInteractiveTerminal?.() === true;
33736
- /**
33737
- * One non-blocking step of a connect handshake for a non-TTY caller. Returns the
33738
- * connected account if one is already linked, otherwise emits the connect URL and
33739
- * reports `pending_approval`. A repeated call re-checks and advances — the skill
33740
- * polls this the same way it polls `social account setup`.
33741
- */
33742
- const runConnectStep = async (deps, platform, listConnected, connectURL) => {
33743
- const connected = (await listConnected()).find((account) => account.status === "connected");
33744
- if (connected) {
33745
- await writeOutput(deps, {
33746
- status: "connected",
33747
- platform,
33748
- account: connected
33749
- });
33750
- return;
33751
- }
33752
- const billing = await deps.client.billing.prepareAccountConnect();
33753
- if (!billing.canConnect) {
33754
- if (!billing.seats) throw new Error("billing_prepare_missing_seats");
33755
- if (billing.paymentURL) writeText(deps, `Open this URL: ${billing.paymentURL}`);
33756
- else if (billing.requiredAction) writeText(deps, billing.requiredAction.reason);
33757
- await writeOutput(deps, {
33758
- status: "pending_billing",
33759
- platform,
33760
- paymentURL: billing.paymentURL ?? null,
33761
- requiredAction: billing.requiredAction ?? null,
33762
- seats: billing.seats
33763
- });
33764
- return;
33765
- }
33766
- const url = await connectURL();
33767
- writeText(deps, `Open this URL: ${url}`);
33768
- await writeOutput(deps, {
33769
- status: "pending_approval",
33791
+ /** One retry-safe connect step for a non-TTY caller; the JSON carries its next attempt ID. */
33792
+ const runConnectStep = async (deps, platform, attemptId) => {
33793
+ const state = await deps.client.connectStep({
33770
33794
  platform,
33771
- connectURL: url
33795
+ ...attemptId ? { attemptId } : {}
33772
33796
  });
33797
+ await writeOutput(deps, state);
33773
33798
  };
33774
33799
  const createConnectPlatformCommand = (platform, run) => defineCommand({
33775
33800
  meta: commandMeta({
@@ -33779,8 +33804,12 @@ const createConnectPlatformCommand = (platform, run) => defineCommand({
33779
33804
  contract: lifecycleConnectContract,
33780
33805
  mutates: true
33781
33806
  }),
33782
- run: async () => {
33783
- await run();
33807
+ args: { attempt: {
33808
+ type: "string",
33809
+ description: "Resume the exact connect attempt returned by a previous call."
33810
+ } },
33811
+ run: async ({ args }) => {
33812
+ await run({ attempt: typeof args.attempt === "string" ? args.attempt : void 0 });
33784
33813
  }
33785
33814
  });
33786
33815
  const createAccountPlatformCommand = (platform, description, run, options = {}) => defineCommand({
@@ -33866,27 +33895,23 @@ const createAccountCommand = (deps, accountSetupCommand = setupCommand) => {
33866
33895
  description: "Connect a LinkedIn or X account."
33867
33896
  },
33868
33897
  subCommands: {
33869
- linkedin: createConnectPlatformCommand("linkedin", async () => {
33898
+ linkedin: createConnectPlatformCommand("linkedin", async ({ attempt }) => {
33870
33899
  if (isInteractiveConnect(deps)) {
33871
- await runConnectOutput(deps, connectLinkedinAccount);
33900
+ await runConnectOutput(deps, (connectDeps) => connectLinkedinAccount(connectDeps, attempt));
33872
33901
  return;
33873
33902
  }
33874
- await runConnectStep(deps, "linkedin", () => listLinkedinLifecycleAccounts(deps), () => createLinkedinConnectURL(deps));
33903
+ await runConnectStep(deps, "linkedin", attempt);
33875
33904
  }),
33876
- x: createConnectPlatformCommand("x", async () => {
33905
+ x: createConnectPlatformCommand("x", async ({ attempt }) => {
33877
33906
  if (isInteractiveConnect(deps)) {
33878
33907
  await runConnectOutput(deps, async (connectDeps) => {
33879
- const result = await connectXAccount(connectDeps);
33908
+ const result = await connectXAccount(connectDeps, attempt);
33880
33909
  if (ae.isError(result)) throwXLifecycleError(result.error);
33881
33910
  return result.value;
33882
33911
  });
33883
33912
  return;
33884
33913
  }
33885
- await runConnectStep(deps, "x", async () => {
33886
- const result = await listXLifecycleAccounts(deps, true);
33887
- if (ae.isError(result)) throwXLifecycleError(result.error);
33888
- return result.value;
33889
- }, () => createXConnectURL(deps));
33914
+ await runConnectStep(deps, "x", attempt);
33890
33915
  })
33891
33916
  }
33892
33917
  });
@@ -39237,25 +39262,19 @@ const createCLIDeps = () => {
39237
39262
  client: {
39238
39263
  listAccounts: client.accounts.list,
39239
39264
  createHostedAuthURL: client.accounts.reconnectURL,
39265
+ connectStep: client.accounts.connectStep,
39240
39266
  disconnectAccount: client.accounts.disconnect,
39241
39267
  accounts: {
39242
39268
  list: client.accounts.list,
39243
39269
  default: client.accounts.default,
39270
+ connectStep: client.accounts.connectStep,
39244
39271
  reconnectURL: client.accounts.reconnectURL,
39245
39272
  disconnect: client.accounts.disconnect
39246
39273
  },
39247
39274
  billing: {
39248
- status: async () => {
39249
- return await client.billing.status();
39250
- },
39251
- prepareAccountConnect: async () => {
39252
- const status = await client.billing.prepareAccountConnect();
39253
- return {
39254
- canConnect: status.canConnect,
39255
- paymentURL: status.paymentURL,
39256
- requiredAction: status.requiredAction,
39257
- seats: status.seats
39258
- };
39275
+ status: client.billing.status,
39276
+ providerStatus: async ({ platform }) => {
39277
+ return (await client.billing.status()).providers[platform];
39259
39278
  },
39260
39279
  portalURL: client.billing.portalURL
39261
39280
  },