@lobu/runtime-device 24.5.0 → 24.7.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.
Files changed (33) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +32 -17
  3. package/npm-shrinkwrap.json +140 -89
  4. package/package.json +2 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +57 -9
  6. package/vendor/cli/dist/commands/_lib/view-bundler.js +9 -1
  7. package/vendor/cli/dist/connectors/linkedin-identity.ts +43 -0
  8. package/vendor/cli/dist/connectors/linkedin.ts +154 -3
  9. package/vendor/cli/dist/connectors/x-like-follow.ts +329 -0
  10. package/vendor/cli/dist/connectors/x.ts +709 -80
  11. package/vendor/cli/dist/internal/connector-compiler.js +3 -1
  12. package/vendor/cli/dist/runtime-components.json +4 -4
  13. package/vendor/cli/package.json +2 -1
  14. package/vendor/connector-sdk/package.json +1 -1
  15. package/vendor/connector-worker/dist/compile/index.d.ts +4 -3
  16. package/vendor/connector-worker/dist/compile/index.js +6 -3
  17. package/vendor/connector-worker/package.json +1 -1
  18. package/vendor/core/dist/contracts/tools/view-host.d.ts +7 -0
  19. package/vendor/core/dist/contracts/tools/view-host.js +28 -0
  20. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -4
  21. package/vendor/core/dist/contracts/tools/view-runtime.js +19 -7
  22. package/vendor/core/package.json +11 -1
  23. package/vendor/views/dist/api.d.ts +290 -0
  24. package/vendor/views/dist/api.js +714 -0
  25. package/vendor/views/dist/bridge.d.ts +157 -0
  26. package/vendor/views/dist/bridge.js +372 -0
  27. package/vendor/views/dist/components.d.ts +172 -0
  28. package/vendor/views/dist/components.js +376 -0
  29. package/vendor/views/dist/index.d.ts +13 -0
  30. package/vendor/views/dist/index.js +3 -0
  31. package/vendor/views/dist/native.d.ts +327 -0
  32. package/vendor/views/dist/native.js +57 -0
  33. package/vendor/views/package.json +53 -0
@@ -0,0 +1,329 @@
1
+ /**
2
+ * X like and follow writes for browser-authenticated connections.
3
+ *
4
+ * Both actions mirror LinkedIn `set_like`: open a scratch tab, read the state
5
+ * from X's stable `data-testid` controls, click only when it differs, reload
6
+ * and re-read the server-backed state, then close the scratch tab. A retry
7
+ * that already matches never toggles. Every page step first proves the
8
+ * signed-in `twid` account is the connection's saved account, the same guard
9
+ * the live DM program uses.
10
+ */
11
+
12
+ import type { ChromeActionDispatcher } from "@lobu/connector-sdk";
13
+ import { normalizeXHandle } from "./x-identity.js";
14
+
15
+ const origins = ["x.com", "*.x.com", "twitter.com", "*.twitter.com"];
16
+
17
+ /** Shared page prelude: account guard and a bounded poll. */
18
+ function pagePrelude(accountId: string): string {
19
+ return String.raw`
20
+ const accountId = ${JSON.stringify(accountId)};
21
+ const assertAccount = () => {
22
+ const raw = document.cookie.split('; ').find(cookie => cookie.startsWith('twid='));
23
+ const identity = raw ? decodeURIComponent(raw.slice(5)) : '';
24
+ if (!identity) throw new Error('Sign in to X in the paired browser');
25
+ if (identity !== 'u=' + accountId) throw new Error('X account changed or belongs to another account; reconnect this connection');
26
+ };
27
+ const sleep = () => new Promise(resolve => setTimeout(resolve, 200));
28
+ const wait = async (read, test, failure) => {
29
+ for (let i = 0; i < 75; i++) {
30
+ const result = read();
31
+ if (result && test(result)) return result;
32
+ await sleep();
33
+ }
34
+ throw new Error(failure);
35
+ };`;
36
+ }
37
+
38
+ /**
39
+ * Read (and with `desired` set, change) the like state of one focal post.
40
+ * Only the focal article counts: X marks it `tabindex="-1"`, and its own
41
+ * permalink (the link wrapping its `<time>`, outside any nested quoted-post
42
+ * card) must name this status. An unavailable post quoted by another article
43
+ * therefore finds no control and is never clicked.
44
+ */
45
+ export function buildXLikeExpression(
46
+ statusId: string,
47
+ accountId: string,
48
+ desired: boolean | null,
49
+ ): string {
50
+ return String.raw`(async () => {
51
+ const statusId = ${JSON.stringify(statusId)};
52
+ const desired = ${JSON.stringify(desired)};
53
+ ${pagePrelude(accountId)}
54
+ const statusOf = (path) => {
55
+ const parts = path.split('/');
56
+ const at = parts.indexOf('status');
57
+ return at > 0 ? parts[at + 1] : undefined;
58
+ };
59
+ const assertPage = () => {
60
+ assertAccount();
61
+ if ((location.hostname !== 'x.com' && location.hostname !== 'twitter.com') || statusOf(location.pathname) !== statusId)
62
+ throw new Error('X post changed; refusing to like');
63
+ };
64
+ const read = () => {
65
+ assertPage();
66
+ const ownPermalink = (article) => [...article.querySelectorAll('a[href]')].some(link => {
67
+ if (!link.querySelector('time') || link.closest('article') !== article) return false;
68
+ // X marks its own <a> tags role="link" too; only an ANCESTOR card is a quote.
69
+ const card = link.parentElement && link.parentElement.closest('[role="link"]');
70
+ if (card && article.contains(card)) return false;
71
+ try { return statusOf(new URL(link.getAttribute('href'), location.href).pathname) === statusId; }
72
+ catch { return false; }
73
+ });
74
+ const articles = [...document.querySelectorAll('article[data-testid="tweet"][tabindex="-1"]')].filter(ownPermalink);
75
+ if (articles.length > 1) throw new Error('X post like control is ambiguous');
76
+ if (!articles.length) return null;
77
+ const buttons = [...articles[0].querySelectorAll('[data-testid="like"], [data-testid="unlike"]')];
78
+ if (buttons.length > 1) throw new Error('X post like control is ambiguous');
79
+ if (!buttons.length) return null;
80
+ const button = buttons[0];
81
+ if (button.disabled || button.getAttribute('aria-disabled') === 'true') throw new Error('X like control is disabled');
82
+ return { button, liked: button.getAttribute('data-testid') === 'unlike' };
83
+ };
84
+ const before = await wait(read, () => true, 'X post like control was not found');
85
+ const changed = desired !== null && before.liked !== desired;
86
+ if (changed) {
87
+ assertPage();
88
+ before.button.click();
89
+ await wait(read, state => state.liked === desired, 'X like state could not be verified');
90
+ }
91
+ const after = read();
92
+ if (!after) throw new Error('X like control disappeared');
93
+ return { liked: after.liked, changed, tweet_id: statusId };
94
+ })()`;
95
+ }
96
+
97
+ /**
98
+ * Read (and with `desired` set, change) whether the signed-in account follows
99
+ * one profile. X keys the profile's control `<userId>-follow`, `-unfollow` or
100
+ * `-cancel` (a pending request to a protected account); suggestion cells are
101
+ * excluded. Unfollowing confirms X's sheet when it asks.
102
+ */
103
+ export function buildXFollowExpression(
104
+ handle: string,
105
+ accountId: string,
106
+ desired: boolean | null,
107
+ ): string {
108
+ return String.raw`(async () => {
109
+ const handle = ${JSON.stringify(handle)};
110
+ const desired = ${JSON.stringify(desired)};
111
+ ${pagePrelude(accountId)}
112
+ const assertPage = () => {
113
+ assertAccount();
114
+ if ((location.hostname !== 'x.com' && location.hostname !== 'twitter.com') || (location.pathname.split('/')[1] || '').toLowerCase() !== handle)
115
+ throw new Error('X profile changed; refusing to follow');
116
+ };
117
+ const ownProfile = () => { throw new Error('Refusing to follow or unfollow the connected X account itself'); };
118
+ const read = () => {
119
+ assertPage();
120
+ if (document.querySelector('[data-testid="editProfileButton"]')) ownProfile();
121
+ const column = document.querySelector('[data-testid="primaryColumn"]');
122
+ if (!column) return null;
123
+ const controls = [...column.querySelectorAll('button[data-testid]')].flatMap(button => {
124
+ if (button.closest('[data-testid="UserCell"]')) return [];
125
+ const testId = button.getAttribute('data-testid');
126
+ const dash = testId.lastIndexOf('-');
127
+ const userId = testId.slice(0, dash);
128
+ const state = testId.slice(dash + 1);
129
+ if (dash < 1 || ![...userId].every(char => char >= '0' && char <= '9')) return [];
130
+ if (state !== 'follow' && state !== 'unfollow' && state !== 'cancel') return [];
131
+ return [{ button, userId, state }];
132
+ });
133
+ if (!controls.length) return null;
134
+ if (controls.some(control => control.userId !== controls[0].userId || control.state !== controls[0].state))
135
+ throw new Error('X profile follow control is ambiguous');
136
+ const control = controls[0];
137
+ if (control.userId === accountId) ownProfile();
138
+ if (control.button.disabled || control.button.getAttribute('aria-disabled') === 'true') throw new Error('X follow control is disabled');
139
+ return control;
140
+ };
141
+ const result = (state, changed) => ({
142
+ following: state.state === 'unfollow',
143
+ pending: state.state === 'cancel',
144
+ changed,
145
+ user_id: state.userId,
146
+ handle,
147
+ });
148
+ const before = await wait(read, () => true, 'X profile follow control was not found');
149
+ if (desired === null) return result(before, false);
150
+ if (before.state === 'cancel') {
151
+ if (desired) return result(before, false);
152
+ throw new Error('A pending X follow request exists; cancelling follow requests is not supported');
153
+ }
154
+ const changed = (before.state === 'unfollow') !== desired;
155
+ if (changed) {
156
+ assertPage();
157
+ before.button.click();
158
+ let confirmed = false;
159
+ await wait(() => {
160
+ const state = read();
161
+ if (!desired && !confirmed && state && state.state === 'unfollow') {
162
+ const confirm = document.querySelector('[data-testid="confirmationSheetConfirm"]');
163
+ if (confirm) { assertPage(); confirm.click(); confirmed = true; }
164
+ }
165
+ return state;
166
+ }, state => state.userId === before.userId && (desired ? state.state !== 'follow' : state.state === 'follow'), 'X follow state could not be verified');
167
+ }
168
+ const after = read();
169
+ if (!after) throw new Error('X follow control disappeared');
170
+ return result(after, changed);
171
+ })()`;
172
+ }
173
+
174
+ /**
175
+ * Open a scratch tab on `url`, apply `desired`, then reload and read the
176
+ * persisted state with no write. Closes only its own scratch tab.
177
+ */
178
+ async function writeThenVerify<T>(
179
+ browser: ChromeActionDispatcher,
180
+ url: string,
181
+ desired: boolean,
182
+ build: (desired: boolean | null) => string,
183
+ valid: (value: unknown) => value is T,
184
+ ): Promise<{ effect: T; persisted: T }> {
185
+ let tabId: number | undefined;
186
+ try {
187
+ const nav = await browser.dispatch<{ tab_id?: number }>("navigate", {
188
+ url,
189
+ new_tab: true,
190
+ wait_for_load: true,
191
+ allowed_origins: origins,
192
+ });
193
+ tabId = nav.tab_id;
194
+ if (typeof tabId !== "number")
195
+ throw new Error("X scratch tab was not created");
196
+ const evaluate = async (state: boolean | null): Promise<T> => {
197
+ const result = await browser.dispatch<{
198
+ value?: unknown;
199
+ exception?: { description?: unknown };
200
+ }>("evaluate", {
201
+ tab_id: tabId,
202
+ expression: build(state),
203
+ allowed_origins: origins,
204
+ });
205
+ const description = result.exception?.description;
206
+ if (typeof description === "string")
207
+ throw new Error(description.split("\n")[0]);
208
+ if (!valid(result.value)) throw new Error("X returned no verified state");
209
+ return result.value;
210
+ };
211
+ const effect = await evaluate(desired);
212
+ // A second navigation reads server-backed state, including on a retry that
213
+ // already matches. Never toggle again after an uncertain write result.
214
+ await browser.dispatch("navigate", {
215
+ url,
216
+ tab_id: tabId,
217
+ wait_for_load: true,
218
+ allowed_origins: origins,
219
+ });
220
+ return { effect, persisted: await evaluate(null) };
221
+ } finally {
222
+ if (typeof tabId === "number")
223
+ await browser.dispatch("close_tab", {
224
+ tab_id: tabId,
225
+ allowed_origins: origins,
226
+ });
227
+ }
228
+ }
229
+
230
+ export interface SetXLikeResult {
231
+ tweet_id: string;
232
+ tweet_url: string;
233
+ liked: boolean;
234
+ changed: boolean;
235
+ verified: true;
236
+ }
237
+
238
+ /** Set the Like on one exact post as the connection's saved account. */
239
+ export async function setXLike(
240
+ browser: ChromeActionDispatcher,
241
+ opts: { tweetUrl: string; tweetId: string; accountId: string; liked: boolean },
242
+ ): Promise<SetXLikeResult> {
243
+ type State = { liked: boolean; changed: boolean; tweet_id: string };
244
+ const { effect, persisted } = await writeThenVerify(
245
+ browser,
246
+ opts.tweetUrl,
247
+ opts.liked,
248
+ (desired) => buildXLikeExpression(opts.tweetId, opts.accountId, desired),
249
+ (value): value is State =>
250
+ typeof (value as State | undefined)?.liked === "boolean" &&
251
+ (value as State).tweet_id === opts.tweetId,
252
+ );
253
+ if (persisted.liked !== opts.liked)
254
+ throw new Error("X like state did not persist after reload");
255
+ return {
256
+ tweet_id: opts.tweetId,
257
+ tweet_url: opts.tweetUrl,
258
+ liked: opts.liked,
259
+ changed: effect.changed,
260
+ verified: true,
261
+ };
262
+ }
263
+
264
+ export interface SetXFollowResult {
265
+ handle: string;
266
+ user_id: string;
267
+ following: boolean;
268
+ /** A follow of a protected account waits for its owner's approval. */
269
+ pending: boolean;
270
+ changed: boolean;
271
+ verified: true;
272
+ }
273
+
274
+ /** Follow or unfollow one profile as the connection's saved account. */
275
+ export async function setXFollow(
276
+ browser: ChromeActionDispatcher,
277
+ opts: { handle: string; accountId: string; following: boolean },
278
+ ): Promise<SetXFollowResult> {
279
+ type State = Omit<SetXFollowResult, "verified">;
280
+ const { effect, persisted } = await writeThenVerify(
281
+ browser,
282
+ `https://x.com/${opts.handle}`,
283
+ opts.following,
284
+ (desired) => buildXFollowExpression(opts.handle, opts.accountId, desired),
285
+ (value): value is State =>
286
+ typeof (value as State | undefined)?.following === "boolean" &&
287
+ typeof (value as State).user_id === "string" &&
288
+ (value as State).handle === opts.handle,
289
+ );
290
+ const settled = opts.following
291
+ ? persisted.following || persisted.pending
292
+ : !persisted.following && !persisted.pending;
293
+ if (!settled || persisted.user_id !== effect.user_id)
294
+ throw new Error("X follow state did not persist after reload");
295
+ return {
296
+ handle: opts.handle,
297
+ user_id: persisted.user_id,
298
+ following: persisted.following,
299
+ pending: persisted.pending,
300
+ changed: effect.changed,
301
+ verified: true,
302
+ };
303
+ }
304
+
305
+ /**
306
+ * Accept `name`, `@name` or an x.com / twitter.com profile URL. URLs are read
307
+ * with the URL parser and must name exactly one path segment, so a post or
308
+ * list URL never resolves to its author.
309
+ */
310
+ export function parseXHandleInput(raw: string): string | null {
311
+ const value = raw.trim();
312
+ if (!value.startsWith("https://") && !value.startsWith("http://"))
313
+ return normalizeXHandle(value);
314
+ let url: URL;
315
+ try {
316
+ url = new URL(value);
317
+ } catch {
318
+ return null;
319
+ }
320
+ const host = url.hostname.toLowerCase();
321
+ const site = host.startsWith("www.")
322
+ ? host.slice(4)
323
+ : host.startsWith("mobile.")
324
+ ? host.slice(7)
325
+ : host;
326
+ if (site !== "x.com" && site !== "twitter.com") return null;
327
+ const segments = url.pathname.split("/").filter(Boolean);
328
+ return segments.length === 1 ? normalizeXHandle(segments[0]) : null;
329
+ }