linkedin-relay-mcp 3.13.0 → 3.15.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) {
@@ -1401,6 +1401,24 @@ 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
+ },
1404
1422
  jobCards: {
1405
1423
  name: "jobCards",
1406
1424
  transport: "voyager-restli",
@@ -1674,10 +1692,10 @@ function createEngine(session, deps, quiet = false) {
1674
1692
  const client = createLiveClient(session, deps, quiet);
1675
1693
  return {
1676
1694
  async whoami() {
1677
- const contract2 = contractFor("me");
1678
- if (contract2 === void 0) return missingContract("me");
1695
+ const contract3 = contractFor("me");
1696
+ if (contract3 === void 0) return missingContract("me");
1679
1697
  const res = await client.request({
1680
- url: contract2.path,
1698
+ url: contract3.path,
1681
1699
  spendClass: "profile",
1682
1700
  operation: "me"
1683
1701
  });
@@ -1685,10 +1703,10 @@ function createEngine(session, deps, quiet = false) {
1685
1703
  return { ok: true, value: parseSingle(res.json) };
1686
1704
  },
1687
1705
  async profile(memberId) {
1688
- const contract2 = contractFor("profile");
1689
- if (contract2 === void 0) return missingContract("profile");
1706
+ const contract3 = contractFor("profile");
1707
+ if (contract3 === void 0) return missingContract("profile");
1690
1708
  const variables = encodeVariables({ memberIdentity: memberId });
1691
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1709
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1692
1710
  const res = await client.request({ url, spendClass: "profile", operation: "profile" });
1693
1711
  if (!res.ok) return res;
1694
1712
  const envelope = res.json;
@@ -1700,9 +1718,9 @@ function createEngine(session, deps, quiet = false) {
1700
1718
  return { ok: true, value: { profile, index } };
1701
1719
  },
1702
1720
  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`;
1721
+ const contract3 = contractFor("feed");
1722
+ if (contract3 === void 0) return missingContract("feed");
1723
+ const url = `${contract3.path}?q=chronFeed&count=${limit}&start=0`;
1706
1724
  const res = await client.request({ url, spendClass: "page", operation: "feed" });
1707
1725
  if (!res.ok) return res;
1708
1726
  const envelope = res.json;
@@ -1711,21 +1729,21 @@ function createEngine(session, deps, quiet = false) {
1711
1729
  value: {
1712
1730
  parsed: parseCollection(res.json, {
1713
1731
  operation: "feed",
1714
- contractCapturedAt: contract2.capturedAt
1732
+ contractCapturedAt: contract3.capturedAt
1715
1733
  }),
1716
1734
  index: indexIncluded(envelope.included)
1717
1735
  }
1718
1736
  };
1719
1737
  },
1720
1738
  async myPosts(profileUrn, limit) {
1721
- const contract2 = contractFor("myPosts");
1722
- if (contract2 === void 0) return missingContract("myPosts");
1739
+ const contract3 = contractFor("myPosts");
1740
+ if (contract3 === void 0) return missingContract("myPosts");
1723
1741
  const variables = encodeVariables({
1724
1742
  count: Math.min(limit, 100),
1725
1743
  start: 0,
1726
1744
  profileUrn: canonicalUrn(profileUrn)
1727
1745
  });
1728
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1746
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1729
1747
  const res = await client.request({ url, spendClass: "page", operation: "myPosts" });
1730
1748
  if (!res.ok) return res;
1731
1749
  const envelope = res.json;
@@ -1734,7 +1752,7 @@ function createEngine(session, deps, quiet = false) {
1734
1752
  value: {
1735
1753
  parsed: parseCollection(res.json, {
1736
1754
  operation: "myPosts",
1737
- contractCapturedAt: contract2.capturedAt,
1755
+ contractCapturedAt: contract3.capturedAt,
1738
1756
  truncated: true
1739
1757
  }),
1740
1758
  index: indexIncluded(envelope.included)
@@ -1747,8 +1765,8 @@ function createEngine(session, deps, quiet = false) {
1747
1765
  * snapshot and diffs, rather than pretending a watermark exists.
1748
1766
  */
1749
1767
  async connections(limit) {
1750
- const contract2 = contractFor("search");
1751
- if (contract2 === void 0) return missingContract("search");
1768
+ const contract3 = contractFor("search");
1769
+ if (contract3 === void 0) return missingContract("search");
1752
1770
  const variables = encodeVariables({
1753
1771
  start: 0,
1754
1772
  origin: "FACETED_SEARCH",
@@ -1761,12 +1779,12 @@ function createEngine(session, deps, quiet = false) {
1761
1779
  includeFiltersInResponse: false
1762
1780
  }
1763
1781
  });
1764
- const url = `${contract2.path}?variables=${variables}&queryId=${contract2.queryId}`;
1782
+ const url = `${contract3.path}?variables=${variables}&queryId=${contract3.queryId}`;
1765
1783
  const res = await client.request({ url, spendClass: "search", operation: "connections" });
1766
1784
  if (!res.ok) return res;
1767
1785
  const parsed = parseCollection(res.json, {
1768
1786
  operation: "connections",
1769
- contractCapturedAt: contract2.capturedAt,
1787
+ contractCapturedAt: contract3.capturedAt,
1770
1788
  claimedCount: totalResultCount(res.json),
1771
1789
  truncated: true
1772
1790
  });
@@ -1776,8 +1794,8 @@ function createEngine(session, deps, quiet = false) {
1776
1794
  return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1777
1795
  },
1778
1796
  async post(postUrn2, limit) {
1779
- const contract2 = contractFor("comments");
1780
- if (contract2 === void 0) return missingContract("comments");
1797
+ const contract3 = contractFor("comments");
1798
+ if (contract3 === void 0) return missingContract("comments");
1781
1799
  const variables = encodeVariables({
1782
1800
  count: Math.min(limit, 100),
1783
1801
  numReplies: 1,
@@ -1785,12 +1803,12 @@ function createEngine(session, deps, quiet = false) {
1785
1803
  sortOrder: "RELEVANCE",
1786
1804
  start: 0
1787
1805
  });
1788
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1806
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1789
1807
  const res = await client.request({ url, spendClass: "page", operation: "comments" });
1790
1808
  if (!res.ok) return res;
1791
1809
  const parsed = parseCollection(res.json, {
1792
1810
  operation: "comments",
1793
- contractCapturedAt: contract2.capturedAt,
1811
+ contractCapturedAt: contract3.capturedAt,
1794
1812
  // A page of many; we follow no cursor yet, so never claim exhaustion.
1795
1813
  truncated: true
1796
1814
  });
@@ -1798,27 +1816,27 @@ function createEngine(session, deps, quiet = false) {
1798
1816
  return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1799
1817
  },
1800
1818
  async reactions(postUrn2, limit) {
1801
- const contract2 = contractFor("reactions");
1802
- if (contract2 === void 0) return missingContract("reactions");
1819
+ const contract3 = contractFor("reactions");
1820
+ if (contract3 === void 0) return missingContract("reactions");
1803
1821
  const variables = encodeVariables({
1804
1822
  count: Math.min(limit, 100),
1805
1823
  start: 0,
1806
1824
  threadUrn: postUrn2
1807
1825
  });
1808
- const url = `${contract2.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract2.queryId}`;
1826
+ const url = `${contract3.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract3.queryId}`;
1809
1827
  const res = await client.request({ url, spendClass: "page", operation: "reactions" });
1810
1828
  if (!res.ok) return res;
1811
1829
  const parsed = parseCollection(res.json, {
1812
1830
  operation: "reactions",
1813
- contractCapturedAt: contract2.capturedAt,
1831
+ contractCapturedAt: contract3.capturedAt,
1814
1832
  truncated: true
1815
1833
  });
1816
1834
  const envelope = res.json;
1817
1835
  return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };
1818
1836
  },
1819
1837
  async search(kind, query, limit) {
1820
- const contract2 = contractFor("search");
1821
- if (contract2 === void 0) return missingContract("search");
1838
+ const contract3 = contractFor("search");
1839
+ if (contract3 === void 0) return missingContract("search");
1822
1840
  const variables = encodeVariables({
1823
1841
  start: 0,
1824
1842
  origin: "GLOBAL_SEARCH_HEADER",
@@ -1829,12 +1847,12 @@ function createEngine(session, deps, quiet = false) {
1829
1847
  includeFiltersInResponse: false
1830
1848
  }
1831
1849
  });
1832
- const url = `${contract2.path}?variables=${variables}&queryId=${contract2.queryId}`;
1850
+ const url = `${contract3.path}?variables=${variables}&queryId=${contract3.queryId}`;
1833
1851
  const res = await client.request({ url, spendClass: "search", operation: "search" });
1834
1852
  if (!res.ok) return res;
1835
1853
  const parsed = parseCollection(res.json, {
1836
1854
  operation: "search",
1837
- contractCapturedAt: contract2.capturedAt,
1855
+ contractCapturedAt: contract3.capturedAt,
1838
1856
  claimedCount: totalResultCount(res.json),
1839
1857
  truncated: true
1840
1858
  // one page of many; we never claim exhaustion
@@ -2028,7 +2046,7 @@ async function fetchCommentMenu(ref, trackingId, client) {
2028
2046
  const stream = result.classification.raw ?? "";
2029
2047
  return { ok: true, stream };
2030
2048
  }
2031
- function textStates(payload, text4) {
2049
+ function textStates(payload, text5) {
2032
2050
  const keyOf = (...names) => {
2033
2051
  for (const n of names) {
2034
2052
  const slot = payload[n];
@@ -2047,12 +2065,12 @@ function textStates(payload, text4) {
2047
2065
  protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: key } }
2048
2066
  });
2049
2067
  return [
2050
- entry2(plain2, text4, "stringValue"),
2051
- entry2(rich, { text: text4, attribute: [], $type: "TextModel", source: "local" }, "textModelForWrite")
2068
+ entry2(plain2, text5, "stringValue"),
2069
+ entry2(rich, { text: text5, attribute: [], $type: "TextModel", source: "local" }, "textModelForWrite")
2052
2070
  ];
2053
2071
  }
2054
- function editStates(payload, text4) {
2055
- return textStates(payload, text4);
2072
+ function editStates(payload, text5) {
2073
+ return textStates(payload, text5);
2056
2074
  }
2057
2075
  async function runCommentAction(ref, operation, trackingId, client, newText) {
2058
2076
  const menu = await fetchCommentMenu(ref, trackingId, client);
@@ -2158,10 +2176,10 @@ function parseScheduledPage(stream) {
2158
2176
  if (claimedCount > 0 && posts.length === 0) {
2159
2177
  return drift(`LinkedIn counts ${claimedCount} scheduled posts but no row could be read`);
2160
2178
  }
2161
- const texts = [...stream.matchAll(TEXT)].map((m) => JSON.parse(`"${m[1]}"`));
2162
- if (texts.length === posts.length) {
2179
+ const texts2 = [...stream.matchAll(TEXT)].map((m) => JSON.parse(`"${m[1]}"`));
2180
+ if (texts2.length === posts.length) {
2163
2181
  posts.forEach((p, i) => {
2164
- p.text = texts[i] ?? null;
2182
+ p.text = texts2[i] ?? null;
2165
2183
  });
2166
2184
  }
2167
2185
  return { ok: true, claimedCount, posts };
@@ -2391,12 +2409,12 @@ var CATEGORY = {
2391
2409
  VIDEO: "VIDEO",
2392
2410
  DOCUMENT: "NATIVE_DOCUMENT"
2393
2411
  };
2394
- function sharePayload(text4, visibility, media = [], scheduledAt) {
2412
+ function sharePayload(text5, visibility, media = [], scheduledAt) {
2395
2413
  const schedule = scheduledAt === void 0 ? { postState: "PUBLISHED" } : { postState: "SCHEDULED", scheduledAt };
2396
2414
  return {
2397
2415
  visibleToConnectionsOnly: visibility === "CONNECTIONS",
2398
2416
  externalAudienceProviders: [],
2399
- commentaryV2: { text: text4, attributes: [] },
2417
+ commentaryV2: { text: text5, attributes: [] },
2400
2418
  origin: "FEED",
2401
2419
  allowedCommentersScope: "ALL",
2402
2420
  ...schedule,
@@ -2510,15 +2528,15 @@ async function share(confirmed, client, bytes) {
2510
2528
  note: "LinkedIn accepted the post but the response carried no recognisable urn. Run `lnrelay sync my-posts && lnrelay my-posts` to confirm what actually landed \u2014 and do NOT re-run this command on the assumption it failed, or you will post twice."
2511
2529
  } : { ok: true, id };
2512
2530
  }
2513
- function editPostBody(text4) {
2514
- return { patch: { $set: { commentaryV2: { text: text4, attributes: [] } } } };
2531
+ function editPostBody(text5) {
2532
+ return { patch: { $set: { commentaryV2: { text: text5, attributes: [] } } } };
2515
2533
  }
2516
2534
  async function editPost(confirmed, client) {
2517
- const { urn, text: text4 } = confirmed.payload;
2535
+ const { urn, text: text5 } = confirmed.payload;
2518
2536
  const result = await client.request({
2519
2537
  url: deleteUrl(urn),
2520
2538
  method: "POST",
2521
- body: editPostBody(text4),
2539
+ body: editPostBody(text5),
2522
2540
  spendClass: "write",
2523
2541
  operation: "edit-post"
2524
2542
  });
@@ -2528,7 +2546,7 @@ async function editPost(confirmed, client) {
2528
2546
  return out;
2529
2547
  }
2530
2548
  const held = result.json?.data?.commentary?.text;
2531
- if (held !== text4) {
2549
+ if (held !== text5) {
2532
2550
  return {
2533
2551
  ok: false,
2534
2552
  code: "SCHEMA_DRIFT",
@@ -2557,14 +2575,14 @@ function pollUrnOf(json) {
2557
2575
  return JSON.stringify(json ?? null).match(/urn:li:fsd_pollSummary:\d+/)?.[0] ?? null;
2558
2576
  }
2559
2577
  async function createPoll(poll, client) {
2560
- const contract2 = contractFor("createPoll");
2561
- if (contract2?.queryId === void 0) {
2578
+ const contract3 = contractFor("createPoll");
2579
+ if (contract3?.queryId === void 0) {
2562
2580
  return { ok: false, code: "NOT_IMPLEMENTED", message: "no verified poll contract" };
2563
2581
  }
2564
2582
  const result = await client.request({
2565
- url: `${contract2.path}?action=execute&queryId=${contract2.queryId}`,
2583
+ url: `${contract3.path}?action=execute&queryId=${contract3.queryId}`,
2566
2584
  method: "POST",
2567
- body: { variables: { poll }, queryId: contract2.queryId, includeWebMetadata: true },
2585
+ body: { variables: { poll }, queryId: contract3.queryId, includeWebMetadata: true },
2568
2586
  spendClass: "write",
2569
2587
  operation: "create-poll"
2570
2588
  });
@@ -2589,16 +2607,16 @@ async function createPoll(poll, client) {
2589
2607
  }
2590
2608
  return { ok: true, urn };
2591
2609
  }
2592
- function firstUrl(text4) {
2593
- const found = text4.match(/https?:\/\/[^\s<>"]+/)?.[0];
2610
+ function firstUrl(text5) {
2611
+ const found = text5.match(/https?:\/\/[^\s<>"]+/)?.[0];
2594
2612
  if (found === void 0) return null;
2595
2613
  let url = found.replace(/[.,;:!?'"]+$/, "");
2596
2614
  if (url.endsWith(")") && !url.includes("(")) url = url.slice(0, -1);
2597
2615
  return url;
2598
2616
  }
2599
2617
  function urlPreviewUrl(url) {
2600
- const contract2 = contractFor("urlPreview");
2601
- return `${contract2?.path}?includeWebMetadata=true&variables=(url:${encodeURIComponent(url)})&queryId=${contract2?.queryId}`;
2618
+ const contract3 = contractFor("urlPreview");
2619
+ return `${contract3?.path}?includeWebMetadata=true&variables=(url:${encodeURIComponent(url)})&queryId=${contract3?.queryId}`;
2602
2620
  }
2603
2621
  function parseUrlPreview(json) {
2604
2622
  const error = gqlError(json);
@@ -2754,8 +2772,8 @@ function previewLines2(post) {
2754
2772
  " about to delete, or that it is yours."
2755
2773
  ];
2756
2774
  }
2757
- const text4 = typeof post.text === "string" ? post.text : "(no text \u2014 media-only post?)";
2758
- const shown = text4.length > PREVIEW_CHARS ? `${text4.slice(0, PREVIEW_CHARS)}\u2026` : text4;
2775
+ const text5 = typeof post.text === "string" ? post.text : "(no text \u2014 media-only post?)";
2776
+ const shown = text5.length > PREVIEW_CHARS ? `${text5.slice(0, PREVIEW_CHARS)}\u2026` : text5;
2759
2777
  const lines = [`content "${shown.replace(/\n/g, " ")}"`];
2760
2778
  if (typeof post.scheduledAt === "string") {
2761
2779
  lines.push(`status scheduled, publishes ${post.scheduledAt} unless cancelled`);
@@ -3661,24 +3679,6 @@ async function runFeed(limit, opts = {}) {
3661
3679
  if (!result.ok) return toEnvelope("feed", result);
3662
3680
  return ok("feed", collection(result.value, opts));
3663
3681
  }
3664
- async function runSearch(kind, query, limit, opts = {}) {
3665
- if (kind === void 0 || !["people", "companies", "jobs"].includes(kind)) {
3666
- return err(
3667
- "search",
3668
- "INVALID_INPUT",
3669
- "kind must be people, companies or jobs",
3670
- 'lnrelay search people "<query>"'
3671
- );
3672
- }
3673
- if (query === void 0 || query === "") {
3674
- return err("search", "INVALID_INPUT", "a query is required", 'lnrelay search people "<query>"');
3675
- }
3676
- const ctx = withSession("search", opts.quiet === true);
3677
- if ("ok" in ctx) return ctx;
3678
- const result = await ctx.engine.search(kind, query, limit);
3679
- if (!result.ok) return toEnvelope("search", result);
3680
- return ok("search", { query, kind, ...collection(result.value, opts) });
3681
- }
3682
3682
  async function runPost(urn, limit, opts = {}) {
3683
3683
  const postUrn2 = normalisePostUrn(urn);
3684
3684
  if (postUrn2 === void 0) {
@@ -3898,288 +3898,181 @@ function runDoctor(now, offline) {
3898
3898
  });
3899
3899
  }
3900
3900
 
3901
- // src/commands/oauth.ts
3902
- import { spawn } from "child_process";
3903
- import { createServer } from "http";
3904
- import { createInterface as createInterface2 } from "readline/promises";
3901
+ // src/commands/messaging.ts
3902
+ import { randomUUID } from "crypto";
3903
+ import { readFileSync as readFileSync2 } from "fs";
3905
3904
 
3906
- // src/engine/oauth.ts
3907
- var AUTHORIZE = "https://www.linkedin.com/oauth/v2/authorization";
3908
- var TOKEN = "https://www.linkedin.com/oauth/v2/accessToken";
3909
- var USERINFO = "https://api.linkedin.com/v2/userinfo";
3910
- var CALLBACK_PORT = 53682;
3911
- var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
3912
- var SCOPES = ["openid", "profile", "w_member_social"];
3913
- function authorizationUrl(clientId, state) {
3914
- const params = new URLSearchParams({
3915
- response_type: "code",
3916
- client_id: clientId,
3917
- redirect_uri: REDIRECT_URI,
3918
- state,
3919
- scope: SCOPES.join(" ")
3920
- });
3921
- return `${AUTHORIZE}?${params.toString()}`;
3922
- }
3923
- async function exchange(code, config, deps) {
3924
- const body = new URLSearchParams({
3925
- grant_type: "authorization_code",
3926
- code,
3927
- redirect_uri: REDIRECT_URI,
3928
- client_id: config.clientId,
3929
- client_secret: config.clientSecret
3930
- });
3931
- let res;
3932
- try {
3933
- res = await deps.fetch(TOKEN, {
3934
- method: "POST",
3935
- headers: { "content-type": "application/x-www-form-urlencoded" },
3936
- body: body.toString()
3937
- });
3938
- } catch (e) {
3939
- return { ok: false, message: `could not reach LinkedIn: ${e.message}` };
3940
- }
3941
- const text4 = await res.text();
3942
- if (res.status !== 200) {
3943
- return {
3944
- ok: false,
3945
- message: `LinkedIn rejected the code exchange (${res.status})`,
3946
- // The most common causes, in the order they actually happen.
3947
- hint: `Check that the app has BOTH products added, and that its Auth tab lists exactly ${REDIRECT_URI} as an authorized redirect URL. Response: ${text4.slice(0, 200)}`
3948
- };
3949
- }
3950
- let parsed;
3951
- try {
3952
- parsed = JSON.parse(text4);
3953
- } catch {
3954
- return { ok: false, message: "token response was not JSON" };
3955
- }
3956
- const accessToken = parsed.access_token;
3957
- const expiresIn = parsed.expires_in;
3958
- if (typeof accessToken !== "string" || accessToken === "") {
3959
- return { ok: false, message: "token response carried no access_token" };
3960
- }
3961
- const lifetimeMs = typeof expiresIn === "number" ? expiresIn * 1e3 : 60 * 864e5;
3962
- return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };
3963
- }
3964
- async function fetchMemberUrn(accessToken, deps) {
3965
- let res;
3966
- try {
3967
- res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });
3968
- } catch (e) {
3969
- return { ok: false, message: `could not reach userinfo: ${e.message}` };
3970
- }
3971
- if (res.status !== 200) {
3972
- return {
3973
- ok: false,
3974
- message: `userinfo returned ${res.status} \u2014 the 'openid'/'profile' scopes may not be granted`
3975
- };
3976
- }
3977
- const parsed = await res.json();
3978
- if (typeof parsed.sub !== "string" || parsed.sub === "") {
3979
- return { ok: false, message: "userinfo carried no subject claim" };
3980
- }
3981
- return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };
3905
+ // src/engine/messaging.ts
3906
+ var FOLDERS = {
3907
+ primary: "PRIMARY_INBOX",
3908
+ other: "SECONDARY_INBOX",
3909
+ inbox: "INBOX",
3910
+ archive: "ARCHIVE",
3911
+ requests: "MESSAGE_REQUEST_PENDING",
3912
+ spam: "SPAM"
3913
+ };
3914
+ var FOLDER_OF = Object.fromEntries(
3915
+ Object.entries(FOLDERS).map(([k, v]) => [v, k])
3916
+ );
3917
+ function contract2(name) {
3918
+ const c = CONTRACTS[name];
3919
+ if (c?.queryId === void 0) throw new Error(`messaging contract '${name}' is missing`);
3920
+ return c;
3982
3921
  }
3983
- function parseCallback(rawUrl, expectedState) {
3984
- let url;
3985
- try {
3986
- url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);
3987
- } catch {
3988
- return { ok: false, message: "callback URL was unparseable" };
3989
- }
3990
- const error = url.searchParams.get("error");
3991
- if (error !== null) {
3992
- const description = url.searchParams.get("error_description") ?? "";
3993
- return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
3994
- }
3995
- const state = url.searchParams.get("state");
3996
- if (state !== expectedState) {
3997
- return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
3998
- }
3999
- const code = url.searchParams.get("code");
4000
- if (code === null || code === "") return { ok: false, message: "callback carried no code" };
4001
- return { ok: true, code };
3922
+ function mailboxOf(meUrn) {
3923
+ const id = meUrn.match(/(?:fs_miniProfile|fsd_profile|fs_profile):([A-Za-z0-9_-]+)/)?.[1];
3924
+ return `urn:li:fsd_profile:${id ?? meUrn}`;
4002
3925
  }
4003
-
4004
- // src/commands/token.ts
4005
- import { existsSync as existsSync3, rmSync } from "fs";
4006
- var TOKEN_FILE = "oauth.json";
4007
- var OAUTH_SETUP = [
4008
- "Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one",
4009
- "legitimacy wedge an individual actually has \u2014 but the app has to be registered by you; it",
4010
- "cannot be created on your behalf.",
4011
- "",
4012
- " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
4013
- ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
4014
- " Both are self-serve: no partner review, no verification, no screencast.",
4015
- ` 3. Auth tab \u2192 add redirect URL ${REDIRECT_URI}`,
4016
- " 4. Run: lnrelay oauth login --client-id <id>",
4017
- " (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)"
4018
- ].join("\n");
4019
- function tokenPath() {
4020
- return cachePath(TOKEN_FILE);
3926
+ function conversationsUrl(q2) {
3927
+ const c = contract2("messengerConversations");
3928
+ const variables = encodeVariables({
3929
+ query: {
3930
+ predicateUnions: [{ conversationCategoryPredicate: { category: FOLDERS[q2.folder] } }]
3931
+ },
3932
+ count: q2.count ?? 20,
3933
+ mailboxUrn: q2.mailbox,
3934
+ nextCursor: q2.cursor
3935
+ });
3936
+ return `${c.path}?queryId=${c.queryId}&variables=${variables}`;
4021
3937
  }
4022
- function loadToken() {
4023
- const result = loadJson(tokenPath());
4024
- return result.state === "ok" ? result.value : null;
3938
+ function messagesUrl(conversationUrn) {
3939
+ const c = contract2("messengerMessages");
3940
+ return `${c.path}?queryId=${c.queryId}&variables=${encodeVariables({ conversationUrn })}`;
4025
3941
  }
4026
- function saveToken(token) {
4027
- saveJson(tokenPath(), token);
3942
+ function conversationIdOf(input, mailbox2) {
3943
+ const s = input.trim();
3944
+ if (/^urn:li:msg_conversation:\(urn:li:fsd_profile:[^,]+,2-[^)]+\)$/.test(s)) return s;
3945
+ const thread = s.match(/messaging\/thread\/(2-[^/?#]+)/)?.[1] ?? s.match(/^(2-[A-Za-z0-9+/=_-]+)$/)?.[1];
3946
+ return thread === void 0 ? void 0 : `urn:li:msg_conversation:(${mailbox2},${thread})`;
4028
3947
  }
4029
- function deleteToken() {
4030
- const path = tokenPath();
4031
- if (!existsSync3(path)) return false;
4032
- rmSync(path, { force: true });
4033
- return true;
3948
+ var DEGREE = {
3949
+ DISTANCE_1: "1st",
3950
+ DISTANCE_2: "2nd",
3951
+ DISTANCE_3: "3rd+",
3952
+ OUT_OF_NETWORK: "out of network"
3953
+ };
3954
+ var txt = (v) => {
3955
+ const t = typeof v === "string" ? v : v?.text;
3956
+ return typeof t === "string" && t.trim() !== "" ? t.trim() : void 0;
3957
+ };
3958
+ var iso = (ms) => typeof ms === "number" ? new Date(ms).toISOString() : void 0;
3959
+ function defined3(obj) {
3960
+ for (const k of Object.keys(obj)) if (obj[k] === void 0) delete obj[k];
3961
+ return obj;
4034
3962
  }
4035
-
4036
- // src/commands/oauth.ts
4037
- var CALLBACK_TIMEOUT_MS = 3e5;
4038
- var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
4039
- <body style="font:16px system-ui;padding:3rem;max-width:32rem">
4040
- <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
4041
- function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
4042
- return new Promise((ready) => {
4043
- let settle = () => {
4044
- };
4045
- const code = new Promise((r) => {
4046
- settle = r;
4047
- });
4048
- const server = createServer((req, res) => {
4049
- const url = req.url ?? "/";
4050
- if (!url.startsWith("/callback")) {
4051
- res.writeHead(404, { connection: "close" });
4052
- res.end();
4053
- return;
4054
- }
4055
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
4056
- res.end(DONE_PAGE);
4057
- settle(parseCallback(url, state));
4058
- });
4059
- const timer = setTimeout(() => {
4060
- settle({
4061
- ok: false,
4062
- message: `timed out after ${Math.round(timeoutMs / 1e3)}s waiting for the LinkedIn callback`
4063
- });
4064
- }, timeoutMs);
4065
- timer.unref?.();
4066
- const close = () => {
4067
- clearTimeout(timer);
4068
- server.closeAllConnections?.();
4069
- server.close();
4070
- };
4071
- server.once("error", (e) => {
4072
- clearTimeout(timer);
4073
- 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}`;
4074
- ready({ ok: false, message: why });
3963
+ function participantOf(p) {
3964
+ const t = p?.participantType ?? {};
3965
+ if (t.member) {
3966
+ const m = t.member;
3967
+ const name = [txt(m.firstName), txt(m.lastName)].filter(Boolean).join(" ");
3968
+ const url = typeof m.profileUrl === "string" ? `${m.profileUrl.replace(/\/$/, "")}/` : void 0;
3969
+ return defined3({
3970
+ name: name !== "" ? name : "LinkedIn Member",
3971
+ kind: "person",
3972
+ headline: txt(m.headline),
3973
+ degree: DEGREE[String(m.distance)],
3974
+ url
4075
3975
  });
4076
- server.listen(CALLBACK_PORT, "127.0.0.1", () => {
4077
- ready({ ok: true, code, close });
3976
+ }
3977
+ if (t.organization) {
3978
+ const o = t.organization;
3979
+ return defined3({
3980
+ name: txt(o.name) ?? "an organization",
3981
+ kind: "organization",
3982
+ url: typeof o.pageUrl === "string" ? o.pageUrl : void 0
4078
3983
  });
3984
+ }
3985
+ if (t.custom) return { name: txt(t.custom.name) ?? "LinkedIn", kind: "other" };
3986
+ return void 0;
3987
+ }
3988
+ var isMe = (urn, mailbox2) => typeof urn === "string" && urn.includes(mailbox2);
3989
+ function messageOf(m, byUrn, mailbox2) {
3990
+ const sender = m["*sender"] ?? m["*actor"];
3991
+ const fromMe = isMe(sender, mailbox2);
3992
+ const who = fromMe ? void 0 : participantOf(byUrn.get(sender));
3993
+ const render2 = Array.isArray(m.renderContent) ? m.renderContent : [];
3994
+ return defined3({
3995
+ from: fromMe ? "you" : who?.name ?? "unknown",
3996
+ fromMe,
3997
+ at: iso(m.deliveredAt),
3998
+ text: txt(m.body),
3999
+ subject: txt(m.subject),
4000
+ sponsored: render2.some((r) => r.conversationAdsMessageContent) ? true : void 0
4079
4001
  });
4080
4002
  }
4081
- function openBrowser(url) {
4082
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
4083
- try {
4084
- spawn(cmd, [url], { detached: true, stdio: "ignore" }).unref();
4085
- } catch {
4086
- }
4003
+ var drift3 = (message) => ({
4004
+ ok: false,
4005
+ code: "SCHEMA_DRIFT",
4006
+ message,
4007
+ hint: "the messaging response changed shape; re-capture it"
4008
+ });
4009
+ function collectionOf(json) {
4010
+ const d = json?.data?.data;
4011
+ const key = d === void 0 ? void 0 : Object.keys(d).find((k) => k.startsWith("messenger"));
4012
+ const c = key === void 0 ? void 0 : d?.[key];
4013
+ return c !== null && typeof c === "object" ? c : void 0;
4087
4014
  }
4088
- function loginDeps() {
4015
+ function refsOf(top) {
4016
+ const refs = top?.["*elements"];
4017
+ if (Array.isArray(refs)) return refs;
4018
+ return Array.isArray(top?.elements) && top.elements.length === 0 ? [] : void 0;
4019
+ }
4020
+ function parseConversations(json, mailbox2) {
4021
+ const top = collectionOf(json);
4022
+ const refs = refsOf(top);
4023
+ if (refs === void 0) return drift3("the conversation list was missing");
4024
+ const included = json.included ?? [];
4025
+ const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4026
+ const conversations = [];
4027
+ for (const ref of refs) {
4028
+ const c = byUrn.get(ref);
4029
+ if (c === void 0) continue;
4030
+ const parts = (c["*conversationParticipants"] ?? []).filter((u) => !isMe(u, mailbox2)).map((u) => participantOf(byUrn.get(u))).filter((p) => p !== void 0);
4031
+ const lastRef = c.messages?.["*elements"]?.[0];
4032
+ const last = lastRef === void 0 ? void 0 : byUrn.get(lastRef);
4033
+ const categories = Array.isArray(c.categories) ? c.categories : [];
4034
+ conversations.push(
4035
+ defined3({
4036
+ id: String(c.entityUrn),
4037
+ url: typeof c.conversationUrl === "string" ? c.conversationUrl : void 0,
4038
+ with: parts,
4039
+ title: c.groupChat === true ? txt(c.title) : void 0,
4040
+ unread: typeof c.unreadCount === "number" ? c.unreadCount : 0,
4041
+ lastActivity: iso(c.lastActivityAt),
4042
+ last: last === void 0 ? void 0 : messageOf(last, byUrn, mailbox2),
4043
+ // PRIMARY_INBOX sits inside INBOX; report the folder a person would name.
4044
+ folders: categories.map((k) => FOLDER_OF[k]).filter(
4045
+ (f) => f !== void 0 && !(f === "primary" && categories.includes("INBOX"))
4046
+ ),
4047
+ inmail: categories.includes("INMAIL")
4048
+ })
4049
+ );
4050
+ }
4051
+ if (refs.length > 0 && conversations.length === 0)
4052
+ return drift3(`${refs.length} conversations were listed but none were sent`);
4053
+ const cursor = top?.metadata?.nextCursor;
4089
4054
  return {
4090
- state: () => crypto.randomUUID(),
4091
- listen: (state) => listenForCallback(state),
4092
- open: openBrowser,
4093
- write: (s) => process.stderr.write(s),
4094
- isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
4095
- prompt: async (question) => {
4096
- const rl = createInterface2({ input: process.stdin, output: process.stderr });
4097
- const answer = await rl.question(question);
4098
- rl.close();
4099
- return answer;
4100
- },
4101
- now: Date.now,
4102
- fetch: globalThis.fetch
4055
+ ok: true,
4056
+ conversations,
4057
+ ...typeof cursor === "string" && cursor !== "" ? { cursor } : {}
4103
4058
  };
4104
4059
  }
4105
- async function credentials(opts, deps) {
4106
- const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;
4107
- if (clientId === void 0 || clientId === "") {
4108
- return err("oauth", "INVALID_INPUT", "a client id is required", OAUTH_SETUP);
4109
- }
4110
- let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;
4111
- if ((clientSecret === void 0 || clientSecret === "") && deps.isTty) {
4112
- clientSecret = (await deps.prompt("client secret (not echoed to argv or logs): ")).trim();
4060
+ function parseMessages(json, mailbox2) {
4061
+ const top = collectionOf(json);
4062
+ const refs = refsOf(top);
4063
+ if (refs === void 0) return drift3("the message list was missing");
4064
+ const included = json.included ?? [];
4065
+ const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4066
+ const messages = [];
4067
+ for (const ref of refs) {
4068
+ const m = byUrn.get(ref);
4069
+ if (m === void 0 || typeof m.deliveredAt !== "number") continue;
4070
+ messages.push({ id: String(m.entityUrn), ...messageOf(m, byUrn, mailbox2) });
4113
4071
  }
4114
- if (clientSecret === void 0 || clientSecret === "") {
4115
- return err(
4116
- "oauth",
4117
- "INVALID_INPUT",
4118
- "a client secret is required, and there is no terminal to ask on",
4119
- `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.
4120
-
4121
- ${OAUTH_SETUP}`
4122
- );
4123
- }
4124
- return { clientId, clientSecret };
4125
- }
4126
- async function runOauthLogin(opts, deps = loginDeps()) {
4127
- const creds = await credentials(opts, deps);
4128
- if ("ok" in creds) return creds;
4129
- const state = deps.state();
4130
- const listener = await deps.listen(state);
4131
- if (!listener.ok) {
4132
- return err("oauth", "AUTH_FAILED", listener.message);
4133
- }
4134
- try {
4135
- const url = authorizationUrl(creds.clientId, state);
4136
- deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
4137
-
4138
- ${url}
4139
-
4140
- `);
4141
- deps.open(url);
4142
- const callback = await listener.code;
4143
- if (!callback.ok) return err("oauth", "AUTH_FAILED", callback.message);
4144
- const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });
4145
- if (!token.ok) return err("oauth", "AUTH_FAILED", token.message, token.hint);
4146
- const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });
4147
- if (!member.ok) return err("oauth", "AUTH_FAILED", member.message, OAUTH_SETUP);
4148
- saveToken({
4149
- accessToken: token.accessToken,
4150
- memberUrn: member.memberUrn,
4151
- expiresAt: token.expiresAt
4152
- });
4153
- return ok("oauth", {
4154
- memberUrn: member.memberUrn,
4155
- scopes: SCOPES,
4156
- expiresAt: new Date(token.expiresAt).toISOString(),
4157
- storedAt: tokenPath(),
4158
- // Refresh tokens are partner-gated, so renewal is re-running this.
4159
- renewal: "run `lnrelay oauth login` again when it expires"
4160
- });
4161
- } finally {
4162
- listener.close();
4163
- }
4164
- }
4165
- function runOauthLogout() {
4166
- const removed = deleteToken();
4167
- return ok("oauth", {
4168
- removed,
4169
- note: removed ? `deleted ${tokenPath()} \u2014 the token stays valid on LinkedIn's side until it expires` : "no token was stored"
4170
- });
4171
- }
4172
- function runOauthStatus() {
4173
- const token = loadToken();
4174
- if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
4175
- return ok("oauth", {
4176
- memberUrn: token.memberUrn,
4177
- expiresAt: new Date(token.expiresAt).toISOString(),
4178
- expired: token.expiresAt <= Date.now(),
4179
- scopes: SCOPES,
4180
- storedAt: tokenPath(),
4181
- writeCap: CAPS.write.perDay
4182
- });
4072
+ if (refs.length > 0 && messages.length === 0)
4073
+ return drift3(`${refs.length} messages were listed but none were sent`);
4074
+ messages.sort((a, b) => a.at.localeCompare(b.at));
4075
+ return { ok: true, messages };
4183
4076
  }
4184
4077
 
4185
4078
  // src/engine/people.ts
@@ -4188,11 +4081,11 @@ var text3 = (v) => {
4188
4081
  const t = v?.text;
4189
4082
  return typeof t === "string" && t.trim() !== "" ? t.trim() : void 0;
4190
4083
  };
4191
- function defined3(obj) {
4084
+ function defined4(obj) {
4192
4085
  for (const k of Object.keys(obj)) if (obj[k] === void 0) delete obj[k];
4193
4086
  return obj;
4194
4087
  }
4195
- var drift3 = (message) => ({
4088
+ var drift4 = (message) => ({
4196
4089
  ok: false,
4197
4090
  code: "SCHEMA_DRIFT",
4198
4091
  message,
@@ -4218,7 +4111,7 @@ function peopleSearchUrl(q2) {
4218
4111
  });
4219
4112
  return `${c.path}?variables=${variables}&queryId=${c.queryId}`;
4220
4113
  }
4221
- var DEGREE = {
4114
+ var DEGREE2 = {
4222
4115
  DISTANCE_1: "1st",
4223
4116
  DISTANCE_2: "2nd",
4224
4117
  DISTANCE_3: "3rd+",
@@ -4241,12 +4134,12 @@ function rowToPerson(row) {
4241
4134
  if (id === void 0 || name === void 0) return void 0;
4242
4135
  const tracking = row.entityCustomTrackingInfo ?? {};
4243
4136
  const badge = JSON.stringify(row.badgeIcon ?? null);
4244
- return defined3({
4137
+ return defined4({
4245
4138
  id,
4246
4139
  name,
4247
4140
  headline: text3(row.primarySubtitle),
4248
4141
  location: text3(row.secondarySubtitle),
4249
- degree: DEGREE[String(tracking.memberDistance)],
4142
+ degree: DEGREE2[String(tracking.memberDistance)],
4250
4143
  verified: badge.includes("VERIFIED") ? true : void 0,
4251
4144
  insight: insightOf(row),
4252
4145
  url: profileUrl(row.navigationUrl)
@@ -4257,14 +4150,22 @@ function clustersOf(json) {
4257
4150
  const c = d?.searchDashClustersByAll;
4258
4151
  return c !== null && typeof c === "object" ? c : void 0;
4259
4152
  }
4260
- var FURNITURE = /* @__PURE__ */ new Set(["*feedbackCard", "*bannerCard", "*searchSuggestionCard", "*simpleText"]);
4153
+ var FURNITURE = /* @__PURE__ */ new Set([
4154
+ "*feedbackCard",
4155
+ "*bannerCard",
4156
+ "*searchSuggestionCard",
4157
+ "*promoCard",
4158
+ "simpleText",
4159
+ "simpleTextV2",
4160
+ "*simpleText"
4161
+ ]);
4261
4162
  function classify2(item) {
4262
4163
  const ref = item?.["*entityResult"];
4263
4164
  if (typeof ref === "string") return { ref };
4264
4165
  const kinds = Object.entries(item ?? {}).filter(([k, v]) => v !== null && !k.startsWith("$")).map(([k]) => k);
4265
4166
  return kinds.every((k) => FURNITURE.has(k)) ? "furniture" : kinds;
4266
4167
  }
4267
- function readItems(c, included) {
4168
+ function readItems(c, included, toRow) {
4268
4169
  const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4269
4170
  const people = [];
4270
4171
  const unknownTypes = {};
@@ -4279,7 +4180,7 @@ function readItems(c, included) {
4279
4180
  for (const k of kind) unknownTypes[k] = (unknownTypes[k] ?? 0) + 1;
4280
4181
  } else {
4281
4182
  const row = byUrn.get(kind.ref);
4282
- const person = row === void 0 ? void 0 : rowToPerson(row);
4183
+ const person = row === void 0 ? void 0 : toRow(row);
4283
4184
  if (person === void 0) unresolved++;
4284
4185
  else if (!people.some((p) => p.id === person.id)) people.push(person);
4285
4186
  }
@@ -4289,15 +4190,15 @@ function readItems(c, included) {
4289
4190
  function parsePeople(json) {
4290
4191
  const c = clustersOf(json);
4291
4192
  if (c === void 0 || !Array.isArray(c.elements))
4292
- return drift3("the people search returned no result list");
4193
+ return drift4("the people search returned no result list");
4293
4194
  const included = json.included ?? [];
4294
- const { people, unknownTypes, excluded, unresolved } = readItems(c, included);
4195
+ const { people, unknownTypes, excluded, unresolved } = readItems(c, included, rowToPerson);
4295
4196
  const total = typeof c.paging?.total === "number" ? c.paging.total : void 0;
4296
4197
  const start = typeof c.paging?.start === "number" ? c.paging.start : 0;
4297
4198
  const claimedRaw = c.metadata?.totalResultCount;
4298
4199
  const claimed = typeof claimedRaw === "number" ? claimedRaw : total;
4299
4200
  if (unresolved > 0 && people.length === 0)
4300
- return drift3(`${unresolved} people were listed but none could be read`);
4201
+ return drift4(`${unresolved} people were listed but none could be read`);
4301
4202
  if (people.length === 0 && total !== void 0 && total > start) {
4302
4203
  return {
4303
4204
  ok: false,
@@ -4319,7 +4220,7 @@ function parsePeople(json) {
4319
4220
  function parsePeopleFilters(json) {
4320
4221
  const cluster = clustersOf(json)?.metadata?.primaryFilterCluster;
4321
4222
  if (cluster === null || cluster === void 0)
4322
- return drift3("the people search returned no filter list");
4223
+ return drift4("the people search returned no filter list");
4323
4224
  const groups = [
4324
4225
  ...cluster.secondaryFilterGroups ?? [],
4325
4226
  ...cluster.primaryFilterGroups ?? []
@@ -4335,13 +4236,13 @@ function parsePeopleFilters(json) {
4335
4236
  ...f.primaryFilterValues ?? []
4336
4237
  ];
4337
4238
  filters.push(
4338
- defined3({
4239
+ defined4({
4339
4240
  key,
4340
4241
  label: text3(f.displayName) ?? key,
4341
4242
  input: f.renderType === "FREE_TEXT" ? "text" : "select",
4342
4243
  lookup: typeof f.typeaheadType === "string" ? f.typeaheadType : void 0,
4343
4244
  options: values.filter((v) => typeof v.value === "string").map(
4344
- (v) => defined3({
4245
+ (v) => defined4({
4345
4246
  value: v.value,
4346
4247
  label: typeof v.displayName === "string" ? v.displayName : String(v.value),
4347
4248
  count: typeof v.count === "number" && v.count > 0 ? v.count : void 0
@@ -4351,12 +4252,12 @@ function parsePeopleFilters(json) {
4351
4252
  );
4352
4253
  }
4353
4254
  }
4354
- if (filters.length === 0) return drift3("the people filter list was empty");
4255
+ if (filters.length === 0) return drift4("the people filter list was empty");
4355
4256
  return { ok: true, filters };
4356
4257
  }
4357
4258
  function parseOrgHits(json) {
4358
4259
  const c = clustersOf(json);
4359
- if (c === void 0) return drift3("the organisation search returned no result list");
4260
+ if (c === void 0) return drift4("the organisation search returned no result list");
4360
4261
  const included = json.included ?? [];
4361
4262
  const byUrn = new Map(included.map((n) => [n.entityUrn, n]));
4362
4263
  const hits = [];
@@ -4413,14 +4314,14 @@ function selection2(o) {
4413
4314
  throw new Refused2(`${flag} takes a profile id (ACo\u2026) or urn, from a people row's \`id\``);
4414
4315
  params[param] = [id];
4415
4316
  }
4416
- const texts = [
4317
+ const texts2 = [
4417
4318
  [o.firstName, "firstName"],
4418
4319
  [o.lastName, "lastName"],
4419
4320
  [o.title, "title"],
4420
4321
  [o.companyText, "company"],
4421
4322
  [o.schoolText, "schoolFreetext"]
4422
4323
  ];
4423
- for (const [given, param] of texts)
4324
+ for (const [given, param] of texts2)
4424
4325
  if (given !== void 0 && given.trim() !== "") params[param] = [given.trim()];
4425
4326
  if (o.openToVolunteer === true) params.openToVolunteer = ["true"];
4426
4327
  for (const r of o.raw ?? []) {
@@ -4636,196 +4537,1363 @@ async function runPeopleFilters(req, opts = {}, fetch2) {
4636
4537
  });
4637
4538
  }
4638
4539
 
4639
- // src/commands/registry.ts
4640
- var COMMANDS = [
4641
- // ─── local / meta — no network, available today ────────────────────────────
4642
- {
4643
- name: "doctor",
4644
- cost: "free with --offline",
4645
- summary: "Diagnose setup: entry point, cache dir, cookies, cooldown, budget.",
4646
- usage: "lnrelay doctor [--offline]",
4647
- audience: ["cli", "mcp"],
4648
- risk: "local",
4649
- implemented: true
4650
- },
4651
- {
4652
- name: "budget",
4653
- cost: "free",
4654
- summary: "Spend ledger per class, with each cap's provenance. Reset a cooldown here.",
4655
- usage: "lnrelay budget [--reset-cooldown --confirm]",
4656
- audience: ["cli", "mcp"],
4657
- risk: "local",
4658
- implemented: true
4659
- },
4660
- {
4661
- name: "risk",
4662
- cost: "free",
4663
- summary: "Circuit-breaker state. Check this BEFORE spending budget on research.",
4664
- usage: "lnrelay risk",
4665
- audience: ["cli", "mcp"],
4666
- risk: "local",
4667
- implemented: true
4668
- },
4669
- // ─── session ───────────────────────────────────────────────────────────────
4670
- {
4671
- name: "login",
4672
- cost: "free \u2014 local browser",
4673
- summary: "Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.",
4674
- usage: "lnrelay login\n Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).",
4675
- audience: ["cli"],
4676
- risk: "local",
4677
- implemented: true
4678
- },
4679
- // ─── reads — verified live 2026-08-01 ─────────────────────────────────────
4680
- {
4681
- name: "whoami",
4682
- cost: "1 call",
4683
- summary: "The authenticated member: name, headline, URN.",
4684
- usage: "lnrelay whoami",
4685
- audience: ["cli", "mcp"],
4686
- risk: "read",
4687
- implemented: true
4688
- },
4689
- {
4690
- name: "profile",
4691
- cost: "1 call (+1 per section)",
4692
- summary: "A member profile. Expensive sections are opt-in.",
4693
- usage: "lnrelay profile <public-id|urn|url> [--raw]\n Returns headline, location, current title, company and school. LinkedIn's profile\n projections do not return a name \u2014 use the identifier you passed in.",
4694
- audience: ["cli", "mcp"],
4695
- risk: "read",
4696
- implemented: true
4697
- },
4698
- {
4699
- name: "search",
4700
- cost: "cheap \u2014 the net",
4701
- summary: "Search people or companies, one page. For people with filters use `people`; jobs: `jobs`.",
4702
- usage: 'lnrelay search people|companies|jobs "<query>" [--limit N] (jobs: see `jobs`)\n [--compact | --fields a,b,c] [--retain] [--raw]',
4703
- audience: ["cli", "mcp"],
4704
- risk: "read",
4705
- implemented: true
4706
- },
4707
- {
4708
- name: "people",
4709
- cost: "1 search call per 50 people; +1 per company, school or place given by name",
4710
- summary: "People search with every filter LinkedIn has: company, past company, school, place, degree, industry, title, connections of someone, \u2026 Several keyword sets merge by person.",
4711
- usage: 'lnrelay people ["<keywords>" ...] [--company "<name|id>" ...] [--past-company "<name|id>" ...]\n [--school "<name|id>" ...] [--location "<place>" | --geo <ids>] [--network 1st,2nd,3rd+]\n [--industry <ids>] [--language en,de] [--service <ids>] [--title "<text>"]\n [--first-name "<text>"] [--last-name "<text>"] [--company-text "<text>"]\n [--school-text "<text>"] [--connection-of <profile-id>] [--follower-of <profile-id>]\n [--open-to-volunteer] [--filter key=v1,v2 ...] [--limit N] [--start N]\n [--compact | --fields a,b,c]\n Names are looked up and data.resolved says what each became: check it.\n LinkedIn pages at most 1000 people per query; meta.servedLimit says when it held back.',
4712
- audience: ["cli", "mcp"],
4713
- risk: "read",
4714
- implemented: true
4715
- },
4716
- {
4717
- name: "people-filters",
4718
- cost: "1 search call (+1 per name looked up)",
4719
- summary: "Every people filter for a query, with option ids and live counts: what `people` and --filter take.",
4720
- usage: 'lnrelay people-filters ["<keywords>"] [people filters]',
4721
- audience: ["cli", "mcp"],
4722
- risk: "read",
4723
- implemented: true
4724
- },
4725
- {
4726
- name: "jobs",
4727
- cost: "1 job-search call per 100 jobs; --details adds 1 job read per 100 jobs",
4728
- summary: "Job search with every filter the jobs page has. Cards carry id, title, company, place, workplace, listed date, Easy Apply. Read finalists with `job`.",
4729
- usage: 'lnrelay jobs "<keywords>" ["<more keywords>" ...] [--location "<place>" | --geo <id>]\n [--distance <miles>]\n [--posted 24h|week|month|<N>h|<N>d] [--experience internship,entry,associate,\n mid-senior,director,executive] [--type full-time,part-time,contract,temporary,\n volunteer,internship,other] [--workplace on-site,remote,hybrid] [--easy-apply]\n [--under-10] [--verified] [--in-network] [--fair-chance] [--company <ids>]\n [--industry <ids>] [--function <codes>] [--title <ids>] [--place <geo-ids>]\n [--filter key=v1,v2 ...] [--sort recent|relevant] [--limit N] [--start N]\n [--details [--description]] [--compact | --fields a,b,c]\n Ids for --company/--industry/--title/--place/--filter come from `job-filters`.\n The resolved place is in data.location: check it, "Vienna" may resolve narrow.',
4730
- audience: ["cli", "mcp"],
4731
- risk: "read",
4732
- implemented: true
4733
- },
4734
- {
4735
- name: "job",
4736
- cost: "1 job read per 100 jobs",
4737
- summary: "Jobs in full: description, apply link (external or Easy Apply), applicants, state. Several ids are read together, 100 a call.",
4738
- usage: "lnrelay job <id|job-url> [<id|job-url> ...] [--compact | --fields a,b,c]",
4739
- audience: ["cli", "mcp"],
4740
- risk: "read",
4741
- implemented: true
4742
- },
4743
- {
4744
- name: "job-filters",
4745
- cost: "1 job-search call",
4746
- summary: "Every job filter for a query, with option ids and live counts: what `jobs --filter` and --company/--industry/--title/--place take.",
4747
- usage: 'lnrelay job-filters "<keywords>" [--location "<place>" | --geo <id>] [jobs filters]',
4748
- audience: ["cli", "mcp"],
4749
- risk: "read",
4750
- implemented: true
4751
- },
4752
- {
4753
- name: "post",
4754
- cost: "expensive \u2014 full read",
4755
- summary: "A post plus its comment thread, cursor-followed.",
4756
- usage: "lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\n Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\n returnedCount 0 is a FAILED FETCH, not an empty thread.",
4757
- audience: ["cli", "mcp"],
4758
- risk: "read",
4759
- implemented: true
4760
- },
4761
- {
4762
- name: "reactions",
4763
- cost: "medium",
4764
- summary: "Who reacted to a post, and with which reaction.",
4765
- usage: "lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]",
4766
- audience: ["cli", "mcp"],
4767
- risk: "read",
4768
- implemented: true
4769
- },
4770
- {
4771
- name: "company",
4772
- cost: "medium",
4773
- summary: "A company page, optionally with a bounded sample of its updates.",
4774
- usage: "lnrelay company <universal-name|url> [--updates N]",
4775
- audience: ["cli", "mcp"],
4776
- risk: "read",
4777
- implemented: false
4778
- },
4779
- {
4780
- name: "feed",
4781
- cost: "medium",
4782
- summary: "Your own chronological feed.",
4783
- usage: "lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]",
4784
- audience: ["cli", "mcp"],
4785
- risk: "read",
4786
- implemented: true
4787
- },
4788
- // ─── cache-backed — Phase 4 ────────────────────────────────────────────────
4789
- {
4790
- name: "sync",
4791
- cost: "medium \u2014 1-2 calls",
4792
- summary: "Pull your own posts or connections into the local cache for offline search.",
4793
- usage: "lnrelay sync my-posts|connections [--limit N] [--force]",
4794
- audience: ["cli"],
4795
- risk: "read",
4796
- implemented: true
4797
- },
4798
- {
4799
- name: "connections",
4800
- cost: "free \u2014 local cache",
4801
- summary: "Your connections, from the local cache. Fill it with `sync connections`.",
4802
- usage: 'lnrelay connections [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
4803
- audience: ["cli", "mcp"],
4804
- risk: "read",
4805
- implemented: true
4806
- },
4807
- {
4808
- name: "my-posts",
4809
- cost: "free \u2014 local cache",
4810
- summary: "Your own authored posts, from the local cache. Fill it with `sync my-posts`.",
4811
- usage: 'lnrelay my-posts [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
4812
- audience: ["cli", "mcp"],
4813
- risk: "read",
4814
- implemented: true
4815
- },
4816
- {
4817
- name: "scheduled",
4818
- cost: "1 call per 10 posts",
4819
- summary: "Your posts waiting to publish, with when. Not in `my-posts` until they go out.",
4820
- usage: "lnrelay scheduled\n Each row: urn (cancel with `delete`, change with `edit`), scheduledAt, text. Links in\n the text show as lnkd.in short links, as LinkedIn lists them.",
4821
- audience: ["cli", "mcp"],
4822
- risk: "read",
4823
- implemented: true
4824
- },
4825
- {
4826
- name: "experience",
4827
- cost: "2 calls",
4828
- summary: "The roles on your own profile, with the position id `role edit|remove` takes.",
4540
+ // src/commands/messaging.ts
4541
+ var MESSAGES_PAGE = 20;
4542
+ var MAX_CONVERSATIONS = 500;
4543
+ function live(command, quiet) {
4544
+ const session = loadSession();
4545
+ if (session.state !== "ok")
4546
+ return err(command, "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
4547
+ const client = createLiveClient(session.session, void 0, quiet);
4548
+ const fetch2 = async (url, spendClass) => {
4549
+ const r = await client.request({ url, spendClass, operation: command });
4550
+ return r.ok ? { ok: true, json: r.json } : r;
4551
+ };
4552
+ return { fetch: fetch2, session: session.session };
4553
+ }
4554
+ async function mailbox(command, quiet) {
4555
+ const known = loadJson(cachePath("me.json"));
4556
+ if (known.state === "ok" && typeof known.value.profileUrn === "string")
4557
+ return known.value.profileUrn;
4558
+ const session = loadSession();
4559
+ if (session.state !== "ok")
4560
+ return err(command, "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
4561
+ const me = await createEngine(session.session, void 0, quiet).whoami();
4562
+ const urn = me.ok ? me.value?.entityUrn : void 0;
4563
+ if (typeof urn !== "string")
4564
+ return err(command, "AUTH_FAILED", "could not tell whose mailbox this is");
4565
+ const profileUrn = mailboxOf(urn);
4566
+ saveJson(cachePath("me.json"), { profileUrn });
4567
+ return profileUrn;
4568
+ }
4569
+ async function setup(command, opts, fetch2) {
4570
+ const box = await mailbox(command, opts.quiet === true);
4571
+ if (typeof box !== "string") return box;
4572
+ if (fetch2 !== void 0) return { box, get: fetch2 };
4573
+ const l = live(command, opts.quiet === true);
4574
+ if ("ok" in l) return l;
4575
+ return { box, get: l.fetch };
4576
+ }
4577
+ function compactConversation(c) {
4578
+ const last = c.last === void 0 ? void 0 : `${c.last.from}: ${(c.last.text ?? "").replace(/\s+/g, " ")}`;
4579
+ return line([
4580
+ c.id,
4581
+ c.with.map((p) => p.name).join(", ") || c.title,
4582
+ c.unread > 0 ? `${c.unread} unread` : void 0,
4583
+ c.lastActivity?.slice(0, 10),
4584
+ c.inmail ? "InMail" : void 0,
4585
+ last !== void 0 && last.length > 140 ? `${last.slice(0, 137)}\u2026` : last
4586
+ ]);
4587
+ }
4588
+ async function runInbox(req, opts = {}, fetch2) {
4589
+ const folder = req.folder ?? "inbox";
4590
+ if (!(folder in FOLDERS)) {
4591
+ return err(
4592
+ "inbox",
4593
+ "INVALID_INPUT",
4594
+ `no folder '${folder}'`,
4595
+ `one of: ${Object.keys(FOLDERS).join(", ")}`
4596
+ );
4597
+ }
4598
+ const ready = await setup("inbox", opts, fetch2);
4599
+ if ("ok" in ready) return ready;
4600
+ const want = Math.max(1, Math.min(req.limit, MAX_CONVERSATIONS));
4601
+ const all = [];
4602
+ let cursor;
4603
+ let stoppedBy;
4604
+ let exhausted = false;
4605
+ while (all.length < want) {
4606
+ const res = await ready.get(
4607
+ conversationsUrl({ mailbox: ready.box, folder, ...cursor ? { cursor } : {} }),
4608
+ "page"
4609
+ );
4610
+ const page = res.ok ? parseConversations(res.json, ready.box) : res;
4611
+ if (!page.ok) {
4612
+ if (all.length === 0) return err("inbox", page.code, page.message, page.hint);
4613
+ stoppedBy = page.code;
4614
+ break;
4615
+ }
4616
+ const room = want - all.length;
4617
+ all.push(...page.conversations.slice(0, room));
4618
+ if (page.conversations.length > room) break;
4619
+ if (page.cursor === void 0 || page.conversations.length === 0) {
4620
+ exhausted = true;
4621
+ break;
4622
+ }
4623
+ cursor = page.cursor;
4624
+ }
4625
+ const shown = req.unread === true ? all.filter((c) => c.unread > 0) : all;
4626
+ return ok("inbox", {
4627
+ folder,
4628
+ items: shape2(shown, opts, compactConversation),
4629
+ meta: {
4630
+ state: exhausted && stoppedBy === void 0 ? "complete" : "partial",
4631
+ operation: "inbox",
4632
+ returnedCount: shown.length,
4633
+ unread: all.filter((c) => c.unread > 0).length,
4634
+ ...stoppedBy !== void 0 ? { stoppedBy } : {}
4635
+ }
4636
+ });
4637
+ }
4638
+ async function runMessages(input, opts = {}, fetch2) {
4639
+ const ready = await setup("messages", opts, fetch2);
4640
+ if ("ok" in ready) return ready;
4641
+ const id = input === void 0 ? void 0 : conversationIdOf(input, ready.box);
4642
+ if (id === void 0) {
4643
+ return err(
4644
+ "messages",
4645
+ "INVALID_INPUT",
4646
+ "a conversation id or /messaging/thread/ URL is required",
4647
+ "ids come from `lnrelay inbox`"
4648
+ );
4649
+ }
4650
+ const res = await ready.get(messagesUrl(id), "page");
4651
+ const parsed = res.ok ? parseMessages(res.json, ready.box) : res;
4652
+ if (!parsed.ok) return err("messages", parsed.code, parsed.message, parsed.hint);
4653
+ return ok("messages", {
4654
+ conversation: id,
4655
+ url: threadUrl(id),
4656
+ items: shape2(
4657
+ parsed.messages,
4658
+ opts,
4659
+ (m) => line([
4660
+ m.at.slice(0, 16).replace("T", " "),
4661
+ m.from,
4662
+ m.subject,
4663
+ (m.text ?? "").replace(/\s+/g, " ")
4664
+ ])
4665
+ ),
4666
+ meta: {
4667
+ // A full page may have older messages behind it; this reads the latest page only.
4668
+ state: parsed.messages.length < MESSAGES_PAGE ? "complete" : "partial",
4669
+ operation: "messages",
4670
+ returnedCount: parsed.messages.length
4671
+ }
4672
+ });
4673
+ }
4674
+ var threadUrl = (conversationUrn) => {
4675
+ const thread = conversationUrn.match(/,(2-[^)]+)\)$/)?.[1];
4676
+ return thread === void 0 ? void 0 : `https://www.linkedin.com/messaging/thread/${thread}/`;
4677
+ };
4678
+ var DRAFTS = () => cachePath("drafts.json");
4679
+ function loadDrafts() {
4680
+ const loaded = loadJson(DRAFTS());
4681
+ if (loaded.state === "missing") return [];
4682
+ if (loaded.state === "corrupt")
4683
+ return {
4684
+ ok: false,
4685
+ code: "CACHE_CORRUPT",
4686
+ message: `drafts were unreadable; moved to ${loaded.quarantinedTo}`
4687
+ };
4688
+ return Array.isArray(loaded.value) ? loaded.value : [];
4689
+ }
4690
+ async function runDraft(conversation, text5, fetch2, opts = {}) {
4691
+ const body = text5?.trim() ?? "";
4692
+ if (body === "")
4693
+ return err(
4694
+ "draft",
4695
+ "INVALID_INPUT",
4696
+ "a draft needs text",
4697
+ 'lnrelay draft <conversation> "<text>" | --file <path>'
4698
+ );
4699
+ const box = await mailbox("draft", opts.quiet === true);
4700
+ if (typeof box !== "string") return box;
4701
+ const id = conversation === void 0 ? void 0 : conversationIdOf(conversation, box);
4702
+ if (id === void 0)
4703
+ return err(
4704
+ "draft",
4705
+ "INVALID_INPUT",
4706
+ "a conversation id or /messaging/thread/ URL is required",
4707
+ "ids come from `lnrelay inbox`"
4708
+ );
4709
+ const ready = await setup("draft", opts, fetch2);
4710
+ if ("ok" in ready) return ready;
4711
+ const res = await ready.get(messagesUrl(id), "page");
4712
+ const parsed = res.ok ? parseMessages(res.json, ready.box) : res;
4713
+ if (!parsed.ok) return err("draft", parsed.code, parsed.message, parsed.hint);
4714
+ const to = [...new Set(parsed.messages.filter((m) => !m.fromMe).map((m) => m.from))];
4715
+ const drafts = loadDrafts();
4716
+ if (!Array.isArray(drafts)) return err("draft", drafts.code, drafts.message);
4717
+ const url = threadUrl(id);
4718
+ const draft = {
4719
+ id: randomUUID().slice(0, 8),
4720
+ conversation: id,
4721
+ ...url !== void 0 ? { url } : {},
4722
+ to,
4723
+ text: body,
4724
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4725
+ };
4726
+ saveJson(DRAFTS(), [...drafts, draft]);
4727
+ return ok("draft", {
4728
+ saved: true,
4729
+ sent: false,
4730
+ draft,
4731
+ notice: "Saved on this machine only. Nothing was sent: open the link, review, and send it yourself."
4732
+ });
4733
+ }
4734
+ function draftText(text5, file) {
4735
+ return file !== void 0 ? readFileSync2(file, "utf-8") : text5;
4736
+ }
4737
+ function runDrafts(opts = {}) {
4738
+ const drafts = loadDrafts();
4739
+ if (!Array.isArray(drafts)) return err("drafts", drafts.code, drafts.message);
4740
+ return ok("drafts", {
4741
+ items: shape2(
4742
+ drafts,
4743
+ opts,
4744
+ (d) => line([d.id, d.to.join(", "), d.createdAt.slice(0, 10), d.text.replace(/\s+/g, " "), d.url])
4745
+ ),
4746
+ meta: { state: "complete", operation: "drafts", returnedCount: drafts.length }
4747
+ });
4748
+ }
4749
+ function runDraftRemove(id) {
4750
+ const drafts = loadDrafts();
4751
+ if (!Array.isArray(drafts)) return err("draft", drafts.code, drafts.message);
4752
+ if (id === void 0 || !drafts.some((d) => d.id === id)) {
4753
+ return err(
4754
+ "draft",
4755
+ "NOT_FOUND",
4756
+ `no draft '${id ?? ""}'`,
4757
+ `drafts: ${drafts.map((d) => d.id).join(", ") || "none"}`
4758
+ );
4759
+ }
4760
+ saveJson(
4761
+ DRAFTS(),
4762
+ drafts.filter((d) => d.id !== id)
4763
+ );
4764
+ return ok("draft", { removed: id });
4765
+ }
4766
+
4767
+ // src/commands/oauth.ts
4768
+ import { spawn } from "child_process";
4769
+ import { createServer } from "http";
4770
+ import { createInterface as createInterface2 } from "readline/promises";
4771
+
4772
+ // src/engine/oauth.ts
4773
+ var AUTHORIZE = "https://www.linkedin.com/oauth/v2/authorization";
4774
+ var TOKEN = "https://www.linkedin.com/oauth/v2/accessToken";
4775
+ var USERINFO = "https://api.linkedin.com/v2/userinfo";
4776
+ var CALLBACK_PORT = 53682;
4777
+ var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
4778
+ var SCOPES = ["openid", "profile", "w_member_social"];
4779
+ function authorizationUrl(clientId, state) {
4780
+ const params = new URLSearchParams({
4781
+ response_type: "code",
4782
+ client_id: clientId,
4783
+ redirect_uri: REDIRECT_URI,
4784
+ state,
4785
+ scope: SCOPES.join(" ")
4786
+ });
4787
+ return `${AUTHORIZE}?${params.toString()}`;
4788
+ }
4789
+ async function exchange(code, config, deps) {
4790
+ const body = new URLSearchParams({
4791
+ grant_type: "authorization_code",
4792
+ code,
4793
+ redirect_uri: REDIRECT_URI,
4794
+ client_id: config.clientId,
4795
+ client_secret: config.clientSecret
4796
+ });
4797
+ let res;
4798
+ try {
4799
+ res = await deps.fetch(TOKEN, {
4800
+ method: "POST",
4801
+ headers: { "content-type": "application/x-www-form-urlencoded" },
4802
+ body: body.toString()
4803
+ });
4804
+ } catch (e) {
4805
+ return { ok: false, message: `could not reach LinkedIn: ${e.message}` };
4806
+ }
4807
+ const text5 = await res.text();
4808
+ if (res.status !== 200) {
4809
+ return {
4810
+ ok: false,
4811
+ message: `LinkedIn rejected the code exchange (${res.status})`,
4812
+ // The most common causes, in the order they actually happen.
4813
+ 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)}`
4814
+ };
4815
+ }
4816
+ let parsed;
4817
+ try {
4818
+ parsed = JSON.parse(text5);
4819
+ } catch {
4820
+ return { ok: false, message: "token response was not JSON" };
4821
+ }
4822
+ const accessToken = parsed.access_token;
4823
+ const expiresIn = parsed.expires_in;
4824
+ if (typeof accessToken !== "string" || accessToken === "") {
4825
+ return { ok: false, message: "token response carried no access_token" };
4826
+ }
4827
+ const lifetimeMs = typeof expiresIn === "number" ? expiresIn * 1e3 : 60 * 864e5;
4828
+ return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };
4829
+ }
4830
+ async function fetchMemberUrn(accessToken, deps) {
4831
+ let res;
4832
+ try {
4833
+ res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });
4834
+ } catch (e) {
4835
+ return { ok: false, message: `could not reach userinfo: ${e.message}` };
4836
+ }
4837
+ if (res.status !== 200) {
4838
+ return {
4839
+ ok: false,
4840
+ message: `userinfo returned ${res.status} \u2014 the 'openid'/'profile' scopes may not be granted`
4841
+ };
4842
+ }
4843
+ const parsed = await res.json();
4844
+ if (typeof parsed.sub !== "string" || parsed.sub === "") {
4845
+ return { ok: false, message: "userinfo carried no subject claim" };
4846
+ }
4847
+ return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };
4848
+ }
4849
+ function parseCallback(rawUrl, expectedState) {
4850
+ let url;
4851
+ try {
4852
+ url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);
4853
+ } catch {
4854
+ return { ok: false, message: "callback URL was unparseable" };
4855
+ }
4856
+ const error = url.searchParams.get("error");
4857
+ if (error !== null) {
4858
+ const description = url.searchParams.get("error_description") ?? "";
4859
+ return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
4860
+ }
4861
+ const state = url.searchParams.get("state");
4862
+ if (state !== expectedState) {
4863
+ return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
4864
+ }
4865
+ const code = url.searchParams.get("code");
4866
+ if (code === null || code === "") return { ok: false, message: "callback carried no code" };
4867
+ return { ok: true, code };
4868
+ }
4869
+
4870
+ // src/commands/token.ts
4871
+ import { existsSync as existsSync3, rmSync } from "fs";
4872
+ var TOKEN_FILE = "oauth.json";
4873
+ var OAUTH_SETUP = [
4874
+ "Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one",
4875
+ "legitimacy wedge an individual actually has \u2014 but the app has to be registered by you; it",
4876
+ "cannot be created on your behalf.",
4877
+ "",
4878
+ " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
4879
+ ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
4880
+ " Both are self-serve: no partner review, no verification, no screencast.",
4881
+ ` 3. Auth tab \u2192 add redirect URL ${REDIRECT_URI}`,
4882
+ " 4. Run: lnrelay oauth login --client-id <id>",
4883
+ " (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)"
4884
+ ].join("\n");
4885
+ function tokenPath() {
4886
+ return cachePath(TOKEN_FILE);
4887
+ }
4888
+ function loadToken() {
4889
+ const result = loadJson(tokenPath());
4890
+ return result.state === "ok" ? result.value : null;
4891
+ }
4892
+ function saveToken(token) {
4893
+ saveJson(tokenPath(), token);
4894
+ }
4895
+ function deleteToken() {
4896
+ const path = tokenPath();
4897
+ if (!existsSync3(path)) return false;
4898
+ rmSync(path, { force: true });
4899
+ return true;
4900
+ }
4901
+
4902
+ // src/commands/oauth.ts
4903
+ var CALLBACK_TIMEOUT_MS = 3e5;
4904
+ var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
4905
+ <body style="font:16px system-ui;padding:3rem;max-width:32rem">
4906
+ <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
4907
+ function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
4908
+ return new Promise((ready) => {
4909
+ let settle = () => {
4910
+ };
4911
+ const code = new Promise((r) => {
4912
+ settle = r;
4913
+ });
4914
+ const server = createServer((req, res) => {
4915
+ const url = req.url ?? "/";
4916
+ if (!url.startsWith("/callback")) {
4917
+ res.writeHead(404, { connection: "close" });
4918
+ res.end();
4919
+ return;
4920
+ }
4921
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
4922
+ res.end(DONE_PAGE);
4923
+ settle(parseCallback(url, state));
4924
+ });
4925
+ const timer = setTimeout(() => {
4926
+ settle({
4927
+ ok: false,
4928
+ message: `timed out after ${Math.round(timeoutMs / 1e3)}s waiting for the LinkedIn callback`
4929
+ });
4930
+ }, timeoutMs);
4931
+ timer.unref?.();
4932
+ const close = () => {
4933
+ clearTimeout(timer);
4934
+ server.closeAllConnections?.();
4935
+ server.close();
4936
+ };
4937
+ server.once("error", (e) => {
4938
+ clearTimeout(timer);
4939
+ 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}`;
4940
+ ready({ ok: false, message: why });
4941
+ });
4942
+ server.listen(CALLBACK_PORT, "127.0.0.1", () => {
4943
+ ready({ ok: true, code, close });
4944
+ });
4945
+ });
4946
+ }
4947
+ function openBrowser(url) {
4948
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
4949
+ try {
4950
+ spawn(cmd, [url], { detached: true, stdio: "ignore" }).unref();
4951
+ } catch {
4952
+ }
4953
+ }
4954
+ function loginDeps() {
4955
+ return {
4956
+ state: () => crypto.randomUUID(),
4957
+ listen: (state) => listenForCallback(state),
4958
+ open: openBrowser,
4959
+ write: (s) => process.stderr.write(s),
4960
+ isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
4961
+ prompt: async (question) => {
4962
+ const rl = createInterface2({ input: process.stdin, output: process.stderr });
4963
+ const answer = await rl.question(question);
4964
+ rl.close();
4965
+ return answer;
4966
+ },
4967
+ now: Date.now,
4968
+ fetch: globalThis.fetch
4969
+ };
4970
+ }
4971
+ async function credentials(opts, deps) {
4972
+ const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;
4973
+ if (clientId === void 0 || clientId === "") {
4974
+ return err("oauth", "INVALID_INPUT", "a client id is required", OAUTH_SETUP);
4975
+ }
4976
+ let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;
4977
+ if ((clientSecret === void 0 || clientSecret === "") && deps.isTty) {
4978
+ clientSecret = (await deps.prompt("client secret (not echoed to argv or logs): ")).trim();
4979
+ }
4980
+ if (clientSecret === void 0 || clientSecret === "") {
4981
+ return err(
4982
+ "oauth",
4983
+ "INVALID_INPUT",
4984
+ "a client secret is required, and there is no terminal to ask on",
4985
+ `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.
4986
+
4987
+ ${OAUTH_SETUP}`
4988
+ );
4989
+ }
4990
+ return { clientId, clientSecret };
4991
+ }
4992
+ async function runOauthLogin(opts, deps = loginDeps()) {
4993
+ const creds = await credentials(opts, deps);
4994
+ if ("ok" in creds) return creds;
4995
+ const state = deps.state();
4996
+ const listener = await deps.listen(state);
4997
+ if (!listener.ok) {
4998
+ return err("oauth", "AUTH_FAILED", listener.message);
4999
+ }
5000
+ try {
5001
+ const url = authorizationUrl(creds.clientId, state);
5002
+ deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
5003
+
5004
+ ${url}
5005
+
5006
+ `);
5007
+ deps.open(url);
5008
+ const callback = await listener.code;
5009
+ if (!callback.ok) return err("oauth", "AUTH_FAILED", callback.message);
5010
+ const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });
5011
+ if (!token.ok) return err("oauth", "AUTH_FAILED", token.message, token.hint);
5012
+ const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });
5013
+ if (!member.ok) return err("oauth", "AUTH_FAILED", member.message, OAUTH_SETUP);
5014
+ saveToken({
5015
+ accessToken: token.accessToken,
5016
+ memberUrn: member.memberUrn,
5017
+ expiresAt: token.expiresAt
5018
+ });
5019
+ return ok("oauth", {
5020
+ memberUrn: member.memberUrn,
5021
+ scopes: SCOPES,
5022
+ expiresAt: new Date(token.expiresAt).toISOString(),
5023
+ storedAt: tokenPath(),
5024
+ // Refresh tokens are partner-gated, so renewal is re-running this.
5025
+ renewal: "run `lnrelay oauth login` again when it expires"
5026
+ });
5027
+ } finally {
5028
+ listener.close();
5029
+ }
5030
+ }
5031
+ function runOauthLogout() {
5032
+ const removed = deleteToken();
5033
+ return ok("oauth", {
5034
+ removed,
5035
+ note: removed ? `deleted ${tokenPath()} \u2014 the token stays valid on LinkedIn's side until it expires` : "no token was stored"
5036
+ });
5037
+ }
5038
+ function runOauthStatus() {
5039
+ const token = loadToken();
5040
+ if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
5041
+ return ok("oauth", {
5042
+ memberUrn: token.memberUrn,
5043
+ expiresAt: new Date(token.expiresAt).toISOString(),
5044
+ expired: token.expiresAt <= Date.now(),
5045
+ scopes: SCOPES,
5046
+ storedAt: tokenPath(),
5047
+ writeCap: CAPS.write.perDay
5048
+ });
5049
+ }
5050
+
5051
+ // src/engine/sdui-form.ts
5052
+ function balanced(s, start) {
5053
+ const open = s[start];
5054
+ const close = open === "[" ? "]" : "}";
5055
+ let depth = 0;
5056
+ let inString = false;
5057
+ let escaped = false;
5058
+ for (let i = start; i < s.length; i++) {
5059
+ const ch = s[i];
5060
+ if (escaped) escaped = false;
5061
+ else if (ch === "\\") escaped = true;
5062
+ else if (ch === '"') inString = !inString;
5063
+ else if (!inString && ch === open) depth++;
5064
+ else if (!inString && ch === close) {
5065
+ depth--;
5066
+ if (depth === 0) return s.slice(start, i + 1);
5067
+ }
5068
+ }
5069
+ return null;
5070
+ }
5071
+ function parseAt(s, start) {
5072
+ const text5 = start < 0 ? null : balanced(s, start);
5073
+ if (text5 === null) return null;
5074
+ try {
5075
+ return JSON.parse(text5);
5076
+ } catch {
5077
+ return null;
5078
+ }
5079
+ }
5080
+ function plain(v) {
5081
+ const protoCase = String(v.$case);
5082
+ const raw = v[protoCase];
5083
+ if (protoCase === "stringListValue") {
5084
+ return { protoCase, value: raw?.stringValues ?? [] };
5085
+ }
5086
+ if (protoCase === "signedLongValue" && typeof raw === "string" && raw.startsWith("$n")) {
5087
+ return { protoCase, value: { type: "bigint", value: raw.slice(2) } };
5088
+ }
5089
+ return { protoCase, value: raw };
5090
+ }
5091
+ function readModel(stream) {
5092
+ const at = stream.indexOf('"modelStates":[');
5093
+ const entries = parseAt(stream, at === -1 ? -1 : stream.indexOf("[", at));
5094
+ if (entries === null) return null;
5095
+ const model = /* @__PURE__ */ new Map();
5096
+ for (const entry2 of entries) {
5097
+ const id = entry2.key?.key?.value?.id;
5098
+ if (id !== void 0 && entry2.value !== void 0 && !model.has(id)) {
5099
+ model.set(id, plain(entry2.value));
5100
+ }
5101
+ }
5102
+ return model;
5103
+ }
5104
+ function findRequest(stream, requestId) {
5105
+ const at = stream.indexOf(`"requestId":"${requestId}","requestedArguments":`);
5106
+ if (at === -1) return null;
5107
+ const args = parseAt(
5108
+ stream,
5109
+ stream.indexOf("{", stream.indexOf('"requestedArguments":', at))
5110
+ );
5111
+ return args !== null && Array.isArray(args.requestedStateKeys) && args.payload !== void 0 ? args : null;
5112
+ }
5113
+ var unknownExpression = (what) => ({
5114
+ ok: false,
5115
+ code: "SCHEMA_DRIFT",
5116
+ message: `the form computes a value with an expression this tool does not evaluate (${what})`,
5117
+ hint: "Nothing was sent. Re-capture the form to see what it has become."
5118
+ });
5119
+ function boundId(body) {
5120
+ return body?.key?.key?.value?.id;
5121
+ }
5122
+ function str2(node, model) {
5123
+ const e = node.expression;
5124
+ if (e?.$case === "stringValue") return String(e.stringValue);
5125
+ if (e?.$case === "bindableString") {
5126
+ const v = model.get(boundId(e.bindableString) ?? "")?.value;
5127
+ return typeof v === "string" ? v : "";
5128
+ }
5129
+ return null;
5130
+ }
5131
+ function bool2(node, model) {
5132
+ const e = node.expression;
5133
+ const body = e?.[e?.$case ?? ""];
5134
+ switch (e?.$case) {
5135
+ case "booleanExpression":
5136
+ return bool2(body, model);
5137
+ case "booleanValue":
5138
+ return e.booleanValue === true;
5139
+ case "bindableBoolean":
5140
+ return model.get(boundId(e.bindableBoolean) ?? "")?.value === true;
5141
+ case "notExpression": {
5142
+ const a = bool2(body?.a ?? {}, model);
5143
+ return a === null ? null : !a;
5144
+ }
5145
+ case "orExpression":
5146
+ case "andExpression": {
5147
+ const a = bool2(body?.a ?? {}, model);
5148
+ const b = bool2(body?.b ?? {}, model);
5149
+ if (a === null || b === null) return null;
5150
+ return e.$case === "orExpression" ? a || b : a && b;
5151
+ }
5152
+ case "stringEqualsExpression": {
5153
+ const a = str2(body?.a ?? {}, model);
5154
+ const b = str2(body?.b ?? {}, model);
5155
+ if (a === null || b === null) return null;
5156
+ return body.ignoreCase === true ? a.toLowerCase() === b.toLowerCase() : a === b;
5157
+ }
5158
+ default:
5159
+ return null;
5160
+ }
5161
+ }
5162
+ function evaluate(expression, model) {
5163
+ const value = bool2(expression, model);
5164
+ return value === null ? unknownExpression(JSON.stringify(expression).slice(0, 80)) : { ok: true, value };
5165
+ }
5166
+ function wireStates(keys, model, resolve) {
5167
+ const out = [];
5168
+ for (const id of keys) {
5169
+ const state = model.get(id);
5170
+ if (state === void 0) continue;
5171
+ let value = state.value;
5172
+ if (state.protoCase === "expression") {
5173
+ const r = resolve(id, state) ?? evaluate(state.value, model);
5174
+ if (!r.ok) return r;
5175
+ value = r.value;
5176
+ }
5177
+ out.push({
5178
+ key: id,
5179
+ namespace: "MemoryNamespace",
5180
+ value,
5181
+ originalProtoCase: state.protoCase,
5182
+ protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id } }
5183
+ });
5184
+ }
5185
+ return out;
5186
+ }
5187
+ var keysOf = (args) => args.requestedStateKeys.map((k) => k.key.value.id);
5188
+ function requestBody(requestId, args, states2, screen) {
5189
+ const requestedArguments = {
5190
+ $type: "proto.sdui.actions.requests.RequestedArguments",
5191
+ requestedStateKeys: args.requestedStateKeys,
5192
+ payload: args.payload,
5193
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
5194
+ };
5195
+ return {
5196
+ requestId,
5197
+ serverRequest: {
5198
+ requestId,
5199
+ requestedArguments,
5200
+ isApfcEnabled: false,
5201
+ isStreaming: false,
5202
+ rumPageKey: ""
5203
+ },
5204
+ states: states2,
5205
+ requestedArguments: { ...requestedArguments, states: states2, screenId: screen, knownTemplateIds: [] }
5206
+ };
5207
+ }
5208
+ function navBody(screen, payload) {
5209
+ return {
5210
+ clientArguments: {
5211
+ $type: "proto.sdui.actions.requests.RequestedArguments",
5212
+ requestedStateKeys: [],
5213
+ payload,
5214
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" },
5215
+ states: [],
5216
+ screenId: screen,
5217
+ knownTemplateIds: []
5218
+ },
5219
+ isModal: true
5220
+ };
5221
+ }
5222
+ function responseErrors(raw) {
5223
+ return raw.match(/"errors":\[([^\]]+)\]/)?.[1]?.slice(0, 300) ?? null;
5224
+ }
5225
+
5226
+ // src/engine/posts.ts
5227
+ var POSTS_PAGER = "com.linkedin.sdui.search.contentSearchResults";
5228
+ var SCREEN = "com.linkedin.sdui.flagshipnav.search.SearchResultsContent";
5229
+ var POSTS_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${POSTS_PAGER}`;
5230
+ var POSTS_PAGE = 20;
5231
+ var POST_FILTERS = [
5232
+ "sortBy",
5233
+ "postedBy",
5234
+ "datePosted",
5235
+ "contentType",
5236
+ "fromMember",
5237
+ "mentionsOrganization",
5238
+ "mentionsMember",
5239
+ "fromOrganization",
5240
+ "authorCompany",
5241
+ "authorIndustry",
5242
+ "authorJobTitle"
5243
+ ];
5244
+ function postsPagerBody(q2) {
5245
+ const payload = {
5246
+ startIndex: q2.start,
5247
+ keywords: q2.keywords ?? "",
5248
+ count: q2.count ?? POSTS_PAGE
5249
+ };
5250
+ for (const f of POST_FILTERS) payload[f] = q2.filters[f] ?? [];
5251
+ payload.spellCheckEnabled = true;
5252
+ const args = {
5253
+ $type: "proto.sdui.actions.requests.RequestedArguments",
5254
+ requestedStateKeys: [],
5255
+ payload,
5256
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
5257
+ };
5258
+ return {
5259
+ pagerId: POSTS_PAGER,
5260
+ clientArguments: { ...args, states: [], screenId: SCREEN, knownTemplateIds: [] },
5261
+ paginationRequest: {
5262
+ $type: "proto.sdui.actions.requests.PaginationRequest",
5263
+ pagerId: POSTS_PAGER,
5264
+ retryCount: 0,
5265
+ requestedArguments: args
5266
+ }
5267
+ };
5268
+ }
5269
+ var Rows = class {
5270
+ constructor(stream) {
5271
+ this.stream = stream;
5272
+ for (const m of stream.matchAll(/(?:^|\n)([0-9a-f]+):/g)) {
5273
+ const at = (m.index ?? 0) + (m[0].startsWith("\n") ? 1 : 0);
5274
+ this.starts.push({ id: m[1], at });
5275
+ }
5276
+ for (let i = 0; i < this.starts.length; i++) {
5277
+ const s = this.starts[i];
5278
+ const end = this.starts[i + 1]?.at ?? stream.length;
5279
+ this.byId.set(s.id, stream.slice(s.at + s.id.length + 1, end));
5280
+ }
5281
+ }
5282
+ stream;
5283
+ byId = /* @__PURE__ */ new Map();
5284
+ starts = [];
5285
+ /** The row a stream position falls in. */
5286
+ at(pos) {
5287
+ let lo = 0;
5288
+ let hi = this.starts.length - 1;
5289
+ while (lo < hi) {
5290
+ const mid = lo + hi + 1 >> 1;
5291
+ if (this.starts[mid].at <= pos) lo = mid;
5292
+ else hi = mid - 1;
5293
+ }
5294
+ return this.starts[lo]?.id;
5295
+ }
5296
+ /** Every row reachable from `id` through references, nearest first. */
5297
+ reach(id, limit = 400) {
5298
+ const seen = /* @__PURE__ */ new Set([id]);
5299
+ const queue = [id];
5300
+ while (queue.length > 0 && seen.size < limit) {
5301
+ const row = this.byId.get(queue.shift()) ?? "";
5302
+ for (const m of row.matchAll(/"\$L?([0-9a-f]+)(?::[^"]*)?"/g)) {
5303
+ const ref = m[1];
5304
+ if (!seen.has(ref) && this.byId.has(ref)) {
5305
+ seen.add(ref);
5306
+ queue.push(ref);
5307
+ }
5308
+ }
5309
+ }
5310
+ return [...seen];
5311
+ }
5312
+ };
5313
+ function strings(v, out = []) {
5314
+ if (typeof v === "string") {
5315
+ if (!v.startsWith("$")) out.push(v);
5316
+ } else if (Array.isArray(v)) {
5317
+ if (v[0] === "$" && v[1] === "br") out.push("\n");
5318
+ else if (v[0] === "$") strings(v[3], out);
5319
+ else for (const x of v) strings(x, out);
5320
+ } else if (v !== null && typeof v === "object" && "children" in v) {
5321
+ strings(v.children, out);
5322
+ }
5323
+ return out;
5324
+ }
5325
+ function texts(row, from = 0) {
5326
+ const part2 = row.slice(Math.max(0, from));
5327
+ const out = [];
5328
+ for (const m of part2.matchAll(/"textProps":/g)) {
5329
+ const obj = balanced(part2, part2.indexOf("{", m.index ?? 0));
5330
+ if (obj === null) continue;
5331
+ const t = strings(JSON.parse(obj)).join("").trim();
5332
+ if (t !== "") out.push(t);
5333
+ }
5334
+ return out;
5335
+ }
5336
+ var jsonString = (s) => JSON.parse(`"${s}"`);
5337
+ var REACTIONS = [
5338
+ "LIKE",
5339
+ "PRAISE",
5340
+ "EMPATHY",
5341
+ "INTEREST",
5342
+ "APPRECIATION",
5343
+ "ENTERTAINMENT",
5344
+ "SUPER_LIKE"
5345
+ ];
5346
+ function part(rows, from, view, depth = 60) {
5347
+ const id = from.find((r) => rows.byId.get(r)?.includes(`"viewName":"${view}"`));
5348
+ return id === void 0 ? void 0 : { row: id, under: rows.reach(id, depth) };
5349
+ }
5350
+ function firstIn(rows, ids, find) {
5351
+ for (const id of ids) {
5352
+ const v = find(rows.byId.get(id) ?? "");
5353
+ if (v !== void 0) return { id, v };
5354
+ }
5355
+ return void 0;
5356
+ }
5357
+ function authorOf(rows, actor) {
5358
+ if (actor === void 0) return { fields: {}, used: [] };
5359
+ const state = (key) => (row) => {
5360
+ const m = row.match(new RegExp(`"${key}"[^]*?"stringValue":"((?:[^"\\\\]|\\\\.)*)"`));
5361
+ return m?.[1] === void 0 ? void 0 : jsonString(m[1]);
5362
+ };
5363
+ const link = firstIn(
5364
+ rows,
5365
+ actor.under,
5366
+ (row) => row.match(
5367
+ /"(?:https:\/\/www\.linkedin\.com)?(\/(?:in|company|school|showcase)\/[^"?/]+)/
5368
+ )?.[1]
5369
+ );
5370
+ const person = firstIn(rows, actor.under, state("profile_name_loading_state"));
5371
+ const headline = firstIn(rows, actor.under, state("profile_headline_loading_state"));
5372
+ const page = person !== void 0 ? void 0 : firstIn(rows, actor.under, (row) => {
5373
+ const labels = [...row.matchAll(/"aria-label":"((?:[^"\\]|\\.)+)"/g)].map(
5374
+ (m) => jsonString(m[1]).trim()
5375
+ );
5376
+ return texts(row).find((t) => labels.some((l) => l === t || l.startsWith(`${t} `)));
5377
+ });
5378
+ const named2 = person ?? page;
5379
+ return {
5380
+ fields: {
5381
+ ...named2 !== void 0 ? { author: named2.v.trim() } : {},
5382
+ ...headline !== void 0 ? { authorHeadline: headline.v } : {},
5383
+ ...link !== void 0 ? { authorUrl: `https://www.linkedin.com${link.v}/` } : {}
5384
+ },
5385
+ used: [link?.id, named2?.id, headline?.id].filter((x) => x !== void 0)
5386
+ };
5387
+ }
5388
+ function readPost(rows, top, model) {
5389
+ const reach = rows.reach(top);
5390
+ const counted = reach.find((r) => /commentCount-urn:li:\w+:\d+/.test(rows.byId.get(r) ?? ""));
5391
+ const id = counted === void 0 ? void 0 : rows.byId.get(counted)?.match(/commentCount-(urn:li:\w+:\d+)/)?.[1];
5392
+ if (id === void 0) return { post: void 0, used: [top] };
5393
+ const actor = part(rows, reach, "feed-actor");
5394
+ const author = authorOf(rows, actor);
5395
+ const sub = part(rows, reach, "feed-actor-sub-description", 4);
5396
+ const commentary = part(rows, reach, "feed-commentary");
5397
+ const n = (k) => {
5398
+ const v = model?.get(k)?.value;
5399
+ return typeof v === "number" ? v : void 0;
5400
+ };
5401
+ const byType = REACTIONS.map((r) => n(`ReactionType_${r}_${id}`));
5402
+ const reactions = byType.some((v) => v !== void 0) ? byType.reduce((a, v) => a + (v ?? 0), 0) : void 0;
5403
+ const subRow = sub === void 0 ? "" : rows.byId.get(sub.row) ?? "";
5404
+ const posted = sub === void 0 ? void 0 : texts(subRow, subRow.indexOf('"viewName":"feed-actor-sub-description"'))[0];
5405
+ const said = commentary === void 0 ? void 0 : firstIn(rows, commentary.under, (row) => texts(row)[0]);
5406
+ const text5 = said?.v;
5407
+ const post = {
5408
+ id,
5409
+ url: `https://www.linkedin.com/feed/update/${id}/`,
5410
+ ...author.fields,
5411
+ ...posted !== void 0 ? { posted } : {},
5412
+ ...text5 !== void 0 ? { text: text5 } : {},
5413
+ ...reactions !== void 0 ? { reactions } : {}
5414
+ };
5415
+ const comments = n(`commentCount-${id}`);
5416
+ const reposts = n(`repostCount-${id}`);
5417
+ if (comments !== void 0) post.comments = comments;
5418
+ if (reposts !== void 0) post.reposts = reposts;
5419
+ const parts = [actor?.row, sub?.row, commentary?.row, said?.id].filter(
5420
+ (x) => x !== void 0
5421
+ );
5422
+ const used = [top, counted, ...author.used, ...parts];
5423
+ return { post, used };
5424
+ }
5425
+ function parsePosts(stream) {
5426
+ if (!stream.includes(POSTS_PAGER) && !stream.includes('"isPartialPage"') && !stream.includes("feed-full-update")) {
5427
+ return {
5428
+ ok: false,
5429
+ code: "SCHEMA_DRIFT",
5430
+ message: "the posts search page could not be read",
5431
+ hint: "the posts search response changed shape; re-capture it"
5432
+ };
5433
+ }
5434
+ const rows = new Rows(stream);
5435
+ const model = readModel(stream);
5436
+ const posts = [];
5437
+ const used = /* @__PURE__ */ new Set();
5438
+ const tops = /* @__PURE__ */ new Set();
5439
+ let unread = 0;
5440
+ for (const m of stream.matchAll(/"viewName":"feed-full-update"/g)) {
5441
+ const top = rows.at(m.index ?? 0);
5442
+ if (top === void 0 || tops.has(top)) continue;
5443
+ tops.add(top);
5444
+ const r = readPost(rows, top, model);
5445
+ for (const u of r.used) used.add(u);
5446
+ if (r.post === void 0) unread++;
5447
+ else if (!posts.some((p) => p.id === r.post?.id)) posts.push(r.post);
5448
+ }
5449
+ if (unread > 0 && posts.length === 0) {
5450
+ return {
5451
+ ok: false,
5452
+ code: "SCHEMA_DRIFT",
5453
+ message: `${unread} posts were listed but none could be read`,
5454
+ hint: "the posts search response changed shape; re-capture it"
5455
+ };
5456
+ }
5457
+ return { ok: true, posts, unread, used };
5458
+ }
5459
+
5460
+ // src/commands/posts-search.ts
5461
+ function liveFetch3(quiet) {
5462
+ const session = loadSession();
5463
+ if (session.state !== "ok")
5464
+ return err("search posts", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
5465
+ const client = createLiveClient(session.session, void 0, quiet);
5466
+ return async (url, body, spendClass) => {
5467
+ const r = await client.request({
5468
+ url,
5469
+ ...body !== void 0 ? { method: "POST", body } : {},
5470
+ spendClass,
5471
+ operation: "search-posts"
5472
+ });
5473
+ if (!r.ok) return r;
5474
+ return { ok: true, raw: r.classification.raw ?? "", json: r.json };
5475
+ };
5476
+ }
5477
+ var PAGING3 = { pageSize: POSTS_PAGE, max: 1e3 };
5478
+ var CHOICES = {
5479
+ sort: { param: "sortBy", values: { recent: "date_posted", relevant: "relevance" } },
5480
+ posted: {
5481
+ param: "datePosted",
5482
+ values: { "24h": "past-24h", day: "past-24h", week: "past-week", month: "past-month" }
5483
+ },
5484
+ type: {
5485
+ param: "contentType",
5486
+ values: {
5487
+ videos: "videos",
5488
+ images: "photos",
5489
+ photos: "photos",
5490
+ jobs: "jobs",
5491
+ live: "liveVideos",
5492
+ articles: "articles",
5493
+ documents: "documents"
5494
+ }
5495
+ },
5496
+ postedBy: { param: "postedBy", values: { "1st": "first", me: "me", first: "first" } }
5497
+ };
5498
+ function choose(name, given) {
5499
+ const { values } = CHOICES[name];
5500
+ const out = [];
5501
+ for (const g of given) {
5502
+ const v = values[g.toLowerCase()];
5503
+ if (v === void 0)
5504
+ return {
5505
+ ok: false,
5506
+ code: "INVALID_INPUT",
5507
+ message: `--${name} '${g}' is not one of: ${Object.keys(values).join(", ")}`
5508
+ };
5509
+ out.push(v);
5510
+ }
5511
+ return out;
5512
+ }
5513
+ async function companies(get, given) {
5514
+ const ids = [];
5515
+ const found = [];
5516
+ for (const v of given) {
5517
+ if (/^\d+$/.test(v)) {
5518
+ ids.push(v);
5519
+ continue;
5520
+ }
5521
+ const res = await get(
5522
+ peopleSearchUrl({ keywords: v, params: {}, start: 0, kind: "COMPANIES" }),
5523
+ void 0,
5524
+ "search"
5525
+ );
5526
+ const hits = res.ok ? parseOrgHits(res.json) : res;
5527
+ if (!hits.ok) return hits;
5528
+ const top = hits.hits[0];
5529
+ if (top === void 0)
5530
+ return { ok: false, code: "INVALID_INPUT", message: `no company on LinkedIn matches "${v}"` };
5531
+ ids.push(top.id);
5532
+ found.push({ given: v, id: top.id, name: top.name });
5533
+ }
5534
+ return { ids, found };
5535
+ }
5536
+ function choices(req) {
5537
+ const filters = {};
5538
+ const picks = [
5539
+ ["sort", req.sort !== void 0 ? [req.sort] : void 0],
5540
+ ["posted", req.posted !== void 0 ? [req.posted] : void 0],
5541
+ ["type", req.type],
5542
+ ["postedBy", req.postedBy]
5543
+ ];
5544
+ for (const [name, given] of picks) {
5545
+ if (given === void 0 || given.length === 0) continue;
5546
+ const v = choose(name, given);
5547
+ if (!Array.isArray(v)) return v;
5548
+ filters[CHOICES[name].param] = v;
5549
+ }
5550
+ if (req.from !== void 0 && req.from.length > 0) filters.fromMember = req.from;
5551
+ if (req.mentions !== void 0 && req.mentions.length > 0) filters.mentionsMember = req.mentions;
5552
+ if (req.authorIndustry !== void 0 && req.authorIndustry.length > 0)
5553
+ filters.authorIndustry = req.authorIndustry;
5554
+ if (req.authorTitle !== void 0 && req.authorTitle.trim() !== "")
5555
+ filters.authorJobTitle = [req.authorTitle.trim()];
5556
+ for (const r of req.raw ?? []) {
5557
+ const m = r.match(/^([A-Za-z_]+)=(.+)$/);
5558
+ if (m?.[1] === void 0 || m[2] === void 0)
5559
+ return {
5560
+ ok: false,
5561
+ code: "INVALID_INPUT",
5562
+ message: `--filter '${r}' is not key=value[,value]`
5563
+ };
5564
+ filters[m[1]] = m[2].split(",").map((v) => v.trim()).filter((v) => v !== "");
5565
+ }
5566
+ return filters;
5567
+ }
5568
+ async function filtersOf(req, get) {
5569
+ const filters = choices(req);
5570
+ if ("ok" in filters) return filters;
5571
+ const resolved = {};
5572
+ const orgs2 = [
5573
+ ["fromCompany", "fromOrganization"],
5574
+ ["mentionsCompany", "mentionsOrganization"],
5575
+ ["authorCompany", "authorCompany"]
5576
+ ];
5577
+ for (const [key, param] of orgs2) {
5578
+ const given = req[key];
5579
+ if (given === void 0 || given.length === 0) continue;
5580
+ const r = await companies(get, given);
5581
+ if ("ok" in r) return r;
5582
+ filters[param] = r.ids;
5583
+ if (r.found.length > 0) resolved[key] = r.found;
5584
+ }
5585
+ return { filters, resolved };
5586
+ }
5587
+ function compactPost(p) {
5588
+ const counts = [
5589
+ p.reactions !== void 0 ? `${p.reactions} reactions` : void 0,
5590
+ p.comments !== void 0 ? `${p.comments} comments` : void 0,
5591
+ p.reposts !== void 0 ? `${p.reposts} reposts` : void 0
5592
+ ].filter(Boolean);
5593
+ const text5 = p.text?.replace(/\s+/g, " ");
5594
+ return line([
5595
+ p.id,
5596
+ p.author,
5597
+ p.posted,
5598
+ counts.length > 0 ? counts.join(" \xB7 ") : void 0,
5599
+ text5 !== void 0 && text5.length > 160 ? `${text5.slice(0, 157)}\u2026` : text5,
5600
+ p.url,
5601
+ p.matched !== void 0 ? `matched: ${p.matched.join(" + ")}` : void 0
5602
+ ]);
5603
+ }
5604
+ async function runPostsSearch(req, opts = {}, fetch2) {
5605
+ const command = "search posts";
5606
+ const sets = keywordSets(req.keywords);
5607
+ const early = choices(req);
5608
+ if ("ok" in early) return err(command, early.code, early.message, early.hint);
5609
+ const anyFilter = Object.keys(early).length > 0 || [req.fromCompany, req.mentionsCompany, req.authorCompany].some((v) => (v?.length ?? 0) > 0);
5610
+ if (sets.length === 0 && !anyFilter)
5611
+ return err(
5612
+ command,
5613
+ "INVALID_INPUT",
5614
+ "give keywords, a filter, or both",
5615
+ 'lnrelay search posts "<keywords>"'
5616
+ );
5617
+ const get = fetch2 ?? liveFetch3(opts.quiet === true);
5618
+ if (typeof get !== "function") return get;
5619
+ const f = await filtersOf(req, get);
5620
+ if ("ok" in f) return err(command, f.code, f.message, f.hint);
5621
+ const first = Math.max(0, req.start ?? 0);
5622
+ const want = Math.max(1, Math.min(req.limit, PAGING3.max - first));
5623
+ const fetchPage = async (keywords, start) => {
5624
+ const body = postsPagerBody({ ...keywords ? { keywords } : {}, filters: f.filters, start });
5625
+ const res = await get(POSTS_URL, body, "search");
5626
+ const page = res.ok ? parsePosts(res.raw) : res;
5627
+ if (!page.ok) return page;
5628
+ const cards = page.posts.length + page.unread;
5629
+ const unknownTypes = page.unread > 0 ? { unreadPostCards: page.unread } : {};
5630
+ return {
5631
+ ok: true,
5632
+ items: page.posts,
5633
+ // No total is given: a short page is the last.
5634
+ ...cards < POSTS_PAGE ? { total: start + cards } : {},
5635
+ unknownTypes
5636
+ };
5637
+ };
5638
+ const merged = await searchAll(
5639
+ fetchPage,
5640
+ sets.length > 0 ? sets : [void 0],
5641
+ first,
5642
+ want,
5643
+ PAGING3
5644
+ );
5645
+ if (merged.rows.length === 0 && merged.failure !== void 0) {
5646
+ const fail2 = merged.failure;
5647
+ return err(command, fail2.code, fail2.message, fail2.hint);
5648
+ }
5649
+ const single = sets.length <= 1;
5650
+ return ok("search", {
5651
+ kind: "posts",
5652
+ query: {
5653
+ ...sets.length > 0 ? { keywords: single ? sets[0] : sets } : {},
5654
+ filters: f.filters
5655
+ },
5656
+ ...Object.keys(f.resolved).length > 0 ? { resolved: f.resolved } : {},
5657
+ items: shape2(merged.rows, opts, compactPost),
5658
+ meta: metaOf(command, merged, single, first)
5659
+ });
5660
+ }
5661
+
5662
+ // src/commands/registry.ts
5663
+ var COMMANDS = [
5664
+ // ─── local / meta — no network, available today ────────────────────────────
5665
+ {
5666
+ name: "doctor",
5667
+ cost: "free with --offline",
5668
+ summary: "Diagnose setup: entry point, cache dir, cookies, cooldown, budget.",
5669
+ usage: "lnrelay doctor [--offline]",
5670
+ audience: ["cli", "mcp"],
5671
+ risk: "local",
5672
+ implemented: true
5673
+ },
5674
+ {
5675
+ name: "budget",
5676
+ cost: "free",
5677
+ summary: "Spend ledger per class, with each cap's provenance. Reset a cooldown here.",
5678
+ usage: "lnrelay budget [--reset-cooldown --confirm]",
5679
+ audience: ["cli", "mcp"],
5680
+ risk: "local",
5681
+ implemented: true
5682
+ },
5683
+ {
5684
+ name: "risk",
5685
+ cost: "free",
5686
+ summary: "Circuit-breaker state. Check this BEFORE spending budget on research.",
5687
+ usage: "lnrelay risk",
5688
+ audience: ["cli", "mcp"],
5689
+ risk: "local",
5690
+ implemented: true
5691
+ },
5692
+ // ─── session ───────────────────────────────────────────────────────────────
5693
+ {
5694
+ name: "login",
5695
+ cost: "free \u2014 local browser",
5696
+ summary: "Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.",
5697
+ usage: "lnrelay login\n Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).",
5698
+ audience: ["cli"],
5699
+ risk: "local",
5700
+ implemented: true
5701
+ },
5702
+ // ─── reads — verified live 2026-08-01 ─────────────────────────────────────
5703
+ {
5704
+ name: "whoami",
5705
+ cost: "1 call",
5706
+ summary: "The authenticated member: name, headline, URN.",
5707
+ usage: "lnrelay whoami",
5708
+ audience: ["cli", "mcp"],
5709
+ risk: "read",
5710
+ implemented: true
5711
+ },
5712
+ {
5713
+ name: "profile",
5714
+ cost: "1 call (+1 per section)",
5715
+ summary: "A member profile. Expensive sections are opt-in.",
5716
+ usage: "lnrelay profile <public-id|urn|url> [--raw]\n Returns headline, location, current title, company and school. LinkedIn's profile\n projections do not return a name \u2014 use the identifier you passed in.",
5717
+ audience: ["cli", "mcp"],
5718
+ risk: "read",
5719
+ implemented: true
5720
+ },
5721
+ {
5722
+ name: "search",
5723
+ cost: "1 search call per 50 results (posts: per 20); +1 per name looked up",
5724
+ summary: "Search any kind the search box has: people, jobs, posts, companies, groups, events, courses, products, services, schools. Several keyword sets merge by id.",
5725
+ usage: 'lnrelay search <kind> "<keywords>" ["<more>" ...] [filters] [--limit N] [--start N]\n [--compact | --fields a,b,c]\n kinds: people, jobs (their own flags: see `people`, `jobs`), posts, companies,\n groups, events, courses, products, services, schools\n companies, services: [--location "<place>"] [--network 1st,2nd,3rd+]\n companies: [--industry <ids>] any kind: [--filter key=v1,v2 ...]\n posts: [--sort recent|relevant] [--posted 24h|week|month]\n [--type videos,images,jobs,live,articles,documents] [--posted-by 1st,me]\n [--from <profile-id>] [--mentions <profile-id>] [--from-company "<name|id>"]\n [--mentions-company "<name|id>"] [--author-company "<name|id>"]\n [--author-industry <ids>] [--author-title "<text>"]',
5726
+ audience: ["cli", "mcp"],
5727
+ risk: "read",
5728
+ implemented: true
5729
+ },
5730
+ {
5731
+ name: "search-filters",
5732
+ cost: "1 search call",
5733
+ summary: "Every filter a search kind has for a query, with option ids and live counts: what `search <kind> --filter key=\u2026` takes.",
5734
+ usage: 'lnrelay search-filters <kind> ["<keywords>"] [filters]',
5735
+ audience: ["cli", "mcp"],
5736
+ risk: "read",
5737
+ implemented: true
5738
+ },
5739
+ {
5740
+ name: "people",
5741
+ cost: "1 search call per 50 people; +1 per company, school or place given by name",
5742
+ summary: "People search with every filter LinkedIn has: company, past company, school, place, degree, industry, title, connections of someone, \u2026 Several keyword sets merge by person.",
5743
+ usage: 'lnrelay people ["<keywords>" ...] [--company "<name|id>" ...] [--past-company "<name|id>" ...]\n [--school "<name|id>" ...] [--location "<place>" | --geo <ids>] [--network 1st,2nd,3rd+]\n [--industry <ids>] [--language en,de] [--service <ids>] [--title "<text>"]\n [--first-name "<text>"] [--last-name "<text>"] [--company-text "<text>"]\n [--school-text "<text>"] [--connection-of <profile-id>] [--follower-of <profile-id>]\n [--open-to-volunteer] [--filter key=v1,v2 ...] [--limit N] [--start N]\n [--compact | --fields a,b,c]\n Names are looked up and data.resolved says what each became: check it.\n LinkedIn pages at most 1000 people per query; meta.servedLimit says when it held back.',
5744
+ audience: ["cli", "mcp"],
5745
+ risk: "read",
5746
+ implemented: true
5747
+ },
5748
+ {
5749
+ name: "people-filters",
5750
+ cost: "1 search call (+1 per name looked up)",
5751
+ summary: "Every people filter for a query, with option ids and live counts: what `people` and --filter take.",
5752
+ usage: 'lnrelay people-filters ["<keywords>"] [people filters]',
5753
+ audience: ["cli", "mcp"],
5754
+ risk: "read",
5755
+ implemented: true
5756
+ },
5757
+ {
5758
+ name: "jobs",
5759
+ cost: "1 job-search call per 100 jobs; --details adds 1 job read per 100 jobs",
5760
+ summary: "Job search with every filter the jobs page has. Cards carry id, title, company, place, workplace, listed date, Easy Apply. Read finalists with `job`.",
5761
+ usage: 'lnrelay jobs "<keywords>" ["<more keywords>" ...] [--location "<place>" | --geo <id>]\n [--distance <miles>]\n [--posted 24h|week|month|<N>h|<N>d] [--experience internship,entry,associate,\n mid-senior,director,executive] [--type full-time,part-time,contract,temporary,\n volunteer,internship,other] [--workplace on-site,remote,hybrid] [--easy-apply]\n [--under-10] [--verified] [--in-network] [--fair-chance] [--company <ids>]\n [--industry <ids>] [--function <codes>] [--title <ids>] [--place <geo-ids>]\n [--filter key=v1,v2 ...] [--sort recent|relevant] [--limit N] [--start N]\n [--details [--description]] [--compact | --fields a,b,c]\n Ids for --company/--industry/--title/--place/--filter come from `job-filters`.\n The resolved place is in data.location: check it, "Vienna" may resolve narrow.',
5762
+ audience: ["cli", "mcp"],
5763
+ risk: "read",
5764
+ implemented: true
5765
+ },
5766
+ {
5767
+ name: "job",
5768
+ cost: "1 job read per 100 jobs",
5769
+ summary: "Jobs in full: description, apply link (external or Easy Apply), applicants, state. Several ids are read together, 100 a call.",
5770
+ usage: "lnrelay job <id|job-url> [<id|job-url> ...] [--compact | --fields a,b,c]",
5771
+ audience: ["cli", "mcp"],
5772
+ risk: "read",
5773
+ implemented: true
5774
+ },
5775
+ {
5776
+ name: "job-filters",
5777
+ cost: "1 job-search call",
5778
+ summary: "Every job filter for a query, with option ids and live counts: what `jobs --filter` and --company/--industry/--title/--place take.",
5779
+ usage: 'lnrelay job-filters "<keywords>" [--location "<place>" | --geo <id>] [jobs filters]',
5780
+ audience: ["cli", "mcp"],
5781
+ risk: "read",
5782
+ implemented: true
5783
+ },
5784
+ {
5785
+ name: "post",
5786
+ cost: "expensive \u2014 full read",
5787
+ summary: "A post plus its comment thread, cursor-followed.",
5788
+ usage: "lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\n Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\n returnedCount 0 is a FAILED FETCH, not an empty thread.",
5789
+ audience: ["cli", "mcp"],
5790
+ risk: "read",
5791
+ implemented: true
5792
+ },
5793
+ {
5794
+ name: "reactions",
5795
+ cost: "medium",
5796
+ summary: "Who reacted to a post, and with which reaction.",
5797
+ usage: "lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]",
5798
+ audience: ["cli", "mcp"],
5799
+ risk: "read",
5800
+ implemented: true
5801
+ },
5802
+ {
5803
+ name: "company",
5804
+ cost: "medium",
5805
+ summary: "A company page, optionally with a bounded sample of its updates.",
5806
+ usage: "lnrelay company <universal-name|url> [--updates N]",
5807
+ audience: ["cli", "mcp"],
5808
+ risk: "read",
5809
+ implemented: false
5810
+ },
5811
+ {
5812
+ name: "feed",
5813
+ cost: "medium",
5814
+ summary: "Your own chronological feed.",
5815
+ usage: "lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]",
5816
+ audience: ["cli", "mcp"],
5817
+ risk: "read",
5818
+ implemented: true
5819
+ },
5820
+ // ─── cache-backed — Phase 4 ────────────────────────────────────────────────
5821
+ {
5822
+ name: "sync",
5823
+ cost: "medium \u2014 1-2 calls",
5824
+ summary: "Pull your own posts or connections into the local cache for offline search.",
5825
+ usage: "lnrelay sync my-posts|connections [--limit N] [--force]",
5826
+ audience: ["cli"],
5827
+ risk: "read",
5828
+ implemented: true
5829
+ },
5830
+ {
5831
+ name: "connections",
5832
+ cost: "free \u2014 local cache",
5833
+ summary: "Your connections, from the local cache. Fill it with `sync connections`.",
5834
+ usage: 'lnrelay connections [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
5835
+ audience: ["cli", "mcp"],
5836
+ risk: "read",
5837
+ implemented: true
5838
+ },
5839
+ {
5840
+ name: "my-posts",
5841
+ cost: "free \u2014 local cache",
5842
+ summary: "Your own authored posts, from the local cache. Fill it with `sync my-posts`.",
5843
+ usage: 'lnrelay my-posts [-q "<query>"] [--limit N] [--compact | --fields a,b] # free; cache',
5844
+ audience: ["cli", "mcp"],
5845
+ risk: "read",
5846
+ implemented: true
5847
+ },
5848
+ {
5849
+ name: "inbox",
5850
+ cost: "1 page call per 20 conversations",
5851
+ summary: "Your conversations in a folder: who with, unread, last message. Reads only: nothing is marked read or seen, and nothing read is stored.",
5852
+ usage: "lnrelay inbox [--folder inbox|primary|other|archive|requests|spam] [--unread] [--limit N]\n [--compact | --fields a,b,c]",
5853
+ audience: ["cli", "mcp"],
5854
+ risk: "read",
5855
+ implemented: true
5856
+ },
5857
+ {
5858
+ name: "messages",
5859
+ cost: "1 page call",
5860
+ summary: "A conversation's latest messages, oldest first, saying which are yours. Reading does not mark it read.",
5861
+ usage: "lnrelay messages <conversation-id|thread-url> [--compact | --fields a,b,c]",
5862
+ audience: ["cli", "mcp"],
5863
+ risk: "read",
5864
+ implemented: true
5865
+ },
5866
+ {
5867
+ name: "draft",
5868
+ cost: "1 page call to check the conversation; the draft stays on this machine",
5869
+ 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.",
5870
+ usage: 'lnrelay draft <conversation-id|thread-url> ("<text>" | --file <path>)\n lnrelay draft remove <draft-id>',
5871
+ audience: ["cli", "mcp"],
5872
+ risk: "local",
5873
+ implemented: true
5874
+ },
5875
+ {
5876
+ name: "drafts",
5877
+ cost: "free \u2014 local",
5878
+ summary: "Your saved reply drafts, with the link to each conversation.",
5879
+ usage: "lnrelay drafts [--compact]",
5880
+ audience: ["cli", "mcp"],
5881
+ risk: "local",
5882
+ implemented: true
5883
+ },
5884
+ {
5885
+ name: "scheduled",
5886
+ cost: "1 call per 10 posts",
5887
+ summary: "Your posts waiting to publish, with when. Not in `my-posts` until they go out.",
5888
+ usage: "lnrelay scheduled\n Each row: urn (cancel with `delete`, change with `edit`), scheduledAt, text. Links in\n the text show as lnkd.in short links, as LinkedIn lists them.",
5889
+ audience: ["cli", "mcp"],
5890
+ risk: "read",
5891
+ implemented: true
5892
+ },
5893
+ {
5894
+ name: "experience",
5895
+ cost: "2 calls",
5896
+ summary: "The roles on your own profile, with the position id `role edit|remove` takes.",
4829
5897
  usage: "lnrelay experience",
4830
5898
  audience: ["cli", "mcp"],
4831
5899
  risk: "read",
@@ -4940,214 +6008,39 @@ var COMMANDS = [
4940
6008
  risk: "write",
4941
6009
  implemented: true
4942
6010
  },
4943
- {
4944
- name: "skill",
4945
- cost: "4-5 reads + 1 write",
4946
- summary: "Add a skill to your profile, or remove one.",
4947
- usage: 'lnrelay skill add "<name>"\n lnrelay skill remove <skill-id>\n Skill ids come from `lnrelay skills`. A skill is added as free text, linked to no role,\n school or project. Removing a skill removes its endorsements with it.',
4948
- audience: ["cli"],
4949
- risk: "write",
4950
- implemented: true
4951
- },
4952
- {
4953
- name: "react",
4954
- cost: "1 call \u2014 write",
4955
- summary: "React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.",
4956
- usage: "lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\n lnrelay react <urn> --remove # take the reaction back",
4957
- audience: ["cli"],
4958
- risk: "write",
4959
- implemented: true
4960
- }
4961
- ];
4962
- var commandNames = COMMANDS.map((c) => c.name);
4963
- function findCommand(name) {
4964
- return COMMANDS.find((c) => c.name === name);
4965
- }
4966
- function helpText() {
4967
- const lines = ["lnrelay \u2014 deep research over LinkedIn from your own account", "", "Commands:"];
4968
- const width = Math.max(...commandNames.map((n) => n.length));
4969
- for (const c of COMMANDS) {
4970
- const flag = c.implemented ? " " : "\xB7";
4971
- lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);
4972
- }
4973
- lines.push("", " \xB7 = specified in docs/DESIGN.md, not yet implemented");
4974
- lines.push("", "Run `lnrelay <command> --help` for usage.");
4975
- return lines.join("\n");
4976
- }
4977
-
4978
- // src/engine/sdui-form.ts
4979
- function balanced(s, start) {
4980
- const open = s[start];
4981
- const close = open === "[" ? "]" : "}";
4982
- let depth = 0;
4983
- let inString = false;
4984
- let escaped = false;
4985
- for (let i = start; i < s.length; i++) {
4986
- const ch = s[i];
4987
- if (escaped) escaped = false;
4988
- else if (ch === "\\") escaped = true;
4989
- else if (ch === '"') inString = !inString;
4990
- else if (!inString && ch === open) depth++;
4991
- else if (!inString && ch === close) {
4992
- depth--;
4993
- if (depth === 0) return s.slice(start, i + 1);
4994
- }
4995
- }
4996
- return null;
4997
- }
4998
- function parseAt(s, start) {
4999
- const text4 = start < 0 ? null : balanced(s, start);
5000
- if (text4 === null) return null;
5001
- try {
5002
- return JSON.parse(text4);
5003
- } catch {
5004
- return null;
5005
- }
5006
- }
5007
- function plain(v) {
5008
- const protoCase = String(v.$case);
5009
- const raw = v[protoCase];
5010
- if (protoCase === "stringListValue") {
5011
- return { protoCase, value: raw?.stringValues ?? [] };
5012
- }
5013
- if (protoCase === "signedLongValue" && typeof raw === "string" && raw.startsWith("$n")) {
5014
- return { protoCase, value: { type: "bigint", value: raw.slice(2) } };
5015
- }
5016
- return { protoCase, value: raw };
5017
- }
5018
- function readModel(stream) {
5019
- const at = stream.indexOf('"modelStates":[');
5020
- const entries = parseAt(stream, at === -1 ? -1 : stream.indexOf("[", at));
5021
- if (entries === null) return null;
5022
- const model = /* @__PURE__ */ new Map();
5023
- for (const entry2 of entries) {
5024
- const id = entry2.key?.key?.value?.id;
5025
- if (id !== void 0 && entry2.value !== void 0 && !model.has(id)) {
5026
- model.set(id, plain(entry2.value));
5027
- }
5028
- }
5029
- return model;
5030
- }
5031
- function findRequest(stream, requestId) {
5032
- const at = stream.indexOf(`"requestId":"${requestId}","requestedArguments":`);
5033
- if (at === -1) return null;
5034
- const args = parseAt(
5035
- stream,
5036
- stream.indexOf("{", stream.indexOf('"requestedArguments":', at))
5037
- );
5038
- return args !== null && Array.isArray(args.requestedStateKeys) && args.payload !== void 0 ? args : null;
5039
- }
5040
- var unknownExpression = (what) => ({
5041
- ok: false,
5042
- code: "SCHEMA_DRIFT",
5043
- message: `the form computes a value with an expression this tool does not evaluate (${what})`,
5044
- hint: "Nothing was sent. Re-capture the form to see what it has become."
5045
- });
5046
- function boundId(body) {
5047
- return body?.key?.key?.value?.id;
5048
- }
5049
- function str2(node, model) {
5050
- const e = node.expression;
5051
- if (e?.$case === "stringValue") return String(e.stringValue);
5052
- if (e?.$case === "bindableString") {
5053
- const v = model.get(boundId(e.bindableString) ?? "")?.value;
5054
- return typeof v === "string" ? v : "";
5055
- }
5056
- return null;
5057
- }
5058
- function bool2(node, model) {
5059
- const e = node.expression;
5060
- const body = e?.[e?.$case ?? ""];
5061
- switch (e?.$case) {
5062
- case "booleanExpression":
5063
- return bool2(body, model);
5064
- case "booleanValue":
5065
- return e.booleanValue === true;
5066
- case "bindableBoolean":
5067
- return model.get(boundId(e.bindableBoolean) ?? "")?.value === true;
5068
- case "notExpression": {
5069
- const a = bool2(body?.a ?? {}, model);
5070
- return a === null ? null : !a;
5071
- }
5072
- case "orExpression":
5073
- case "andExpression": {
5074
- const a = bool2(body?.a ?? {}, model);
5075
- const b = bool2(body?.b ?? {}, model);
5076
- if (a === null || b === null) return null;
5077
- return e.$case === "orExpression" ? a || b : a && b;
5078
- }
5079
- case "stringEqualsExpression": {
5080
- const a = str2(body?.a ?? {}, model);
5081
- const b = str2(body?.b ?? {}, model);
5082
- if (a === null || b === null) return null;
5083
- return body.ignoreCase === true ? a.toLowerCase() === b.toLowerCase() : a === b;
5084
- }
5085
- default:
5086
- return null;
6011
+ {
6012
+ name: "skill",
6013
+ cost: "4-5 reads + 1 write",
6014
+ summary: "Add a skill to your profile, or remove one.",
6015
+ usage: 'lnrelay skill add "<name>"\n lnrelay skill remove <skill-id>\n Skill ids come from `lnrelay skills`. A skill is added as free text, linked to no role,\n school or project. Removing a skill removes its endorsements with it.',
6016
+ audience: ["cli"],
6017
+ risk: "write",
6018
+ implemented: true
6019
+ },
6020
+ {
6021
+ name: "react",
6022
+ cost: "1 call \u2014 write",
6023
+ summary: "React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.",
6024
+ usage: "lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\n lnrelay react <urn> --remove # take the reaction back",
6025
+ audience: ["cli"],
6026
+ risk: "write",
6027
+ implemented: true
5087
6028
  }
6029
+ ];
6030
+ var commandNames = COMMANDS.map((c) => c.name);
6031
+ function findCommand(name) {
6032
+ return COMMANDS.find((c) => c.name === name);
5088
6033
  }
5089
- function evaluate(expression, model) {
5090
- const value = bool2(expression, model);
5091
- return value === null ? unknownExpression(JSON.stringify(expression).slice(0, 80)) : { ok: true, value };
5092
- }
5093
- function wireStates(keys, model, resolve) {
5094
- const out = [];
5095
- for (const id of keys) {
5096
- const state = model.get(id);
5097
- if (state === void 0) continue;
5098
- let value = state.value;
5099
- if (state.protoCase === "expression") {
5100
- const r = resolve(id, state) ?? evaluate(state.value, model);
5101
- if (!r.ok) return r;
5102
- value = r.value;
5103
- }
5104
- out.push({
5105
- key: id,
5106
- namespace: "MemoryNamespace",
5107
- value,
5108
- originalProtoCase: state.protoCase,
5109
- protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id } }
5110
- });
6034
+ function helpText() {
6035
+ const lines = ["lnrelay \u2014 deep research over LinkedIn from your own account", "", "Commands:"];
6036
+ const width = Math.max(...commandNames.map((n) => n.length));
6037
+ for (const c of COMMANDS) {
6038
+ const flag = c.implemented ? " " : "\xB7";
6039
+ lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);
5111
6040
  }
5112
- return out;
5113
- }
5114
- var keysOf = (args) => args.requestedStateKeys.map((k) => k.key.value.id);
5115
- function requestBody(requestId, args, states2, screen) {
5116
- const requestedArguments = {
5117
- $type: "proto.sdui.actions.requests.RequestedArguments",
5118
- requestedStateKeys: args.requestedStateKeys,
5119
- payload: args.payload,
5120
- requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
5121
- };
5122
- return {
5123
- requestId,
5124
- serverRequest: {
5125
- requestId,
5126
- requestedArguments,
5127
- isApfcEnabled: false,
5128
- isStreaming: false,
5129
- rumPageKey: ""
5130
- },
5131
- states: states2,
5132
- requestedArguments: { ...requestedArguments, states: states2, screenId: screen, knownTemplateIds: [] }
5133
- };
5134
- }
5135
- function navBody(screen, payload) {
5136
- return {
5137
- clientArguments: {
5138
- $type: "proto.sdui.actions.requests.RequestedArguments",
5139
- requestedStateKeys: [],
5140
- payload,
5141
- requestMetadata: { $type: "proto.sdui.common.RequestMetadata" },
5142
- states: [],
5143
- screenId: screen,
5144
- knownTemplateIds: []
5145
- },
5146
- isModal: true
5147
- };
5148
- }
5149
- function responseErrors(raw) {
5150
- return raw.match(/"errors":\[([^\]]+)\]/)?.[1]?.slice(0, 300) ?? null;
6041
+ lines.push("", " \xB7 = specified in docs/DESIGN.md, not yet implemented");
6042
+ lines.push("", "Run `lnrelay <command> --help` for usage.");
6043
+ return lines.join("\n");
5151
6044
  }
5152
6045
 
5153
6046
  // src/engine/sdui-profile.ts
@@ -5170,7 +6063,7 @@ var PROFILE_FIELDS = {
5170
6063
  maxLength: 2600
5171
6064
  }
5172
6065
  };
5173
- var drift4 = (message) => ({
6066
+ var drift5 = (message) => ({
5174
6067
  ok: false,
5175
6068
  code: "SCHEMA_DRIFT",
5176
6069
  message,
@@ -5178,10 +6071,10 @@ var drift4 = (message) => ({
5178
6071
  });
5179
6072
  function readForm(stream, field) {
5180
6073
  const states2 = readModel(stream);
5181
- if (states2 === null) return drift4("the profile form carried no initial values");
6074
+ if (states2 === null) return drift5("the profile form carried no initial values");
5182
6075
  const args = findRequest(stream, field.save);
5183
6076
  if (args === null)
5184
- return drift4(`the profile form carried no ${field.save.split(".").pop()} action`);
6077
+ return drift5(`the profile form carried no ${field.save.split(".").pop()} action`);
5185
6078
  return { ok: true, args, states: states2, screen: field.screen, save: field.save };
5186
6079
  }
5187
6080
  function boundKey(form, property) {
@@ -5197,7 +6090,7 @@ function topSkills(form) {
5197
6090
  return (key) => {
5198
6091
  if (!key.endsWith("ReorderableSkillsFormBindingsskillIdsBinding")) return void 0;
5199
6092
  const initial = [...form.states.entries()].find(([k]) => k.startsWith("initialSkills"))?.[1];
5200
- if (initial === void 0) return drift4("the About form carried no initial top skills");
6093
+ if (initial === void 0) return drift5("the About form carried no initial top skills");
5201
6094
  if (!Array.isArray(initial.value) || initial.value.length > 0) {
5202
6095
  return {
5203
6096
  ok: false,
@@ -5220,7 +6113,7 @@ function saveBody(form, field, value) {
5220
6113
  const target = boundKey(form, field.binding);
5221
6114
  const current = target === void 0 ? void 0 : form.states.get(target);
5222
6115
  if (target === void 0 || current === void 0) {
5223
- return drift4(`the profile form has no ${field.name} field`);
6116
+ return drift5(`the profile form has no ${field.name} field`);
5224
6117
  }
5225
6118
  const model = new Map(form.states);
5226
6119
  model.set(target, { ...current, value });
@@ -5289,7 +6182,7 @@ var POSITION = {
5289
6182
  var EDIT_NAV = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${POSITION.editScreen}"`;
5290
6183
  function listPositions(stream) {
5291
6184
  if (readModel(stream) === null && !stream.includes(EDIT_NAV) && !stream.includes('"rows"')) {
5292
- return drift4("the Experience screen could not be read");
6185
+ return drift5("the Experience screen could not be read");
5293
6186
  }
5294
6187
  const positions = [];
5295
6188
  const seen = /* @__PURE__ */ new Set();
@@ -5297,27 +6190,27 @@ function listPositions(stream) {
5297
6190
  for (; ; ) {
5298
6191
  i = stream.indexOf(EDIT_NAV, i);
5299
6192
  if (i === -1) break;
5300
- const text4 = balanced(stream, i);
6193
+ const text5 = balanced(stream, i);
5301
6194
  i += EDIT_NAV.length;
5302
- if (text4 === null) continue;
5303
- const payload = JSON.parse(text4).requestedArguments?.payload;
6195
+ if (text5 === null) continue;
6196
+ const payload = JSON.parse(text5).requestedArguments?.payload;
5304
6197
  const id = payload?.positionId;
5305
6198
  if (typeof id !== "string" || seen.has(id) || payload === void 0) continue;
5306
6199
  seen.add(id);
5307
6200
  positions.push({ positionId: id, title: String(payload.title ?? ""), payload });
5308
6201
  }
5309
6202
  if (positions.length === 0 && !stream.includes('"rows"') && !stream.includes("Experience")) {
5310
- return drift4("the Experience screen listed no roles and did not look like one");
6203
+ return drift5("the Experience screen listed no roles and did not look like one");
5311
6204
  }
5312
6205
  return { ok: true, positions };
5313
6206
  }
5314
6207
  function readPositionForm(stream) {
5315
6208
  const model = readModel(stream);
5316
- if (model === null) return drift4("the position form carried no initial values");
6209
+ if (model === null) return drift5("the position form carried no initial values");
5317
6210
  const media = findRequest(stream, POSITION.media);
5318
6211
  const prefix = media?.payload.formIdPrefix;
5319
6212
  if (media === null || typeof prefix !== "string") {
5320
- return drift4("the position form carried no save step (uploadPositionMedia)");
6213
+ return drift5("the position form carried no save step (uploadPositionMedia)");
5321
6214
  }
5322
6215
  const del = findRequest(stream, POSITION.delete);
5323
6216
  return {
@@ -5368,7 +6261,7 @@ function applyChanges(form, changes) {
5368
6261
  }
5369
6262
  need("dynamicallyCreateHeadline", false);
5370
6263
  need("allowProfileEditBroadcasts", changes.notify === true);
5371
- if (missing.length > 0) return drift4(`the position form has no ${missing.join(", ")} field`);
6264
+ if (missing.length > 0) return drift5(`the position form has no ${missing.join(", ")} field`);
5372
6265
  const s = roleSummary(model);
5373
6266
  if (!s.current && s.start !== null && s.end !== null && s.end < s.start) {
5374
6267
  return {
@@ -5413,7 +6306,7 @@ function mediaBody(form, model) {
5413
6306
  }
5414
6307
  function saveFromReply(reply) {
5415
6308
  const args = findRequest(reply, POSITION.save);
5416
- return args === null ? drift4("the media step did not hand back the save action") : { ok: true, args };
6309
+ return args === null ? drift5("the media step did not hand back the save action") : { ok: true, args };
5417
6310
  }
5418
6311
  function positionSaveBody(save, model, screen) {
5419
6312
  const sending = new Map(model);
@@ -5425,7 +6318,7 @@ function positionSaveBody(save, model, screen) {
5425
6318
  }
5426
6319
  function deleteBody(form) {
5427
6320
  if (form.del === null)
5428
- return drift4("this form has no delete action (it is not an existing role)");
6321
+ return drift5("this form has no delete action (it is not an existing role)");
5429
6322
  const states2 = wireStates(keysOf(form.del), form.model, resolver);
5430
6323
  if (!Array.isArray(states2)) return states2;
5431
6324
  return { ok: true, body: requestBody(POSITION.delete, form.del, states2, form.screen) };
@@ -5468,7 +6361,7 @@ async function sendPositionDelete(form, client) {
5468
6361
  }
5469
6362
 
5470
6363
  // src/commands/write.ts
5471
- import { readFileSync as readFileSync2, statSync } from "fs";
6364
+ import { readFileSync as readFileSync3, statSync } from "fs";
5472
6365
  import { basename } from "path";
5473
6366
 
5474
6367
  // src/engine/oauth-write.ts
@@ -5503,9 +6396,9 @@ async function send(url, body, token, deps) {
5503
6396
  } catch (e) {
5504
6397
  return { ok: false, code: "FETCH_FAILED", message: e.message };
5505
6398
  }
5506
- const text4 = await res.text();
6399
+ const text5 = await res.text();
5507
6400
  if (res.status === 201 || res.status === 200) {
5508
- const id = res.headers.get("x-restli-id") ?? extractId(text4);
6401
+ const id = res.headers.get("x-restli-id") ?? extractId(text5);
5509
6402
  return {
5510
6403
  ok: true,
5511
6404
  id: id ?? "(unknown)",
@@ -5532,7 +6425,7 @@ async function send(url, body, token, deps) {
5532
6425
  ok: false,
5533
6426
  code: "FETCH_FAILED",
5534
6427
  message: `write failed (${res.status})`,
5535
- hint: text4.slice(0, 300)
6428
+ hint: text5.slice(0, 300)
5536
6429
  };
5537
6430
  }
5538
6431
  function extractId(body) {
@@ -5580,7 +6473,7 @@ function feedTypeFor(bindingKey) {
5580
6473
  function stateKey(prefix, body) {
5581
6474
  return `${prefix}-${body}`;
5582
6475
  }
5583
- function states(text4, body) {
6476
+ function states(text5, body) {
5584
6477
  return STATE_PREFIXES.map((prefix) => {
5585
6478
  const key = stateKey(prefix, body);
5586
6479
  const base = {
@@ -5589,19 +6482,19 @@ function states(text4, body) {
5589
6482
  protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: key } }
5590
6483
  };
5591
6484
  if (prefix === "commentBoxText") {
5592
- return { ...base, value: text4, originalProtoCase: "stringValue" };
6485
+ return { ...base, value: text5, originalProtoCase: "stringValue" };
5593
6486
  }
5594
6487
  if (prefix === "richCommentBoxText") {
5595
6488
  return {
5596
6489
  ...base,
5597
- value: { text: text4, attribute: [], $type: "TextModel", source: "local" },
6490
+ value: { text: text5, attribute: [], $type: "TextModel", source: "local" },
5598
6491
  originalProtoCase: "textModelForWrite"
5599
6492
  };
5600
6493
  }
5601
6494
  return { ...base, value: "", originalProtoCase: "stringValue" };
5602
6495
  });
5603
6496
  }
5604
- function commentBody(activityId, text4, tokens, feedType) {
6497
+ function commentBody(activityId, text5, tokens, feedType) {
5605
6498
  const body = keyBody(tokens.bindingKey);
5606
6499
  const activityUrn = { activityUrn: { activityId } };
5607
6500
  const binding = (prefix) => ({
@@ -5648,17 +6541,17 @@ function commentBody(activityId, text4, tokens, feedType) {
5648
6541
  isStreaming: false,
5649
6542
  rumPageKey: ""
5650
6543
  },
5651
- states: states(text4, body),
6544
+ states: states(text5, body),
5652
6545
  requestedArguments: {
5653
6546
  ...args,
5654
- states: states(text4, body),
6547
+ states: states(text5, body),
5655
6548
  screenId: SCREEN_ID3,
5656
6549
  knownTemplateIds: []
5657
6550
  }
5658
6551
  };
5659
6552
  }
5660
6553
  async function comment(confirmed, client) {
5661
- const { activityId, text: text4, tokens } = confirmed.payload;
6554
+ const { activityId, text: text5, tokens } = confirmed.payload;
5662
6555
  if (!keyMatchesPost(tokens.bindingKey, activityId)) {
5663
6556
  return {
5664
6557
  ok: false,
@@ -5679,7 +6572,7 @@ async function comment(confirmed, client) {
5679
6572
  const result = await client.request({
5680
6573
  url: COMMENT_URL,
5681
6574
  method: "POST",
5682
- body: commentBody(activityId, text4, tokens, feedType),
6575
+ body: commentBody(activityId, text5, tokens, feedType),
5683
6576
  spendClass: "write",
5684
6577
  operation: "comment.create"
5685
6578
  });
@@ -5694,7 +6587,7 @@ async function comment(confirmed, client) {
5694
6587
  // src/engine/sdui-write.ts
5695
6588
  var SDUI_ACTION3 = "https://www.linkedin.com/flagship-web/rsc-action/actions/server-request";
5696
6589
  var SCREEN_ID4 = "com.linkedin.sdui.flagshipnav.feed.UpdateDetail";
5697
- var REACTIONS = [
6590
+ var REACTIONS2 = [
5698
6591
  "LIKE",
5699
6592
  "PRAISE",
5700
6593
  "EMPATHY",
@@ -5803,10 +6696,10 @@ var REPLY_URL = `https://www.linkedin.com/voyager/api/voyagerSocialDashNormComme
5803
6696
  function parentThreadUrn(ref) {
5804
6697
  return `urn:li:comment:(${ref.threadType}:${ref.activityId},${ref.commentId})`;
5805
6698
  }
5806
- function replyBody(ref, text4) {
6699
+ function replyBody(ref, text5) {
5807
6700
  return {
5808
6701
  commentary: {
5809
- text: text4,
6702
+ text: text5,
5810
6703
  // The captured reply carried a profileMention, because LinkedIn's UI
5811
6704
  // pre-fills "@Author " into the box. We send none: an @mention notifies a
5812
6705
  // real person, and inventing one would put words — and a notification —
@@ -5818,11 +6711,11 @@ function replyBody(ref, text4) {
5818
6711
  };
5819
6712
  }
5820
6713
  async function replyToComment(confirmed, client) {
5821
- const { ref, text: text4 } = confirmed.payload;
6714
+ const { ref, text: text5 } = confirmed.payload;
5822
6715
  const result = await client.request({
5823
6716
  url: REPLY_URL,
5824
6717
  method: "POST",
5825
- body: replyBody(ref, text4),
6718
+ body: replyBody(ref, text5),
5826
6719
  spendClass: "write",
5827
6720
  operation: "reply"
5828
6721
  });
@@ -6014,7 +6907,7 @@ function loadMedia(flag, path) {
6014
6907
  let bytes;
6015
6908
  try {
6016
6909
  if (!statSync(path).isFile()) throw new Error("not a file");
6017
- bytes = new Uint8Array(readFileSync2(path));
6910
+ bytes = new Uint8Array(readFileSync3(path));
6018
6911
  } catch {
6019
6912
  return err("share", "INVALID_INPUT", `cannot read ${path}`);
6020
6913
  }
@@ -6030,8 +6923,8 @@ function loadMedia(flag, path) {
6030
6923
  };
6031
6924
  }
6032
6925
  function parseScheduleTime(input) {
6033
- const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
6034
- if (iso.test(input)) {
6926
+ const iso2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
6927
+ if (iso2.test(input)) {
6035
6928
  const t = Date.parse(input);
6036
6929
  return Number.isNaN(t) ? null : t;
6037
6930
  }
@@ -6184,8 +7077,8 @@ function whenLine(at, now) {
6184
7077
  const away = hours < 48 ? `in ${hours} h` : `in ${Math.round(hours / 24)} days`;
6185
7078
  return `when ${local} (${zone}) \u2014 ${away}`;
6186
7079
  }
6187
- async function runShare(text4, visibility, now = Date.now(), deps = terminalDeps(), via2, media, at, poll, link = {}) {
6188
- if (text4 === void 0 || text4.trim() === "") {
7080
+ async function runShare(text5, visibility, now = Date.now(), deps = terminalDeps(), via2, media, at, poll, link = {}) {
7081
+ if (text5 === void 0 || text5.trim() === "") {
6189
7082
  return err("share", "INVALID_INPUT", "text is required", 'lnrelay share "<text>"');
6190
7083
  }
6191
7084
  const vis = visibility === "connections" ? "CONNECTIONS" : "PUBLIC";
@@ -6200,7 +7093,7 @@ async function runShare(text4, visibility, now = Date.now(), deps = terminalDeps
6200
7093
  via: via2
6201
7094
  });
6202
7095
  if (pollSpec !== void 0 && "ok" in pollSpec) return pollSpec;
6203
- const cardUrl = link.card !== false && loaded === void 0 && pollSpec === void 0 && via2 !== "oauth" ? firstUrl(text4) : null;
7096
+ const cardUrl = link.card !== false && loaded === void 0 && pollSpec === void 0 && via2 !== "oauth" ? firstUrl(text5) : null;
6204
7097
  const needs = shareNeeds(loaded?.approved.length, scheduledAt, pollSpec, cardUrl);
6205
7098
  const ctx = prepare("share", now, needs.voyagerOnly ? "voyager" : via2, needs.calls);
6206
7099
  if ("ok" in ctx) return ctx;
@@ -6209,7 +7102,7 @@ async function runShare(text4, visibility, now = Date.now(), deps = terminalDeps
6209
7102
  const plan = sharePlan({
6210
7103
  author: authorLine(ctx.transport),
6211
7104
  transport: ctx.transport.kind,
6212
- text: text4,
7105
+ text: text5,
6213
7106
  visibility: vis,
6214
7107
  media: loaded?.approved,
6215
7108
  scheduledAt,
@@ -6232,7 +7125,7 @@ async function runShare(text4, visibility, now = Date.now(), deps = terminalDeps
6232
7125
  note: "note" in result ? result.note : ctx.note
6233
7126
  });
6234
7127
  }
6235
- async function runEditPost(urn, text4, now, deps) {
7128
+ async function runEditPost(urn, text5, now, deps) {
6236
7129
  const unapprovable = refuseUnapprovable("edit", "editing", deps);
6237
7130
  if (unapprovable !== null) return unapprovable;
6238
7131
  const ctx = prepare("edit", now, "voyager");
@@ -6247,12 +7140,12 @@ async function runEditPost(urn, text4, now, deps) {
6247
7140
  const before = await lookup(urn, true);
6248
7141
  const plan = {
6249
7142
  action: "edit your post",
6250
- payload: { urn, text: text4 },
7143
+ payload: { urn, text: text5 },
6251
7144
  summary: [
6252
7145
  authorLine(ctx.transport),
6253
7146
  `post ${urn}`,
6254
7147
  ...previewLines2(before).map((l) => l.replace(/^content /, "was ")),
6255
- `new text "${text4}"`
7148
+ `new text "${text5}"`
6256
7149
  ],
6257
7150
  reversibility: "editable again, but the previous text is NOT kept here, LinkedIn marks the post as edited, and an @mention in the old text is not carried over",
6258
7151
  transport: "voyager"
@@ -6276,7 +7169,7 @@ function liveProfile(session) {
6276
7169
  };
6277
7170
  }
6278
7171
  var PROFILE_HINT = `profile fields: ${Object.keys(PROFILE_FIELDS).join(", ")}`;
6279
- async function runEditProfile(name, text4, now = Date.now(), deps = terminalDeps(), surface) {
7172
+ async function runEditProfile(name, text5, now = Date.now(), deps = terminalDeps(), surface) {
6280
7173
  const field = PROFILE_FIELDS[name];
6281
7174
  if (field === void 0) {
6282
7175
  return err(
@@ -6286,7 +7179,7 @@ async function runEditProfile(name, text4, now = Date.now(), deps = terminalDeps
6286
7179
  PROFILE_HINT
6287
7180
  );
6288
7181
  }
6289
- if (text4 === void 0 || text4.trim() === "") {
7182
+ if (text5 === void 0 || text5.trim() === "") {
6290
7183
  return err(
6291
7184
  "edit",
6292
7185
  "INVALID_INPUT",
@@ -6294,11 +7187,11 @@ async function runEditProfile(name, text4, now = Date.now(), deps = terminalDeps
6294
7187
  `lnrelay edit ${name} "<text>"`
6295
7188
  );
6296
7189
  }
6297
- if (text4.length > field.maxLength) {
7190
+ if (text5.length > field.maxLength) {
6298
7191
  return err(
6299
7192
  "edit",
6300
7193
  "INVALID_INPUT",
6301
- `the ${name} is ${text4.length} characters; LinkedIn allows ${field.maxLength}`
7194
+ `the ${name} is ${text5.length} characters; LinkedIn allows ${field.maxLength}`
6302
7195
  );
6303
7196
  }
6304
7197
  const unapprovable = refuseUnapprovable("edit", "editing", deps);
@@ -6314,19 +7207,19 @@ async function runEditProfile(name, text4, now = Date.now(), deps = terminalDeps
6314
7207
  const form = await profile.open(field, me.vanity);
6315
7208
  if (!form.ok) return err("edit", form.code, form.message, form.hint);
6316
7209
  const was = currentValue(form, field) ?? "";
6317
- if (was === text4) {
7210
+ if (was === text5) {
6318
7211
  return err("edit", "INVALID_INPUT", `your ${name} already reads exactly that; nothing to save`);
6319
7212
  }
6320
- const built = saveBody(form, field, text4);
7213
+ const built = saveBody(form, field, text5);
6321
7214
  if (!built.ok) return err("edit", built.code, built.message, built.hint);
6322
7215
  const plan = {
6323
7216
  action: `change your ${name}`,
6324
- payload: { field: name, was, text: text4 },
7217
+ payload: { field: name, was, text: text5 },
6325
7218
  summary: [
6326
7219
  authorLine(ctx.transport),
6327
7220
  `field ${name}`,
6328
7221
  `was "${was}"`,
6329
- `new "${text4}"`
7222
+ `new "${text5}"`
6330
7223
  ],
6331
7224
  reversibility: "editable again, but the old text is kept only in this preview and the audit log (~/.lnrelay/writes.jsonl). Every other profile field is sent back as LinkedIn holds it.",
6332
7225
  transport: "voyager"
@@ -6337,7 +7230,7 @@ async function runEditProfile(name, text4, now = Date.now(), deps = terminalDeps
6337
7230
  if (!sent.ok) return err("edit", sent.code, sent.message, sent.hint);
6338
7231
  const after = await profile.open(field, me.vanity);
6339
7232
  const reads = after.ok ? currentValue(after, field) : void 0;
6340
- if (reads !== text4) {
7233
+ if (reads !== text5) {
6341
7234
  return err(
6342
7235
  "edit",
6343
7236
  "SCHEMA_DRIFT",
@@ -6376,8 +7269,8 @@ async function harvest(activityId, session, now) {
6376
7269
  if (!found.ok) return err("comment", "SCHEMA_DRIFT", found.message, found.hint);
6377
7270
  return { ok: true, tokens: { bindingKey: found.bindingKey, trackingId: found.trackingId } };
6378
7271
  }
6379
- async function runComment(postUrn2, text4, now = Date.now(), deps = terminalDeps()) {
6380
- if (postUrn2 === void 0 || text4 === void 0 || text4.trim() === "") {
7272
+ async function runComment(postUrn2, text5, now = Date.now(), deps = terminalDeps()) {
7273
+ if (postUrn2 === void 0 || text5 === void 0 || text5.trim() === "") {
6381
7274
  return err(
6382
7275
  "comment",
6383
7276
  "INVALID_INPUT",
@@ -6414,11 +7307,11 @@ async function runComment(postUrn2, text4, now = Date.now(), deps = terminalDeps
6414
7307
  if (!("tokens" in harvested)) return harvested;
6415
7308
  const plan = {
6416
7309
  action: "comment on a post",
6417
- payload: { activityId, text: text4, tokens: harvested.tokens },
7310
+ payload: { activityId, text: text5, tokens: harvested.tokens },
6418
7311
  // The harvested trackingId changes on every render, so --plan and --confirm
6419
7312
  // would never agree on a token derived from it. The intent is what's approved.
6420
- tokenBasis: { activityId, text: text4 },
6421
- summary: [authorLine(ctx.transport), `on ${postUrn2}`, `content "${text4}"`],
7313
+ tokenBasis: { activityId, text: text5 },
7314
+ summary: [authorLine(ctx.transport), `on ${postUrn2}`, `content "${text5}"`],
6422
7315
  reversibility: "deletable with `lnrelay delete <comment-urn>`; the author is notified immediately",
6423
7316
  transport: "voyager"
6424
7317
  };
@@ -6430,8 +7323,8 @@ async function runComment(postUrn2, text4, now = Date.now(), deps = terminalDeps
6430
7323
  );
6431
7324
  return result.ok ? ok("comment", { on: postUrn2 }) : err("comment", result.code, result.message, result.hint);
6432
7325
  }
6433
- async function runEdit(commentUrn, text4, now = Date.now(), deps = terminalDeps()) {
6434
- if (commentUrn === void 0 || text4 === void 0 || text4.trim() === "") {
7326
+ async function runEdit(commentUrn, text5, now = Date.now(), deps = terminalDeps()) {
7327
+ if (commentUrn === void 0 || text5 === void 0 || text5.trim() === "") {
6435
7328
  return err(
6436
7329
  "edit",
6437
7330
  "INVALID_INPUT",
@@ -6441,11 +7334,11 @@ async function runEdit(commentUrn, text4, now = Date.now(), deps = terminalDeps(
6441
7334
  }
6442
7335
  const ref = parseCommentUrn(commentUrn);
6443
7336
  if (ref === null && !commentUrn.startsWith("urn:")) {
6444
- return runEditProfile(commentUrn, text4, now, deps);
7337
+ return runEditProfile(commentUrn, text5, now, deps);
6445
7338
  }
6446
7339
  if (ref === null) {
6447
7340
  if (/^urn:li:(share|ugcPost):\d+$/.test(commentUrn)) {
6448
- return runEditPost(commentUrn, text4, now, deps);
7341
+ return runEditPost(commentUrn, text5, now, deps);
6449
7342
  }
6450
7343
  return err(
6451
7344
  "edit",
@@ -6465,8 +7358,8 @@ async function runEdit(commentUrn, text4, now = Date.now(), deps = terminalDeps(
6465
7358
  if (!("tokens" in harvested)) return harvested;
6466
7359
  const plan = {
6467
7360
  action: "edit your comment",
6468
- payload: { urn: commentUrn, text: text4 },
6469
- summary: [authorLine(ctx.transport), `comment ${commentUrn}`, `new text "${text4}"`],
7361
+ payload: { urn: commentUrn, text: text5 },
7362
+ summary: [authorLine(ctx.transport), `comment ${commentUrn}`, `new text "${text5}"`],
6470
7363
  reversibility: "editable again, but the previous text is NOT recoverable here and LinkedIn marks the comment as edited",
6471
7364
  transport: "voyager"
6472
7365
  };
@@ -6477,11 +7370,11 @@ async function runEdit(commentUrn, text4, now = Date.now(), deps = terminalDeps(
6477
7370
  UPDATE_OP,
6478
7371
  harvested.tokens.trackingId,
6479
7372
  createLiveClient(ctx.transport.session),
6480
- text4
7373
+ text5
6481
7374
  );
6482
7375
  return result.ok ? ok("edit", { edited: commentUrn }) : err("edit", result.code, result.message, result.hint);
6483
7376
  }
6484
- var REACTIONS2 = REACTIONS;
7377
+ var REACTIONS3 = REACTIONS2;
6485
7378
  async function runReact(postUrn2, type, now = Date.now(), deps = terminalDeps(), remove = false) {
6486
7379
  const reaction = type.toUpperCase();
6487
7380
  if (postUrn2 === void 0) {
@@ -6492,12 +7385,12 @@ async function runReact(postUrn2, type, now = Date.now(), deps = terminalDeps(),
6492
7385
  "lnrelay react <urn> [--type LIKE] [--remove]"
6493
7386
  );
6494
7387
  }
6495
- if (!REACTIONS2.includes(reaction)) {
7388
+ if (!REACTIONS3.includes(reaction)) {
6496
7389
  return err(
6497
7390
  "react",
6498
7391
  "INVALID_INPUT",
6499
7392
  `unknown reaction '${type}'`,
6500
- `one of: ${REACTIONS2.join(", ")}`
7393
+ `one of: ${REACTIONS3.join(", ")}`
6501
7394
  );
6502
7395
  }
6503
7396
  const ctx = prepare("react", now, "voyager");
@@ -6521,8 +7414,8 @@ async function runReact(postUrn2, type, now = Date.now(), deps = terminalDeps(),
6521
7414
  const result = await react(gated.confirmed, createLiveClient(ctx.transport.session));
6522
7415
  return result.ok ? ok("react", { id: result.id, removed: remove }) : err("react", result.code, result.message, result.hint);
6523
7416
  }
6524
- async function runReply(commentUrn, text4, now = Date.now(), deps = terminalDeps()) {
6525
- if (commentUrn === void 0 || text4 === void 0 || text4.trim() === "") {
7417
+ async function runReply(commentUrn, text5, now = Date.now(), deps = terminalDeps()) {
7418
+ if (commentUrn === void 0 || text5 === void 0 || text5.trim() === "") {
6526
7419
  return err(
6527
7420
  "reply",
6528
7421
  "INVALID_INPUT",
@@ -6548,8 +7441,8 @@ async function runReply(commentUrn, text4, now = Date.now(), deps = terminalDeps
6548
7441
  }
6549
7442
  const plan = {
6550
7443
  action: "reply to a comment",
6551
- payload: { ref: parent, text: text4 },
6552
- summary: [authorLine(ctx.transport), `replying to ${commentUrn}`, `content "${text4}"`],
7444
+ payload: { ref: parent, text: text5 },
7445
+ summary: [authorLine(ctx.transport), `replying to ${commentUrn}`, `content "${text5}"`],
6553
7446
  reversibility: "deletable with `lnrelay delete <the reply urn>`; the comment author is notified immediately",
6554
7447
  transport: "voyager"
6555
7448
  };
@@ -6808,6 +7701,254 @@ async function runExperience(quiet = false) {
6808
7701
  });
6809
7702
  }
6810
7703
 
7704
+ // src/engine/search.ts
7705
+ var SEARCH_KINDS = {
7706
+ companies: "COMPANIES",
7707
+ groups: "GROUPS",
7708
+ events: "EVENTS",
7709
+ courses: "LEARNING",
7710
+ products: "PRODUCTS",
7711
+ services: "SERVICES",
7712
+ schools: "SCHOOLS"
7713
+ };
7714
+ var SEARCH_PAGE = PEOPLE_PAGE;
7715
+ function searchUrl(q2) {
7716
+ return peopleSearchUrl({
7717
+ ...q2.keywords !== void 0 ? { keywords: q2.keywords } : {},
7718
+ params: q2.params,
7719
+ start: q2.start,
7720
+ ...q2.withFilters === true ? { withFilters: true } : {},
7721
+ kind: SEARCH_KINDS[q2.kind]
7722
+ });
7723
+ }
7724
+ var text4 = (v) => {
7725
+ const t = v?.text;
7726
+ return typeof t === "string" && t.trim() !== "" ? t.trim().replace(/\s+/g, " ") : void 0;
7727
+ };
7728
+ function idOf(entityUrn) {
7729
+ const inner = String(entityUrn ?? "").match(/\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];
7730
+ return inner?.split(":").pop();
7731
+ }
7732
+ function cleanUrl2(nav) {
7733
+ if (typeof nav !== "string" || !nav.startsWith("https://")) return void 0;
7734
+ return nav.split("?")[0];
7735
+ }
7736
+ function rowToFound(row) {
7737
+ const id = idOf(row.entityUrn);
7738
+ const name = text4(row.title);
7739
+ if (id === void 0 || name === void 0) return void 0;
7740
+ const found = { id, name };
7741
+ const fields = [
7742
+ ["subtitle", text4(row.primarySubtitle)],
7743
+ ["detail", text4(row.secondarySubtitle)],
7744
+ ["summary", text4(row.summary)],
7745
+ ["url", cleanUrl2(row.navigationUrl)]
7746
+ ];
7747
+ for (const [k, v] of fields)
7748
+ if (v !== void 0) found[k] = v;
7749
+ if (JSON.stringify(row.badgeIcon ?? null).includes("VERIFIED")) found.verified = true;
7750
+ return found;
7751
+ }
7752
+ var drift6 = (message) => ({
7753
+ ok: false,
7754
+ code: "SCHEMA_DRIFT",
7755
+ message,
7756
+ hint: "the search response changed shape; re-capture it"
7757
+ });
7758
+ function parseResults(json) {
7759
+ const c = clustersOf(json);
7760
+ if (c === void 0 || !Array.isArray(c.elements))
7761
+ return drift6("the search returned no result list");
7762
+ const included = json.included ?? [];
7763
+ const { people: items, unknownTypes, excluded, unresolved } = readItems(c, included, rowToFound);
7764
+ const total = typeof c.paging?.total === "number" ? c.paging.total : void 0;
7765
+ const start = typeof c.paging?.start === "number" ? c.paging.start : 0;
7766
+ const claimedRaw = c.metadata?.totalResultCount;
7767
+ const claimed = typeof claimedRaw === "number" ? claimedRaw : total;
7768
+ if (unresolved > 0 && items.length === 0)
7769
+ return drift6(`${unresolved} results were listed but none could be read`);
7770
+ if (items.length === 0 && total !== void 0 && total > start) {
7771
+ return {
7772
+ ok: false,
7773
+ code: "SCHEMA_DRIFT",
7774
+ message: `LinkedIn claims ${total} results but returned none from ${start}`,
7775
+ hint: 'a failed fetch, not an empty search; do not report "none"'
7776
+ };
7777
+ }
7778
+ return {
7779
+ ok: true,
7780
+ items,
7781
+ ...total !== void 0 ? { total } : {},
7782
+ ...claimed !== void 0 ? { claimed } : {},
7783
+ start,
7784
+ excluded,
7785
+ unknownTypes
7786
+ };
7787
+ }
7788
+
7789
+ // src/commands/search-kinds.ts
7790
+ var PAGING4 = { pageSize: SEARCH_PAGE, max: 1e3 };
7791
+ var FLAGS = {
7792
+ location: { companies: "companyHqGeo", services: "geoUrn" },
7793
+ industry: { companies: "industryCompanyVertical" },
7794
+ network: { companies: "network", services: "network" }
7795
+ };
7796
+ var NETWORK2 = {
7797
+ "1st": "F",
7798
+ "2nd": "S",
7799
+ "3rd+": "O",
7800
+ F: "F",
7801
+ S: "S",
7802
+ O: "O"
7803
+ };
7804
+ function paramFor(flag, kind) {
7805
+ const param = FLAGS[flag][kind];
7806
+ if (param !== void 0) return param;
7807
+ return {
7808
+ ok: false,
7809
+ code: "INVALID_INPUT",
7810
+ message: `${kind} cannot be filtered by --${flag}`,
7811
+ hint: `--${flag} works for: ${Object.keys(FLAGS[flag]).join(", ")}; other filters are in \`search-filters ${kind}\``
7812
+ };
7813
+ }
7814
+ async function paramsOf(kind, req, get) {
7815
+ const params = {};
7816
+ const resolved = {};
7817
+ if (req.industry !== void 0 && req.industry.length > 0) {
7818
+ const p = paramFor("industry", kind);
7819
+ if (typeof p !== "string") return p;
7820
+ params[p] = req.industry;
7821
+ }
7822
+ if (req.network !== void 0 && req.network.length > 0) {
7823
+ const p = paramFor("network", kind);
7824
+ if (typeof p !== "string") return p;
7825
+ const codes = req.network.map((n) => NETWORK2[n]);
7826
+ if (codes.some((c) => c === void 0))
7827
+ return { ok: false, code: "INVALID_INPUT", message: "--network takes 1st, 2nd, 3rd+" };
7828
+ params[p] = codes;
7829
+ }
7830
+ for (const r of req.raw ?? []) {
7831
+ const m = r.match(/^([A-Za-z_]+)=(.+)$/);
7832
+ if (m?.[1] === void 0 || m[2] === void 0)
7833
+ return {
7834
+ ok: false,
7835
+ code: "INVALID_INPUT",
7836
+ message: `--filter '${r}' is not key=value[,value]`
7837
+ };
7838
+ params[m[1]] = m[2].split(",").map((v) => v.trim()).filter((v) => v !== "");
7839
+ }
7840
+ if (req.location !== void 0 && req.location.trim() !== "") {
7841
+ const p = paramFor("location", kind);
7842
+ if (typeof p !== "string") return p;
7843
+ const place = await resolvePlace(get, req.location.trim());
7844
+ if ("ok" in place) return place;
7845
+ params[p] = [...params[p] ?? [], place.id];
7846
+ resolved.location = place;
7847
+ }
7848
+ return { params, resolved };
7849
+ }
7850
+ function compactFound(f) {
7851
+ return line([
7852
+ f.id,
7853
+ f.name,
7854
+ f.subtitle,
7855
+ f.detail,
7856
+ f.verified ? "verified" : void 0,
7857
+ f.summary !== void 0 && f.summary.length > 120 ? `${f.summary.slice(0, 117)}\u2026` : f.summary,
7858
+ f.url,
7859
+ f.matched !== void 0 ? `matched: ${f.matched.join(" + ")}` : void 0
7860
+ ]);
7861
+ }
7862
+ async function runFind(kind, req, opts = {}, fetch2) {
7863
+ const command = `search ${kind}`;
7864
+ const sets = keywordSets(req.keywords);
7865
+ const anyFilter = (req.location ?? "").trim() !== "" || (req.industry?.length ?? 0) > 0 || (req.network?.length ?? 0) > 0 || (req.raw?.length ?? 0) > 0;
7866
+ if (sets.length === 0 && !anyFilter) {
7867
+ return err(
7868
+ command,
7869
+ "INVALID_INPUT",
7870
+ "give keywords, a filter, or both",
7871
+ `lnrelay search ${kind} "<keywords>"`
7872
+ );
7873
+ }
7874
+ const get = fetch2 ?? liveFetch2(command, opts.quiet === true);
7875
+ if (typeof get !== "function") return get;
7876
+ const p = await paramsOf(kind, req, get);
7877
+ if ("ok" in p) return err(command, p.code, p.message, p.hint);
7878
+ const first = Math.max(0, req.start ?? 0);
7879
+ const want = Math.max(1, Math.min(req.limit, PAGING4.max - first));
7880
+ const fetchPage = async (keywords, start) => {
7881
+ const res = await get(
7882
+ searchUrl({ kind, ...keywords ? { keywords } : {}, params: p.params, start }),
7883
+ "search"
7884
+ );
7885
+ const page = res.ok ? parseResults(res.json) : res;
7886
+ if (!page.ok) return page;
7887
+ return {
7888
+ ok: true,
7889
+ items: page.items,
7890
+ ...page.total !== void 0 ? { total: page.total } : {},
7891
+ ...page.claimed !== void 0 ? { claimed: page.claimed } : {},
7892
+ unknownTypes: page.unknownTypes
7893
+ };
7894
+ };
7895
+ const merged = await searchAll(
7896
+ fetchPage,
7897
+ sets.length > 0 ? sets : [void 0],
7898
+ first,
7899
+ want,
7900
+ PAGING4
7901
+ );
7902
+ if (merged.rows.length === 0 && merged.failure !== void 0) {
7903
+ const f = merged.failure;
7904
+ return err(command, f.code, f.message, f.hint);
7905
+ }
7906
+ const single = sets.length <= 1;
7907
+ return ok("search", {
7908
+ kind,
7909
+ query: { ...sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}, params: p.params },
7910
+ ...Object.keys(p.resolved).length > 0 ? { resolved: p.resolved } : {},
7911
+ items: shape2(merged.rows, opts, compactFound),
7912
+ meta: metaOf(command, merged, single, first)
7913
+ });
7914
+ }
7915
+ async function runFindFilters(kind, req, opts = {}, fetch2) {
7916
+ const command = `search-filters ${kind}`;
7917
+ const sets = keywordSets(req.keywords);
7918
+ if (sets.length > 1)
7919
+ return err(
7920
+ command,
7921
+ "INVALID_INPUT",
7922
+ "search-filters takes one keyword set: its counts belong to that one query"
7923
+ );
7924
+ const get = fetch2 ?? liveFetch2(command, opts.quiet === true);
7925
+ if (typeof get !== "function") return get;
7926
+ const p = await paramsOf(kind, req, get);
7927
+ if ("ok" in p) return err(command, p.code, p.message, p.hint);
7928
+ const res = await get(
7929
+ searchUrl({
7930
+ kind,
7931
+ ...sets[0] !== void 0 ? { keywords: sets[0] } : {},
7932
+ params: p.params,
7933
+ start: 0,
7934
+ withFilters: true
7935
+ }),
7936
+ "search"
7937
+ );
7938
+ const parsed = res.ok ? parsePeopleFilters(res.json) : res;
7939
+ if (!parsed.ok) return err(command, parsed.code, parsed.message, parsed.hint);
7940
+ return ok("search-filters", {
7941
+ kind,
7942
+ ...Object.keys(p.resolved).length > 0 ? { resolved: p.resolved } : {},
7943
+ items: shape2(parsed.filters, opts, (f) => {
7944
+ const how = f.input === "text" ? "free text" : "ids";
7945
+ const options = f.options.map((o) => `${o.value}=${o.label}${o.count !== void 0 ? ` (${o.count})` : ""}`).join(", ");
7946
+ return `${f.key} [${how}]${options !== "" ? `: ${options}` : ""}`;
7947
+ }),
7948
+ meta: { state: "complete", operation: command, returnedCount: parsed.filters.length }
7949
+ });
7950
+ }
7951
+
6811
7952
  // src/engine/sdui-skill.ts
6812
7953
  var SKILL = {
6813
7954
  addScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileSkillAddForm",
@@ -6821,7 +7962,7 @@ var EDIT_NAV2 = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":
6821
7962
  var TEXT2 = /"children":\["((?:[^"\\]|\\.)*)"\]/g;
6822
7963
  function skillsFromPage(stream) {
6823
7964
  if (!stream.includes(SKILL.pager) && !stream.includes(EDIT_NAV2) && !stream.includes("isPartialPage")) {
6824
- return drift4("the skills page could not be read");
7965
+ return drift5("the skills page could not be read");
6825
7966
  }
6826
7967
  const skills = [];
6827
7968
  let from = 0;
@@ -6829,11 +7970,11 @@ function skillsFromPage(stream) {
6829
7970
  for (; ; ) {
6830
7971
  i = stream.indexOf(EDIT_NAV2, i);
6831
7972
  if (i === -1) break;
6832
- const text4 = balanced(stream, i);
7973
+ const text5 = balanced(stream, i);
6833
7974
  const end = i;
6834
7975
  i += EDIT_NAV2.length;
6835
- if (text4 === null) continue;
6836
- const payload = JSON.parse(text4).requestedArguments?.payload;
7976
+ if (text5 === null) continue;
7977
+ const payload = JSON.parse(text5).requestedArguments?.payload;
6837
7978
  const id = payload?.skillId;
6838
7979
  if (typeof id !== "string" || payload === void 0 || skills.some((s) => s.skillId === id))
6839
7980
  continue;
@@ -6841,7 +7982,7 @@ function skillsFromPage(stream) {
6841
7982
  (m) => JSON.parse(`"${m[1]}"`)
6842
7983
  );
6843
7984
  skills.push({ skillId: id, name: names.length === 1 ? names[0] ?? null : null, payload });
6844
- from = end + text4.length;
7985
+ from = end + text5.length;
6845
7986
  }
6846
7987
  return { ok: true, skills };
6847
7988
  }
@@ -6865,11 +8006,11 @@ function pagerFrom(payload, start) {
6865
8006
  }
6866
8007
  function readSkillForm(stream) {
6867
8008
  const model = readModel(stream);
6868
- if (model === null) return drift4("the skill form carried no initial values");
8009
+ if (model === null) return drift5("the skill form carried no initial values");
6869
8010
  const save = findRequest(stream, SKILL.save);
6870
8011
  const del = findRequest(stream, SKILL.delete);
6871
8012
  if (save === null && del === null)
6872
- return drift4("the skill form carried neither a save nor a delete");
8013
+ return drift5("the skill form carried neither a save nor a delete");
6873
8014
  return { ok: true, model, save, del, screen: del === null ? SKILL.addScreen : SKILL.editScreen };
6874
8015
  }
6875
8016
  var nameKey = (model) => [...model.keys()].find((k) => k.startsWith("addSkillsTypeaheadSkillName"));
@@ -6881,10 +8022,10 @@ function skillNameOf(form) {
6881
8022
  function addSkillBody(form, name) {
6882
8023
  if (name.trim() === "")
6883
8024
  return { ok: false, code: "INVALID_INPUT", message: "a skill needs a name" };
6884
- if (form.save === null) return drift4("this form has no save action (it is not the add form)");
8025
+ if (form.save === null) return drift5("this form has no save action (it is not the add form)");
6885
8026
  const key = nameKey(form.model);
6886
8027
  const current = key === void 0 ? void 0 : form.model.get(key);
6887
- if (key === void 0 || current === void 0) return drift4("the skill form has no name field");
8028
+ if (key === void 0 || current === void 0) return drift5("the skill form has no name field");
6888
8029
  const model = new Map(form.model);
6889
8030
  model.set(key, { ...current, value: name.trim() });
6890
8031
  const states2 = wireStates(keysOf(form.save), model, () => void 0);
@@ -6893,7 +8034,7 @@ function addSkillBody(form, name) {
6893
8034
  }
6894
8035
  function removeSkillBody(form) {
6895
8036
  if (form.del === null)
6896
- return drift4("this form has no delete action (it is not an existing skill)");
8037
+ return drift5("this form has no delete action (it is not an existing skill)");
6897
8038
  const states2 = wireStates(keysOf(form.del), form.model, () => void 0);
6898
8039
  if (!Array.isArray(states2)) return states2;
6899
8040
  return { ok: true, body: requestBody(SKILL.delete, form.del, states2, form.screen) };
@@ -6910,9 +8051,9 @@ async function fetchSkills(vanityName, client) {
6910
8051
  if (typeof screen !== "string") return screen;
6911
8052
  const at = screen.indexOf('"filter":"ProfileSkillCategory_ALL"');
6912
8053
  const open = at === -1 ? -1 : screen.lastIndexOf('"payload":{', at);
6913
- const text4 = open === -1 ? null : balanced(screen, open + '"payload":'.length);
6914
- if (text4 === null) return drift4("the Skills screen carried no list request");
6915
- const payload = JSON.parse(text4);
8054
+ const text5 = open === -1 ? null : balanced(screen, open + '"payload":'.length);
8055
+ if (text5 === null) return drift5("the Skills screen carried no list request");
8056
+ const payload = JSON.parse(text5);
6916
8057
  const count2 = typeof payload.count === "number" ? payload.count : 10;
6917
8058
  const skills = [];
6918
8059
  for (let page = 0; page < MAX_PAGES2; page++) {
@@ -7339,6 +8480,111 @@ function peopleRequest(args) {
7339
8480
  if (start !== void 0) req.start = start;
7340
8481
  return req;
7341
8482
  }
8483
+ var KINDS = ["people", "jobs", "posts", ...Object.keys(SEARCH_KINDS)];
8484
+ var afterKind = (args) => ({
8485
+ ...args,
8486
+ positionals: args.positionals.slice(1)
8487
+ });
8488
+ function findRequest2(args) {
8489
+ const req = { limit: num(args, "limit") ?? 25 };
8490
+ const keywords = args.positionals.slice(1);
8491
+ if (keywords.length > 0) req.keywords = keywords;
8492
+ const location = str(args, "location");
8493
+ if (location !== void 0) req.location = location;
8494
+ const industry = many(args, "industry");
8495
+ if (industry.length > 0) req.industry = industry;
8496
+ const network = many(args, "network");
8497
+ if (network.length > 0) req.network = network;
8498
+ const raw = list(args, "filter");
8499
+ if (raw.length > 0) req.raw = raw;
8500
+ const start = num(args, "start");
8501
+ if (start !== void 0) req.start = start;
8502
+ return req;
8503
+ }
8504
+ function postsRequest(args) {
8505
+ const req = { limit: num(args, "limit") ?? 20 };
8506
+ const keywords = args.positionals.slice(1);
8507
+ if (keywords.length > 0) req.keywords = keywords;
8508
+ for (const [flag, key] of [
8509
+ ["sort", "sort"],
8510
+ ["posted", "posted"],
8511
+ ["author-title", "authorTitle"]
8512
+ ]) {
8513
+ const v = str(args, flag);
8514
+ if (v !== void 0) req[key] = v;
8515
+ }
8516
+ for (const [flag, key] of [
8517
+ ["type", "type"],
8518
+ ["posted-by", "postedBy"],
8519
+ ["from", "from"],
8520
+ ["mentions", "mentions"],
8521
+ ["author-industry", "authorIndustry"]
8522
+ ]) {
8523
+ const v = many(args, flag);
8524
+ if (v.length > 0) req[key] = v;
8525
+ }
8526
+ for (const [flag, key] of [
8527
+ ["from-company", "fromCompany"],
8528
+ ["mentions-company", "mentionsCompany"],
8529
+ ["author-company", "authorCompany"]
8530
+ ]) {
8531
+ const v = orgs(args, flag);
8532
+ if (v.length > 0) req[key] = v;
8533
+ }
8534
+ const raw = list(args, "filter");
8535
+ if (raw.length > 0) req.raw = raw;
8536
+ const start = num(args, "start");
8537
+ if (start !== void 0) req.start = start;
8538
+ return req;
8539
+ }
8540
+ function search2(args, filtersOnly) {
8541
+ const command = filtersOnly ? "search-filters" : "search";
8542
+ const kind = args.positionals[0];
8543
+ if (kind === void 0 || !KINDS.includes(kind)) {
8544
+ return err(
8545
+ command,
8546
+ "INVALID_INPUT",
8547
+ `unknown search kind '${kind ?? ""}'`,
8548
+ `one of: ${KINDS.join(", ")} \u2014 e.g. lnrelay ${command} companies "<keywords>"`
8549
+ );
8550
+ }
8551
+ const opts = output(args);
8552
+ if (kind === "people")
8553
+ return filtersOnly ? runPeopleFilters(peopleRequest(afterKind(args)), opts) : runPeople(peopleRequest(afterKind(args)), opts);
8554
+ if (kind === "jobs")
8555
+ return filtersOnly ? runJobFilters(jobsRequest(afterKind(args)), opts) : runJobs(jobsRequest(afterKind(args)), opts);
8556
+ if (kind === "posts") {
8557
+ if (filtersOnly)
8558
+ return err(
8559
+ command,
8560
+ "INVALID_INPUT",
8561
+ "posts filters are fixed: see `lnrelay help search`",
8562
+ "sort, posted, type, posted-by, from, mentions, from-company, mentions-company, author-company, author-industry, author-title"
8563
+ );
8564
+ return runPostsSearch(postsRequest(args), opts);
8565
+ }
8566
+ return filtersOnly ? runFindFilters(kind, findRequest2(args), opts) : runFind(kind, findRequest2(args), opts);
8567
+ }
8568
+ function messaging(command, args) {
8569
+ if (command === "inbox")
8570
+ return runInbox(
8571
+ {
8572
+ folder: str(args, "folder") ?? "inbox",
8573
+ limit: num(args, "limit") ?? 20,
8574
+ ...bool(args, "unread") ? { unread: true } : {}
8575
+ },
8576
+ output(args)
8577
+ );
8578
+ if (command === "messages") return runMessages(args.positionals[0], output(args));
8579
+ if (command === "drafts") return runDrafts(output(args));
8580
+ if (args.positionals[0] === "remove") return runDraftRemove(args.positionals[1]);
8581
+ return runDraft(
8582
+ args.positionals[0],
8583
+ draftText(args.positionals[1], str(args, "file")),
8584
+ void 0,
8585
+ output(args)
8586
+ );
8587
+ }
7342
8588
  function via(args) {
7343
8589
  const value = str(args, "via");
7344
8590
  if (value === void 0) return void 0;
@@ -7459,18 +8705,15 @@ async function dispatch(argv, now) {
7459
8705
  return runPeople(peopleRequest(args), output(args));
7460
8706
  case "people-filters":
7461
8707
  return runPeopleFilters(peopleRequest(args), output(args));
8708
+ case "inbox":
8709
+ case "messages":
8710
+ case "draft":
8711
+ case "drafts":
8712
+ return messaging(command, args);
7462
8713
  case "search":
7463
- if (args.positionals[0] === "jobs")
7464
- return runJobs(
7465
- { keywords: args.positionals[1] ?? "", limit: num(args, "limit") ?? 10, filter: {} },
7466
- output(args)
7467
- );
7468
- return runSearch(
7469
- args.positionals[0],
7470
- args.positionals[1],
7471
- num(args, "limit") ?? 10,
7472
- output(args)
7473
- );
8714
+ return search2(args, false);
8715
+ case "search-filters":
8716
+ return search2(args, true);
7474
8717
  default:
7475
8718
  return err(command, "NOT_IMPLEMENTED", `'${command}' has no runner wired`);
7476
8719
  }
@@ -7521,13 +8764,13 @@ function edit(args, now, deps) {
7521
8764
  if (inline !== void 0) {
7522
8765
  return err("edit", "INVALID_INPUT", "pass the new text inline or with --file, not both");
7523
8766
  }
7524
- let text4;
8767
+ let text5;
7525
8768
  try {
7526
- text4 = readFileSync3(file, "utf-8").replace(/\n$/, "");
8769
+ text5 = readFileSync4(file, "utf-8").replace(/\n$/, "");
7527
8770
  } catch {
7528
8771
  return err("edit", "INVALID_INPUT", `cannot read ${file}`);
7529
8772
  }
7530
- return runEdit(target, text4, now, deps);
8773
+ return runEdit(target, text5, now, deps);
7531
8774
  }
7532
8775
  function role(args, now, deps) {
7533
8776
  const [sub, target] = args.positionals;
@@ -7554,7 +8797,7 @@ function role(args, now, deps) {
7554
8797
  return err("role", "INVALID_INPUT", "pass --description or --description-file, not both");
7555
8798
  }
7556
8799
  try {
7557
- req.description = readFileSync3(file, "utf-8").replace(/\n$/, "");
8800
+ req.description = readFileSync4(file, "utf-8").replace(/\n$/, "");
7558
8801
  } catch {
7559
8802
  return err("role", "INVALID_INPUT", `cannot read ${file}`);
7560
8803
  }
@@ -7667,7 +8910,9 @@ function share3(args, now, deps) {
7667
8910
  }
7668
8911
  export {
7669
8912
  dispatch,
8913
+ findRequest2 as findRequest,
7670
8914
  jobsRequest,
7671
- peopleRequest
8915
+ peopleRequest,
8916
+ postsRequest
7672
8917
  };
7673
8918
  //# sourceMappingURL=cli.js.map