linkedin-relay-mcp 3.14.0 → 3.16.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/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // src/cli.ts
3
- import { readFileSync as readFileSync3 } from "fs";
3
+ import { readFileSync as readFileSync4 } from "fs";
4
4
 
5
5
  // src/args.ts
6
6
  function parseArgs(argv) {
@@ -630,7 +630,7 @@ function shapePost(node, index) {
630
630
  const actor = node.actor;
631
631
  const urn = postUrn(node);
632
632
  const social = deref(node, "*socialDetail", index);
633
- const counts = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
633
+ const counts2 = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
634
634
  const meta = node.metadata;
635
635
  return defined({
636
636
  type: typeOf(node),
@@ -643,9 +643,9 @@ function shapePost(node, index) {
643
643
  // `text()` already trims; LinkedIn pads these with trailing spaces.
644
644
  posted: text(actor?.subDescription),
645
645
  text: text(node.commentary),
646
- likes: numberOf(counts?.numLikes),
647
- comments: numberOf(counts?.numComments),
648
- shares: numberOf(counts?.numShares ?? social?.totalShares),
646
+ likes: numberOf(counts2?.numLikes),
647
+ comments: numberOf(counts2?.numComments),
648
+ shares: numberOf(counts2?.numShares ?? social?.totalShares),
649
649
  url: urn === void 0 ? void 0 : `https://www.linkedin.com/feed/update/${urn}/`
650
650
  });
651
651
  }
@@ -701,7 +701,7 @@ function shapeMember(node) {
701
701
  function shapeComment(node, index) {
702
702
  const commenter = node.commenter;
703
703
  const social = deref(node, "*socialDetail", index);
704
- const counts = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
704
+ const counts2 = social === void 0 ? void 0 : deref(social, "*totalSocialActivityCounts", index);
705
705
  return defined({
706
706
  type: typeOf(node),
707
707
  urn: typeof node.urn === "string" ? node.urn : void 0,
@@ -709,7 +709,7 @@ function shapeComment(node, index) {
709
709
  headline: text(commenter?.subtitle),
710
710
  authorUrl: cleanUrl(commenter?.navigationUrl),
711
711
  text: text(node.comment) ?? text(node.commentary),
712
- likes: numberOf(counts?.numLikes),
712
+ likes: numberOf(counts2?.numLikes),
713
713
  postedAt: typeof node.createdAt === "number" ? new Date(node.createdAt).toISOString() : void 0,
714
714
  edited: node.edited === true ? true : void 0,
715
715
  url: cleanUrl(node.permalink)
@@ -776,8 +776,8 @@ function compactRows(rows) {
776
776
  const v = row[key];
777
777
  if (typeof v === "string" && v !== "") parts.push(v);
778
778
  }
779
- const counts = ["likes", "comments"].map((k) => typeof row[k] === "number" ? `${row[k]} ${k}` : void 0).filter((v) => v !== void 0);
780
- parts.push(...counts);
779
+ const counts2 = ["likes", "comments"].map((k) => typeof row[k] === "number" ? `${row[k]} ${k}` : void 0).filter((v) => v !== void 0);
780
+ parts.push(...counts2);
781
781
  if (parts.length === 0) {
782
782
  const urn = row.urn ?? row.type;
783
783
  if (typeof urn === "string") parts.push(urn);
@@ -1401,6 +1401,33 @@ var CONTRACTS = {
1401
1401
  // "AI job search" that drops filters it does not support; these are the
1402
1402
  // classic Voyager resources still behind /jobs/search/, which take them all.
1403
1403
  // See engine/jobs.ts.
1404
+ // The owner's messages, captured 2026-10-14; see engine/messaging.ts. Reads
1405
+ // only: the page's own "seen", read and delivery calls are not made.
1406
+ messengerConversations: {
1407
+ name: "messengerConversations",
1408
+ transport: "voyager-graphql",
1409
+ path: `${VOYAGER}/voyagerMessagingGraphQL/graphql`,
1410
+ queryId: "messengerConversations.9501074288a12f3ae9e3c7ea243bccbf",
1411
+ provenance: "verified",
1412
+ capturedAt: "2026-10-14"
1413
+ },
1414
+ messengerMessages: {
1415
+ name: "messengerMessages",
1416
+ transport: "voyager-graphql",
1417
+ path: `${VOYAGER}/voyagerMessagingGraphQL/graphql`,
1418
+ queryId: "messengerMessages.5846eeb71c981f11e0134cb6626cc314",
1419
+ provenance: "verified",
1420
+ capturedAt: "2026-10-14"
1421
+ },
1422
+ // Connection invitations the owner has sent, captured 2026-10-14; see
1423
+ // engine/network.ts.
1424
+ sentInvitations: {
1425
+ name: "sentInvitations",
1426
+ transport: "voyager-restli",
1427
+ path: `${VOYAGER}/relationships/sentInvitationViewsV2`,
1428
+ provenance: "verified",
1429
+ capturedAt: "2026-10-14"
1430
+ },
1404
1431
  jobCards: {
1405
1432
  name: "jobCards",
1406
1433
  transport: "voyager-restli",
@@ -1674,10 +1701,10 @@ function createEngine(session, deps, quiet = false) {
1674
1701
  const client = createLiveClient(session, deps, quiet);
1675
1702
  return {
1676
1703
  async whoami() {
1677
- const contract2 = contractFor("me");
1678
- if (contract2 === void 0) return missingContract("me");
1704
+ const contract3 = contractFor("me");
1705
+ if (contract3 === void 0) return missingContract("me");
1679
1706
  const res = await client.request({
1680
- url: contract2.path,
1707
+ url: contract3.path,
1681
1708
  spendClass: "profile",
1682
1709
  operation: "me"
1683
1710
  });
@@ -1685,10 +1712,10 @@ function createEngine(session, deps, quiet = false) {
1685
1712
  return { ok: true, value: parseSingle(res.json) };
1686
1713
  },
1687
1714
  async profile(memberId) {
1688
- const contract2 = contractFor("profile");
1689
- if (contract2 === void 0) return missingContract("profile");
1715
+ const contract3 = contractFor("profile");
1716
+ if (contract3 === void 0) return missingContract("profile");
1690
1717
  const variables = encodeVariables({ memberIdentity: memberId });
1691
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1718
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1692
1719
  const res = await client.request({ url, spendClass: "profile", operation: "profile" });
1693
1720
  if (!res.ok) return res;
1694
1721
  const envelope = res.json;
@@ -1700,9 +1727,9 @@ function createEngine(session, deps, quiet = false) {
1700
1727
  return { ok: true, value: { profile, index } };
1701
1728
  },
1702
1729
  async feed(limit) {
1703
- const contract2 = contractFor("feed");
1704
- if (contract2 === void 0) return missingContract("feed");
1705
- const url = `${contract2.path}?q=chronFeed&count=${limit}&start=0`;
1730
+ const contract3 = contractFor("feed");
1731
+ if (contract3 === void 0) return missingContract("feed");
1732
+ const url = `${contract3.path}?q=chronFeed&count=${limit}&start=0`;
1706
1733
  const res = await client.request({ url, spendClass: "page", operation: "feed" });
1707
1734
  if (!res.ok) return res;
1708
1735
  const envelope = res.json;
@@ -1711,21 +1738,21 @@ function createEngine(session, deps, quiet = false) {
1711
1738
  value: {
1712
1739
  parsed: parseCollection(res.json, {
1713
1740
  operation: "feed",
1714
- contractCapturedAt: contract2.capturedAt
1741
+ contractCapturedAt: contract3.capturedAt
1715
1742
  }),
1716
1743
  index: indexIncluded(envelope.included)
1717
1744
  }
1718
1745
  };
1719
1746
  },
1720
1747
  async myPosts(profileUrn, limit) {
1721
- const contract2 = contractFor("myPosts");
1722
- if (contract2 === void 0) return missingContract("myPosts");
1748
+ const contract3 = contractFor("myPosts");
1749
+ if (contract3 === void 0) return missingContract("myPosts");
1723
1750
  const variables = encodeVariables({
1724
1751
  count: Math.min(limit, 100),
1725
1752
  start: 0,
1726
1753
  profileUrn: canonicalUrn(profileUrn)
1727
1754
  });
1728
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1755
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1729
1756
  const res = await client.request({ url, spendClass: "page", operation: "myPosts" });
1730
1757
  if (!res.ok) return res;
1731
1758
  const envelope = res.json;
@@ -1734,7 +1761,7 @@ function createEngine(session, deps, quiet = false) {
1734
1761
  value: {
1735
1762
  parsed: parseCollection(res.json, {
1736
1763
  operation: "myPosts",
1737
- contractCapturedAt: contract2.capturedAt,
1764
+ contractCapturedAt: contract3.capturedAt,
1738
1765
  truncated: true
1739
1766
  }),
1740
1767
  index: indexIncluded(envelope.included)
@@ -1747,8 +1774,8 @@ function createEngine(session, deps, quiet = false) {
1747
1774
  * snapshot and diffs, rather than pretending a watermark exists.
1748
1775
  */
1749
1776
  async connections(limit) {
1750
- const contract2 = contractFor("search");
1751
- if (contract2 === void 0) return missingContract("search");
1777
+ const contract3 = contractFor("search");
1778
+ if (contract3 === void 0) return missingContract("search");
1752
1779
  const variables = encodeVariables({
1753
1780
  start: 0,
1754
1781
  origin: "FACETED_SEARCH",
@@ -1761,12 +1788,12 @@ function createEngine(session, deps, quiet = false) {
1761
1788
  includeFiltersInResponse: false
1762
1789
  }
1763
1790
  });
1764
- const url = `${contract2.path}?variables=${variables}&queryId=${contract2.queryId}`;
1791
+ const url = `${contract3.path}?variables=${variables}&queryId=${contract3.queryId}`;
1765
1792
  const res = await client.request({ url, spendClass: "search", operation: "connections" });
1766
1793
  if (!res.ok) return res;
1767
1794
  const parsed = parseCollection(res.json, {
1768
1795
  operation: "connections",
1769
- contractCapturedAt: contract2.capturedAt,
1796
+ contractCapturedAt: contract3.capturedAt,
1770
1797
  claimedCount: totalResultCount(res.json),
1771
1798
  truncated: true
1772
1799
  });
@@ -1776,8 +1803,8 @@ function createEngine(session, deps, quiet = false) {
1776
1803
  return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1777
1804
  },
1778
1805
  async post(postUrn2, limit) {
1779
- const contract2 = contractFor("comments");
1780
- if (contract2 === void 0) return missingContract("comments");
1806
+ const contract3 = contractFor("comments");
1807
+ if (contract3 === void 0) return missingContract("comments");
1781
1808
  const variables = encodeVariables({
1782
1809
  count: Math.min(limit, 100),
1783
1810
  numReplies: 1,
@@ -1785,12 +1812,12 @@ function createEngine(session, deps, quiet = false) {
1785
1812
  sortOrder: "RELEVANCE",
1786
1813
  start: 0
1787
1814
  });
1788
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1815
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1789
1816
  const res = await client.request({ url, spendClass: "page", operation: "comments" });
1790
1817
  if (!res.ok) return res;
1791
1818
  const parsed = parseCollection(res.json, {
1792
1819
  operation: "comments",
1793
- contractCapturedAt: contract2.capturedAt,
1820
+ contractCapturedAt: contract3.capturedAt,
1794
1821
  // A page of many; we follow no cursor yet, so never claim exhaustion.
1795
1822
  truncated: true
1796
1823
  });
@@ -1798,27 +1825,27 @@ function createEngine(session, deps, quiet = false) {
1798
1825
  return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1799
1826
  },
1800
1827
  async reactions(postUrn2, limit) {
1801
- const contract2 = contractFor("reactions");
1802
- if (contract2 === void 0) return missingContract("reactions");
1828
+ const contract3 = contractFor("reactions");
1829
+ if (contract3 === void 0) return missingContract("reactions");
1803
1830
  const variables = encodeVariables({
1804
1831
  count: Math.min(limit, 100),
1805
1832
  start: 0,
1806
1833
  threadUrn: postUrn2
1807
1834
  });
1808
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1835
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1809
1836
  const res = await client.request({ url, spendClass: "page", operation: "reactions" });
1810
1837
  if (!res.ok) return res;
1811
1838
  const parsed = parseCollection(res.json, {
1812
1839
  operation: "reactions",
1813
- contractCapturedAt: contract2.capturedAt,
1840
+ contractCapturedAt: contract3.capturedAt,
1814
1841
  truncated: true
1815
1842
  });
1816
1843
  const envelope = res.json;
1817
1844
  return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1818
1845
  },
1819
1846
  async search(kind, query, limit) {
1820
- const contract2 = contractFor("search");
1821
- if (contract2 === void 0) return missingContract("search");
1847
+ const contract3 = contractFor("search");
1848
+ if (contract3 === void 0) return missingContract("search");
1822
1849
  const variables = encodeVariables({
1823
1850
  start: 0,
1824
1851
  origin: "GLOBAL_SEARCH_HEADER",
@@ -1829,12 +1856,12 @@ function createEngine(session, deps, quiet = false) {
1829
1856
  includeFiltersInResponse: false
1830
1857
  }
1831
1858
  });
1832
- const url = `${contract2.path}?variables=${variables}&queryId=${contract2.queryId}`;
1859
+ const url = `${contract3.path}?variables=${variables}&queryId=${contract3.queryId}`;
1833
1860
  const res = await client.request({ url, spendClass: "search", operation: "search" });
1834
1861
  if (!res.ok) return res;
1835
1862
  const parsed = parseCollection(res.json, {
1836
1863
  operation: "search",
1837
- contractCapturedAt: contract2.capturedAt,
1864
+ contractCapturedAt: contract3.capturedAt,
1838
1865
  claimedCount: totalResultCount(res.json),
1839
1866
  truncated: true
1840
1867
  // one page of many; we never claim exhaustion
@@ -2557,14 +2584,14 @@ function pollUrnOf(json) {
2557
2584
  return JSON.stringify(json ?? null).match(/urn:li:fsd_pollSummary:\d+/)?.[0] ?? null;
2558
2585
  }
2559
2586
  async function createPoll(poll, client) {
2560
- const contract2 = contractFor("createPoll");
2561
- if (contract2?.queryId === void 0) {
2587
+ const contract3 = contractFor("createPoll");
2588
+ if (contract3?.queryId === void 0) {
2562
2589
  return { ok: false, code: "NOT_IMPLEMENTED", message: "no verified poll contract" };
2563
2590
  }
2564
2591
  const result = await client.request({
2565
- url: `${contract2.path}?action=execute&queryId=${contract2.queryId}`,
2592
+ url: `${contract3.path}?action=execute&queryId=${contract3.queryId}`,
2566
2593
  method: "POST",
2567
- body: { variables: { poll }, queryId: contract2.queryId, includeWebMetadata: true },
2594
+ body: { variables: { poll }, queryId: contract3.queryId, includeWebMetadata: true },
2568
2595
  spendClass: "write",
2569
2596
  operation: "create-poll"
2570
2597
  });
@@ -2597,8 +2624,8 @@ function firstUrl(text5) {
2597
2624
  return url;
2598
2625
  }
2599
2626
  function urlPreviewUrl(url) {
2600
- const contract2 = contractFor("urlPreview");
2601
- return `${contract2?.path}?includeWebMetadata=true&variables=(url:${encodeURIComponent(url)})&queryId=${contract2?.queryId}`;
2627
+ const contract3 = contractFor("urlPreview");
2628
+ return `${contract3?.path}?includeWebMetadata=true&variables=(url:${encodeURIComponent(url)})&queryId=${contract3?.queryId}`;
2602
2629
  }
2603
2630
  function parseUrlPreview(json) {
2604
2631
  const error = gqlError(json);
@@ -3880,288 +3907,181 @@ function runDoctor(now, offline) {
3880
3907
  });
3881
3908
  }
3882
3909
 
3883
- // src/commands/oauth.ts
3884
- import { spawn } from "child_process";
3885
- import { createServer } from "http";
3886
- import { createInterface as createInterface2 } from "readline/promises";
3910
+ // src/commands/messaging.ts
3911
+ import { randomUUID } from "crypto";
3912
+ import { readFileSync as readFileSync2 } from "fs";
3887
3913
 
3888
- // src/engine/oauth.ts
3889
- var AUTHORIZE = "https://www.linkedin.com/oauth/v2/authorization";
3890
- var TOKEN = "https://www.linkedin.com/oauth/v2/accessToken";
3891
- var USERINFO = "https://api.linkedin.com/v2/userinfo";
3892
- var CALLBACK_PORT = 53682;
3893
- var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
3894
- var SCOPES = ["openid", "profile", "w_member_social"];
3895
- function authorizationUrl(clientId, state) {
3896
- const params = new URLSearchParams({
3897
- response_type: "code",
3898
- client_id: clientId,
3899
- redirect_uri: REDIRECT_URI,
3900
- state,
3901
- scope: SCOPES.join(" ")
3902
- });
3903
- return `${AUTHORIZE}?${params.toString()}`;
3904
- }
3905
- async function exchange(code, config, deps) {
3906
- const body = new URLSearchParams({
3907
- grant_type: "authorization_code",
3908
- code,
3909
- redirect_uri: REDIRECT_URI,
3910
- client_id: config.clientId,
3911
- client_secret: config.clientSecret
3912
- });
3913
- let res;
3914
- try {
3915
- res = await deps.fetch(TOKEN, {
3916
- method: "POST",
3917
- headers: { "content-type": "application/x-www-form-urlencoded" },
3918
- body: body.toString()
3919
- });
3920
- } catch (e) {
3921
- return { ok: false, message: `could not reach LinkedIn: ${e.message}` };
3922
- }
3923
- const text5 = await res.text();
3924
- if (res.status !== 200) {
3925
- return {
3926
- ok: false,
3927
- message: `LinkedIn rejected the code exchange (${res.status})`,
3928
- // The most common causes, in the order they actually happen.
3929
- hint: `Check that the app has BOTH products added, and that its Auth tab lists exactly ${REDIRECT_URI} as an authorized redirect URL. Response: ${text5.slice(0, 200)}`
3930
- };
3931
- }
3932
- let parsed;
3933
- try {
3934
- parsed = JSON.parse(text5);
3935
- } catch {
3936
- return { ok: false, message: "token response was not JSON" };
3937
- }
3938
- const accessToken = parsed.access_token;
3939
- const expiresIn = parsed.expires_in;
3940
- if (typeof accessToken !== "string" || accessToken === "") {
3941
- return { ok: false, message: "token response carried no access_token" };
3942
- }
3943
- const lifetimeMs = typeof expiresIn === "number" ? expiresIn * 1e3 : 60 * 864e5;
3944
- return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };
3945
- }
3946
- async function fetchMemberUrn(accessToken, deps) {
3947
- let res;
3948
- try {
3949
- res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });
3950
- } catch (e) {
3951
- return { ok: false, message: `could not reach userinfo: ${e.message}` };
3952
- }
3953
- if (res.status !== 200) {
3954
- return {
3955
- ok: false,
3956
- message: `userinfo returned ${res.status} \u2014 the 'openid'/'profile' scopes may not be granted`
3957
- };
3958
- }
3959
- const parsed = await res.json();
3960
- if (typeof parsed.sub !== "string" || parsed.sub === "") {
3961
- return { ok: false, message: "userinfo carried no subject claim" };
3962
- }
3963
- return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };
3914
+ // src/engine/messaging.ts
3915
+ var FOLDERS = {
3916
+ primary: "PRIMARY_INBOX",
3917
+ other: "SECONDARY_INBOX",
3918
+ inbox: "INBOX",
3919
+ archive: "ARCHIVE",
3920
+ requests: "MESSAGE_REQUEST_PENDING",
3921
+ spam: "SPAM"
3922
+ };
3923
+ var FOLDER_OF = Object.fromEntries(
3924
+ Object.entries(FOLDERS).map(([k, v]) => [v, k])
3925
+ );
3926
+ function contract2(name) {
3927
+ const c = CONTRACTS[name];
3928
+ if (c?.queryId === void 0) throw new Error(`messaging contract '${name}' is missing`);
3929
+ return c;
3964
3930
  }
3965
- function parseCallback(rawUrl, expectedState) {
3966
- let url;
3967
- try {
3968
- url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);
3969
- } catch {
3970
- return { ok: false, message: "callback URL was unparseable" };
3971
- }
3972
- const error = url.searchParams.get("error");
3973
- if (error !== null) {
3974
- const description = url.searchParams.get("error_description") ?? "";
3975
- return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
3976
- }
3977
- const state = url.searchParams.get("state");
3978
- if (state !== expectedState) {
3979
- return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
3980
- }
3981
- const code = url.searchParams.get("code");
3982
- if (code === null || code === "") return { ok: false, message: "callback carried no code" };
3983
- return { ok: true, code };
3931
+ function mailboxOf(meUrn) {
3932
+ const id = meUrn.match(/(?:fs_miniProfile|fsd_profile|fs_profile):([A-Za-z0-9_-]+)/)?.[1];
3933
+ return `urn:li:fsd_profile:${id ?? meUrn}`;
3984
3934
  }
3985
-
3986
- // src/commands/token.ts
3987
- import { existsSync as existsSync3, rmSync } from "fs";
3988
- var TOKEN_FILE = "oauth.json";
3989
- var OAUTH_SETUP = [
3990
- "Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one",
3991
- "legitimacy wedge an individual actually has \u2014 but the app has to be registered by you; it",
3992
- "cannot be created on your behalf.",
3993
- "",
3994
- " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
3995
- ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
3996
- " Both are self-serve: no partner review, no verification, no screencast.",
3997
- ` 3. Auth tab \u2192 add redirect URL ${REDIRECT_URI}`,
3998
- " 4. Run: lnrelay oauth login --client-id <id>",
3999
- " (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)"
4000
- ].join("\n");
4001
- function tokenPath() {
4002
- return cachePath(TOKEN_FILE);
3935
+ function conversationsUrl(q2) {
3936
+ const c = contract2("messengerConversations");
3937
+ const variables = encodeVariables({
3938
+ query: {
3939
+ predicateUnions: [{ conversationCategoryPredicate: { category: FOLDERS[q2.folder] } }]
3940
+ },
3941
+ count: q2.count ?? 20,
3942
+ mailboxUrn: q2.mailbox,
3943
+ nextCursor: q2.cursor
3944
+ });
3945
+ return `${c.path}?queryId=${c.queryId}&variables=${variables}`;
4003
3946
  }
4004
- function loadToken() {
4005
- const result = loadJson(tokenPath());
4006
- return result.state === "ok" ? result.value : null;
3947
+ function messagesUrl(conversationUrn) {
3948
+ const c = contract2("messengerMessages");
3949
+ return `${c.path}?queryId=${c.queryId}&variables=${encodeVariables({ conversationUrn })}`;
4007
3950
  }
4008
- function saveToken(token) {
4009
- saveJson(tokenPath(), token);
3951
+ function conversationIdOf(input, mailbox2) {
3952
+ const s = input.trim();
3953
+ if (/^urn:li:msg_conversation:\(urn:li:fsd_profile:[^,]+,2-[^)]+\)$/.test(s)) return s;
3954
+ const thread = s.match(/messaging\/thread\/(2-[^/?#]+)/)?.[1] ?? s.match(/^(2-[A-Za-z0-9+/=_-]+)$/)?.[1];
3955
+ return thread === void 0 ? void 0 : `urn:li:msg_conversation:(${mailbox2},${thread})`;
4010
3956
  }
4011
- function deleteToken() {
4012
- const path = tokenPath();
4013
- if (!existsSync3(path)) return false;
4014
- rmSync(path, { force: true });
4015
- return true;
3957
+ var DEGREE = {
3958
+ DISTANCE_1: "1st",
3959
+ DISTANCE_2: "2nd",
3960
+ DISTANCE_3: "3rd+",
3961
+ OUT_OF_NETWORK: "out of network"
3962
+ };
3963
+ var txt = (v) => {
3964
+ const t = typeof v === "string" ? v : v?.text;
3965
+ return typeof t === "string" && t.trim() !== "" ? t.trim() : void 0;
3966
+ };
3967
+ var iso = (ms) => typeof ms === "number" ? new Date(ms).toISOString() : void 0;
3968
+ function defined3(obj) {
3969
+ for (const k of Object.keys(obj)) if (obj[k] === void 0) delete obj[k];
3970
+ return obj;
4016
3971
  }
4017
-
4018
- // src/commands/oauth.ts
4019
- var CALLBACK_TIMEOUT_MS = 3e5;
4020
- var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
4021
- <body style="font:16px system-ui;padding:3rem;max-width:32rem">
4022
- <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
4023
- function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
4024
- return new Promise((ready) => {
4025
- let settle = () => {
4026
- };
4027
- const code = new Promise((r) => {
4028
- settle = r;
4029
- });
4030
- const server = createServer((req, res) => {
4031
- const url = req.url ?? "/";
4032
- if (!url.startsWith("/callback")) {
4033
- res.writeHead(404, { connection: "close" });
4034
- res.end();
4035
- return;
4036
- }
4037
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
4038
- res.end(DONE_PAGE);
4039
- settle(parseCallback(url, state));
4040
- });
4041
- const timer = setTimeout(() => {
4042
- settle({
4043
- ok: false,
4044
- message: `timed out after ${Math.round(timeoutMs / 1e3)}s waiting for the LinkedIn callback`
4045
- });
4046
- }, timeoutMs);
4047
- timer.unref?.();
4048
- const close = () => {
4049
- clearTimeout(timer);
4050
- server.closeAllConnections?.();
4051
- server.close();
4052
- };
4053
- server.once("error", (e) => {
4054
- clearTimeout(timer);
4055
- const why = e.code === "EADDRINUSE" ? `port ${CALLBACK_PORT} is already in use \u2014 close whatever holds it and retry` : `could not open the callback listener: ${e.message}`;
4056
- ready({ ok: false, message: why });
3972
+ function participantOf(p) {
3973
+ const t = p?.participantType ?? {};
3974
+ if (t.member) {
3975
+ const m = t.member;
3976
+ const name = [txt(m.firstName), txt(m.lastName)].filter(Boolean).join(" ");
3977
+ const url = typeof m.profileUrl === "string" ? `${m.profileUrl.replace(/\/$/, "")}/` : void 0;
3978
+ return defined3({
3979
+ name: name !== "" ? name : "LinkedIn Member",
3980
+ kind: "person",
3981
+ headline: txt(m.headline),
3982
+ degree: DEGREE[String(m.distance)],
3983
+ url
4057
3984
  });
4058
- server.listen(CALLBACK_PORT, "127.0.0.1", () => {
4059
- ready({ ok: true, code, close });
3985
+ }
3986
+ if (t.organization) {
3987
+ const o = t.organization;
3988
+ return defined3({
3989
+ name: txt(o.name) ?? "an organization",
3990
+ kind: "organization",
3991
+ url: typeof o.pageUrl === "string" ? o.pageUrl : void 0
4060
3992
  });
3993
+ }
3994
+ if (t.custom) return { name: txt(t.custom.name) ?? "LinkedIn", kind: "other" };
3995
+ return void 0;
3996
+ }
3997
+ var isMe = (urn, mailbox2) => typeof urn === "string" && urn.includes(mailbox2);
3998
+ function messageOf(m, byUrn, mailbox2) {
3999
+ const sender = m["*sender"] ?? m["*actor"];
4000
+ const fromMe = isMe(sender, mailbox2);
4001
+ const who = fromMe ? void 0 : participantOf(byUrn.get(sender));
4002
+ const render2 = Array.isArray(m.renderContent) ? m.renderContent : [];
4003
+ return defined3({
4004
+ from: fromMe ? "you" : who?.name ?? "unknown",
4005
+ fromMe,
4006
+ at: iso(m.deliveredAt),
4007
+ text: txt(m.body),
4008
+ subject: txt(m.subject),
4009
+ sponsored: render2.some((r) => r.conversationAdsMessageContent) ? true : void 0
4061
4010
  });
4062
4011
  }
4063
- function openBrowser(url) {
4064
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
4065
- try {
4066
- spawn(cmd, [url], { detached: true, stdio: "ignore" }).unref();
4067
- } catch {
4068
- }
4012
+ var drift3 = (message) => ({
4013
+ ok: false,
4014
+ code: "SCHEMA_DRIFT",
4015
+ message,
4016
+ hint: "the messaging response changed shape; re-capture it"
4017
+ });
4018
+ function collectionOf(json) {
4019
+ const d = json?.data?.data;
4020
+ const key = d === void 0 ? void 0 : Object.keys(d).find((k) => k.startsWith("messenger"));
4021
+ const c = key === void 0 ? void 0 : d?.[key];
4022
+ return c !== null && typeof c === "object" ? c : void 0;
4069
4023
  }
4070
- function loginDeps() {
4024
+ function refsOf(top) {
4025
+ const refs = top?.["*elements"];
4026
+ if (Array.isArray(refs)) return refs;
4027
+ return Array.isArray(top?.elements) && top.elements.length === 0 ? [] : void 0;
4028
+ }
4029
+ function parseConversations(json, mailbox2) {
4030
+ const top = collectionOf(json);
4031
+ const refs = refsOf(top);
4032
+ if (refs === void 0) return drift3("the conversation list was missing");
4033
+ const included = json.included ?? [];
4034
+ const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4035
+ const conversations = [];
4036
+ for (const ref of refs) {
4037
+ const c = byUrn.get(ref);
4038
+ if (c === void 0) continue;
4039
+ const parts = (c["*conversationParticipants"] ?? []).filter((u) => !isMe(u, mailbox2)).map((u) => participantOf(byUrn.get(u))).filter((p) => p !== void 0);
4040
+ const lastRef = c.messages?.["*elements"]?.[0];
4041
+ const last = lastRef === void 0 ? void 0 : byUrn.get(lastRef);
4042
+ const categories = Array.isArray(c.categories) ? c.categories : [];
4043
+ conversations.push(
4044
+ defined3({
4045
+ id: String(c.entityUrn),
4046
+ url: typeof c.conversationUrl === "string" ? c.conversationUrl : void 0,
4047
+ with: parts,
4048
+ title: c.groupChat === true ? txt(c.title) : void 0,
4049
+ unread: typeof c.unreadCount === "number" ? c.unreadCount : 0,
4050
+ lastActivity: iso(c.lastActivityAt),
4051
+ last: last === void 0 ? void 0 : messageOf(last, byUrn, mailbox2),
4052
+ // PRIMARY_INBOX sits inside INBOX; report the folder a person would name.
4053
+ folders: categories.map((k) => FOLDER_OF[k]).filter(
4054
+ (f) => f !== void 0 && !(f === "primary" && categories.includes("INBOX"))
4055
+ ),
4056
+ inmail: categories.includes("INMAIL")
4057
+ })
4058
+ );
4059
+ }
4060
+ if (refs.length > 0 && conversations.length === 0)
4061
+ return drift3(`${refs.length} conversations were listed but none were sent`);
4062
+ const cursor = top?.metadata?.nextCursor;
4071
4063
  return {
4072
- state: () => crypto.randomUUID(),
4073
- listen: (state) => listenForCallback(state),
4074
- open: openBrowser,
4075
- write: (s) => process.stderr.write(s),
4076
- isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
4077
- prompt: async (question) => {
4078
- const rl = createInterface2({ input: process.stdin, output: process.stderr });
4079
- const answer = await rl.question(question);
4080
- rl.close();
4081
- return answer;
4082
- },
4083
- now: Date.now,
4084
- fetch: globalThis.fetch
4064
+ ok: true,
4065
+ conversations,
4066
+ ...typeof cursor === "string" && cursor !== "" ? { cursor } : {}
4085
4067
  };
4086
4068
  }
4087
- async function credentials(opts, deps) {
4088
- const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;
4089
- if (clientId === void 0 || clientId === "") {
4090
- return err("oauth", "INVALID_INPUT", "a client id is required", OAUTH_SETUP);
4091
- }
4092
- let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;
4093
- if ((clientSecret === void 0 || clientSecret === "") && deps.isTty) {
4094
- clientSecret = (await deps.prompt("client secret (not echoed to argv or logs): ")).trim();
4069
+ function parseMessages(json, mailbox2) {
4070
+ const top = collectionOf(json);
4071
+ const refs = refsOf(top);
4072
+ if (refs === void 0) return drift3("the message list was missing");
4073
+ const included = json.included ?? [];
4074
+ const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4075
+ const messages = [];
4076
+ for (const ref of refs) {
4077
+ const m = byUrn.get(ref);
4078
+ if (m === void 0 || typeof m.deliveredAt !== "number") continue;
4079
+ messages.push({ id: String(m.entityUrn), ...messageOf(m, byUrn, mailbox2) });
4095
4080
  }
4096
- if (clientSecret === void 0 || clientSecret === "") {
4097
- return err(
4098
- "oauth",
4099
- "INVALID_INPUT",
4100
- "a client secret is required, and there is no terminal to ask on",
4101
- `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.
4102
-
4103
- ${OAUTH_SETUP}`
4104
- );
4105
- }
4106
- return { clientId, clientSecret };
4107
- }
4108
- async function runOauthLogin(opts, deps = loginDeps()) {
4109
- const creds = await credentials(opts, deps);
4110
- if ("ok" in creds) return creds;
4111
- const state = deps.state();
4112
- const listener = await deps.listen(state);
4113
- if (!listener.ok) {
4114
- return err("oauth", "AUTH_FAILED", listener.message);
4115
- }
4116
- try {
4117
- const url = authorizationUrl(creds.clientId, state);
4118
- deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
4119
-
4120
- ${url}
4121
-
4122
- `);
4123
- deps.open(url);
4124
- const callback = await listener.code;
4125
- if (!callback.ok) return err("oauth", "AUTH_FAILED", callback.message);
4126
- const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });
4127
- if (!token.ok) return err("oauth", "AUTH_FAILED", token.message, token.hint);
4128
- const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });
4129
- if (!member.ok) return err("oauth", "AUTH_FAILED", member.message, OAUTH_SETUP);
4130
- saveToken({
4131
- accessToken: token.accessToken,
4132
- memberUrn: member.memberUrn,
4133
- expiresAt: token.expiresAt
4134
- });
4135
- return ok("oauth", {
4136
- memberUrn: member.memberUrn,
4137
- scopes: SCOPES,
4138
- expiresAt: new Date(token.expiresAt).toISOString(),
4139
- storedAt: tokenPath(),
4140
- // Refresh tokens are partner-gated, so renewal is re-running this.
4141
- renewal: "run `lnrelay oauth login` again when it expires"
4142
- });
4143
- } finally {
4144
- listener.close();
4145
- }
4146
- }
4147
- function runOauthLogout() {
4148
- const removed = deleteToken();
4149
- return ok("oauth", {
4150
- removed,
4151
- note: removed ? `deleted ${tokenPath()} \u2014 the token stays valid on LinkedIn's side until it expires` : "no token was stored"
4152
- });
4153
- }
4154
- function runOauthStatus() {
4155
- const token = loadToken();
4156
- if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
4157
- return ok("oauth", {
4158
- memberUrn: token.memberUrn,
4159
- expiresAt: new Date(token.expiresAt).toISOString(),
4160
- expired: token.expiresAt <= Date.now(),
4161
- scopes: SCOPES,
4162
- storedAt: tokenPath(),
4163
- writeCap: CAPS.write.perDay
4164
- });
4081
+ if (refs.length > 0 && messages.length === 0)
4082
+ return drift3(`${refs.length} messages were listed but none were sent`);
4083
+ messages.sort((a, b) => a.at.localeCompare(b.at));
4084
+ return { ok: true, messages };
4165
4085
  }
4166
4086
 
4167
4087
  // src/engine/people.ts
@@ -4170,11 +4090,11 @@ var text3 = (v) => {
4170
4090
  const t = v?.text;
4171
4091
  return typeof t === "string" && t.trim() !== "" ? t.trim() : void 0;
4172
4092
  };
4173
- function defined3(obj) {
4093
+ function defined4(obj) {
4174
4094
  for (const k of Object.keys(obj)) if (obj[k] === void 0) delete obj[k];
4175
4095
  return obj;
4176
4096
  }
4177
- var drift3 = (message) => ({
4097
+ var drift4 = (message) => ({
4178
4098
  ok: false,
4179
4099
  code: "SCHEMA_DRIFT",
4180
4100
  message,
@@ -4190,17 +4110,18 @@ function peopleSearchUrl(q2) {
4190
4110
  const variables = encodeVariables({
4191
4111
  start: q2.start,
4192
4112
  count: PEOPLE_PAGE,
4193
- origin: "FACETED_SEARCH",
4113
+ origin: q2.origin ?? "FACETED_SEARCH",
4194
4114
  query: {
4195
- keywords: q2.keywords,
4196
- flagshipSearchIntent: "SEARCH_SRP",
4115
+ // An empty `keywords` is answered with a 400: none is sent then.
4116
+ keywords: q2.keywords === "" ? void 0 : q2.keywords,
4117
+ flagshipSearchIntent: q2.intent ?? "SEARCH_SRP",
4197
4118
  queryParameters,
4198
4119
  includeFiltersInResponse: q2.withFilters === true
4199
4120
  }
4200
4121
  });
4201
4122
  return `${c.path}?variables=${variables}&queryId=${c.queryId}`;
4202
4123
  }
4203
- var DEGREE = {
4124
+ var DEGREE2 = {
4204
4125
  DISTANCE_1: "1st",
4205
4126
  DISTANCE_2: "2nd",
4206
4127
  DISTANCE_3: "3rd+",
@@ -4223,12 +4144,12 @@ function rowToPerson(row) {
4223
4144
  if (id === void 0 || name === void 0) return void 0;
4224
4145
  const tracking = row.entityCustomTrackingInfo ?? {};
4225
4146
  const badge = JSON.stringify(row.badgeIcon ?? null);
4226
- return defined3({
4147
+ return defined4({
4227
4148
  id,
4228
4149
  name,
4229
4150
  headline: text3(row.primarySubtitle),
4230
4151
  location: text3(row.secondarySubtitle),
4231
- degree: DEGREE[String(tracking.memberDistance)],
4152
+ degree: DEGREE2[String(tracking.memberDistance)],
4232
4153
  verified: badge.includes("VERIFIED") ? true : void 0,
4233
4154
  insight: insightOf(row),
4234
4155
  url: profileUrl(row.navigationUrl)
@@ -4279,7 +4200,7 @@ function readItems(c, included, toRow) {
4279
4200
  function parsePeople(json) {
4280
4201
  const c = clustersOf(json);
4281
4202
  if (c === void 0 || !Array.isArray(c.elements))
4282
- return drift3("the people search returned no result list");
4203
+ return drift4("the people search returned no result list");
4283
4204
  const included = json.included ?? [];
4284
4205
  const { people, unknownTypes, excluded, unresolved } = readItems(c, included, rowToPerson);
4285
4206
  const total = typeof c.paging?.total === "number" ? c.paging.total : void 0;
@@ -4287,7 +4208,7 @@ function parsePeople(json) {
4287
4208
  const claimedRaw = c.metadata?.totalResultCount;
4288
4209
  const claimed = typeof claimedRaw === "number" ? claimedRaw : total;
4289
4210
  if (unresolved > 0 && people.length === 0)
4290
- return drift3(`${unresolved} people were listed but none could be read`);
4211
+ return drift4(`${unresolved} people were listed but none could be read`);
4291
4212
  if (people.length === 0 && total !== void 0 && total > start) {
4292
4213
  return {
4293
4214
  ok: false,
@@ -4309,7 +4230,7 @@ function parsePeople(json) {
4309
4230
  function parsePeopleFilters(json) {
4310
4231
  const cluster = clustersOf(json)?.metadata?.primaryFilterCluster;
4311
4232
  if (cluster === null || cluster === void 0)
4312
- return drift3("the people search returned no filter list");
4233
+ return drift4("the people search returned no filter list");
4313
4234
  const groups = [
4314
4235
  ...cluster.secondaryFilterGroups ?? [],
4315
4236
  ...cluster.primaryFilterGroups ?? []
@@ -4325,13 +4246,13 @@ function parsePeopleFilters(json) {
4325
4246
  ...f.primaryFilterValues ?? []
4326
4247
  ];
4327
4248
  filters.push(
4328
- defined3({
4249
+ defined4({
4329
4250
  key,
4330
4251
  label: text3(f.displayName) ?? key,
4331
4252
  input: f.renderType === "FREE_TEXT" ? "text" : "select",
4332
4253
  lookup: typeof f.typeaheadType === "string" ? f.typeaheadType : void 0,
4333
4254
  options: values.filter((v) => typeof v.value === "string").map(
4334
- (v) => defined3({
4255
+ (v) => defined4({
4335
4256
  value: v.value,
4336
4257
  label: typeof v.displayName === "string" ? v.displayName : String(v.value),
4337
4258
  count: typeof v.count === "number" && v.count > 0 ? v.count : void 0
@@ -4341,12 +4262,12 @@ function parsePeopleFilters(json) {
4341
4262
  );
4342
4263
  }
4343
4264
  }
4344
- if (filters.length === 0) return drift3("the people filter list was empty");
4265
+ if (filters.length === 0) return drift4("the people filter list was empty");
4345
4266
  return { ok: true, filters };
4346
4267
  }
4347
4268
  function parseOrgHits(json) {
4348
4269
  const c = clustersOf(json);
4349
- if (c === void 0) return drift3("the organisation search returned no result list");
4270
+ if (c === void 0) return drift4("the organisation search returned no result list");
4350
4271
  const included = json.included ?? [];
4351
4272
  const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4352
4273
  const hits = [];
@@ -4590,39 +4511,829 @@ async function runPeople(req, opts = {}, fetch2) {
4590
4511
  meta: metaOf("people", merged, single, first)
4591
4512
  });
4592
4513
  }
4593
- async function runPeopleFilters(req, opts = {}, fetch2) {
4594
- const sets = keywordSets(req.keywords);
4595
- if (sets.length > 1) {
4514
+ async function runPeopleFilters(req, opts = {}, fetch2) {
4515
+ const sets = keywordSets(req.keywords);
4516
+ if (sets.length > 1) {
4517
+ return err(
4518
+ "people-filters",
4519
+ "INVALID_INPUT",
4520
+ "people-filters takes one keyword set: its counts belong to that one query",
4521
+ 'lnrelay people-filters "<keywords>" [filters]'
4522
+ );
4523
+ }
4524
+ const get = fetch2 ?? liveFetch2("people-filters", opts.quiet === true);
4525
+ if (typeof get !== "function") return get;
4526
+ const names = await resolveNames(get, req);
4527
+ if ("ok" in names) return err("people-filters", names.code, names.message, names.hint);
4528
+ const selection3 = peopleFilterSelection(names.filter);
4529
+ if (!selection3.ok) return err("people-filters", selection3.code, selection3.message);
4530
+ const url = peopleSearchUrl({
4531
+ ...sets[0] !== void 0 ? { keywords: sets[0] } : {},
4532
+ params: selection3.params,
4533
+ start: 0,
4534
+ withFilters: true
4535
+ });
4536
+ const res = await get(url, "search");
4537
+ const parsed = res.ok ? parsePeopleFilters(res.json) : res;
4538
+ if (!parsed.ok) return err("people-filters", parsed.code, parsed.message, parsed.hint);
4539
+ return ok("people-filters", {
4540
+ ...Object.keys(names.resolved).length > 0 ? { resolved: names.resolved } : {},
4541
+ items: shape2(parsed.filters, opts, (f) => {
4542
+ const how = f.input === "text" ? "free text" : BY_NAME[f.key] ?? "ids";
4543
+ const options = f.options.map((o) => `${o.value}=${o.label}${o.count !== void 0 ? ` (${o.count})` : ""}`).join(", ");
4544
+ return `${f.key} [${how}]${options !== "" ? `: ${options}` : ""}`;
4545
+ }),
4546
+ meta: { state: "complete", operation: "people-filters", returnedCount: parsed.filters.length }
4547
+ });
4548
+ }
4549
+
4550
+ // src/commands/messaging.ts
4551
+ var MESSAGES_PAGE = 20;
4552
+ var MAX_CONVERSATIONS = 500;
4553
+ function live(command, quiet) {
4554
+ const session = loadSession();
4555
+ if (session.state !== "ok")
4556
+ return err(command, "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
4557
+ const client = createLiveClient(session.session, void 0, quiet);
4558
+ const fetch2 = async (url, spendClass) => {
4559
+ const r = await client.request({ url, spendClass, operation: command });
4560
+ return r.ok ? { ok: true, json: r.json } : r;
4561
+ };
4562
+ return { fetch: fetch2, session: session.session };
4563
+ }
4564
+ async function mailbox(command, quiet) {
4565
+ const known = loadJson(cachePath("me.json"));
4566
+ if (known.state === "ok" && typeof known.value.profileUrn === "string")
4567
+ return known.value.profileUrn;
4568
+ const session = loadSession();
4569
+ if (session.state !== "ok")
4570
+ return err(command, "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
4571
+ const me = await createEngine(session.session, void 0, quiet).whoami();
4572
+ const urn = me.ok ? me.value?.entityUrn : void 0;
4573
+ if (typeof urn !== "string")
4574
+ return err(command, "AUTH_FAILED", "could not tell whose mailbox this is");
4575
+ const profileUrn = mailboxOf(urn);
4576
+ saveJson(cachePath("me.json"), { profileUrn });
4577
+ return profileUrn;
4578
+ }
4579
+ async function setup(command, opts, fetch2) {
4580
+ const box = await mailbox(command, opts.quiet === true);
4581
+ if (typeof box !== "string") return box;
4582
+ if (fetch2 !== void 0) return { box, get: fetch2 };
4583
+ const l = live(command, opts.quiet === true);
4584
+ if ("ok" in l) return l;
4585
+ return { box, get: l.fetch };
4586
+ }
4587
+ function compactConversation(c) {
4588
+ const last = c.last === void 0 ? void 0 : `${c.last.from}: ${(c.last.text ?? "").replace(/\s+/g, " ")}`;
4589
+ return line([
4590
+ c.id,
4591
+ c.with.map((p) => p.name).join(", ") || c.title,
4592
+ c.unread > 0 ? `${c.unread} unread` : void 0,
4593
+ c.lastActivity?.slice(0, 10),
4594
+ c.inmail ? "InMail" : void 0,
4595
+ last !== void 0 && last.length > 140 ? `${last.slice(0, 137)}\u2026` : last
4596
+ ]);
4597
+ }
4598
+ async function runInbox(req, opts = {}, fetch2) {
4599
+ const folder = req.folder ?? "inbox";
4600
+ if (!(folder in FOLDERS)) {
4601
+ return err(
4602
+ "inbox",
4603
+ "INVALID_INPUT",
4604
+ `no folder '${folder}'`,
4605
+ `one of: ${Object.keys(FOLDERS).join(", ")}`
4606
+ );
4607
+ }
4608
+ const ready = await setup("inbox", opts, fetch2);
4609
+ if ("ok" in ready) return ready;
4610
+ const want = Math.max(1, Math.min(req.limit, MAX_CONVERSATIONS));
4611
+ const all = [];
4612
+ let cursor;
4613
+ let stoppedBy;
4614
+ let exhausted = false;
4615
+ while (all.length < want) {
4616
+ const res = await ready.get(
4617
+ conversationsUrl({ mailbox: ready.box, folder, ...cursor ? { cursor } : {} }),
4618
+ "page"
4619
+ );
4620
+ const page = res.ok ? parseConversations(res.json, ready.box) : res;
4621
+ if (!page.ok) {
4622
+ if (all.length === 0) return err("inbox", page.code, page.message, page.hint);
4623
+ stoppedBy = page.code;
4624
+ break;
4625
+ }
4626
+ const room = want - all.length;
4627
+ all.push(...page.conversations.slice(0, room));
4628
+ if (page.conversations.length > room) break;
4629
+ if (page.cursor === void 0 || page.conversations.length === 0) {
4630
+ exhausted = true;
4631
+ break;
4632
+ }
4633
+ cursor = page.cursor;
4634
+ }
4635
+ const shown = req.unread === true ? all.filter((c) => c.unread > 0) : all;
4636
+ return ok("inbox", {
4637
+ folder,
4638
+ items: shape2(shown, opts, compactConversation),
4639
+ meta: {
4640
+ state: exhausted && stoppedBy === void 0 ? "complete" : "partial",
4641
+ operation: "inbox",
4642
+ returnedCount: shown.length,
4643
+ unread: all.filter((c) => c.unread > 0).length,
4644
+ ...stoppedBy !== void 0 ? { stoppedBy } : {}
4645
+ }
4646
+ });
4647
+ }
4648
+ async function runMessages(input, opts = {}, fetch2) {
4649
+ const ready = await setup("messages", opts, fetch2);
4650
+ if ("ok" in ready) return ready;
4651
+ const id = input === void 0 ? void 0 : conversationIdOf(input, ready.box);
4652
+ if (id === void 0) {
4653
+ return err(
4654
+ "messages",
4655
+ "INVALID_INPUT",
4656
+ "a conversation id or /messaging/thread/ URL is required",
4657
+ "ids come from `lnrelay inbox`"
4658
+ );
4659
+ }
4660
+ const res = await ready.get(messagesUrl(id), "page");
4661
+ const parsed = res.ok ? parseMessages(res.json, ready.box) : res;
4662
+ if (!parsed.ok) return err("messages", parsed.code, parsed.message, parsed.hint);
4663
+ return ok("messages", {
4664
+ conversation: id,
4665
+ url: threadUrl(id),
4666
+ items: shape2(
4667
+ parsed.messages,
4668
+ opts,
4669
+ (m) => line([
4670
+ m.at.slice(0, 16).replace("T", " "),
4671
+ m.from,
4672
+ m.subject,
4673
+ (m.text ?? "").replace(/\s+/g, " ")
4674
+ ])
4675
+ ),
4676
+ meta: {
4677
+ // A full page may have older messages behind it; this reads the latest page only.
4678
+ state: parsed.messages.length < MESSAGES_PAGE ? "complete" : "partial",
4679
+ operation: "messages",
4680
+ returnedCount: parsed.messages.length
4681
+ }
4682
+ });
4683
+ }
4684
+ var threadUrl = (conversationUrn) => {
4685
+ const thread = conversationUrn.match(/,(2-[^)]+)\)$/)?.[1];
4686
+ return thread === void 0 ? void 0 : `https://www.linkedin.com/messaging/thread/${thread}/`;
4687
+ };
4688
+ var DRAFTS = () => cachePath("drafts.json");
4689
+ function loadDrafts() {
4690
+ const loaded = loadJson(DRAFTS());
4691
+ if (loaded.state === "missing") return [];
4692
+ if (loaded.state === "corrupt")
4693
+ return {
4694
+ ok: false,
4695
+ code: "CACHE_CORRUPT",
4696
+ message: `drafts were unreadable; moved to ${loaded.quarantinedTo}`
4697
+ };
4698
+ return Array.isArray(loaded.value) ? loaded.value : [];
4699
+ }
4700
+ async function runDraft(conversation, text5, fetch2, opts = {}) {
4701
+ const body = text5?.trim() ?? "";
4702
+ if (body === "")
4703
+ return err(
4704
+ "draft",
4705
+ "INVALID_INPUT",
4706
+ "a draft needs text",
4707
+ 'lnrelay draft <conversation> "<text>" | --file <path>'
4708
+ );
4709
+ const box = await mailbox("draft", opts.quiet === true);
4710
+ if (typeof box !== "string") return box;
4711
+ const id = conversation === void 0 ? void 0 : conversationIdOf(conversation, box);
4712
+ if (id === void 0)
4713
+ return err(
4714
+ "draft",
4715
+ "INVALID_INPUT",
4716
+ "a conversation id or /messaging/thread/ URL is required",
4717
+ "ids come from `lnrelay inbox`"
4718
+ );
4719
+ const ready = await setup("draft", opts, fetch2);
4720
+ if ("ok" in ready) return ready;
4721
+ const res = await ready.get(messagesUrl(id), "page");
4722
+ const parsed = res.ok ? parseMessages(res.json, ready.box) : res;
4723
+ if (!parsed.ok) return err("draft", parsed.code, parsed.message, parsed.hint);
4724
+ const to = [...new Set(parsed.messages.filter((m) => !m.fromMe).map((m) => m.from))];
4725
+ const drafts = loadDrafts();
4726
+ if (!Array.isArray(drafts)) return err("draft", drafts.code, drafts.message);
4727
+ const url = threadUrl(id);
4728
+ const draft = {
4729
+ id: randomUUID().slice(0, 8),
4730
+ conversation: id,
4731
+ ...url !== void 0 ? { url } : {},
4732
+ to,
4733
+ text: body,
4734
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4735
+ };
4736
+ saveJson(DRAFTS(), [...drafts, draft]);
4737
+ return ok("draft", {
4738
+ saved: true,
4739
+ sent: false,
4740
+ draft,
4741
+ notice: "Saved on this machine only. Nothing was sent: open the link, review, and send it yourself."
4742
+ });
4743
+ }
4744
+ function draftText(text5, file) {
4745
+ return file !== void 0 ? readFileSync2(file, "utf-8") : text5;
4746
+ }
4747
+ function runDrafts(opts = {}) {
4748
+ const drafts = loadDrafts();
4749
+ if (!Array.isArray(drafts)) return err("drafts", drafts.code, drafts.message);
4750
+ return ok("drafts", {
4751
+ items: shape2(
4752
+ drafts,
4753
+ opts,
4754
+ (d) => line([d.id, d.to.join(", "), d.createdAt.slice(0, 10), d.text.replace(/\s+/g, " "), d.url])
4755
+ ),
4756
+ meta: { state: "complete", operation: "drafts", returnedCount: drafts.length }
4757
+ });
4758
+ }
4759
+ function runDraftRemove(id) {
4760
+ const drafts = loadDrafts();
4761
+ if (!Array.isArray(drafts)) return err("draft", drafts.code, drafts.message);
4762
+ if (id === void 0 || !drafts.some((d) => d.id === id)) {
4763
+ return err(
4764
+ "draft",
4765
+ "NOT_FOUND",
4766
+ `no draft '${id ?? ""}'`,
4767
+ `drafts: ${drafts.map((d) => d.id).join(", ") || "none"}`
4768
+ );
4769
+ }
4770
+ saveJson(
4771
+ DRAFTS(),
4772
+ drafts.filter((d) => d.id !== id)
4773
+ );
4774
+ return ok("draft", { removed: id });
4775
+ }
4776
+
4777
+ // src/engine/search.ts
4778
+ var SEARCH_KINDS = {
4779
+ companies: "COMPANIES",
4780
+ groups: "GROUPS",
4781
+ events: "EVENTS",
4782
+ courses: "LEARNING",
4783
+ products: "PRODUCTS",
4784
+ services: "SERVICES",
4785
+ schools: "SCHOOLS"
4786
+ };
4787
+ var SEARCH_PAGE = PEOPLE_PAGE;
4788
+ function searchUrl(q2) {
4789
+ return peopleSearchUrl({
4790
+ ...q2.keywords !== void 0 ? { keywords: q2.keywords } : {},
4791
+ params: q2.params,
4792
+ start: q2.start,
4793
+ ...q2.withFilters === true ? { withFilters: true } : {},
4794
+ kind: SEARCH_KINDS[q2.kind]
4795
+ });
4796
+ }
4797
+ var text4 = (v) => {
4798
+ const t = v?.text;
4799
+ return typeof t === "string" && t.trim() !== "" ? t.trim().replace(/\s+/g, " ") : void 0;
4800
+ };
4801
+ function idOf(entityUrn) {
4802
+ const inner = String(entityUrn ?? "").match(/\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];
4803
+ return inner?.split(":").pop();
4804
+ }
4805
+ function cleanUrl2(nav) {
4806
+ if (typeof nav !== "string" || !nav.startsWith("https://")) return void 0;
4807
+ return nav.split("?")[0];
4808
+ }
4809
+ function rowToFound(row) {
4810
+ const id = idOf(row.entityUrn);
4811
+ const name = text4(row.title);
4812
+ if (id === void 0 || name === void 0) return void 0;
4813
+ const found = { id, name };
4814
+ const fields = [
4815
+ ["subtitle", text4(row.primarySubtitle)],
4816
+ ["detail", text4(row.secondarySubtitle)],
4817
+ ["summary", text4(row.summary)],
4818
+ ["url", cleanUrl2(row.navigationUrl)]
4819
+ ];
4820
+ for (const [k, v] of fields)
4821
+ if (v !== void 0) found[k] = v;
4822
+ if (JSON.stringify(row.badgeIcon ?? null).includes("VERIFIED")) found.verified = true;
4823
+ return found;
4824
+ }
4825
+ var drift5 = (message) => ({
4826
+ ok: false,
4827
+ code: "SCHEMA_DRIFT",
4828
+ message,
4829
+ hint: "the search response changed shape; re-capture it"
4830
+ });
4831
+ function parseResults(json) {
4832
+ const c = clustersOf(json);
4833
+ if (c === void 0 || !Array.isArray(c.elements))
4834
+ return drift5("the search returned no result list");
4835
+ const included = json.included ?? [];
4836
+ const { people: items, unknownTypes, excluded, unresolved } = readItems(c, included, rowToFound);
4837
+ const total = typeof c.paging?.total === "number" ? c.paging.total : void 0;
4838
+ const start = typeof c.paging?.start === "number" ? c.paging.start : 0;
4839
+ const claimedRaw = c.metadata?.totalResultCount;
4840
+ const claimed = typeof claimedRaw === "number" ? claimedRaw : total;
4841
+ if (unresolved > 0 && items.length === 0)
4842
+ return drift5(`${unresolved} results were listed but none could be read`);
4843
+ if (items.length === 0 && total !== void 0 && total > start) {
4844
+ return {
4845
+ ok: false,
4846
+ code: "SCHEMA_DRIFT",
4847
+ message: `LinkedIn claims ${total} results but returned none from ${start}`,
4848
+ hint: 'a failed fetch, not an empty search; do not report "none"'
4849
+ };
4850
+ }
4851
+ return {
4852
+ ok: true,
4853
+ items,
4854
+ ...total !== void 0 ? { total } : {},
4855
+ ...claimed !== void 0 ? { claimed } : {},
4856
+ start,
4857
+ excluded,
4858
+ unknownTypes
4859
+ };
4860
+ }
4861
+
4862
+ // src/engine/network.ts
4863
+ var HUB = {
4864
+ connections: "CONNECTIONS",
4865
+ following: "PEOPLE_FOLLOW",
4866
+ followers: "FOLLOWERS",
4867
+ pages: "PAGES",
4868
+ events: "EVENTS",
4869
+ groups: "GROUPS"
4870
+ };
4871
+ var PEOPLE_LISTS = /* @__PURE__ */ new Set(["connections", "following", "followers"]);
4872
+ function hubUrl(list2, start) {
4873
+ return peopleSearchUrl({
4874
+ params: {},
4875
+ start,
4876
+ kind: HUB[list2],
4877
+ origin: "CurationHub",
4878
+ intent: "MYNETWORK_CURATION_HUB"
4879
+ });
4880
+ }
4881
+ var HUB_PAGE = PEOPLE_PAGE;
4882
+ function parseHub(list2, json) {
4883
+ if (PEOPLE_LISTS.has(list2)) {
4884
+ const r2 = parsePeople(json);
4885
+ if (!r2.ok) return r2;
4886
+ return {
4887
+ ok: true,
4888
+ items: r2.people,
4889
+ ...r2.total !== void 0 ? { total: r2.total } : {},
4890
+ unknownTypes: r2.unknownTypes
4891
+ };
4892
+ }
4893
+ const r = parseResults(json);
4894
+ if (!r.ok) return r;
4895
+ return {
4896
+ ok: true,
4897
+ items: r.items,
4898
+ ...r.total !== void 0 ? { total: r.total } : {},
4899
+ unknownTypes: r.unknownTypes
4900
+ };
4901
+ }
4902
+ function sentInvitationsUrl(start, count2 = 10) {
4903
+ const c = CONTRACTS.sentInvitations;
4904
+ if (c === void 0) throw new Error("the 'sentInvitations' contract is missing");
4905
+ return `${c.path}?count=${count2}&invitationType=CONNECTION&q=invitationType&start=${start}`;
4906
+ }
4907
+ function parseSentInvitations(json) {
4908
+ const data = json?.data;
4909
+ const refs = data?.["*elements"] ?? data?.elements;
4910
+ if (!Array.isArray(refs))
4911
+ return { ok: false, code: "SCHEMA_DRIFT", message: "the sent invitations list was missing" };
4912
+ const included = json.included ?? [];
4913
+ const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4914
+ const invitations2 = [];
4915
+ for (const ref of refs) {
4916
+ const view = byUrn.get(ref);
4917
+ const inv = byUrn.get(view?.["*invitation"]) ?? included.find(
4918
+ (n) => String(n.$type).endsWith(".Invitation") && typeof ref === "string" && ref.endsWith(String(n.entityUrn))
4919
+ );
4920
+ if (inv === void 0) continue;
4921
+ const who = byUrn.get(inv["*toMember"]);
4922
+ const name = [who?.firstName, who?.lastName].filter((x) => typeof x === "string" && x !== "").join(" ");
4923
+ const id = String(inv["*toMember"] ?? "").split(":").pop();
4924
+ const note = typeof inv.message === "string" ? inv.message : inv.message?.text;
4925
+ const out = { to: name !== "" ? name : "LinkedIn Member" };
4926
+ if (id) out.id = id;
4927
+ if (typeof who?.occupation === "string") out.headline = who.occupation;
4928
+ if (typeof who?.publicIdentifier === "string")
4929
+ out.url = `https://www.linkedin.com/in/${who.publicIdentifier}/`;
4930
+ if (typeof inv.sentTime === "number") out.sent = new Date(inv.sentTime).toISOString();
4931
+ if (typeof note === "string" && note.trim() !== "") out.note = note.trim();
4932
+ invitations2.push(out);
4933
+ }
4934
+ if (refs.length > 0 && invitations2.length === 0)
4935
+ return {
4936
+ ok: false,
4937
+ code: "SCHEMA_DRIFT",
4938
+ message: `${refs.length} invitations were listed but none were sent`
4939
+ };
4940
+ return { ok: true, invitations: invitations2 };
4941
+ }
4942
+
4943
+ // src/commands/network.ts
4944
+ function liveFetch3(quiet) {
4945
+ const session = loadSession();
4946
+ if (session.state !== "ok")
4947
+ return err("network", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
4948
+ const client = createLiveClient(session.session, void 0, quiet);
4949
+ return async (url, spendClass) => {
4950
+ const r = await client.request({ url, spendClass, operation: "network" });
4951
+ return r.ok ? { ok: true, json: r.json } : r;
4952
+ };
4953
+ }
4954
+ var LISTS = [...Object.keys(HUB), "invitations"];
4955
+ var PAGING3 = { pageSize: HUB_PAGE, max: 1e3 };
4956
+ var INVITATIONS_PAGE = 10;
4957
+ function compactRow(r) {
4958
+ const p = r;
4959
+ return line([p.id, p.name, p.headline ?? p.subtitle, p.location ?? p.detail, p.degree, p.url]);
4960
+ }
4961
+ async function counts(get) {
4962
+ const out = {};
4963
+ for (const list2 of Object.keys(HUB)) {
4964
+ const res2 = await get(hubUrl(list2, 0), "page");
4965
+ const page = res2.ok ? parseHub(list2, res2.json) : res2;
4966
+ if (!page.ok) return err("network", page.code, `${list2}: ${page.message}`, page.hint);
4967
+ out[list2] = page.total ?? page.items.length;
4968
+ }
4969
+ const res = await get(sentInvitationsUrl(0, INVITATIONS_PAGE), "page");
4970
+ const inv = res.ok ? parseSentInvitations(res.json) : res;
4971
+ if (!inv.ok) return err("network", inv.code, `invitations: ${inv.message}`);
4972
+ out.invitationsSent = inv.invitations.length;
4973
+ return { counts: out };
4974
+ }
4975
+ async function invitations(get, req, opts) {
4976
+ const all = [];
4977
+ let exhausted = false;
4978
+ let stoppedBy;
4979
+ for (let start = req.start ?? 0; all.length < req.limit; start += INVITATIONS_PAGE) {
4980
+ const res = await get(sentInvitationsUrl(start, INVITATIONS_PAGE), "page");
4981
+ const page = res.ok ? parseSentInvitations(res.json) : res;
4982
+ if (!page.ok) {
4983
+ if (all.length === 0) return err("network", page.code, page.message);
4984
+ stoppedBy = page.code;
4985
+ break;
4986
+ }
4987
+ all.push(...page.invitations.slice(0, req.limit - all.length));
4988
+ if (page.invitations.length < INVITATIONS_PAGE) {
4989
+ exhausted = true;
4990
+ break;
4991
+ }
4992
+ }
4993
+ return ok("network", {
4994
+ list: "invitations",
4995
+ items: shape2(
4996
+ all,
4997
+ opts,
4998
+ (i) => line([i.id, i.to, i.headline, i.sent?.slice(0, 10), i.note, i.url])
4999
+ ),
5000
+ meta: {
5001
+ state: exhausted && stoppedBy === void 0 ? "complete" : "partial",
5002
+ operation: "network invitations",
5003
+ returnedCount: all.length,
5004
+ ...stoppedBy !== void 0 ? { stoppedBy } : {}
5005
+ }
5006
+ });
5007
+ }
5008
+ async function runNetwork(list2, req, opts = {}, fetch2) {
5009
+ if (list2 !== void 0 && !LISTS.includes(list2)) {
5010
+ return err(
5011
+ "network",
5012
+ "INVALID_INPUT",
5013
+ `no list '${list2}'`,
5014
+ `one of: ${LISTS.join(", ")} \u2014 or none, for the counts`
5015
+ );
5016
+ }
5017
+ const get = fetch2 ?? liveFetch3(opts.quiet === true);
5018
+ if (typeof get !== "function") return get;
5019
+ if (list2 === void 0) {
5020
+ const c = await counts(get);
5021
+ if (!("counts" in c)) return c;
5022
+ return ok("network", { counts: c.counts, meta: { state: "complete", operation: "network" } });
5023
+ }
5024
+ if (list2 === "invitations") return invitations(get, req, opts);
5025
+ const hub = list2;
5026
+ const first = Math.max(0, req.start ?? 0);
5027
+ const fetchPage = async (_keywords, start) => {
5028
+ const res = await get(hubUrl(hub, start), "page");
5029
+ const page = res.ok ? parseHub(hub, res.json) : res;
5030
+ if (!page.ok) return page;
5031
+ return {
5032
+ ok: true,
5033
+ items: page.items,
5034
+ ...page.total !== void 0 ? { total: page.total } : {},
5035
+ unknownTypes: page.unknownTypes
5036
+ };
5037
+ };
5038
+ const merged = await searchAll(
5039
+ fetchPage,
5040
+ [void 0],
5041
+ first,
5042
+ Math.max(1, Math.min(req.limit, PAGING3.max - first)),
5043
+ PAGING3
5044
+ );
5045
+ if (merged.rows.length === 0 && merged.failure !== void 0) {
5046
+ const f = merged.failure;
5047
+ return err("network", f.code, f.message, f.hint);
5048
+ }
5049
+ return ok("network", {
5050
+ list: hub,
5051
+ items: shape2(merged.rows, opts, compactRow),
5052
+ meta: metaOf(`network ${hub}`, merged, true, first)
5053
+ });
5054
+ }
5055
+
5056
+ // src/commands/oauth.ts
5057
+ import { spawn } from "child_process";
5058
+ import { createServer } from "http";
5059
+ import { createInterface as createInterface2 } from "readline/promises";
5060
+
5061
+ // src/engine/oauth.ts
5062
+ var AUTHORIZE = "https://www.linkedin.com/oauth/v2/authorization";
5063
+ var TOKEN = "https://www.linkedin.com/oauth/v2/accessToken";
5064
+ var USERINFO = "https://api.linkedin.com/v2/userinfo";
5065
+ var CALLBACK_PORT = 53682;
5066
+ var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
5067
+ var SCOPES = ["openid", "profile", "w_member_social"];
5068
+ function authorizationUrl(clientId, state) {
5069
+ const params = new URLSearchParams({
5070
+ response_type: "code",
5071
+ client_id: clientId,
5072
+ redirect_uri: REDIRECT_URI,
5073
+ state,
5074
+ scope: SCOPES.join(" ")
5075
+ });
5076
+ return `${AUTHORIZE}?${params.toString()}`;
5077
+ }
5078
+ async function exchange(code, config, deps) {
5079
+ const body = new URLSearchParams({
5080
+ grant_type: "authorization_code",
5081
+ code,
5082
+ redirect_uri: REDIRECT_URI,
5083
+ client_id: config.clientId,
5084
+ client_secret: config.clientSecret
5085
+ });
5086
+ let res;
5087
+ try {
5088
+ res = await deps.fetch(TOKEN, {
5089
+ method: "POST",
5090
+ headers: { "content-type": "application/x-www-form-urlencoded" },
5091
+ body: body.toString()
5092
+ });
5093
+ } catch (e) {
5094
+ return { ok: false, message: `could not reach LinkedIn: ${e.message}` };
5095
+ }
5096
+ const text5 = await res.text();
5097
+ if (res.status !== 200) {
5098
+ return {
5099
+ ok: false,
5100
+ message: `LinkedIn rejected the code exchange (${res.status})`,
5101
+ // The most common causes, in the order they actually happen.
5102
+ hint: `Check that the app has BOTH products added, and that its Auth tab lists exactly ${REDIRECT_URI} as an authorized redirect URL. Response: ${text5.slice(0, 200)}`
5103
+ };
5104
+ }
5105
+ let parsed;
5106
+ try {
5107
+ parsed = JSON.parse(text5);
5108
+ } catch {
5109
+ return { ok: false, message: "token response was not JSON" };
5110
+ }
5111
+ const accessToken = parsed.access_token;
5112
+ const expiresIn = parsed.expires_in;
5113
+ if (typeof accessToken !== "string" || accessToken === "") {
5114
+ return { ok: false, message: "token response carried no access_token" };
5115
+ }
5116
+ const lifetimeMs = typeof expiresIn === "number" ? expiresIn * 1e3 : 60 * 864e5;
5117
+ return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };
5118
+ }
5119
+ async function fetchMemberUrn(accessToken, deps) {
5120
+ let res;
5121
+ try {
5122
+ res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });
5123
+ } catch (e) {
5124
+ return { ok: false, message: `could not reach userinfo: ${e.message}` };
5125
+ }
5126
+ if (res.status !== 200) {
5127
+ return {
5128
+ ok: false,
5129
+ message: `userinfo returned ${res.status} \u2014 the 'openid'/'profile' scopes may not be granted`
5130
+ };
5131
+ }
5132
+ const parsed = await res.json();
5133
+ if (typeof parsed.sub !== "string" || parsed.sub === "") {
5134
+ return { ok: false, message: "userinfo carried no subject claim" };
5135
+ }
5136
+ return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };
5137
+ }
5138
+ function parseCallback(rawUrl, expectedState) {
5139
+ let url;
5140
+ try {
5141
+ url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);
5142
+ } catch {
5143
+ return { ok: false, message: "callback URL was unparseable" };
5144
+ }
5145
+ const error = url.searchParams.get("error");
5146
+ if (error !== null) {
5147
+ const description = url.searchParams.get("error_description") ?? "";
5148
+ return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
5149
+ }
5150
+ const state = url.searchParams.get("state");
5151
+ if (state !== expectedState) {
5152
+ return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
5153
+ }
5154
+ const code = url.searchParams.get("code");
5155
+ if (code === null || code === "") return { ok: false, message: "callback carried no code" };
5156
+ return { ok: true, code };
5157
+ }
5158
+
5159
+ // src/commands/token.ts
5160
+ import { existsSync as existsSync3, rmSync } from "fs";
5161
+ var TOKEN_FILE = "oauth.json";
5162
+ var OAUTH_SETUP = [
5163
+ "Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one",
5164
+ "legitimacy wedge an individual actually has \u2014 but the app has to be registered by you; it",
5165
+ "cannot be created on your behalf.",
5166
+ "",
5167
+ " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
5168
+ ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
5169
+ " Both are self-serve: no partner review, no verification, no screencast.",
5170
+ ` 3. Auth tab \u2192 add redirect URL ${REDIRECT_URI}`,
5171
+ " 4. Run: lnrelay oauth login --client-id <id>",
5172
+ " (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)"
5173
+ ].join("\n");
5174
+ function tokenPath() {
5175
+ return cachePath(TOKEN_FILE);
5176
+ }
5177
+ function loadToken() {
5178
+ const result = loadJson(tokenPath());
5179
+ return result.state === "ok" ? result.value : null;
5180
+ }
5181
+ function saveToken(token) {
5182
+ saveJson(tokenPath(), token);
5183
+ }
5184
+ function deleteToken() {
5185
+ const path = tokenPath();
5186
+ if (!existsSync3(path)) return false;
5187
+ rmSync(path, { force: true });
5188
+ return true;
5189
+ }
5190
+
5191
+ // src/commands/oauth.ts
5192
+ var CALLBACK_TIMEOUT_MS = 3e5;
5193
+ var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
5194
+ <body style="font:16px system-ui;padding:3rem;max-width:32rem">
5195
+ <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
5196
+ function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
5197
+ return new Promise((ready) => {
5198
+ let settle = () => {
5199
+ };
5200
+ const code = new Promise((r) => {
5201
+ settle = r;
5202
+ });
5203
+ const server = createServer((req, res) => {
5204
+ const url = req.url ?? "/";
5205
+ if (!url.startsWith("/callback")) {
5206
+ res.writeHead(404, { connection: "close" });
5207
+ res.end();
5208
+ return;
5209
+ }
5210
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
5211
+ res.end(DONE_PAGE);
5212
+ settle(parseCallback(url, state));
5213
+ });
5214
+ const timer = setTimeout(() => {
5215
+ settle({
5216
+ ok: false,
5217
+ message: `timed out after ${Math.round(timeoutMs / 1e3)}s waiting for the LinkedIn callback`
5218
+ });
5219
+ }, timeoutMs);
5220
+ timer.unref?.();
5221
+ const close = () => {
5222
+ clearTimeout(timer);
5223
+ server.closeAllConnections?.();
5224
+ server.close();
5225
+ };
5226
+ server.once("error", (e) => {
5227
+ clearTimeout(timer);
5228
+ const why = e.code === "EADDRINUSE" ? `port ${CALLBACK_PORT} is already in use \u2014 close whatever holds it and retry` : `could not open the callback listener: ${e.message}`;
5229
+ ready({ ok: false, message: why });
5230
+ });
5231
+ server.listen(CALLBACK_PORT, "127.0.0.1", () => {
5232
+ ready({ ok: true, code, close });
5233
+ });
5234
+ });
5235
+ }
5236
+ function openBrowser(url) {
5237
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
5238
+ try {
5239
+ spawn(cmd, [url], { detached: true, stdio: "ignore" }).unref();
5240
+ } catch {
5241
+ }
5242
+ }
5243
+ function loginDeps() {
5244
+ return {
5245
+ state: () => crypto.randomUUID(),
5246
+ listen: (state) => listenForCallback(state),
5247
+ open: openBrowser,
5248
+ write: (s) => process.stderr.write(s),
5249
+ isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
5250
+ prompt: async (question) => {
5251
+ const rl = createInterface2({ input: process.stdin, output: process.stderr });
5252
+ const answer = await rl.question(question);
5253
+ rl.close();
5254
+ return answer;
5255
+ },
5256
+ now: Date.now,
5257
+ fetch: globalThis.fetch
5258
+ };
5259
+ }
5260
+ async function credentials(opts, deps) {
5261
+ const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;
5262
+ if (clientId === void 0 || clientId === "") {
5263
+ return err("oauth", "INVALID_INPUT", "a client id is required", OAUTH_SETUP);
5264
+ }
5265
+ let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;
5266
+ if ((clientSecret === void 0 || clientSecret === "") && deps.isTty) {
5267
+ clientSecret = (await deps.prompt("client secret (not echoed to argv or logs): ")).trim();
5268
+ }
5269
+ if (clientSecret === void 0 || clientSecret === "") {
4596
5270
  return err(
4597
- "people-filters",
5271
+ "oauth",
4598
5272
  "INVALID_INPUT",
4599
- "people-filters takes one keyword set: its counts belong to that one query",
4600
- 'lnrelay people-filters "<keywords>" [filters]'
5273
+ "a client secret is required, and there is no terminal to ask on",
5274
+ `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.
5275
+
5276
+ ${OAUTH_SETUP}`
4601
5277
  );
4602
5278
  }
4603
- const get = fetch2 ?? liveFetch2("people-filters", opts.quiet === true);
4604
- if (typeof get !== "function") return get;
4605
- const names = await resolveNames(get, req);
4606
- if ("ok" in names) return err("people-filters", names.code, names.message, names.hint);
4607
- const selection3 = peopleFilterSelection(names.filter);
4608
- if (!selection3.ok) return err("people-filters", selection3.code, selection3.message);
4609
- const url = peopleSearchUrl({
4610
- ...sets[0] !== void 0 ? { keywords: sets[0] } : {},
4611
- params: selection3.params,
4612
- start: 0,
4613
- withFilters: true
5279
+ return { clientId, clientSecret };
5280
+ }
5281
+ async function runOauthLogin(opts, deps = loginDeps()) {
5282
+ const creds = await credentials(opts, deps);
5283
+ if ("ok" in creds) return creds;
5284
+ const state = deps.state();
5285
+ const listener = await deps.listen(state);
5286
+ if (!listener.ok) {
5287
+ return err("oauth", "AUTH_FAILED", listener.message);
5288
+ }
5289
+ try {
5290
+ const url = authorizationUrl(creds.clientId, state);
5291
+ deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
5292
+
5293
+ ${url}
5294
+
5295
+ `);
5296
+ deps.open(url);
5297
+ const callback = await listener.code;
5298
+ if (!callback.ok) return err("oauth", "AUTH_FAILED", callback.message);
5299
+ const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });
5300
+ if (!token.ok) return err("oauth", "AUTH_FAILED", token.message, token.hint);
5301
+ const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });
5302
+ if (!member.ok) return err("oauth", "AUTH_FAILED", member.message, OAUTH_SETUP);
5303
+ saveToken({
5304
+ accessToken: token.accessToken,
5305
+ memberUrn: member.memberUrn,
5306
+ expiresAt: token.expiresAt
5307
+ });
5308
+ return ok("oauth", {
5309
+ memberUrn: member.memberUrn,
5310
+ scopes: SCOPES,
5311
+ expiresAt: new Date(token.expiresAt).toISOString(),
5312
+ storedAt: tokenPath(),
5313
+ // Refresh tokens are partner-gated, so renewal is re-running this.
5314
+ renewal: "run `lnrelay oauth login` again when it expires"
5315
+ });
5316
+ } finally {
5317
+ listener.close();
5318
+ }
5319
+ }
5320
+ function runOauthLogout() {
5321
+ const removed = deleteToken();
5322
+ return ok("oauth", {
5323
+ removed,
5324
+ note: removed ? `deleted ${tokenPath()} \u2014 the token stays valid on LinkedIn's side until it expires` : "no token was stored"
4614
5325
  });
4615
- const res = await get(url, "search");
4616
- const parsed = res.ok ? parsePeopleFilters(res.json) : res;
4617
- if (!parsed.ok) return err("people-filters", parsed.code, parsed.message, parsed.hint);
4618
- return ok("people-filters", {
4619
- ...Object.keys(names.resolved).length > 0 ? { resolved: names.resolved } : {},
4620
- items: shape2(parsed.filters, opts, (f) => {
4621
- const how = f.input === "text" ? "free text" : BY_NAME[f.key] ?? "ids";
4622
- const options = f.options.map((o) => `${o.value}=${o.label}${o.count !== void 0 ? ` (${o.count})` : ""}`).join(", ");
4623
- return `${f.key} [${how}]${options !== "" ? `: ${options}` : ""}`;
4624
- }),
4625
- meta: { state: "complete", operation: "people-filters", returnedCount: parsed.filters.length }
5326
+ }
5327
+ function runOauthStatus() {
5328
+ const token = loadToken();
5329
+ if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
5330
+ return ok("oauth", {
5331
+ memberUrn: token.memberUrn,
5332
+ expiresAt: new Date(token.expiresAt).toISOString(),
5333
+ expired: token.expiresAt <= Date.now(),
5334
+ scopes: SCOPES,
5335
+ storedAt: tokenPath(),
5336
+ writeCap: CAPS.write.perDay
4626
5337
  });
4627
5338
  }
4628
5339
 
@@ -5036,7 +5747,7 @@ function parsePosts(stream) {
5036
5747
  }
5037
5748
 
5038
5749
  // src/commands/posts-search.ts
5039
- function liveFetch3(quiet) {
5750
+ function liveFetch4(quiet) {
5040
5751
  const session = loadSession();
5041
5752
  if (session.state !== "ok")
5042
5753
  return err("search posts", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
@@ -5052,7 +5763,7 @@ function liveFetch3(quiet) {
5052
5763
  return { ok: true, raw: r.classification.raw ?? "", json: r.json };
5053
5764
  };
5054
5765
  }
5055
- var PAGING3 = { pageSize: POSTS_PAGE, max: 1e3 };
5766
+ var PAGING4 = { pageSize: POSTS_PAGE, max: 1e3 };
5056
5767
  var CHOICES = {
5057
5768
  sort: { param: "sortBy", values: { recent: "date_posted", relevant: "relevance" } },
5058
5769
  posted: {
@@ -5163,7 +5874,7 @@ async function filtersOf(req, get) {
5163
5874
  return { filters, resolved };
5164
5875
  }
5165
5876
  function compactPost(p) {
5166
- const counts = [
5877
+ const counts2 = [
5167
5878
  p.reactions !== void 0 ? `${p.reactions} reactions` : void 0,
5168
5879
  p.comments !== void 0 ? `${p.comments} comments` : void 0,
5169
5880
  p.reposts !== void 0 ? `${p.reposts} reposts` : void 0
@@ -5173,7 +5884,7 @@ function compactPost(p) {
5173
5884
  p.id,
5174
5885
  p.author,
5175
5886
  p.posted,
5176
- counts.length > 0 ? counts.join(" \xB7 ") : void 0,
5887
+ counts2.length > 0 ? counts2.join(" \xB7 ") : void 0,
5177
5888
  text5 !== void 0 && text5.length > 160 ? `${text5.slice(0, 157)}\u2026` : text5,
5178
5889
  p.url,
5179
5890
  p.matched !== void 0 ? `matched: ${p.matched.join(" + ")}` : void 0
@@ -5192,12 +5903,12 @@ async function runPostsSearch(req, opts = {}, fetch2) {
5192
5903
  "give keywords, a filter, or both",
5193
5904
  'lnrelay search posts "<keywords>"'
5194
5905
  );
5195
- const get = fetch2 ?? liveFetch3(opts.quiet === true);
5906
+ const get = fetch2 ?? liveFetch4(opts.quiet === true);
5196
5907
  if (typeof get !== "function") return get;
5197
5908
  const f = await filtersOf(req, get);
5198
5909
  if ("ok" in f) return err(command, f.code, f.message, f.hint);
5199
5910
  const first = Math.max(0, req.start ?? 0);
5200
- const want = Math.max(1, Math.min(req.limit, PAGING3.max - first));
5911
+ const want = Math.max(1, Math.min(req.limit, PAGING4.max - first));
5201
5912
  const fetchPage = async (keywords, start) => {
5202
5913
  const body = postsPagerBody({ ...keywords ? { keywords } : {}, filters: f.filters, start });
5203
5914
  const res = await get(POSTS_URL, body, "search");
@@ -5218,7 +5929,7 @@ async function runPostsSearch(req, opts = {}, fetch2) {
5218
5929
  sets.length > 0 ? sets : [void 0],
5219
5930
  first,
5220
5931
  want,
5221
- PAGING3
5932
+ PAGING4
5222
5933
  );
5223
5934
  if (merged.rows.length === 0 && merged.failure !== void 0) {
5224
5935
  const fail2 = merged.failure;
@@ -5423,6 +6134,51 @@ var COMMANDS = [
5423
6134
  risk: "read",
5424
6135
  implemented: true
5425
6136
  },
6137
+ {
6138
+ name: "network",
6139
+ cost: "1 page call per 50 rows; the counts are 7 calls",
6140
+ summary: "Your My Network: connections, people you follow, followers, pages, events, groups, and invitations you sent. With no list, the count of each. Read only.",
6141
+ usage: "lnrelay network [connections|following|followers|pages|events|groups|invitations]\n [--limit N] [--start N] [--compact | --fields a,b,c]",
6142
+ audience: ["cli", "mcp"],
6143
+ risk: "read",
6144
+ implemented: true
6145
+ },
6146
+ {
6147
+ name: "inbox",
6148
+ cost: "1 page call per 20 conversations",
6149
+ summary: "Your conversations in a folder: who with, unread, last message. Reads only: nothing is marked read or seen, and nothing read is stored.",
6150
+ usage: "lnrelay inbox [--folder inbox|primary|other|archive|requests|spam] [--unread] [--limit N]\n [--compact | --fields a,b,c]",
6151
+ audience: ["cli", "mcp"],
6152
+ risk: "read",
6153
+ implemented: true
6154
+ },
6155
+ {
6156
+ name: "messages",
6157
+ cost: "1 page call",
6158
+ summary: "A conversation's latest messages, oldest first, saying which are yours. Reading does not mark it read.",
6159
+ usage: "lnrelay messages <conversation-id|thread-url> [--compact | --fields a,b,c]",
6160
+ audience: ["cli", "mcp"],
6161
+ risk: "read",
6162
+ implemented: true
6163
+ },
6164
+ {
6165
+ name: "draft",
6166
+ cost: "1 page call to check the conversation; the draft stays on this machine",
6167
+ summary: "Draft a reply, saved locally with the conversation link for you to review and send. Nothing is sent: this tool cannot send a message.",
6168
+ usage: 'lnrelay draft <conversation-id|thread-url> ("<text>" | --file <path>)\n lnrelay draft remove <draft-id>',
6169
+ audience: ["cli", "mcp"],
6170
+ risk: "local",
6171
+ implemented: true
6172
+ },
6173
+ {
6174
+ name: "drafts",
6175
+ cost: "free \u2014 local",
6176
+ summary: "Your saved reply drafts, with the link to each conversation.",
6177
+ usage: "lnrelay drafts [--compact]",
6178
+ audience: ["cli", "mcp"],
6179
+ risk: "local",
6180
+ implemented: true
6181
+ },
5426
6182
  {
5427
6183
  name: "scheduled",
5428
6184
  cost: "1 call per 10 posts",
@@ -5605,7 +6361,7 @@ var PROFILE_FIELDS = {
5605
6361
  maxLength: 2600
5606
6362
  }
5607
6363
  };
5608
- var drift4 = (message) => ({
6364
+ var drift6 = (message) => ({
5609
6365
  ok: false,
5610
6366
  code: "SCHEMA_DRIFT",
5611
6367
  message,
@@ -5613,10 +6369,10 @@ var drift4 = (message) => ({
5613
6369
  });
5614
6370
  function readForm(stream, field) {
5615
6371
  const states2 = readModel(stream);
5616
- if (states2 === null) return drift4("the profile form carried no initial values");
6372
+ if (states2 === null) return drift6("the profile form carried no initial values");
5617
6373
  const args = findRequest(stream, field.save);
5618
6374
  if (args === null)
5619
- return drift4(`the profile form carried no ${field.save.split(".").pop()} action`);
6375
+ return drift6(`the profile form carried no ${field.save.split(".").pop()} action`);
5620
6376
  return { ok: true, args, states: states2, screen: field.screen, save: field.save };
5621
6377
  }
5622
6378
  function boundKey(form, property) {
@@ -5632,7 +6388,7 @@ function topSkills(form) {
5632
6388
  return (key) => {
5633
6389
  if (!key.endsWith("ReorderableSkillsFormBindingsskillIdsBinding")) return void 0;
5634
6390
  const initial = [...form.states.entries()].find(([k]) => k.startsWith("initialSkills"))?.[1];
5635
- if (initial === void 0) return drift4("the About form carried no initial top skills");
6391
+ if (initial === void 0) return drift6("the About form carried no initial top skills");
5636
6392
  if (!Array.isArray(initial.value) || initial.value.length > 0) {
5637
6393
  return {
5638
6394
  ok: false,
@@ -5655,7 +6411,7 @@ function saveBody(form, field, value) {
5655
6411
  const target = boundKey(form, field.binding);
5656
6412
  const current = target === void 0 ? void 0 : form.states.get(target);
5657
6413
  if (target === void 0 || current === void 0) {
5658
- return drift4(`the profile form has no ${field.name} field`);
6414
+ return drift6(`the profile form has no ${field.name} field`);
5659
6415
  }
5660
6416
  const model = new Map(form.states);
5661
6417
  model.set(target, { ...current, value });
@@ -5724,7 +6480,7 @@ var POSITION = {
5724
6480
  var EDIT_NAV = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${POSITION.editScreen}"`;
5725
6481
  function listPositions(stream) {
5726
6482
  if (readModel(stream) === null && !stream.includes(EDIT_NAV) && !stream.includes('"rows"')) {
5727
- return drift4("the Experience screen could not be read");
6483
+ return drift6("the Experience screen could not be read");
5728
6484
  }
5729
6485
  const positions = [];
5730
6486
  const seen = /* @__PURE__ */ new Set();
@@ -5742,17 +6498,17 @@ function listPositions(stream) {
5742
6498
  positions.push({ positionId: id, title: String(payload.title ?? ""), payload });
5743
6499
  }
5744
6500
  if (positions.length === 0 && !stream.includes('"rows"') && !stream.includes("Experience")) {
5745
- return drift4("the Experience screen listed no roles and did not look like one");
6501
+ return drift6("the Experience screen listed no roles and did not look like one");
5746
6502
  }
5747
6503
  return { ok: true, positions };
5748
6504
  }
5749
6505
  function readPositionForm(stream) {
5750
6506
  const model = readModel(stream);
5751
- if (model === null) return drift4("the position form carried no initial values");
6507
+ if (model === null) return drift6("the position form carried no initial values");
5752
6508
  const media = findRequest(stream, POSITION.media);
5753
6509
  const prefix = media?.payload.formIdPrefix;
5754
6510
  if (media === null || typeof prefix !== "string") {
5755
- return drift4("the position form carried no save step (uploadPositionMedia)");
6511
+ return drift6("the position form carried no save step (uploadPositionMedia)");
5756
6512
  }
5757
6513
  const del = findRequest(stream, POSITION.delete);
5758
6514
  return {
@@ -5803,7 +6559,7 @@ function applyChanges(form, changes) {
5803
6559
  }
5804
6560
  need("dynamicallyCreateHeadline", false);
5805
6561
  need("allowProfileEditBroadcasts", changes.notify === true);
5806
- if (missing.length > 0) return drift4(`the position form has no ${missing.join(", ")} field`);
6562
+ if (missing.length > 0) return drift6(`the position form has no ${missing.join(", ")} field`);
5807
6563
  const s = roleSummary(model);
5808
6564
  if (!s.current && s.start !== null && s.end !== null && s.end < s.start) {
5809
6565
  return {
@@ -5848,7 +6604,7 @@ function mediaBody(form, model) {
5848
6604
  }
5849
6605
  function saveFromReply(reply) {
5850
6606
  const args = findRequest(reply, POSITION.save);
5851
- return args === null ? drift4("the media step did not hand back the save action") : { ok: true, args };
6607
+ return args === null ? drift6("the media step did not hand back the save action") : { ok: true, args };
5852
6608
  }
5853
6609
  function positionSaveBody(save, model, screen) {
5854
6610
  const sending = new Map(model);
@@ -5860,7 +6616,7 @@ function positionSaveBody(save, model, screen) {
5860
6616
  }
5861
6617
  function deleteBody(form) {
5862
6618
  if (form.del === null)
5863
- return drift4("this form has no delete action (it is not an existing role)");
6619
+ return drift6("this form has no delete action (it is not an existing role)");
5864
6620
  const states2 = wireStates(keysOf(form.del), form.model, resolver);
5865
6621
  if (!Array.isArray(states2)) return states2;
5866
6622
  return { ok: true, body: requestBody(POSITION.delete, form.del, states2, form.screen) };
@@ -5903,7 +6659,7 @@ async function sendPositionDelete(form, client) {
5903
6659
  }
5904
6660
 
5905
6661
  // src/commands/write.ts
5906
- import { readFileSync as readFileSync2, statSync } from "fs";
6662
+ import { readFileSync as readFileSync3, statSync } from "fs";
5907
6663
  import { basename } from "path";
5908
6664
 
5909
6665
  // src/engine/oauth-write.ts
@@ -6449,7 +7205,7 @@ function loadMedia(flag, path) {
6449
7205
  let bytes;
6450
7206
  try {
6451
7207
  if (!statSync(path).isFile()) throw new Error("not a file");
6452
- bytes = new Uint8Array(readFileSync2(path));
7208
+ bytes = new Uint8Array(readFileSync3(path));
6453
7209
  } catch {
6454
7210
  return err("share", "INVALID_INPUT", `cannot read ${path}`);
6455
7211
  }
@@ -6465,8 +7221,8 @@ function loadMedia(flag, path) {
6465
7221
  };
6466
7222
  }
6467
7223
  function parseScheduleTime(input) {
6468
- const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
6469
- if (iso.test(input)) {
7224
+ const iso2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
7225
+ if (iso2.test(input)) {
6470
7226
  const t = Date.parse(input);
6471
7227
  return Number.isNaN(t) ? null : t;
6472
7228
  }
@@ -7243,93 +7999,8 @@ async function runExperience(quiet = false) {
7243
7999
  });
7244
8000
  }
7245
8001
 
7246
- // src/engine/search.ts
7247
- var SEARCH_KINDS = {
7248
- companies: "COMPANIES",
7249
- groups: "GROUPS",
7250
- events: "EVENTS",
7251
- courses: "LEARNING",
7252
- products: "PRODUCTS",
7253
- services: "SERVICES",
7254
- schools: "SCHOOLS"
7255
- };
7256
- var SEARCH_PAGE = PEOPLE_PAGE;
7257
- function searchUrl(q2) {
7258
- return peopleSearchUrl({
7259
- ...q2.keywords !== void 0 ? { keywords: q2.keywords } : {},
7260
- params: q2.params,
7261
- start: q2.start,
7262
- ...q2.withFilters === true ? { withFilters: true } : {},
7263
- kind: SEARCH_KINDS[q2.kind]
7264
- });
7265
- }
7266
- var text4 = (v) => {
7267
- const t = v?.text;
7268
- return typeof t === "string" && t.trim() !== "" ? t.trim().replace(/\s+/g, " ") : void 0;
7269
- };
7270
- function idOf(entityUrn) {
7271
- const inner = String(entityUrn ?? "").match(/\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];
7272
- return inner?.split(":").pop();
7273
- }
7274
- function cleanUrl2(nav) {
7275
- if (typeof nav !== "string" || !nav.startsWith("https://")) return void 0;
7276
- return nav.split("?")[0];
7277
- }
7278
- function rowToFound(row) {
7279
- const id = idOf(row.entityUrn);
7280
- const name = text4(row.title);
7281
- if (id === void 0 || name === void 0) return void 0;
7282
- const found = { id, name };
7283
- const fields = [
7284
- ["subtitle", text4(row.primarySubtitle)],
7285
- ["detail", text4(row.secondarySubtitle)],
7286
- ["summary", text4(row.summary)],
7287
- ["url", cleanUrl2(row.navigationUrl)]
7288
- ];
7289
- for (const [k, v] of fields)
7290
- if (v !== void 0) found[k] = v;
7291
- if (JSON.stringify(row.badgeIcon ?? null).includes("VERIFIED")) found.verified = true;
7292
- return found;
7293
- }
7294
- var drift5 = (message) => ({
7295
- ok: false,
7296
- code: "SCHEMA_DRIFT",
7297
- message,
7298
- hint: "the search response changed shape; re-capture it"
7299
- });
7300
- function parseResults(json) {
7301
- const c = clustersOf(json);
7302
- if (c === void 0 || !Array.isArray(c.elements))
7303
- return drift5("the search returned no result list");
7304
- const included = json.included ?? [];
7305
- const { people: items, unknownTypes, excluded, unresolved } = readItems(c, included, rowToFound);
7306
- const total = typeof c.paging?.total === "number" ? c.paging.total : void 0;
7307
- const start = typeof c.paging?.start === "number" ? c.paging.start : 0;
7308
- const claimedRaw = c.metadata?.totalResultCount;
7309
- const claimed = typeof claimedRaw === "number" ? claimedRaw : total;
7310
- if (unresolved > 0 && items.length === 0)
7311
- return drift5(`${unresolved} results were listed but none could be read`);
7312
- if (items.length === 0 && total !== void 0 && total > start) {
7313
- return {
7314
- ok: false,
7315
- code: "SCHEMA_DRIFT",
7316
- message: `LinkedIn claims ${total} results but returned none from ${start}`,
7317
- hint: 'a failed fetch, not an empty search; do not report "none"'
7318
- };
7319
- }
7320
- return {
7321
- ok: true,
7322
- items,
7323
- ...total !== void 0 ? { total } : {},
7324
- ...claimed !== void 0 ? { claimed } : {},
7325
- start,
7326
- excluded,
7327
- unknownTypes
7328
- };
7329
- }
7330
-
7331
8002
  // src/commands/search-kinds.ts
7332
- var PAGING4 = { pageSize: SEARCH_PAGE, max: 1e3 };
8003
+ var PAGING5 = { pageSize: SEARCH_PAGE, max: 1e3 };
7333
8004
  var FLAGS = {
7334
8005
  location: { companies: "companyHqGeo", services: "geoUrn" },
7335
8006
  industry: { companies: "industryCompanyVertical" },
@@ -7418,7 +8089,7 @@ async function runFind(kind, req, opts = {}, fetch2) {
7418
8089
  const p = await paramsOf(kind, req, get);
7419
8090
  if ("ok" in p) return err(command, p.code, p.message, p.hint);
7420
8091
  const first = Math.max(0, req.start ?? 0);
7421
- const want = Math.max(1, Math.min(req.limit, PAGING4.max - first));
8092
+ const want = Math.max(1, Math.min(req.limit, PAGING5.max - first));
7422
8093
  const fetchPage = async (keywords, start) => {
7423
8094
  const res = await get(
7424
8095
  searchUrl({ kind, ...keywords ? { keywords } : {}, params: p.params, start }),
@@ -7439,7 +8110,7 @@ async function runFind(kind, req, opts = {}, fetch2) {
7439
8110
  sets.length > 0 ? sets : [void 0],
7440
8111
  first,
7441
8112
  want,
7442
- PAGING4
8113
+ PAGING5
7443
8114
  );
7444
8115
  if (merged.rows.length === 0 && merged.failure !== void 0) {
7445
8116
  const f = merged.failure;
@@ -7504,7 +8175,7 @@ var EDIT_NAV2 = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":
7504
8175
  var TEXT2 = /"children":\["((?:[^"\\]|\\.)*)"\]/g;
7505
8176
  function skillsFromPage(stream) {
7506
8177
  if (!stream.includes(SKILL.pager) && !stream.includes(EDIT_NAV2) && !stream.includes("isPartialPage")) {
7507
- return drift4("the skills page could not be read");
8178
+ return drift6("the skills page could not be read");
7508
8179
  }
7509
8180
  const skills = [];
7510
8181
  let from = 0;
@@ -7548,11 +8219,11 @@ function pagerFrom(payload, start) {
7548
8219
  }
7549
8220
  function readSkillForm(stream) {
7550
8221
  const model = readModel(stream);
7551
- if (model === null) return drift4("the skill form carried no initial values");
8222
+ if (model === null) return drift6("the skill form carried no initial values");
7552
8223
  const save = findRequest(stream, SKILL.save);
7553
8224
  const del = findRequest(stream, SKILL.delete);
7554
8225
  if (save === null && del === null)
7555
- return drift4("the skill form carried neither a save nor a delete");
8226
+ return drift6("the skill form carried neither a save nor a delete");
7556
8227
  return { ok: true, model, save, del, screen: del === null ? SKILL.addScreen : SKILL.editScreen };
7557
8228
  }
7558
8229
  var nameKey = (model) => [...model.keys()].find((k) => k.startsWith("addSkillsTypeaheadSkillName"));
@@ -7564,10 +8235,10 @@ function skillNameOf(form) {
7564
8235
  function addSkillBody(form, name) {
7565
8236
  if (name.trim() === "")
7566
8237
  return { ok: false, code: "INVALID_INPUT", message: "a skill needs a name" };
7567
- if (form.save === null) return drift4("this form has no save action (it is not the add form)");
8238
+ if (form.save === null) return drift6("this form has no save action (it is not the add form)");
7568
8239
  const key = nameKey(form.model);
7569
8240
  const current = key === void 0 ? void 0 : form.model.get(key);
7570
- if (key === void 0 || current === void 0) return drift4("the skill form has no name field");
8241
+ if (key === void 0 || current === void 0) return drift6("the skill form has no name field");
7571
8242
  const model = new Map(form.model);
7572
8243
  model.set(key, { ...current, value: name.trim() });
7573
8244
  const states2 = wireStates(keysOf(form.save), model, () => void 0);
@@ -7576,7 +8247,7 @@ function addSkillBody(form, name) {
7576
8247
  }
7577
8248
  function removeSkillBody(form) {
7578
8249
  if (form.del === null)
7579
- return drift4("this form has no delete action (it is not an existing skill)");
8250
+ return drift6("this form has no delete action (it is not an existing skill)");
7580
8251
  const states2 = wireStates(keysOf(form.del), form.model, () => void 0);
7581
8252
  if (!Array.isArray(states2)) return states2;
7582
8253
  return { ok: true, body: requestBody(SKILL.delete, form.del, states2, form.screen) };
@@ -7594,7 +8265,7 @@ async function fetchSkills(vanityName, client) {
7594
8265
  const at = screen.indexOf('"filter":"ProfileSkillCategory_ALL"');
7595
8266
  const open = at === -1 ? -1 : screen.lastIndexOf('"payload":{', at);
7596
8267
  const text5 = open === -1 ? null : balanced(screen, open + '"payload":'.length);
7597
- if (text5 === null) return drift4("the Skills screen carried no list request");
8268
+ if (text5 === null) return drift6("the Skills screen carried no list request");
7598
8269
  const payload = JSON.parse(text5);
7599
8270
  const count2 = typeof payload.count === "number" ? payload.count : 10;
7600
8271
  const skills = [];
@@ -8107,6 +8778,26 @@ function search2(args, filtersOnly) {
8107
8778
  }
8108
8779
  return filtersOnly ? runFindFilters(kind, findRequest2(args), opts) : runFind(kind, findRequest2(args), opts);
8109
8780
  }
8781
+ function messaging(command, args) {
8782
+ if (command === "inbox")
8783
+ return runInbox(
8784
+ {
8785
+ folder: str(args, "folder") ?? "inbox",
8786
+ limit: num(args, "limit") ?? 20,
8787
+ ...bool(args, "unread") ? { unread: true } : {}
8788
+ },
8789
+ output(args)
8790
+ );
8791
+ if (command === "messages") return runMessages(args.positionals[0], output(args));
8792
+ if (command === "drafts") return runDrafts(output(args));
8793
+ if (args.positionals[0] === "remove") return runDraftRemove(args.positionals[1]);
8794
+ return runDraft(
8795
+ args.positionals[0],
8796
+ draftText(args.positionals[1], str(args, "file")),
8797
+ void 0,
8798
+ output(args)
8799
+ );
8800
+ }
8110
8801
  function via(args) {
8111
8802
  const value = str(args, "via");
8112
8803
  if (value === void 0) return void 0;
@@ -8227,6 +8918,20 @@ async function dispatch(argv, now) {
8227
8918
  return runPeople(peopleRequest(args), output(args));
8228
8919
  case "people-filters":
8229
8920
  return runPeopleFilters(peopleRequest(args), output(args));
8921
+ case "network":
8922
+ return runNetwork(
8923
+ args.positionals[0],
8924
+ {
8925
+ limit: num(args, "limit") ?? 50,
8926
+ ...num(args, "start") !== void 0 ? { start: num(args, "start") } : {}
8927
+ },
8928
+ output(args)
8929
+ );
8930
+ case "inbox":
8931
+ case "messages":
8932
+ case "draft":
8933
+ case "drafts":
8934
+ return messaging(command, args);
8230
8935
  case "search":
8231
8936
  return search2(args, false);
8232
8937
  case "search-filters":
@@ -8283,7 +8988,7 @@ function edit(args, now, deps) {
8283
8988
  }
8284
8989
  let text5;
8285
8990
  try {
8286
- text5 = readFileSync3(file, "utf-8").replace(/\n$/, "");
8991
+ text5 = readFileSync4(file, "utf-8").replace(/\n$/, "");
8287
8992
  } catch {
8288
8993
  return err("edit", "INVALID_INPUT", `cannot read ${file}`);
8289
8994
  }
@@ -8314,7 +9019,7 @@ function role(args, now, deps) {
8314
9019
  return err("role", "INVALID_INPUT", "pass --description or --description-file, not both");
8315
9020
  }
8316
9021
  try {
8317
- req.description = readFileSync3(file, "utf-8").replace(/\n$/, "");
9022
+ req.description = readFileSync4(file, "utf-8").replace(/\n$/, "");
8318
9023
  } catch {
8319
9024
  return err("role", "INVALID_INPUT", `cannot read ${file}`);
8320
9025
  }