@onairosofficial/onairos-capacitor 0.1.4 → 0.1.5

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 (88) hide show
  1. package/OnairosofficialOnairosCapacitor.podspec +1 -1
  2. package/README.md +1 -1
  3. package/dist/onairos.capacitor.esm.js +509 -1
  4. package/dist/onairos.capacitor.esm.turbopack.js +509 -1
  5. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +187 -945
  6. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosRNScrapers.swift +1800 -0
  7. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +180 -629
  8. package/onairos.d.ts +24 -0
  9. package/package.json +5 -2
  10. package/src/assets/connectors/Linkedinicon.png +0 -0
  11. package/src/assets/connectors/Redditicon.png +0 -0
  12. package/src/assets/connectors/YouTubeicon2.png +0 -0
  13. package/src/assets/connectors/chatgpt.png +0 -0
  14. package/src/assets/connectors/claude.png +0 -0
  15. package/src/assets/connectors/instagram.png +0 -0
  16. package/src/assets/connectors/netflix.png +0 -0
  17. package/src/assets/connectors/pinterest.png +0 -0
  18. package/src/assets/connectors/sephora.png +0 -0
  19. package/src/assets/connectors/spotify.png +0 -0
  20. package/src/assets/connectors/tiktok.png +0 -0
  21. package/src/assets/permissions/onairos.png +0 -0
  22. package/src/assets/permissions/personalization.png +0 -0
  23. package/src/assets/permissions/public-profile-person.png +0 -0
  24. package/src/assets/permissions/raw-memories.png +0 -0
  25. package/src/capacitorConnectorCatalog.js +2 -6
  26. package/src/components/DataRequest.jsx +96 -532
  27. package/src/components/PinSetup.jsx +39 -226
  28. package/src/components/SDKDesignPreview.jsx +33 -0
  29. package/src/components/SessionUserBar.jsx +2 -1
  30. package/src/components/UniversalOnboarding.jsx +190 -423
  31. package/src/components/WelcomeScreen.jsx +7 -0
  32. package/src/components/parity/NativeConnections.jsx +136 -0
  33. package/src/components/parity/NativeScreens.jsx +48 -0
  34. package/src/components/ui/PageLayout.jsx +7 -3
  35. package/src/nativeImport/ConnectorLoading.jsx +13 -0
  36. package/src/nativeImport/CustomImportSession.js +115 -0
  37. package/src/nativeImport/ImportIcon.jsx +29 -0
  38. package/src/nativeImport/ImportProgress.jsx +24 -0
  39. package/src/nativeImport/ImportStatus.jsx +9 -0
  40. package/src/nativeImport/NativeChatImport.jsx +28 -0
  41. package/src/nativeImport/NativeImportSession.js +123 -0
  42. package/src/nativeImport/NativeScraperImport.jsx +57 -0
  43. package/src/nativeImport/SmartFilter.jsx +28 -0
  44. package/src/nativeImport/customPayload.js +37 -0
  45. package/src/nativeImport/netflixExport.js +30 -0
  46. package/src/nativeImport/netflixHistory.js +28 -0
  47. package/src/nativeImport/netflixSession.js +59 -0
  48. package/src/nativeImport/rawHandoff.js +7 -0
  49. package/src/nativeImport/rn/config/api.js +5 -0
  50. package/src/nativeImport/rn/services/apiKeyService.js +2 -0
  51. package/src/nativeImport/rn/services/hingePayload.js +37 -0
  52. package/src/nativeImport/rn/services/nativeConversationImport.js +138 -0
  53. package/src/nativeImport/rn/services/nativeFileTransfer.js +127 -0
  54. package/src/nativeImport/rn/services/nativeRawRedaction.js +136 -0
  55. package/src/nativeImport/rn/services/netflixPayload.js +70 -0
  56. package/src/nativeImport/rn/services/rawMemoryPolicy.js +38 -0
  57. package/src/nativeImport/rn/services/sephoraPayload.js +166 -0
  58. package/src/nativeImport/rn/services/spotifyPayload.js +99 -0
  59. package/src/nativeImport/rn/source-manifest.json +45 -0
  60. package/src/nativeImport/rn/utils/importedFiles.js +74 -0
  61. package/src/nativeImport/rn/utils/nativeImportDates.js +45 -0
  62. package/src/nativeImport/rn/utils/nativeImportFileReceiver.js +51 -0
  63. package/src/nativeImport/rn/utils/nativeImportMetadata.js +74 -0
  64. package/src/nativeImport/rn/utils/nativeImportTopics.js +56 -0
  65. package/src/nativeImport/rn/utils/rawExportDelivery.js +12 -0
  66. package/src/nativeImport/rn/utils/webviewScripts/chatgptDiscovery.js +99 -0
  67. package/src/nativeImport/rn/utils/webviewScripts/claude.js +349 -0
  68. package/src/nativeImport/rn/utils/webviewScripts/gemini.js +356 -0
  69. package/src/nativeImport/rn/utils/webviewScripts/hinge.js +375 -0
  70. package/src/nativeImport/rn/utils/webviewScripts/instagram.js +152 -0
  71. package/src/nativeImport/rn/utils/webviewScripts/linkedin.js +825 -0
  72. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTImport.js +202 -0
  73. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTSession.js +63 -0
  74. package/src/nativeImport/rn/utils/webviewScripts/nativeImportFiles.js +132 -0
  75. package/src/nativeImport/rn/utils/webviewScripts/nativeImportProviders.js +80 -0
  76. package/src/nativeImport/rn/utils/webviewScripts/nativeLoginViewport.js +28 -0
  77. package/src/nativeImport/rn/utils/webviewScripts/netflix.js +257 -0
  78. package/src/nativeImport/rn/utils/webviewScripts/sephora.js +862 -0
  79. package/src/nativeImport/rn/utils/webviewScripts/sephoraSession.js +160 -0
  80. package/src/nativeImport/rn/utils/webviewScripts/spotify.js +1868 -0
  81. package/src/nativeImport/rn/utils/webviewScripts/telegram.js +630 -0
  82. package/src/nativeImport/rn/utils/webviewScripts/tiktok.js +2920 -0
  83. package/src/onairos.core.jsx +3 -0
  84. package/src/onairosButton.jsx +23 -17
  85. package/src/styles/onairos-rn-parity.css +175 -0
  86. package/src/styles/tailwind.capacitor.css +4 -0
  87. package/src/utils/nativeConnectorSession.js +18 -0
  88. package/src/utils/parityPolicy.js +41 -0
@@ -0,0 +1,2920 @@
1
+ // Synced from RN utils/webviewScripts/tiktok.ts by scripts/sync-rn-connectors.cjs.
2
+ const TIKTOK_EXPORT_SCRIPT = `
3
+ (async function() {
4
+ try {
5
+ var postMsg = function(obj) {
6
+ window.ReactNativeWebView.postMessage(JSON.stringify(obj));
7
+ };
8
+
9
+ var progress = function(stage, pct, msg) {
10
+ postMsg({ type: 'TIKTOK_EXPORT_PROGRESS', stage: stage, progress: pct, message: msg });
11
+ };
12
+
13
+ var debug = function(step, details) {
14
+ postMsg({
15
+ type: 'TIKTOK_EXPORT_DEBUG',
16
+ step: step,
17
+ details: details || {},
18
+ timestamp: Date.now()
19
+ });
20
+ };
21
+
22
+ function delay(ms) { return new Promise(function(resolve) { setTimeout(resolve, ms); }); }
23
+
24
+ function text(selector, root) {
25
+ var el = (root || document).querySelector(selector);
26
+ return el && el.textContent ? el.textContent.trim() : '';
27
+ }
28
+
29
+ function attr(selector, name, root) {
30
+ var el = (root || document).querySelector(selector);
31
+ return el ? (el.getAttribute(name) || '') : '';
32
+ }
33
+
34
+ function cleanNumber(value) {
35
+ if (typeof value === 'number') return value;
36
+ if (!value || typeof value !== 'string') return undefined;
37
+ var normalized = value.replace(/,/g, '').trim().toUpperCase();
38
+ var multiplier = 1;
39
+ if (normalized.endsWith('K')) multiplier = 1000;
40
+ if (normalized.endsWith('M')) multiplier = 1000000;
41
+ if (normalized.endsWith('B')) multiplier = 1000000000;
42
+ var parsed = parseFloat(normalized.replace(/[^0-9.]/g, ''));
43
+ return Number.isFinite(parsed) ? Math.round(parsed * multiplier) : undefined;
44
+ }
45
+
46
+ function findByKeys(root, predicate, limit) {
47
+ var results = [];
48
+ var seen = [];
49
+ function visit(node) {
50
+ if (!node || results.length >= limit) return;
51
+ if (typeof node !== 'object') return;
52
+ if (seen.indexOf(node) !== -1) return;
53
+ seen.push(node);
54
+ try {
55
+ if (predicate(node)) results.push(node);
56
+ if (Array.isArray(node)) {
57
+ for (var i = 0; i < node.length; i++) visit(node[i]);
58
+ return;
59
+ }
60
+ var keys = Object.keys(node);
61
+ for (var k = 0; k < keys.length; k++) visit(node[keys[k]]);
62
+ } catch(e) {}
63
+ }
64
+ visit(root);
65
+ return results;
66
+ }
67
+
68
+ function parseHydrationStates(doc) {
69
+ var states = [];
70
+ var scripts = (doc || document).querySelectorAll('script');
71
+ for (var i = 0; i < scripts.length; i++) {
72
+ var id = scripts[i].id || '';
73
+ var raw = scripts[i].textContent || '';
74
+ if (!raw || raw.length < 20) continue;
75
+ if (id.indexOf('SIGI_STATE') === -1 && id.indexOf('UNIVERSAL_DATA') === -1 && raw.indexOf('"ItemModule"') === -1 && raw.indexOf('"UserModule"') === -1) continue;
76
+ try {
77
+ states.push(JSON.parse(raw));
78
+ } catch(e) {}
79
+ }
80
+ return states;
81
+ }
82
+
83
+ function normalizeVideo(raw, fallbackAuthor, source) {
84
+ if (!raw || typeof raw !== 'object') return null;
85
+ var id = raw.id || raw.videoId || raw.aweme_id || raw.item_id || raw.group_id;
86
+ var desc = raw.desc || raw.description || raw.title || raw.caption || (raw.contents && raw.contents[0] && raw.contents[0].desc) || '';
87
+ var author = raw.author || raw.authorInfo || raw.authorStats || {};
88
+ var authorUsername = raw.authorId || raw.authorUniqueId || author.uniqueId || author.username || fallbackAuthor || '';
89
+ var stats = raw.stats || raw.statsV2 || raw.statistics || {};
90
+ var covers = raw.video || raw.covers || {};
91
+ var music = raw.music || {};
92
+ var url = id ? ('https://www.tiktok.com/@' + encodeURIComponent(authorUsername || 'user') + '/video/' + encodeURIComponent(String(id))) : '';
93
+ var hashtags = [];
94
+ if (Array.isArray(raw.textExtra)) {
95
+ hashtags = raw.textExtra.map(function(tag) { return tag && (tag.hashtagName || tag.name); }).filter(Boolean);
96
+ } else if (desc) {
97
+ hashtags = (desc.match(/#[\\w.-]+/g) || []).map(function(tag) { return tag.slice(1); });
98
+ }
99
+ if (!id && !desc && !url) return null;
100
+ return {
101
+ videoId: id ? String(id) : url || desc.slice(0, 80),
102
+ description: desc || undefined,
103
+ caption: desc || undefined,
104
+ authorUsername: authorUsername || undefined,
105
+ authorDisplayName: author.nickname || author.displayName || undefined,
106
+ createdAt: raw.createTime ? new Date(Number(raw.createTime) * 1000).toISOString() : undefined,
107
+ url: url || raw.shareUrl || raw.webVideoUrl || undefined,
108
+ thumbnailUrl: covers.cover || covers.originCover || covers.dynamicCover || raw.cover || undefined,
109
+ musicTitle: music.title || undefined,
110
+ musicAuthor: music.authorName || music.author || undefined,
111
+ stats: {
112
+ likes: cleanNumber(stats.diggCount || stats.digg_count || stats.likeCount || stats.likes),
113
+ comments: cleanNumber(stats.commentCount || stats.comment_count || stats.comments),
114
+ shares: cleanNumber(stats.shareCount || stats.share_count || stats.shares),
115
+ views: cleanNumber(stats.playCount || stats.play_count || stats.views),
116
+ },
117
+ hashtags: hashtags,
118
+ source: source,
119
+ };
120
+ }
121
+
122
+ function normalizeUser(raw) {
123
+ if (!raw || typeof raw !== 'object') return null;
124
+ var user = raw.user || raw.userInfo || raw;
125
+ var stats = raw.stats || raw.statsV2 || user.stats || {};
126
+ var username = user.uniqueId || user.username || user.secUid || '';
127
+ if (!username && !user.nickname && !user.signature) return null;
128
+ return {
129
+ userId: user.id || user.uid || user.secUid || undefined,
130
+ username: username || undefined,
131
+ displayName: user.nickname || user.displayName || undefined,
132
+ bio: user.signature || user.bio || undefined,
133
+ avatarUrl: user.avatarLarger || user.avatarMedium || user.avatarThumb || undefined,
134
+ profileUrl: username ? ('https://www.tiktok.com/@' + username) : undefined,
135
+ stats: {
136
+ following: cleanNumber(stats.followingCount || stats.following),
137
+ followers: cleanNumber(stats.followerCount || stats.followers),
138
+ likes: cleanNumber(stats.heartCount || stats.diggCount || stats.likes),
139
+ videos: cleanNumber(stats.videoCount || stats.videos),
140
+ },
141
+ verified: !!user.verified,
142
+ privateAccount: !!user.privateAccount,
143
+ };
144
+ }
145
+
146
+ function extractFromStates(states, fallbackAuthor, source) {
147
+ var videos = [];
148
+ var users = [];
149
+ var seenVideos = {};
150
+ states.forEach(function(state) {
151
+ var candidates = findByKeys(state, function(node) {
152
+ return !!(node && (node.desc || node.description || node.video || node.stats) && (node.id || node.videoId || node.aweme_id || node.item_id));
153
+ }, 120);
154
+ candidates.forEach(function(item) {
155
+ var video = normalizeVideo(item, fallbackAuthor, source);
156
+ if (video && !seenVideos[video.videoId]) {
157
+ seenVideos[video.videoId] = true;
158
+ videos.push(video);
159
+ }
160
+ });
161
+
162
+ var userCandidates = findByKeys(state, function(node) {
163
+ return !!(node && (node.uniqueId || node.username || node.signature) && (node.nickname || node.avatarThumb || node.stats));
164
+ }, 20);
165
+ userCandidates.forEach(function(item) {
166
+ var user = normalizeUser(item);
167
+ if (user) users.push(user);
168
+ });
169
+ });
170
+ return { videos: videos, users: users };
171
+ }
172
+
173
+ function extractProfileFromDom() {
174
+ var urlMatch = location.pathname.match(/@([^/?]+)/);
175
+ var username = urlMatch ? decodeURIComponent(urlMatch[1]) : '';
176
+ var displayName = text('[data-e2e="user-title"]') || text('h1');
177
+ var bio = text('[data-e2e="user-bio"]') || text('[data-e2e="user-signature"]');
178
+ var followers = text('[data-e2e="followers-count"]');
179
+ var following = text('[data-e2e="following-count"]');
180
+ var likes = text('[data-e2e="likes-count"]');
181
+ var avatarUrl = attr('img[alt*="avatar" i], [data-e2e="user-avatar"] img', 'src');
182
+ if (!username && !displayName && !bio) return null;
183
+ return {
184
+ username: username || undefined,
185
+ displayName: displayName || undefined,
186
+ bio: bio || undefined,
187
+ avatarUrl: avatarUrl || undefined,
188
+ profileUrl: username ? ('https://www.tiktok.com/@' + username) : location.href,
189
+ stats: {
190
+ following: cleanNumber(following),
191
+ followers: cleanNumber(followers),
192
+ likes: cleanNumber(likes),
193
+ },
194
+ };
195
+ }
196
+
197
+ function extractVideosFromDom(source, fallbackAuthor, root) {
198
+ var seen = {};
199
+ var videos = [];
200
+ var scope = root || document;
201
+ var anchors = scope.querySelectorAll('a[href*="/video/"]');
202
+ for (var i = 0; i < anchors.length; i++) {
203
+ var href = anchors[i].href || anchors[i].getAttribute('href') || '';
204
+ var match = href.match(/\\/video\\/(\\d+)/);
205
+ var authorMatch = href.match(/\\/(@[^/]+)\\/video\\//);
206
+ var card = anchors[i].closest('div') || anchors[i];
207
+ var img = card.querySelector('img');
208
+ var desc = anchors[i].getAttribute('title') || (img && img.getAttribute('alt')) || text('[data-e2e="video-desc"]', card);
209
+ var views = text('[data-e2e="video-views"]', card) || text('strong', card);
210
+ var id = match ? match[1] : href;
211
+ if (!id || seen[id]) continue;
212
+ seen[id] = true;
213
+ videos.push({
214
+ videoId: id,
215
+ description: desc || undefined,
216
+ caption: desc || undefined,
217
+ authorUsername: authorMatch ? decodeURIComponent(authorMatch[1].replace(/^@/, '')) : (fallbackAuthor || undefined),
218
+ url: href || undefined,
219
+ thumbnailUrl: img ? (img.src || img.getAttribute('src') || undefined) : undefined,
220
+ stats: { views: cleanNumber(views) },
221
+ hashtags: desc ? ((desc.match(/#[\\w.-]+/g) || []).map(function(tag) { return tag.slice(1); })) : [],
222
+ source: source,
223
+ });
224
+ }
225
+ return videos;
226
+ }
227
+
228
+ function findLikedVideoContainer() {
229
+ var selectors = [
230
+ '[data-e2e="user-liked-item-list"]',
231
+ '[data-e2e="liked-item-list"]',
232
+ '[data-e2e="user-liked-list"]',
233
+ '[data-e2e*="liked"][data-e2e*="list"]',
234
+ '[data-e2e*="Liked"][data-e2e*="list"]'
235
+ ];
236
+
237
+ for (var i = 0; i < selectors.length; i++) {
238
+ try {
239
+ var container = document.querySelector(selectors[i]);
240
+ if (container && container.querySelector('a[href*="/video/"]')) {
241
+ return container;
242
+ }
243
+ } catch(e) {}
244
+ }
245
+
246
+ return null;
247
+ }
248
+
249
+ function linksLookLikeOwnPosts(videos, username) {
250
+ if (!videos.length || !username) return false;
251
+ var ownCount = videos.filter(function(video) {
252
+ return video && video.authorUsername && video.authorUsername.toLowerCase() === username.toLowerCase();
253
+ }).length;
254
+ return ownCount === videos.length;
255
+ }
256
+
257
+ function isVisibleElement(element) {
258
+ try {
259
+ var rect = element && element.getBoundingClientRect ? element.getBoundingClientRect() : null;
260
+ var style = element && window.getComputedStyle ? window.getComputedStyle(element) : null;
261
+ return !!(
262
+ rect &&
263
+ rect.width > 0 &&
264
+ rect.height > 0 &&
265
+ rect.bottom > 0 &&
266
+ rect.right > 0 &&
267
+ rect.top < window.innerHeight &&
268
+ rect.left < window.innerWidth &&
269
+ (!style || (style.visibility !== 'hidden' && style.display !== 'none' && style.opacity !== '0'))
270
+ );
271
+ } catch(e) {
272
+ return false;
273
+ }
274
+ }
275
+
276
+ function getElementSignature(element) {
277
+ if (!element) return '';
278
+ try {
279
+ return [
280
+ element.tagName ? element.tagName.toLowerCase() : '',
281
+ element.getAttribute && (element.getAttribute('role') || ''),
282
+ element.getAttribute && (element.getAttribute('data-e2e') || ''),
283
+ element.getAttribute && (element.getAttribute('aria-label') || ''),
284
+ (element.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 80)
285
+ ].filter(Boolean).join(' | ');
286
+ } catch(e) {
287
+ return '';
288
+ }
289
+ }
290
+
291
+ function toRectString(rect) {
292
+ if (!rect) return '';
293
+ return Math.round(rect.left) + ',' + Math.round(rect.top) + ',' + Math.round(rect.width) + 'x' + Math.round(rect.height);
294
+ }
295
+
296
+ function isClickableElement(el) {
297
+ if (!el) return false;
298
+ var role = (el.getAttribute && el.getAttribute('role')) || '';
299
+ var tabIndex = el.getAttribute && el.getAttribute('tabindex');
300
+ var tag = el.tagName ? el.tagName.toLowerCase() : '';
301
+ var hasInlineOnClick = !!(el.getAttribute && el.getAttribute('onclick'));
302
+ return role === 'tab' || role === 'button' || tabIndex != null || tag === 'button' || tag === 'a' || hasInlineOnClick;
303
+ }
304
+
305
+ function findClickableTabAncestor(element) {
306
+ var current = element;
307
+ var best = element;
308
+ var depth = 0;
309
+ while (current && depth < 8) {
310
+ var role = (current.getAttribute && current.getAttribute('role')) || '';
311
+ var tabIndex = current.getAttribute && current.getAttribute('tabindex');
312
+ var tag = current.tagName ? current.tagName.toLowerCase() : '';
313
+ var textValue = (current.textContent || '').trim().replace(/\\s+/g, ' ').toLowerCase();
314
+ var rect = current.getBoundingClientRect ? current.getBoundingClientRect() : null;
315
+ var compactTabText = textValue === 'liked' || textValue === 'likes';
316
+ var looksClickable = role === 'tab' || role === 'button' || tabIndex != null || tag === 'button' || tag === 'a' || typeof current.onclick === 'function';
317
+ var staysInTabSize = rect && rect.width <= window.innerWidth && rect.height <= 90;
318
+
319
+ if (isVisibleElement(current) && compactTabText && (looksClickable || staysInTabSize)) {
320
+ best = current;
321
+ }
322
+
323
+ if (isVisibleElement(current) && looksClickable && (compactTabText || depth > 0)) {
324
+ return current;
325
+ }
326
+
327
+ current = current.parentElement;
328
+ depth++;
329
+ }
330
+ return best;
331
+ }
332
+
333
+ function findLikedSpanTabButton() {
334
+ try {
335
+ var spans = Array.prototype.slice.call(document.querySelectorAll('span'));
336
+ var firstGridTop = getFirstVideoGridTop();
337
+ var visibleLikedSpans = spans.filter(function(span) {
338
+ var value = (span.textContent || '').trim().toLowerCase();
339
+ if (value !== 'liked') return false;
340
+ if (!isVisibleElement(span)) return false;
341
+ var dataE2e = span.getAttribute && (span.getAttribute('data-e2e') || '').toLowerCase();
342
+ if (dataE2e === 'likes' || dataE2e === 'user-likes') return false;
343
+ var rect = span.getBoundingClientRect();
344
+ // The real profile tab is above the video grid; captions and other page text are not.
345
+ return !firstGridTop || rect.top < firstGridTop;
346
+ });
347
+
348
+ if (visibleLikedSpans.length > 0) {
349
+ visibleLikedSpans.sort(function(a, b) {
350
+ var ar = a.getBoundingClientRect();
351
+ var br = b.getBoundingClientRect();
352
+ return (br.left - ar.left) || (ar.top - br.top);
353
+ });
354
+ return findClickableTabAncestor(visibleLikedSpans[0]);
355
+ }
356
+ } catch(e) {}
357
+
358
+ return null;
359
+ }
360
+
361
+ function detectProfileTabRow(firstGridTop) {
362
+ var selectors = '[role="tab"], button, a, div[tabindex], span[tabindex], div, span';
363
+ var rowTopLimit = firstGridTop ? Math.min(firstGridTop + 12, window.innerHeight - 40) : Math.round(window.innerHeight * 0.72);
364
+ var rowBottomFloor = 40;
365
+ var candidates = [];
366
+ try {
367
+ var nodes = Array.prototype.slice.call(document.querySelectorAll(selectors));
368
+ for (var i = 0; i < nodes.length; i++) {
369
+ var el = nodes[i];
370
+ if (!el || !isVisibleElement(el)) continue;
371
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
372
+ if (!rect) continue;
373
+ if (rect.top < rowBottomFloor || rect.top > rowTopLimit) continue;
374
+ if (rect.height < 14 || rect.height > 70) continue;
375
+ if (rect.width < 20 || rect.width > Math.max(200, window.innerWidth * 0.75)) continue;
376
+ var textValue = (el.textContent || '').trim().replace(/s+/g, ' ');
377
+ var textLower = textValue.toLowerCase();
378
+ if (textValue.length > 60) continue;
379
+ if (textLower === 'following' || textLower === 'followers' || textLower === 'likes') continue;
380
+ var hasIcon = !!el.querySelector && !!el.querySelector('svg, path, img');
381
+ if (!isClickableElement(el) && !hasIcon && textValue.length === 0) continue;
382
+ candidates.push({ el: el, rect: rect, text: textLower, hasIcon: hasIcon });
383
+ }
384
+ } catch(e) {}
385
+
386
+ var byRow = {};
387
+ for (var j = 0; j < candidates.length; j++) {
388
+ var centerY = candidates[j].rect.top + (candidates[j].rect.height / 2);
389
+ var key = String(Math.round(centerY / 8) * 8);
390
+ if (!byRow[key]) byRow[key] = [];
391
+ byRow[key].push(candidates[j]);
392
+ }
393
+
394
+ var bestRow = null;
395
+ var bestScore = -1;
396
+ var keys = Object.keys(byRow);
397
+ for (var k = 0; k < keys.length; k++) {
398
+ var row = byRow[keys[k]].sort(function(a, b) { return a.rect.left - b.rect.left; });
399
+ var spread = row.length ? (row[row.length - 1].rect.right - row[0].rect.left) : 0;
400
+ var uniqueXBuckets = {};
401
+ for (var r = 0; r < row.length; r++) uniqueXBuckets[String(Math.round(row[r].rect.left / 24))] = true;
402
+ var uniqueCount = Object.keys(uniqueXBuckets).length;
403
+ if (uniqueCount < 3 || spread < window.innerWidth * 0.45) continue;
404
+ var statsWordCount = row.filter(function(entry) {
405
+ var text = (entry.text || '').toLowerCase();
406
+ if (!text) return false;
407
+ return (
408
+ text === 'following' ||
409
+ text === 'followers' ||
410
+ text === 'likes' ||
411
+ /d+s*following$/.test(text) ||
412
+ /d+s*followers$/.test(text) ||
413
+ /d+s*likes$/.test(text)
414
+ );
415
+ }).length;
416
+ if (statsWordCount >= 2) continue;
417
+ var iconCount = row.filter(function(entry) { return entry.hasIcon; }).length;
418
+ var rowY = parseInt(keys[k], 10);
419
+ var expectedTabY = firstGridTop ? Math.max(80, firstGridTop - 108) : Math.round(window.innerHeight * 0.28);
420
+ var closeness = firstGridTop ? (1000 - Math.abs(firstGridTop - rowY)) : 600;
421
+ var tabOffsetCloseness = 1000 - Math.abs(expectedTabY - rowY);
422
+ var countBoost = uniqueCount >= 4 ? 520 : (uniqueCount === 3 ? 80 : 0);
423
+ var score = closeness + tabOffsetCloseness + countBoost + (uniqueCount * 30) + (iconCount * 24) + Math.min(240, spread);
424
+ if (score > bestScore) {
425
+ bestScore = score;
426
+ bestRow = row;
427
+ }
428
+ }
429
+
430
+ if (!bestRow) {
431
+ return null;
432
+ }
433
+
434
+ return {
435
+ rowY: Math.round(bestRow[0].rect.top + (bestRow[0].rect.height / 2)),
436
+ elements: bestRow
437
+ };
438
+ }
439
+
440
+ function isStatsLikeText(text) {
441
+ var t = String(text || '').toLowerCase().replace(/s+/g, '');
442
+ if (!t) return false;
443
+ if (t === 'following' || t === 'followers' || t === 'likes') return true;
444
+ if (t.indexOf('following') !== -1 || t.indexOf('followers') !== -1 || t.indexOf('likes') !== -1) {
445
+ return /d/.test(t) || t === 'following' || t === 'followers' || t === 'likes';
446
+ }
447
+ return false;
448
+ }
449
+
450
+ function isStatsLikeRow(rowCandidate) {
451
+ if (!rowCandidate || !rowCandidate.elements || !rowCandidate.elements.length) return false;
452
+ var statsCount = 0;
453
+ for (var i = 0; i < rowCandidate.elements.length; i++) {
454
+ var text = rowCandidate.elements[i] && rowCandidate.elements[i].text;
455
+ if (isStatsLikeText(text)) statsCount++;
456
+ }
457
+ return statsCount >= 2;
458
+ }
459
+
460
+ function isStatsLikeRowBySignature(rowCandidate) {
461
+ if (!rowCandidate || !rowCandidate.elements || !rowCandidate.elements.length) return false;
462
+ var statsMatches = 0;
463
+ for (var i = 0; i < rowCandidate.elements.length; i++) {
464
+ var entry = rowCandidate.elements[i];
465
+ var sig = getElementSignature(entry && entry.el).toLowerCase();
466
+ if (!sig) continue;
467
+ if (/(d+s*)?(following|followers|likes)\b/.test(sig)) {
468
+ statsMatches++;
469
+ }
470
+ }
471
+ return statsMatches >= 2;
472
+ }
473
+
474
+ function isLikelyTabCellRow(rowCandidate, firstGridTop) {
475
+ if (!rowCandidate || !rowCandidate.elements || rowCandidate.elements.length < 4) return false;
476
+ var row = rowCandidate.elements;
477
+ var rowY = rowCandidate.rowY || 0;
478
+ if (firstGridTop) {
479
+ var minExpected = Math.max(56, firstGridTop - 170);
480
+ var maxExpected = Math.max(minExpected + 16, firstGridTop - 26);
481
+ if (rowY < minExpected || rowY > maxExpected) return false;
482
+ }
483
+
484
+ var shortOrEmptyTextCount = 0;
485
+ var narrowCellCount = 0;
486
+ var widthValues = [];
487
+ for (var i = 0; i < row.length; i++) {
488
+ var entry = row[i];
489
+ var text = (entry && entry.text ? entry.text : '').trim();
490
+ var rect = entry && entry.rect;
491
+ if (text.length <= 12) shortOrEmptyTextCount++;
492
+ if (rect && rect.width >= 48 && rect.width <= 100 && rect.height >= 30 && rect.height <= 68) {
493
+ narrowCellCount++;
494
+ widthValues.push(rect.width);
495
+ }
496
+ }
497
+ var avgWidth = widthValues.length ? widthValues.reduce(function(sum, width) { return sum + width; }, 0) / widthValues.length : 0;
498
+ var widthVarianceCount = widthValues.filter(function(width) { return Math.abs(width - avgWidth) <= 16; }).length;
499
+ return (
500
+ narrowCellCount >= Math.max(3, row.length - 1) &&
501
+ widthVarianceCount >= Math.max(3, row.length - 1) &&
502
+ (shortOrEmptyTextCount >= Math.max(2, row.length - 2))
503
+ );
504
+ }
505
+
506
+ function detectAnonymousTabCellRow(firstGridTop) {
507
+ if (!firstGridTop) return null;
508
+ var minY = Math.max(64, firstGridTop - 170);
509
+ var maxY = Math.max(minY + 20, firstGridTop - 18);
510
+ var candidates = [];
511
+ try {
512
+ var els = Array.prototype.slice.call(document.querySelectorAll('div, span, button, [role="tab"], [tabindex]'));
513
+ for (var i = 0; i < els.length; i++) {
514
+ var el = els[i];
515
+ if (!el || !isVisibleElement(el)) continue;
516
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
517
+ if (!rect) continue;
518
+ if (rect.top < minY || rect.top > maxY) continue;
519
+ if (rect.width < 52 || rect.width > 96) continue;
520
+ if (rect.height < 30 || rect.height > 72) continue;
521
+ var txt = (el.textContent || '').trim().replace(/s+/g, ' ').toLowerCase();
522
+ if (isStatsLikeText(txt)) continue;
523
+ candidates.push({ el: el, rect: rect, text: txt, hasIcon: !!el.querySelector && !!el.querySelector('svg, path, img') });
524
+ }
525
+ } catch(e) {}
526
+
527
+ var rows = {};
528
+ for (var j = 0; j < candidates.length; j++) {
529
+ var key = String(Math.round((candidates[j].rect.top + candidates[j].rect.height / 2) / 6) * 6);
530
+ if (!rows[key]) rows[key] = [];
531
+ rows[key].push(candidates[j]);
532
+ }
533
+
534
+ var best = null;
535
+ var bestScore = -1;
536
+ var keys = Object.keys(rows);
537
+ for (var k = 0; k < keys.length; k++) {
538
+ var row = rows[keys[k]].sort(function(a, b) { return a.rect.left - b.rect.left; });
539
+ if (row.length < 4) continue;
540
+ var spread = row[row.length - 1].rect.right - row[0].rect.left;
541
+ if (spread < window.innerWidth * 0.58) continue;
542
+ var rowY = parseInt(keys[k], 10);
543
+ var expectedY = Math.max(68, firstGridTop - 108);
544
+ var closeness = 1000 - Math.abs(expectedY - rowY);
545
+ var score = closeness + (row.length * 120) + Math.min(220, spread);
546
+ if (score > bestScore) {
547
+ bestScore = score;
548
+ best = row;
549
+ }
550
+ }
551
+
552
+ if (!best) return null;
553
+ return {
554
+ rowY: Math.round(best[0].rect.top + best[0].rect.height / 2),
555
+ elements: best
556
+ };
557
+ }
558
+
559
+ function detectIconTabRowNearGrid(firstGridTop) {
560
+ if (!firstGridTop) return null;
561
+ var minY = Math.max(72, firstGridTop - 96);
562
+ var maxY = Math.max(minY + 24, firstGridTop - 12);
563
+ var nodes = [];
564
+ try {
565
+ var els = Array.prototype.slice.call(document.querySelectorAll('button, [role="tab"], div, span, a'));
566
+ for (var i = 0; i < els.length; i++) {
567
+ var el = els[i];
568
+ if (!el || !isVisibleElement(el)) continue;
569
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
570
+ if (!rect) continue;
571
+ if (rect.top < minY || rect.top > maxY) continue;
572
+ if (rect.width < 28 || rect.width > 130) continue;
573
+ if (rect.height < 20 || rect.height > 72) continue;
574
+ var text = (el.textContent || '').trim().replace(/s+/g, ' ');
575
+ if (text.length > 28) continue;
576
+ if (isStatsLikeText(text)) continue;
577
+ var hasIcon = !!el.querySelector && !!el.querySelector('svg, path, img');
578
+ var clickable = isClickableElement(el);
579
+ if (!hasIcon && !clickable && !text) continue;
580
+ nodes.push({ el: el, rect: rect, text: text.toLowerCase(), hasIcon: hasIcon });
581
+ }
582
+ } catch(e) {}
583
+
584
+ var byRow = {};
585
+ for (var j = 0; j < nodes.length; j++) {
586
+ var yKey = String(Math.round((nodes[j].rect.top + nodes[j].rect.height / 2) / 6) * 6);
587
+ if (!byRow[yKey]) byRow[yKey] = [];
588
+ byRow[yKey].push(nodes[j]);
589
+ }
590
+
591
+ var best = null;
592
+ var bestScore = -1;
593
+ var keys = Object.keys(byRow);
594
+ for (var k = 0; k < keys.length; k++) {
595
+ var row = byRow[keys[k]].sort(function(a, b) { return a.rect.left - b.rect.left; });
596
+ if (row.length < 3) continue;
597
+ var spread = row[row.length - 1].rect.right - row[0].rect.left;
598
+ if (spread < window.innerWidth * 0.5) continue;
599
+ var iconCount = row.filter(function(entry) { return entry.hasIcon; }).length;
600
+ var statsCount = row.filter(function(entry) { return isStatsLikeText(entry.text); }).length;
601
+ if (statsCount > 0) continue;
602
+ var rowY = parseInt(keys[k], 10);
603
+ var expected = Math.max(64, firstGridTop - 48);
604
+ var score = (1000 - Math.abs(expected - rowY)) + (row.length * 90) + (iconCount * 60) + Math.min(260, spread);
605
+ if (score > bestScore) {
606
+ bestScore = score;
607
+ best = row;
608
+ }
609
+ }
610
+
611
+ if (!best) return null;
612
+ return {
613
+ rowY: Math.round(best[0].rect.top + best[0].rect.height / 2),
614
+ elements: best
615
+ };
616
+ }
617
+
618
+ function findLikedTabButton() {
619
+ var spanTab = findLikedSpanTabButton();
620
+ if (spanTab) return spanTab;
621
+
622
+ var explicitSelectors = [
623
+ '[data-e2e="liked-tab"]',
624
+ '[data-e2e="user-liked-tab"]',
625
+ '[data-e2e="profile-liked-tab"]',
626
+ '[data-e2e*="liked"][role="tab"]',
627
+ '[data-e2e*="Liked"][role="tab"]',
628
+ '[aria-label*="liked" i][role="tab"]',
629
+ '[aria-label*="liked" i][role="button"]'
630
+ ];
631
+
632
+ for (var si = 0; si < explicitSelectors.length; si++) {
633
+ try {
634
+ var explicit = document.querySelector(explicitSelectors[si]);
635
+ if (explicit) return explicit;
636
+ } catch(e) {}
637
+ }
638
+
639
+ try {
640
+ var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
641
+ acceptNode: function(node) {
642
+ var value = (node && node.nodeValue ? node.nodeValue : '').trim().toLowerCase();
643
+ return value === 'liked'
644
+ ? NodeFilter.FILTER_ACCEPT
645
+ : NodeFilter.FILTER_REJECT;
646
+ }
647
+ });
648
+ var textNode = walker.nextNode();
649
+ while (textNode) {
650
+ var element = textNode.parentElement;
651
+ var depth = 0;
652
+ while (element && depth < 8) {
653
+ var elementText = (element.textContent || '').trim().toLowerCase();
654
+ var role = (element.getAttribute && element.getAttribute('role')) || '';
655
+ var tabIndex = element.getAttribute && element.getAttribute('tabindex');
656
+ var tag = element.tagName ? element.tagName.toLowerCase() : '';
657
+ var clickable = role === 'tab' || role === 'button' || tabIndex != null || tag === 'button' || tag === 'a' || typeof element.onclick === 'function';
658
+ var exactOrCompact = elementText === 'liked' || elementText.replace(/\\s+/g, ' ').indexOf('liked') !== -1;
659
+ if (isVisibleElement(element) && exactOrCompact && (clickable || depth >= 1)) {
660
+ return element;
661
+ }
662
+ element = element.parentElement;
663
+ depth++;
664
+ }
665
+ textNode = walker.nextNode();
666
+ }
667
+ } catch(e) {}
668
+
669
+ var candidates = Array.prototype.slice.call(document.querySelectorAll('[role="tab"], button, div[tabindex], span[tabindex], div, span'));
670
+ return candidates.find(function(el) {
671
+ var label = [
672
+ el.getAttribute('aria-label') || '',
673
+ el.getAttribute('title') || '',
674
+ el.getAttribute('data-e2e') || '',
675
+ el.textContent || ''
676
+ ].join(' ').trim().toLowerCase();
677
+ var inTabArea = !!el.closest('[role="tablist"], [data-e2e*="profile"], main');
678
+ if (!inTabArea) return false;
679
+ if (label === 'liked') return true;
680
+ if (label.indexOf('liked videos') !== -1) return true;
681
+ if (label.indexOf(' liked') !== -1 && label.indexOf('favorites') !== -1) return true;
682
+ return false;
683
+ });
684
+ }
685
+
686
+ function triggerUserClick(element) {
687
+ if (!element) return false;
688
+ try {
689
+ if (!isVisibleElement(element)) {
690
+ element.scrollIntoView({ block: 'center', inline: 'center' });
691
+ }
692
+ } catch(e) {}
693
+
694
+ try {
695
+ var rect = element.getBoundingClientRect ? element.getBoundingClientRect() : null;
696
+ var x = rect ? rect.left + rect.width / 2 : 0;
697
+ var y = rect ? rect.top + rect.height / 2 : 0;
698
+ var pointTarget = rect ? document.elementFromPoint(x, y) : element;
699
+ var pointIsGenericRoot = pointTarget === document.documentElement || pointTarget === document.body;
700
+ var target = (!pointTarget || pointIsGenericRoot) ? element : pointTarget;
701
+ ['pointerdown', 'mousedown', 'mouseup', 'pointerup', 'click'].forEach(function(type) {
702
+ var EventCtor = type.indexOf('pointer') === 0 && typeof PointerEvent !== 'undefined' ? PointerEvent : MouseEvent;
703
+ var eventObj = new EventCtor(type, {
704
+ bubbles: true,
705
+ cancelable: true,
706
+ clientX: x,
707
+ clientY: y,
708
+ pointerType: 'touch'
709
+ });
710
+ try { element.dispatchEvent(eventObj); } catch(e) {}
711
+ if (target !== element) {
712
+ try {
713
+ target.dispatchEvent(new EventCtor(type, {
714
+ bubbles: true,
715
+ cancelable: true,
716
+ clientX: x,
717
+ clientY: y,
718
+ pointerType: 'touch'
719
+ }));
720
+ } catch(e) {}
721
+ }
722
+ });
723
+ if (typeof element.click === 'function') {
724
+ element.click();
725
+ }
726
+ return true;
727
+ } catch(e) {
728
+ try {
729
+ element.click();
730
+ return true;
731
+ } catch(_e) {
732
+ return false;
733
+ }
734
+ }
735
+ }
736
+
737
+ function dispatchTapAt(x, y) {
738
+ try {
739
+ var target = document.elementFromPoint(x, y);
740
+ if (!target) return false;
741
+ ['touchstart', 'pointerdown', 'mousedown', 'mouseup', 'pointerup', 'touchend', 'click'].forEach(function(type) {
742
+ var EventCtor = type.indexOf('pointer') === 0 && typeof PointerEvent !== 'undefined' ? PointerEvent : MouseEvent;
743
+ var eventOptions = {
744
+ bubbles: true,
745
+ cancelable: true,
746
+ clientX: x,
747
+ clientY: y,
748
+ pointerType: 'touch'
749
+ };
750
+ if (type.indexOf('touch') === 0 && typeof TouchEvent !== 'undefined') {
751
+ target.dispatchEvent(new TouchEvent(type, { bubbles: true, cancelable: true }));
752
+ } else {
753
+ target.dispatchEvent(new EventCtor(type, eventOptions));
754
+ }
755
+ });
756
+ if (target && typeof target.click === 'function') {
757
+ target.click();
758
+ }
759
+ return true;
760
+ } catch(e) {
761
+ return false;
762
+ }
763
+ }
764
+
765
+ function getFirstVideoGridTop() {
766
+ var anchors = Array.prototype.slice.call(document.querySelectorAll('a[href*="/video/"]'));
767
+ var tops = anchors
768
+ .map(function(anchor) {
769
+ try {
770
+ var rect = anchor.getBoundingClientRect();
771
+ return rect && rect.width > 30 && rect.height > 30 ? rect.top : null;
772
+ } catch(e) {
773
+ return null;
774
+ }
775
+ })
776
+ .filter(function(value) { return typeof value === 'number' && value > 16 && value < window.innerHeight; })
777
+ .sort(function(a, b) { return a - b; });
778
+ return tops.length ? tops[0] : 0;
779
+ }
780
+
781
+ function getScrollableElements() {
782
+ var elements = [];
783
+ try {
784
+ var all = Array.prototype.slice.call(document.querySelectorAll('body *'));
785
+ for (var i = 0; i < all.length; i++) {
786
+ var el = all[i];
787
+ if (!el || !el.scrollHeight || !el.clientHeight) continue;
788
+ if (el.scrollHeight <= el.clientHeight + 24) continue;
789
+ var style = window.getComputedStyle ? window.getComputedStyle(el) : null;
790
+ var overflowY = style ? (style.overflowY || '') : '';
791
+ var scrollable = overflowY === 'auto' || overflowY === 'scroll' || /webkit-overflow-scrolling/i.test(String(style && style.cssText));
792
+ if (scrollable || el.scrollTop > 0) {
793
+ elements.push(el);
794
+ }
795
+ }
796
+ } catch(e) {}
797
+
798
+ elements.sort(function(a, b) {
799
+ return (b.scrollHeight - b.clientHeight) - (a.scrollHeight - a.clientHeight);
800
+ });
801
+ return elements.slice(0, 12);
802
+ }
803
+
804
+ async function scrollAllTargetsTo(position) {
805
+ var targets = getScrollableElements();
806
+ try {
807
+ window.scrollTo(0, position);
808
+ } catch(e) {}
809
+ for (var i = 0; i < targets.length; i++) {
810
+ try {
811
+ targets[i].scrollTop = position;
812
+ } catch(e) {}
813
+ }
814
+ await delay(180);
815
+ }
816
+
817
+ async function resetProfileScrollToTabs() {
818
+ for (var i = 0; i < 3; i++) {
819
+ try {
820
+ window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
821
+ } catch(e) {
822
+ try { window.scrollTo(0, 0); } catch(_e) {}
823
+ }
824
+ await scrollAllTargetsTo(0);
825
+ }
826
+ try {
827
+ var profileHeader = document.querySelector('[data-e2e="user-title"], h2[data-e2e="user-title"], h2');
828
+ if (profileHeader && profileHeader.scrollIntoView) {
829
+ profileHeader.scrollIntoView({ block: 'start', inline: 'nearest' });
830
+ }
831
+ } catch(e) {}
832
+ await delay(260);
833
+ }
834
+
835
+ function findExactLikedTabButton() {
836
+ var selectors = [
837
+ 'p[role="tab"][data-e2e="liked-tab"]',
838
+ '[role="tab"][data-e2e="liked-tab"]',
839
+ '[role="tab"][data-e2e*="liked"]',
840
+ 'p[data-e2e="liked"]',
841
+ '[data-e2e="liked"]',
842
+ '[data-e2e="liked-tab"][tabindex]',
843
+ '[data-e2e="liked-tab"]'
844
+ ];
845
+ for (var i = 0; i < selectors.length; i++) {
846
+ try {
847
+ var node = document.querySelector(selectors[i]);
848
+ if (node) return node;
849
+ } catch(e) {}
850
+ }
851
+ return null;
852
+ }
853
+
854
+ function findTextLikedTabButton() {
855
+ try {
856
+ var tabs = Array.prototype.slice.call(document.querySelectorAll('p, [role="tab"], div, span, button, a'));
857
+ var likedTabs = tabs.filter(function(tab) {
858
+ if (!tab) return false;
859
+ var label = [
860
+ tab.getAttribute('data-e2e') || '',
861
+ tab.getAttribute('aria-label') || '',
862
+ tab.textContent || ''
863
+ ].join(' ').trim().toLowerCase();
864
+ var rect = tab.getBoundingClientRect ? tab.getBoundingClientRect() : null;
865
+ if (!rect || rect.width < 40 || rect.height < 18) return false;
866
+ if (rect.top < 40 || rect.top > (window.innerHeight * 0.6)) return false;
867
+ return (
868
+ label === 'liked' ||
869
+ label.indexOf(' liked') !== -1 ||
870
+ label.indexOf('liked ') !== -1 ||
871
+ label.indexOf('liked') === 0
872
+ );
873
+ });
874
+ if (likedTabs.length === 0) return null;
875
+ likedTabs.sort(function(a, b) {
876
+ var ar = a.getBoundingClientRect ? a.getBoundingClientRect() : { left: 0, top: 0 };
877
+ var br = b.getBoundingClientRect ? b.getBoundingClientRect() : { left: 0, top: 0 };
878
+ return (br.left - ar.left) || (ar.top - br.top);
879
+ });
880
+ return likedTabs[0];
881
+ } catch(e) {
882
+ return null;
883
+ }
884
+ }
885
+
886
+ function getTabSelectedState(tab) {
887
+ if (!tab) return '';
888
+ try {
889
+ return String(tab.getAttribute('aria-selected') || tab.getAttribute('data-selected') || '').toLowerCase();
890
+ } catch(e) {
891
+ return '';
892
+ }
893
+ }
894
+
895
+ function findClickableTarget(element) {
896
+ var current = element;
897
+ var depth = 0;
898
+ while (current && depth < 6) {
899
+ if (isClickableElement(current)) return current;
900
+ current = current.parentElement;
901
+ depth++;
902
+ }
903
+ return element;
904
+ }
905
+
906
+ function hasTabLikeAttributes(el) {
907
+ if (!el || !el.getAttribute) return false;
908
+ var role = (el.getAttribute('role') || '').toLowerCase();
909
+ var data = (el.getAttribute('data-e2e') || '').toLowerCase();
910
+ var tabIndex = el.getAttribute('tabindex');
911
+ if (role === 'tab') return true;
912
+ if (data.indexOf('tab') !== -1) return true;
913
+ if (data.indexOf('liked-tab') !== -1) return true;
914
+ if (data === 'liked') return true;
915
+ if (tabIndex != null && String(tabIndex) !== '') return true;
916
+ return false;
917
+ }
918
+
919
+ function isWeakLikedLeaf(el) {
920
+ if (!el || !el.getAttribute) return false;
921
+ var tag = el.tagName ? el.tagName.toLowerCase() : '';
922
+ var role = (el.getAttribute('role') || '').toLowerCase();
923
+ var data = (el.getAttribute('data-e2e') || '').toLowerCase();
924
+ var tabIndex = el.getAttribute('tabindex');
925
+ return (
926
+ data === 'liked' &&
927
+ role !== 'tab' &&
928
+ (tabIndex == null || String(tabIndex) === '') &&
929
+ (tag === 'p' || tag === 'span' || tag === 'div')
930
+ );
931
+ }
932
+
933
+ function resolveLikedInteractionTarget(element) {
934
+ if (!element) return null;
935
+ var current = element;
936
+ var depth = 0;
937
+ var best = element;
938
+ var foundStrongTarget = false;
939
+ while (current && depth < 10) {
940
+ if (current === document.body || current === document.documentElement) {
941
+ break;
942
+ }
943
+ if (hasTabLikeAttributes(current) || isClickableElement(current)) {
944
+ best = current;
945
+ if (hasTabLikeAttributes(current)) {
946
+ if (!isWeakLikedLeaf(current)) {
947
+ foundStrongTarget = true;
948
+ return current;
949
+ }
950
+ }
951
+ }
952
+ current = current.parentElement;
953
+ depth++;
954
+ }
955
+ if (!foundStrongTarget || best === document.body || best === document.documentElement) {
956
+ return element;
957
+ }
958
+ return best;
959
+ }
960
+
961
+ async function clickLikedTabWithState(tab) {
962
+ if (!tab) {
963
+ return { clicked: false, beforeSelected: '', afterSelected: '', signature: '' };
964
+ }
965
+ var target = resolveLikedInteractionTarget(tab) || findClickableTarget(tab);
966
+ var clickedAny = false;
967
+ var finalBefore = '';
968
+ var finalAfter = '';
969
+ var finalTarget = target;
970
+ var targetRect = target && target.getBoundingClientRect ? target.getBoundingClientRect() : null;
971
+ var centerTapResult = false;
972
+ if (targetRect) {
973
+ centerTapResult = dispatchTapAt(
974
+ Math.round(targetRect.left + (targetRect.width / 2)),
975
+ Math.round(targetRect.top + (targetRect.height / 2))
976
+ );
977
+ }
978
+ var directBefore = getTabSelectedState(target);
979
+ var directClicked = triggerUserClick(target) || centerTapResult;
980
+ await delay(280);
981
+ var directAfter = getTabSelectedState(target);
982
+ if (directAfter === 'true' || directClicked) {
983
+ return {
984
+ clicked: !!directClicked,
985
+ beforeSelected: directBefore,
986
+ afterSelected: directAfter,
987
+ signature: getElementSignature(tab),
988
+ targetSignature: getElementSignature(target),
989
+ };
990
+ }
991
+
992
+ var attempts = [];
993
+ var seen = [];
994
+ var cursor = target;
995
+ var depth = 0;
996
+ while (cursor && depth < 5) {
997
+ if (cursor === document.body || cursor === document.documentElement) break;
998
+ var role = (cursor.getAttribute && cursor.getAttribute('role') || '').toLowerCase();
999
+ var tag = cursor.tagName ? cursor.tagName.toLowerCase() : '';
1000
+ var tabIndex = cursor.getAttribute && cursor.getAttribute('tabindex');
1001
+ var isGoodAncestor = role === 'tab' || role === 'button' || tag === 'button' || tag === 'a' || (tabIndex != null && String(tabIndex) !== '');
1002
+ if (!isGoodAncestor) {
1003
+ cursor = cursor.parentElement;
1004
+ depth++;
1005
+ continue;
1006
+ }
1007
+ var sig = getElementSignature(cursor);
1008
+ if (sig && seen.indexOf(sig) === -1) {
1009
+ seen.push(sig);
1010
+ attempts.push(cursor);
1011
+ }
1012
+ cursor = cursor.parentElement;
1013
+ depth++;
1014
+ }
1015
+
1016
+ for (var i = 0; i < attempts.length; i++) {
1017
+ var candidate = attempts[i];
1018
+ var before = getTabSelectedState(candidate);
1019
+ var rect = candidate.getBoundingClientRect ? candidate.getBoundingClientRect() : null;
1020
+ var clickByPoint = rect ? dispatchTapAt(Math.round(rect.left + rect.width / 2), Math.round(rect.top + rect.height / 2)) : false;
1021
+ var clicked = triggerUserClick(candidate) || clickByPoint;
1022
+ await delay(260);
1023
+ var after = getTabSelectedState(candidate);
1024
+ if (clicked) {
1025
+ clickedAny = true;
1026
+ finalBefore = before;
1027
+ finalAfter = after;
1028
+ finalTarget = candidate;
1029
+ }
1030
+ if (after === 'true') {
1031
+ return {
1032
+ clicked: !!clicked,
1033
+ beforeSelected: before,
1034
+ afterSelected: after,
1035
+ signature: getElementSignature(tab),
1036
+ targetSignature: getElementSignature(candidate),
1037
+ };
1038
+ }
1039
+ }
1040
+
1041
+ return {
1042
+ clicked: !!clickedAny,
1043
+ beforeSelected: finalBefore,
1044
+ afterSelected: finalAfter,
1045
+ signature: getElementSignature(tab),
1046
+ targetSignature: getElementSignature(finalTarget),
1047
+ };
1048
+ }
1049
+
1050
+ function getElementMeta(el) {
1051
+ if (!el) return null;
1052
+ try {
1053
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
1054
+ return {
1055
+ signature: getElementSignature(el),
1056
+ tag: el.tagName ? el.tagName.toLowerCase() : '',
1057
+ role: el.getAttribute ? (el.getAttribute('role') || '') : '',
1058
+ dataE2E: el.getAttribute ? (el.getAttribute('data-e2e') || '') : '',
1059
+ ariaSelected: el.getAttribute ? (el.getAttribute('aria-selected') || '') : '',
1060
+ className: typeof el.className === 'string' ? el.className.slice(0, 120) : '',
1061
+ text: ((el.textContent || '').trim().replace(/s+/g, ' ')).slice(0, 80),
1062
+ rect: rect ? toRectString(rect) : '',
1063
+ };
1064
+ } catch(e) {
1065
+ return { signature: getElementSignature(el) };
1066
+ }
1067
+ }
1068
+
1069
+ function getVisibleVideoIds(scopeUsername) {
1070
+ return extractVideosFromDom('baseline-visible', scopeUsername).map(function(video) {
1071
+ return video && video.videoId ? video.videoId : '';
1072
+ }).filter(Boolean);
1073
+ }
1074
+
1075
+ function collectTopTabLikeElements() {
1076
+ try {
1077
+ var nodes = Array.prototype.slice.call(document.querySelectorAll('p, [role="tab"], div, span, button, a'))
1078
+ .filter(function(el) {
1079
+ if (!el || !isVisibleElement(el)) return false;
1080
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
1081
+ if (!rect) return false;
1082
+ if (rect.top < 48 || rect.top > (window.innerHeight * 0.52)) return false;
1083
+ if (rect.width < 46 || rect.width > 260) return false;
1084
+ if (rect.height < 18 || rect.height > 80) return false;
1085
+ var txt = (el.textContent || '').trim().toLowerCase();
1086
+ var data = (el.getAttribute && el.getAttribute('data-e2e') || '').toLowerCase();
1087
+ if (txt.indexOf('liked') !== -1) return true;
1088
+ if (data.indexOf('liked') !== -1 || data.indexOf('tab') !== -1) return true;
1089
+ if (el.getAttribute && el.getAttribute('role') === 'tab') return true;
1090
+ return false;
1091
+ });
1092
+ nodes.sort(function(a, b) {
1093
+ var ar = a.getBoundingClientRect ? a.getBoundingClientRect() : { left: 0, top: 0 };
1094
+ var br = b.getBoundingClientRect ? b.getBoundingClientRect() : { left: 0, top: 0 };
1095
+ return (ar.top - br.top) || (br.left - ar.left);
1096
+ });
1097
+ var unique = [];
1098
+ var seen = [];
1099
+ for (var i = 0; i < nodes.length; i++) {
1100
+ var sig = getElementSignature(nodes[i]);
1101
+ if (!sig || seen.indexOf(sig) !== -1) continue;
1102
+ seen.push(sig);
1103
+ unique.push(nodes[i]);
1104
+ if (unique.length >= 8) break;
1105
+ }
1106
+ return unique;
1107
+ } catch(e) {
1108
+ return [];
1109
+ }
1110
+ }
1111
+
1112
+ function collectAnonymousTopTabCells() {
1113
+ try {
1114
+ var elements = Array.prototype.slice.call(document.querySelectorAll('div, p, span, button, a'))
1115
+ .filter(function(el) {
1116
+ if (!el || !isVisibleElement(el)) return false;
1117
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
1118
+ if (!rect) return false;
1119
+ if (rect.top < 120 || rect.top > (window.innerHeight * 0.45)) return false;
1120
+ if (rect.width < 58 || rect.width > 96) return false;
1121
+ if (rect.height < 34 || rect.height > 68) return false;
1122
+ var txt = (el.textContent || '').trim().toLowerCase();
1123
+ if (txt.length > 20) return false;
1124
+ return true;
1125
+ });
1126
+
1127
+ var byRow = {};
1128
+ for (var i = 0; i < elements.length; i++) {
1129
+ var rect = elements[i].getBoundingClientRect();
1130
+ var rowKey = String(Math.round((rect.top + rect.height / 2) / 6) * 6);
1131
+ if (!byRow[rowKey]) byRow[rowKey] = [];
1132
+ byRow[rowKey].push(elements[i]);
1133
+ }
1134
+
1135
+ var bestRow = null;
1136
+ var bestScore = -1;
1137
+ var keys = Object.keys(byRow);
1138
+ for (var k = 0; k < keys.length; k++) {
1139
+ var row = byRow[keys[k]].sort(function(a, b) {
1140
+ return a.getBoundingClientRect().left - b.getBoundingClientRect().left;
1141
+ });
1142
+ if (row.length < 4) continue;
1143
+ var first = row[0].getBoundingClientRect();
1144
+ var last = row[row.length - 1].getBoundingClientRect();
1145
+ var spread = last.right - first.left;
1146
+ if (spread < window.innerWidth * 0.58) continue;
1147
+ var y = parseInt(keys[k], 10);
1148
+ var score = (row.length * 120) + Math.min(260, spread) - Math.abs(218 - y);
1149
+ if (score > bestScore) {
1150
+ bestScore = score;
1151
+ bestRow = row;
1152
+ }
1153
+ }
1154
+
1155
+ if (!bestRow) return [];
1156
+ return bestRow.slice().reverse(); // right-most first
1157
+ } catch(e) {
1158
+ return [];
1159
+ }
1160
+ }
1161
+
1162
+ async function tryOpenLikedByTabCandidates(username) {
1163
+ await resetProfileScrollToTabs();
1164
+ var baselineIds = getVisibleVideoIds(username).join('|');
1165
+ var candidates = [];
1166
+ var appendCandidate = function(node) {
1167
+ if (!node) return;
1168
+ if (candidates.indexOf(node) === -1) candidates.push(node);
1169
+ };
1170
+
1171
+ appendCandidate(findExactLikedTabButton());
1172
+ var textLikedCandidate = findTextLikedTabButton();
1173
+ appendCandidate(textLikedCandidate);
1174
+ appendCandidate(resolveLikedInteractionTarget(textLikedCandidate));
1175
+ appendCandidate(findLikedTabButton());
1176
+ var collected = collectTopTabLikeElements();
1177
+ for (var i = 0; i < collected.length; i++) appendCandidate(collected[i]);
1178
+ var anonymousCells = collectAnonymousTopTabCells();
1179
+ for (var j = 0; j < anonymousCells.length; j++) appendCandidate(anonymousCells[j]);
1180
+
1181
+ var candidateLogs = [];
1182
+ if (candidates.length === 0) {
1183
+ return {
1184
+ opened: false,
1185
+ videos: [],
1186
+ containerFound: false,
1187
+ coordinateTapped: true,
1188
+ coordinate: {
1189
+ mode: 'candidate-tab-failed',
1190
+ reason: 'NO_CANDIDATES',
1191
+ tabCandidates: collectLikedTabCandidates(),
1192
+ candidates: candidateLogs
1193
+ }
1194
+ };
1195
+ }
1196
+ for (var ci = 0; ci < candidates.length; ci++) {
1197
+ var candidate = candidates[ci];
1198
+ var beforeMeta = getElementMeta(candidate);
1199
+ var clickState = await clickLikedTabWithState(candidate);
1200
+ await delay(950);
1201
+ var likedContainer = findLikedVideoContainer();
1202
+ if (likedContainer) {
1203
+ var containerVideos = extractVideosFromDom('liked-dom-candidate-container', username, likedContainer);
1204
+ if (containerVideos.length > 0 && !linksLookLikeOwnPosts(containerVideos, username)) {
1205
+ return {
1206
+ opened: true,
1207
+ videos: containerVideos,
1208
+ containerFound: true,
1209
+ coordinateTapped: true,
1210
+ coordinate: {
1211
+ mode: 'candidate-tab-container',
1212
+ clicked: beforeMeta,
1213
+ clickState: clickState,
1214
+ candidates: candidateLogs
1215
+ }
1216
+ };
1217
+ }
1218
+ }
1219
+ var videos = extractVideosFromDom('liked-dom-candidate', username);
1220
+ var afterIds = videos.map(function(video) { return video.videoId; }).join('|');
1221
+ candidateLogs.push({
1222
+ clicked: beforeMeta,
1223
+ clickState: clickState,
1224
+ videoCount: videos.length,
1225
+ changedFromBaseline: afterIds !== baselineIds,
1226
+ });
1227
+ if (videos.length > 0 && afterIds !== baselineIds && !linksLookLikeOwnPosts(videos, username)) {
1228
+ return {
1229
+ opened: true,
1230
+ videos: videos,
1231
+ containerFound: false,
1232
+ coordinateTapped: true,
1233
+ coordinate: {
1234
+ mode: 'candidate-tab',
1235
+ clicked: beforeMeta,
1236
+ clickState: clickState,
1237
+ candidates: candidateLogs
1238
+ }
1239
+ };
1240
+ }
1241
+ }
1242
+
1243
+ return {
1244
+ opened: false,
1245
+ videos: [],
1246
+ containerFound: false,
1247
+ coordinateTapped: true,
1248
+ coordinate: {
1249
+ mode: 'candidate-tab-failed',
1250
+ tabCandidates: collectLikedTabCandidates(),
1251
+ candidates: candidateLogs
1252
+ }
1253
+ };
1254
+ }
1255
+
1256
+ function getPrivateAccountNotice() {
1257
+ try {
1258
+ var candidates = Array.prototype.slice.call(document.querySelectorAll('div, p, span, h2, h3'));
1259
+ for (var i = 0; i < candidates.length; i++) {
1260
+ if (!isVisibleElement(candidates[i])) continue;
1261
+ var rect = candidates[i].getBoundingClientRect ? candidates[i].getBoundingClientRect() : null;
1262
+ if (!rect || rect.top > window.innerHeight * 0.92 || rect.bottom < 24) continue;
1263
+ var value = (candidates[i].textContent || '').trim().toLowerCase();
1264
+ if (!value || value.length < 18 || value.length > 420) continue;
1265
+ var match = value.match(/this account is private[^.]{0,140}|follow this account[^.]{0,140}|this user'?s liked videos are private[^.]{0,140}|liked videos are private[^.]{0,140}/i);
1266
+ if (match && match[0]) {
1267
+ return String(match[0]).trim().slice(0, 180);
1268
+ }
1269
+ }
1270
+ } catch(e) {}
1271
+ return '';
1272
+ }
1273
+
1274
+ function getManualDebugConfig() {
1275
+ try {
1276
+ var enabled = !!window.__ONAIROS_TIKTOK_MANUAL_DEBUG;
1277
+ var passiveLogOnly = !!window.__ONAIROS_TIKTOK_PASSIVE_LOG_ONLY;
1278
+ var timeoutMsRaw = Number(window.__ONAIROS_TIKTOK_MANUAL_TIMEOUT_MS || 0);
1279
+ var timeoutMs = Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0 ? timeoutMsRaw : 120000;
1280
+ var passiveWarmupRaw = Number(window.__ONAIROS_TIKTOK_PASSIVE_WARMUP_MS || 0);
1281
+ var passiveWarmupMs = Number.isFinite(passiveWarmupRaw) && passiveWarmupRaw > 0 ? passiveWarmupRaw : 7000;
1282
+ return {
1283
+ enabled: enabled,
1284
+ passiveLogOnly: passiveLogOnly,
1285
+ timeoutMs: Math.max(10000, timeoutMs),
1286
+ passiveWarmupMs: Math.max(5000, passiveWarmupMs)
1287
+ };
1288
+ } catch (e) {
1289
+ return { enabled: false, passiveLogOnly: false, timeoutMs: 120000, passiveWarmupMs: 7000 };
1290
+ }
1291
+ }
1292
+
1293
+ function getVideoIdList(videos, max) {
1294
+ return (videos || []).map(function(video) { return video && video.videoId; }).filter(Boolean).slice(0, max || 10);
1295
+ }
1296
+
1297
+ function collectManualSnapshot(username, baselineIds) {
1298
+ var state = getLikedTabDebugState();
1299
+ var videos = extractVideosFromDom('manual-debug-visible', username);
1300
+ var ids = getVideoIdList(videos, 12);
1301
+ var privateNotice = getPrivateAccountNotice();
1302
+ var liked = findExactLikedTabButton() || findTextLikedTabButton();
1303
+ var likedRect = liked && liked.getBoundingClientRect ? liked.getBoundingClientRect() : null;
1304
+ var points = [];
1305
+ if (likedRect) {
1306
+ points = [
1307
+ { x: Math.round(likedRect.left + likedRect.width * 0.5), y: Math.round(likedRect.top + likedRect.height * 0.5) },
1308
+ { x: Math.round(likedRect.left + likedRect.width * 0.85), y: Math.round(likedRect.top + likedRect.height * 0.5) }
1309
+ ];
1310
+ } else {
1311
+ var y = state.firstGridTop ? Math.max(88, state.firstGridTop - 42) : 120;
1312
+ points = [
1313
+ { x: Math.round(window.innerWidth * 0.5), y: y },
1314
+ { x: Math.round(window.innerWidth * 0.82), y: y },
1315
+ ];
1316
+ }
1317
+ var pointTargets = points.map(function(point) {
1318
+ return {
1319
+ x: point.x,
1320
+ y: point.y,
1321
+ target: getElementSignature(document.elementFromPoint(point.x, point.y))
1322
+ };
1323
+ });
1324
+ return {
1325
+ path: location.pathname,
1326
+ state: state,
1327
+ privateNotice: privateNotice,
1328
+ visibleVideoCount: videos.length,
1329
+ visibleVideoIds: ids,
1330
+ changedFromBaseline: ids.join('|') !== (baselineIds || ''),
1331
+ pointTargets: pointTargets,
1332
+ tabCandidates: collectLikedTabCandidates(),
1333
+ };
1334
+ }
1335
+
1336
+ async function runPassiveManualLogging(timeoutMs) {
1337
+ var started = Date.now();
1338
+ var tick = 0;
1339
+ var overrideUsername = getProfileUsernameOverride();
1340
+ if (overrideUsername) {
1341
+ var profileUrl = 'https://www.tiktok.com/@' + encodeURIComponent(overrideUsername);
1342
+ var routedToProfile = routeToProfileUrl(profileUrl);
1343
+ debug('manual:passive-route-profile', {
1344
+ overrideUsername: overrideUsername,
1345
+ profileUrl: profileUrl,
1346
+ routed: routedToProfile,
1347
+ path: location.pathname
1348
+ });
1349
+ await delay(700);
1350
+ }
1351
+ debug('manual:passive-start', {
1352
+ timeoutMs: timeoutMs,
1353
+ instructions: 'Passive log mode active. Use normal TikTok feed/profile manually while logs stream.'
1354
+ });
1355
+ while (Date.now() - started < timeoutMs) {
1356
+ tick += 1;
1357
+ var snapshot = collectManualSnapshot('', '');
1358
+ debug('manual:passive-tick', Object.assign({
1359
+ tick: tick,
1360
+ elapsedMs: Date.now() - started
1361
+ }, snapshot));
1362
+ // Exit early once profile content is clearly loaded and we logged enough samples.
1363
+ if (tick >= 3 && snapshot && snapshot.visibleVideoCount > 0) {
1364
+ debug('manual:passive-ready', {
1365
+ tick: tick,
1366
+ elapsedMs: Date.now() - started,
1367
+ visibleVideoCount: snapshot.visibleVideoCount
1368
+ });
1369
+ return;
1370
+ }
1371
+ await delay(1500);
1372
+ }
1373
+ debug('manual:passive-end', { elapsedMs: Date.now() - started });
1374
+ }
1375
+
1376
+ async function waitForManualLikedContext(username, timeoutMs) {
1377
+ var started = Date.now();
1378
+ var baselineVideos = extractVideosFromDom('manual-debug-baseline', username);
1379
+ var baselineIds = getVideoIdList(baselineVideos, 20).join('|');
1380
+ var tick = 0;
1381
+ debug('manual:start', {
1382
+ timeoutMs: timeoutMs,
1383
+ baselineCount: baselineVideos.length,
1384
+ baselineIds: getVideoIdList(baselineVideos, 12),
1385
+ instructions: 'Manually open your profile, tap Liked tab, wait on that screen.'
1386
+ });
1387
+
1388
+ while (Date.now() - started < timeoutMs) {
1389
+ tick += 1;
1390
+ var snapshot = collectManualSnapshot(username, baselineIds);
1391
+ debug('manual:tick', Object.assign({ tick: tick, elapsedMs: Date.now() - started }, snapshot));
1392
+
1393
+ var onLikedPath = /\\/@[^/]+\\/liked\\/?$/i.test(location.pathname || '');
1394
+ var hasLikedContainer = !!findLikedVideoContainer();
1395
+ var hasNonOwnVideos = snapshot.visibleVideoCount > 0 && !linksLookLikeOwnPosts(
1396
+ extractVideosFromDom('manual-debug-check', username),
1397
+ username
1398
+ );
1399
+ if (onLikedPath || hasLikedContainer || hasNonOwnVideos) {
1400
+ debug('manual:ready', {
1401
+ tick: tick,
1402
+ elapsedMs: Date.now() - started,
1403
+ onLikedPath: onLikedPath,
1404
+ hasLikedContainer: hasLikedContainer,
1405
+ hasNonOwnVideos: hasNonOwnVideos
1406
+ });
1407
+ return { completed: true, baselineIds: baselineIds };
1408
+ }
1409
+ await delay(1500);
1410
+ }
1411
+
1412
+ debug('manual:timeout', { elapsedMs: Date.now() - started });
1413
+ return { completed: false, baselineIds: baselineIds };
1414
+ }
1415
+
1416
+ function collectLikedTabCandidates() {
1417
+ try {
1418
+ return Array.prototype.slice.call(document.querySelectorAll('p[role="tab"], [role="tab"], [data-e2e*="tab"], [data-e2e*="liked"]'))
1419
+ .map(function(el) {
1420
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
1421
+ return getElementSignature(el) + (rect ? (' @ ' + toRectString(rect)) : '');
1422
+ })
1423
+ .filter(Boolean)
1424
+ .slice(0, 24);
1425
+ } catch(e) {
1426
+ return [];
1427
+ }
1428
+ }
1429
+
1430
+ async function waitForLikedTabReady(timeoutMs) {
1431
+ var started = Date.now();
1432
+ var lastSnapshot = null;
1433
+ while (Date.now() - started < timeoutMs) {
1434
+ var exact = findExactLikedTabButton();
1435
+ var textLiked = findTextLikedTabButton();
1436
+ var generic = findLikedTabButton();
1437
+ var privateNotice = getPrivateAccountNotice();
1438
+ var textPrivate = textLiked && isVisibleElement(textLiked) && /liked videos are private/i.test((textLiked.textContent || ''));
1439
+ lastSnapshot = {
1440
+ path: location.pathname,
1441
+ scrollY: window.scrollY || 0,
1442
+ firstGridTop: getFirstVideoGridTop(),
1443
+ hasExactLikedTab: !!exact,
1444
+ exactLikedSignature: getElementSignature(exact),
1445
+ hasTextLikedTab: !!textLiked,
1446
+ textLikedSignature: getElementSignature(textLiked),
1447
+ hasGenericLiked: !!generic,
1448
+ genericLikedSignature: getElementSignature(generic),
1449
+ privateNotice: privateNotice || (textPrivate ? 'This user liked videos are private' : ''),
1450
+ tabCandidates: collectLikedTabCandidates(),
1451
+ };
1452
+ if (exact || textLiked || generic) {
1453
+ return {
1454
+ ready: true,
1455
+ exact: exact || null,
1456
+ textLiked: textLiked || null,
1457
+ generic: generic || null,
1458
+ snapshot: lastSnapshot
1459
+ };
1460
+ }
1461
+ await delay(350);
1462
+ }
1463
+ return { ready: false, exact: null, textLiked: null, generic: null, snapshot: lastSnapshot };
1464
+ }
1465
+
1466
+ async function waitForProfileContentReady(timeoutMs) {
1467
+ var started = Date.now();
1468
+ while (Date.now() - started < timeoutMs) {
1469
+ var hasHeader = !!document.querySelector('[data-e2e="user-title"], h2[data-e2e="user-title"], h2');
1470
+ var firstGridTop = getFirstVideoGridTop();
1471
+ if (hasHeader || firstGridTop > 0) {
1472
+ return { ready: true, hasHeader: hasHeader, firstGridTop: firstGridTop };
1473
+ }
1474
+ await delay(250);
1475
+ }
1476
+ return { ready: false, hasHeader: !!document.querySelector('[data-e2e="user-title"], h2[data-e2e="user-title"], h2'), firstGridTop: getFirstVideoGridTop() };
1477
+ }
1478
+
1479
+ function getLikedTabDebugState() {
1480
+ var likedTab = findExactLikedTabButton();
1481
+ var textLikedTab = findTextLikedTabButton();
1482
+ var genericLiked = findLikedTabButton();
1483
+ var activeTab = null;
1484
+ try {
1485
+ activeTab = document.querySelector('[role="tab"][aria-selected="true"]');
1486
+ } catch(e) {}
1487
+ return {
1488
+ path: location.pathname,
1489
+ scrollY: window.scrollY || 0,
1490
+ firstGridTop: getFirstVideoGridTop(),
1491
+ hasExactLikedTab: !!likedTab,
1492
+ exactLikedSignature: getElementSignature(likedTab),
1493
+ exactLikedSelected: !!(likedTab && String(likedTab.getAttribute('aria-selected') || '').toLowerCase() === 'true'),
1494
+ hasTextLikedTab: !!textLikedTab,
1495
+ textLikedSignature: getElementSignature(textLikedTab),
1496
+ textLikedSelected: !!(textLikedTab && String(textLikedTab.getAttribute('aria-selected') || '').toLowerCase() === 'true'),
1497
+ hasGenericLiked: !!genericLiked,
1498
+ genericLikedSignature: getElementSignature(genericLiked),
1499
+ activeTabSignature: getElementSignature(activeTab),
1500
+ };
1501
+ }
1502
+
1503
+ function captureTapProbe(firstGridTop, rowCandidate) {
1504
+ var y = rowCandidate && rowCandidate.rowY
1505
+ ? rowCandidate.rowY
1506
+ : (firstGridTop ? Math.max(72, firstGridTop - 18) : Math.round(window.innerHeight * 0.56));
1507
+ var xPoints = [0.18, 0.5, 0.82].map(function(mult) { return Math.round(window.innerWidth * mult); });
1508
+ return xPoints.map(function(x) {
1509
+ var el = document.elementFromPoint(x, y);
1510
+ return { x: x, y: y, target: getElementSignature(el) };
1511
+ });
1512
+ }
1513
+
1514
+ async function tapMobileLikedTabByPosition(username) {
1515
+ await resetProfileScrollToTabs();
1516
+ var firstGridTop = getFirstVideoGridTop();
1517
+ var beforeIds = extractVideosFromDom('before-liked-coordinate', username).map(function(video) { return video.videoId; }).join('|');
1518
+ var directLikedTab = findExactLikedTabButton() || findTextLikedTabButton();
1519
+ if (directLikedTab) {
1520
+ var tabRect = directLikedTab.getBoundingClientRect ? directLikedTab.getBoundingClientRect() : null;
1521
+ var tabPoints = tabRect ? [
1522
+ { x: Math.round(tabRect.left + tabRect.width * 0.5), y: Math.round(tabRect.top + tabRect.height * 0.5) },
1523
+ { x: Math.round(tabRect.left + tabRect.width * 0.7), y: Math.round(tabRect.top + tabRect.height * 0.5) },
1524
+ { x: Math.round(tabRect.left + tabRect.width * 0.85), y: Math.round(tabRect.top + tabRect.height * 0.45) },
1525
+ { x: Math.round(tabRect.right - 8), y: Math.round(tabRect.top + tabRect.height * 0.5) }
1526
+ ] : [];
1527
+ for (var dti = 0; dti < tabPoints.length; dti++) {
1528
+ dispatchTapAt(tabPoints[dti].x, tabPoints[dti].y);
1529
+ triggerUserClick(directLikedTab);
1530
+ await delay(900);
1531
+ var exactVideos = extractVideosFromDom('liked-dom-exact-tab', username);
1532
+ var exactIds = exactVideos.map(function(video) { return video.videoId; }).join('|');
1533
+ if (exactVideos.length > 0 && exactIds !== beforeIds && !linksLookLikeOwnPosts(exactVideos, username)) {
1534
+ return {
1535
+ opened: true,
1536
+ videos: exactVideos,
1537
+ containerFound: false,
1538
+ coordinateTapped: true,
1539
+ coordinate: {
1540
+ mode: 'exact-liked-tab-rect',
1541
+ target: getElementSignature(directLikedTab),
1542
+ point: tabPoints[dti]
1543
+ }
1544
+ };
1545
+ }
1546
+ }
1547
+ }
1548
+ var rowCandidate = detectIconTabRowNearGrid(firstGridTop);
1549
+ if (isStatsLikeRow(rowCandidate) || isStatsLikeRowBySignature(rowCandidate)) {
1550
+ rowCandidate = null;
1551
+ }
1552
+ if (!rowCandidate) {
1553
+ var anonymousRowCandidate = detectAnonymousTabCellRow(firstGridTop);
1554
+ if (anonymousRowCandidate && isLikelyTabCellRow(anonymousRowCandidate, firstGridTop)) {
1555
+ rowCandidate = anonymousRowCandidate;
1556
+ }
1557
+ }
1558
+ if (!rowCandidate) {
1559
+ var profileRowCandidate = detectProfileTabRow(firstGridTop);
1560
+ if (
1561
+ profileRowCandidate &&
1562
+ (
1563
+ (!isStatsLikeRow(profileRowCandidate) && !isStatsLikeRowBySignature(profileRowCandidate) && isLikelyTabCellRow(profileRowCandidate, firstGridTop)) ||
1564
+ (profileRowCandidate.elements && profileRowCandidate.elements.length >= 4)
1565
+ )
1566
+ ) {
1567
+ rowCandidate = profileRowCandidate;
1568
+ }
1569
+ }
1570
+ var baseTabY = rowCandidate && rowCandidate.rowY
1571
+ ? rowCandidate.rowY
1572
+ : (firstGridTop ? Math.max(96, firstGridTop - 44) : Math.round(window.innerHeight * 0.30));
1573
+ var attemptLog = [];
1574
+ if (rowCandidate && rowCandidate.elements && rowCandidate.elements.length >= 3) {
1575
+ var rowTargets = rowCandidate.elements.map(function(entry) { return entry.el; });
1576
+ var preferenceOrder = rowTargets.slice().reverse().filter(Boolean);
1577
+
1578
+ for (var t = 0; t < preferenceOrder.length; t++) {
1579
+ var targetEl = preferenceOrder[t];
1580
+ try {
1581
+ var rect = targetEl && targetEl.getBoundingClientRect ? targetEl.getBoundingClientRect() : null;
1582
+ if (rect) {
1583
+ dispatchTapAt(Math.round(rect.left + rect.width / 2), Math.round(rect.top + rect.height / 2));
1584
+ attemptLog.push({
1585
+ mode: 'row-target-dispatch',
1586
+ target: getElementSignature(targetEl),
1587
+ rect: toRectString(rect)
1588
+ });
1589
+ await delay(220);
1590
+ }
1591
+ } catch(e) {}
1592
+ triggerUserClick(targetEl);
1593
+ attemptLog.push({
1594
+ mode: 'row-target-click',
1595
+ target: getElementSignature(targetEl)
1596
+ });
1597
+ await delay(1150);
1598
+ var directVideos = extractVideosFromDom('liked-dom-row-target', username);
1599
+ var directIds = directVideos.map(function(video) { return video.videoId; }).join('|');
1600
+ if (directVideos.length > 0 && directIds !== beforeIds && !linksLookLikeOwnPosts(directVideos, username)) {
1601
+ return {
1602
+ opened: true,
1603
+ videos: directVideos,
1604
+ containerFound: false,
1605
+ coordinateTapped: true,
1606
+ coordinate: {
1607
+ mode: 'row-target',
1608
+ rowY: rowCandidate.rowY,
1609
+ target: getElementSignature(preferenceOrder[t]),
1610
+ attempts: attemptLog.slice(0, 10)
1611
+ }
1612
+ };
1613
+ }
1614
+ }
1615
+ }
1616
+
1617
+ var xPositions = [
1618
+ Math.round(window.innerWidth * 0.82),
1619
+ Math.round(window.innerWidth * 0.75),
1620
+ Math.round(window.innerWidth * 0.68),
1621
+ Math.round(window.innerWidth * 0.67),
1622
+ Math.round(window.innerWidth * 0.58),
1623
+ Math.round(window.innerWidth * 0.50)
1624
+ ];
1625
+ var yOffsets = [-36, -24, -12, 0, 12, 24, 36];
1626
+
1627
+ for (var yi = 0; yi < yOffsets.length; yi++) {
1628
+ var tabY = Math.max(84, baseTabY + yOffsets[yi]);
1629
+ for (var i = 0; i < xPositions.length; i++) {
1630
+ dispatchTapAt(xPositions[i], tabY);
1631
+ attemptLog.push({
1632
+ mode: 'coordinate-dispatch',
1633
+ x: xPositions[i],
1634
+ y: tabY,
1635
+ pointTarget: getElementSignature(document.elementFromPoint(xPositions[i], tabY))
1636
+ });
1637
+ await delay(1150);
1638
+
1639
+ var immediateVideos = extractVideosFromDom('liked-dom-coordinate-immediate', username);
1640
+ var immediateIds = immediateVideos.map(function(video) { return video.videoId; }).join('|');
1641
+ if (immediateVideos.length > 0 && immediateIds !== beforeIds && !linksLookLikeOwnPosts(immediateVideos, username)) {
1642
+ return {
1643
+ opened: true,
1644
+ videos: immediateVideos,
1645
+ containerFound: false,
1646
+ coordinateTapped: true,
1647
+ coordinate: { x: xPositions[i], y: tabY, attempts: attemptLog.slice(0, 14) }
1648
+ };
1649
+ }
1650
+
1651
+ await scrollLikedGrid();
1652
+ var videos = extractVideosFromDom('liked-dom-coordinate', username);
1653
+ var afterIds = videos.map(function(video) { return video.videoId; }).join('|');
1654
+ if (videos.length > 0 && afterIds !== beforeIds && !linksLookLikeOwnPosts(videos, username)) {
1655
+ return {
1656
+ opened: true,
1657
+ videos: videos,
1658
+ containerFound: false,
1659
+ coordinateTapped: true,
1660
+ coordinate: { x: xPositions[i], y: tabY, attempts: attemptLog.slice(0, 14) }
1661
+ };
1662
+ }
1663
+ }
1664
+ }
1665
+
1666
+ return {
1667
+ opened: false,
1668
+ videos: [],
1669
+ containerFound: false,
1670
+ coordinateTapped: true,
1671
+ coordinate: {
1672
+ y: baseTabY,
1673
+ triedX: xPositions,
1674
+ triedYOffset: yOffsets,
1675
+ firstGridTop: firstGridTop,
1676
+ attempts: attemptLog.slice(0, 18),
1677
+ rowCandidate: rowCandidate ? {
1678
+ rowY: rowCandidate.rowY,
1679
+ elements: rowCandidate.elements.slice(0, 5).map(function(entry) {
1680
+ return getElementSignature(entry.el) + ' @ ' + toRectString(entry.rect);
1681
+ })
1682
+ } : null
1683
+ },
1684
+ diagnostics: collectTabDiagnostics({ firstGridTop: firstGridTop, rowCandidate: rowCandidate })
1685
+ };
1686
+ }
1687
+
1688
+ function collectTabDiagnostics(context) {
1689
+ var firstGridTop = context && typeof context.firstGridTop === 'number' ? context.firstGridTop : getFirstVideoGridTop();
1690
+ try {
1691
+ var labels = Array.prototype.slice.call(document.querySelectorAll('span, [role="tab"], button, [tabindex], div'))
1692
+ .map(function(el) {
1693
+ var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
1694
+ var pos = rect ? Math.round(rect.left) + ',' + Math.round(rect.top) + ',' + Math.round(rect.width) + 'x' + Math.round(rect.height) : '';
1695
+ var combined = [getElementSignature(el), pos].filter(Boolean).join(' @ ');
1696
+ return combined.length > 160 ? combined.slice(0, 160) : combined;
1697
+ })
1698
+ .filter(function(value) { return value && /liked|likes|favorite|video|post|lock|tab/i.test(value); })
1699
+ .slice(0, 30);
1700
+ var rowCandidate = (context && context.rowCandidate) || detectProfileTabRow(firstGridTop);
1701
+ var probes = captureTapProbe(firstGridTop, rowCandidate);
1702
+ return {
1703
+ path: location.pathname,
1704
+ viewport: { width: window.innerWidth, height: window.innerHeight },
1705
+ scroll: {
1706
+ windowY: window.scrollY || 0,
1707
+ bodyTop: document.body && document.body.getBoundingClientRect ? Math.round(document.body.getBoundingClientRect().top) : 0
1708
+ },
1709
+ firstGridTop: firstGridTop,
1710
+ probeTargets: probes,
1711
+ rowCandidate: rowCandidate ? {
1712
+ rowY: rowCandidate.rowY,
1713
+ elements: rowCandidate.elements.slice(0, 6).map(function(entry) {
1714
+ return getElementSignature(entry.el) + ' @ ' + toRectString(entry.rect);
1715
+ })
1716
+ } : null,
1717
+ labels: labels
1718
+ };
1719
+ } catch(e) {
1720
+ return { error: String(e && e.message ? e.message : e) };
1721
+ }
1722
+ }
1723
+
1724
+ async function scrollLikedGrid() {
1725
+ for (var i = 0; i < 4; i++) {
1726
+ try {
1727
+ window.scrollTo(0, document.body.scrollHeight);
1728
+ } catch(e) {}
1729
+ var targets = getScrollableElements();
1730
+ for (var j = 0; j < targets.length; j++) {
1731
+ try {
1732
+ targets[j].scrollTop = Math.max(targets[j].scrollTop, targets[j].scrollHeight);
1733
+ } catch(e) {}
1734
+ }
1735
+ await delay(700);
1736
+ }
1737
+ }
1738
+
1739
+ function isOwnProfilePath(pathname) {
1740
+ return /^\\/@[^/]+\\/?$/i.test(pathname || '');
1741
+ }
1742
+
1743
+ function absolutizeTikTokUrl(href) {
1744
+ if (!href || typeof href !== 'string') return '';
1745
+ try {
1746
+ return new URL(href, 'https://www.tiktok.com').href;
1747
+ } catch(e) {
1748
+ return '';
1749
+ }
1750
+ }
1751
+
1752
+ function isProfileUrl(href) {
1753
+ if (!href) return false;
1754
+ try {
1755
+ var parsed = new URL(href, 'https://www.tiktok.com');
1756
+ return /\\/(@[^/]+)\\/?$/i.test(parsed.pathname || '');
1757
+ } catch(e) {
1758
+ return false;
1759
+ }
1760
+ }
1761
+
1762
+ function getProfileUsernameOverride() {
1763
+ try {
1764
+ var value = window.__ONAIROS_TIKTOK_PROFILE_USERNAME;
1765
+ if (!value || typeof value !== 'string') return '';
1766
+ return value.replace(/^@/, '').trim();
1767
+ } catch(e) {
1768
+ return '';
1769
+ }
1770
+ }
1771
+
1772
+ function getCurrentProfileUsername() {
1773
+ var currentProfileMatch = location.pathname.match(/^\\/@([^/]+)\\/?$/);
1774
+ return currentProfileMatch ? decodeURIComponent(currentProfileMatch[1]).replace(/^@/, '') : '';
1775
+ }
1776
+
1777
+ /**
1778
+ * Detects the logged-in user's TikTok handle by parsing the current page's
1779
+ * hydration scripts (__UNIVERSAL_DATA_FOR_REHYDRATION__ / SIGI_STATE).
1780
+ *
1781
+ * TikTok's webapp embeds the current session user under known keys; we
1782
+ * check them in order of specificity, falling back to a generic deep scan
1783
+ * for any object that carries both a uniqueId AND looks like the logged-in
1784
+ * user (has private/login/app-context signals rather than being some other
1785
+ * user's UserModule entry).
1786
+ *
1787
+ * Returns '' when no logged-in user can be confidently identified.
1788
+ */
1789
+ function detectLoggedInUsernameFromHydration() {
1790
+ try {
1791
+ var states = parseHydrationStates(document);
1792
+ var sanitize = function(value) {
1793
+ if (typeof value !== 'string') return '';
1794
+ return value.replace(/^@/, '').trim();
1795
+ };
1796
+
1797
+ for (var s = 0; s < states.length; s++) {
1798
+ var state = states[s];
1799
+ if (!state || typeof state !== 'object') continue;
1800
+
1801
+ // __UNIVERSAL_DATA_FOR_REHYDRATION__ shape (current TikTok webapp).
1802
+ var defaultScope = state.__DEFAULT_SCOPE__ || state.default_scope || state.defaultScope;
1803
+ if (defaultScope && typeof defaultScope === 'object') {
1804
+ var appContext = defaultScope['webapp.app-context'] || defaultScope['webapp.user-detail'];
1805
+ var ctxUser = appContext && appContext.user;
1806
+ if (ctxUser) {
1807
+ var ctxName = sanitize(ctxUser.uniqueId || ctxUser.unique_id || ctxUser.nickName || ctxUser.nickname);
1808
+ if (ctxName) return ctxName;
1809
+ }
1810
+ }
1811
+
1812
+ // Legacy SIGI_STATE shape \u2014 AppContext / UserModule / userInfo.
1813
+ var legacyCtx = state.AppContext || state.appContext;
1814
+ var legacyUser = legacyCtx && (legacyCtx.user || (legacyCtx.userInfo && legacyCtx.userInfo.user));
1815
+ if (legacyUser) {
1816
+ var legacyName = sanitize(legacyUser.uniqueId || legacyUser.unique_id || legacyUser.nickname);
1817
+ if (legacyName) return legacyName;
1818
+ }
1819
+
1820
+ // Heuristic deep scan: an object carrying a uniqueId together with
1821
+ // signals that mark it as the *current* session user (rather than
1822
+ // some random profile from a video feed). We look for app-context
1823
+ // markers like aid/appId/isLogin, or "self" markers on the node.
1824
+ var candidates = findByKeys(state, function(node) {
1825
+ if (!node || typeof node !== 'object') return false;
1826
+ if (!(node.uniqueId || node.unique_id)) return false;
1827
+ return !!(
1828
+ node.isLogin === true ||
1829
+ node.is_login === true ||
1830
+ node.isSelf === true ||
1831
+ node.is_self === true ||
1832
+ node.appId ||
1833
+ node.app_id ||
1834
+ node.aid ||
1835
+ (node.user && (node.user.uniqueId || node.user.unique_id))
1836
+ );
1837
+ }, 5);
1838
+
1839
+ for (var i = 0; i < candidates.length; i++) {
1840
+ var c = candidates[i];
1841
+ var nested = c && c.user && (c.user.uniqueId || c.user.unique_id);
1842
+ var name = sanitize(nested || c.uniqueId || c.unique_id);
1843
+ if (name) return name;
1844
+ }
1845
+ }
1846
+ } catch (e) {}
1847
+ return '';
1848
+ }
1849
+
1850
+ function routeToProfileUrl(profileUrl) {
1851
+ try {
1852
+ var parsed = new URL(profileUrl, 'https://www.tiktok.com');
1853
+ var nextPath = parsed.pathname || '';
1854
+ if (!/^\\/@[^/]+\\/?$/i.test(nextPath)) return false;
1855
+ history.pushState(null, '', nextPath);
1856
+ try {
1857
+ window.dispatchEvent(typeof PopStateEvent !== 'undefined' ? new PopStateEvent('popstate') : new Event('popstate'));
1858
+ } catch(e) {}
1859
+ return true;
1860
+ } catch(e) {
1861
+ return false;
1862
+ }
1863
+ }
1864
+
1865
+ async function tryExtractFromLikedRoute(username) {
1866
+ if (!username) return null;
1867
+ var likedUrl = 'https://www.tiktok.com/@' + encodeURIComponent(String(username).replace(/^@/, '')) + '/liked';
1868
+ debug('liked:route-liked-attempt', { username: username, fetchUrl: likedUrl, path: location.pathname });
1869
+ try {
1870
+ var response = await fetch(likedUrl, {
1871
+ method: 'GET',
1872
+ credentials: 'include',
1873
+ headers: { 'Accept': 'text/html,application/xhtml+xml' },
1874
+ });
1875
+ if (!response.ok) {
1876
+ debug('liked:route-liked-empty', { reason: 'FETCH_NOT_OK', status: response.status, path: location.pathname });
1877
+ return null;
1878
+ }
1879
+ var html = await response.text();
1880
+ var doc = new DOMParser().parseFromString(html, 'text/html');
1881
+ var states = parseHydrationStates(doc);
1882
+ var extracted = extractFromStates(states, username, 'liked-fetch-hydration');
1883
+ var videos = (extracted && extracted.videos ? extracted.videos : []).filter(function(video) {
1884
+ return !!(video && video.videoId);
1885
+ });
1886
+ if (videos.length > 0 && !linksLookLikeOwnPosts(videos, username)) {
1887
+ return {
1888
+ opened: true,
1889
+ videos: videos,
1890
+ containerFound: false,
1891
+ coordinateTapped: true,
1892
+ coordinate: { mode: 'route-liked-fetch', path: location.pathname, count: videos.length }
1893
+ };
1894
+ }
1895
+ debug('liked:route-liked-empty', {
1896
+ reason: 'NO_LIKED_VIDEOS_FROM_FETCH',
1897
+ path: location.pathname,
1898
+ count: videos.length,
1899
+ });
1900
+ return null;
1901
+ } catch (e) {
1902
+ debug('liked:route-liked-empty', {
1903
+ reason: 'FETCH_EXCEPTION',
1904
+ path: location.pathname,
1905
+ message: String(e && e.message ? e.message : e),
1906
+ });
1907
+ return null;
1908
+ }
1909
+ }
1910
+
1911
+ function resolveSecUidFromStates(states, username) {
1912
+ var target = (username || '').toLowerCase();
1913
+ var secUid = '';
1914
+ (states || []).forEach(function(state) {
1915
+ if (secUid) return;
1916
+ var users = findByKeys(state, function(node) {
1917
+ if (!node || typeof node !== 'object') return false;
1918
+ var uniqueId = String(node.uniqueId || node.username || '').toLowerCase();
1919
+ var nodeSecUid = String(node.secUid || node.sec_uid || '');
1920
+ if (!nodeSecUid) return false;
1921
+ if (!target) return true;
1922
+ return uniqueId === target;
1923
+ }, 50);
1924
+ for (var i = 0; i < users.length; i++) {
1925
+ var candidate = users[i];
1926
+ var value = candidate && (candidate.secUid || candidate.sec_uid);
1927
+ if (value) {
1928
+ secUid = String(value);
1929
+ break;
1930
+ }
1931
+ }
1932
+ });
1933
+ return secUid;
1934
+ }
1935
+
1936
+ function extractVideoArrayFromApiPayload(payload) {
1937
+ if (!payload || typeof payload !== 'object') return [];
1938
+ var buckets = [
1939
+ payload.itemList,
1940
+ payload.item_list,
1941
+ payload.items,
1942
+ payload.aweme_list,
1943
+ payload.videoList,
1944
+ payload.data && payload.data.itemList,
1945
+ payload.data && payload.data.item_list,
1946
+ payload.data && payload.data.items,
1947
+ payload.body && payload.body.itemList,
1948
+ payload.body && payload.body.item_list
1949
+ ];
1950
+ for (var i = 0; i < buckets.length; i++) {
1951
+ if (Array.isArray(buckets[i]) && buckets[i].length > 0) return buckets[i];
1952
+ }
1953
+ return [];
1954
+ }
1955
+
1956
+ async function fetchLikedVideosViaApi(username, states) {
1957
+ if (!username) return null;
1958
+ var secUid = resolveSecUidFromStates(states, username);
1959
+ var base = 'https://www.tiktok.com';
1960
+ var endpoints = [];
1961
+ if (secUid) {
1962
+ endpoints.push(base + '/api/favorite/item_list/?aid=1988&count=35&cursor=0&secUid=' + encodeURIComponent(secUid));
1963
+ endpoints.push(base + '/api/user/liked/list/?aid=1988&count=35&cursor=0&secUid=' + encodeURIComponent(secUid));
1964
+ endpoints.push(base + '/api/item_list/?aid=1988&count=35&cursor=0&type=2&secUid=' + encodeURIComponent(secUid));
1965
+ }
1966
+ endpoints.push(base + '/api/user/liked/list/?aid=1988&count=35&cursor=0&uniqueId=' + encodeURIComponent(username));
1967
+
1968
+ var attemptLog = [];
1969
+ var seen = {};
1970
+ var videos = [];
1971
+ for (var i = 0; i < endpoints.length; i++) {
1972
+ var url = endpoints[i];
1973
+ try {
1974
+ var response = await fetch(url, {
1975
+ method: 'GET',
1976
+ credentials: 'include',
1977
+ headers: { 'Accept': 'application/json,text/plain,*/*' },
1978
+ });
1979
+ var status = response.status;
1980
+ var body = null;
1981
+ try {
1982
+ body = await response.json();
1983
+ } catch (e) {
1984
+ attemptLog.push({ endpoint: url, status: status, parse: 'json-failed' });
1985
+ continue;
1986
+ }
1987
+
1988
+ var rawItems = extractVideoArrayFromApiPayload(body);
1989
+ var normalized = rawItems.map(function(item) {
1990
+ return normalizeVideo(item, username, 'liked-api');
1991
+ }).filter(function(video) { return !!(video && video.videoId); });
1992
+
1993
+ for (var vi = 0; vi < normalized.length; vi++) {
1994
+ var key = normalized[vi].videoId;
1995
+ if (!seen[key]) {
1996
+ seen[key] = true;
1997
+ videos.push(normalized[vi]);
1998
+ }
1999
+ }
2000
+
2001
+ attemptLog.push({
2002
+ endpoint: url,
2003
+ status: status,
2004
+ rawCount: rawItems.length,
2005
+ normalizedCount: normalized.length
2006
+ });
2007
+
2008
+ if (videos.length > 0 && !linksLookLikeOwnPosts(videos, username)) {
2009
+ debug('liked:api-liked-success', {
2010
+ endpoint: url,
2011
+ secUidFound: !!secUid,
2012
+ attempts: attemptLog
2013
+ });
2014
+ return {
2015
+ opened: true,
2016
+ videos: videos,
2017
+ containerFound: false,
2018
+ coordinateTapped: true,
2019
+ coordinate: { mode: 'liked-api', endpoint: url, attempts: attemptLog }
2020
+ };
2021
+ }
2022
+ } catch (e) {
2023
+ attemptLog.push({ endpoint: url, status: 'fetch-error', message: String(e && e.message ? e.message : e) });
2024
+ }
2025
+ }
2026
+
2027
+ debug('liked:api-liked-empty', {
2028
+ secUidFound: !!secUid,
2029
+ attempts: attemptLog,
2030
+ totalVideos: videos.length
2031
+ });
2032
+ return null;
2033
+ }
2034
+
2035
+ async function waitForProfileRoute(expectedUsername, timeoutMs) {
2036
+ var startedAt = Date.now();
2037
+ var expected = expectedUsername ? expectedUsername.toLowerCase() : '';
2038
+ while (Date.now() - startedAt < timeoutMs) {
2039
+ var currentUsername = getCurrentProfileUsername();
2040
+ var domProfile = extractProfileFromDom();
2041
+ var domUsername = domProfile && domProfile.username ? domProfile.username.toLowerCase() : '';
2042
+ var pathMatches = currentUsername && (!expected || currentUsername.toLowerCase() === expected);
2043
+ var domMatches = domUsername && (!expected || domUsername === expected);
2044
+ if (pathMatches && (domMatches || document.querySelector('a[href*="/video/"], [data-e2e="user-bio"], [data-e2e="user-title"]'))) {
2045
+ return true;
2046
+ }
2047
+ await delay(350);
2048
+ }
2049
+ return false;
2050
+ }
2051
+
2052
+ function findOwnProfileUrl() {
2053
+ var overrideUsername = getProfileUsernameOverride();
2054
+
2055
+ var explicitSelectors = [
2056
+ 'a[data-e2e="nav-profile"]',
2057
+ '[data-e2e="nav-profile"] a[href*="/@"]',
2058
+ '[data-e2e="profile-icon"] a[href*="/@"]',
2059
+ '[data-e2e="user-avatar"] a[href*="/@"]',
2060
+ '[data-e2e="profile-button"] a[href*="/@"]',
2061
+ '[data-e2e="profile-link"]',
2062
+ '[data-e2e^="nav-"] a[href*="/@"]',
2063
+ 'a[href*="/@"][aria-label*="profile" i]',
2064
+ 'a[href*="/@"][title*="profile" i]'
2065
+ ];
2066
+
2067
+ for (var si = 0; si < explicitSelectors.length; si++) {
2068
+ try {
2069
+ var el = document.querySelector(explicitSelectors[si]);
2070
+ var href = el && (el.href || el.getAttribute('href'));
2071
+ var absolute = absolutizeTikTokUrl(href);
2072
+ if (isProfileUrl(absolute)) return absolute;
2073
+ } catch(e) {}
2074
+ }
2075
+
2076
+ var anchors = Array.prototype.slice.call(document.querySelectorAll('a[href*="/@"]:not([href*="/video/"])'));
2077
+ for (var i = 0; i < anchors.length; i++) {
2078
+ var anchor = anchors[i];
2079
+ var label = [
2080
+ anchor.getAttribute('aria-label') || '',
2081
+ anchor.getAttribute('title') || '',
2082
+ anchor.getAttribute('data-e2e') || '',
2083
+ anchor.textContent || ''
2084
+ ].join(' ').toLowerCase();
2085
+ var inNav = !!anchor.closest('nav, aside, header, [role="navigation"]');
2086
+ var looksLikeSelfProfile = inNav && (
2087
+ label.indexOf('profile') !== -1 ||
2088
+ label.indexOf('view profile') !== -1 ||
2089
+ label.trim() === 'me'
2090
+ );
2091
+ if (!looksLikeSelfProfile) continue;
2092
+ var absoluteHref = absolutizeTikTokUrl(anchor.href || anchor.getAttribute('href'));
2093
+ if (isProfileUrl(absoluteHref)) return absoluteHref;
2094
+ }
2095
+
2096
+ // Hydration fallback: parse __UNIVERSAL_DATA_FOR_REHYDRATION__ / SIGI_STATE
2097
+ // for the logged-in user's uniqueId. Way more reliable than DOM selectors
2098
+ // because TikTok ships the session user in the page bootstrap regardless
2099
+ // of which sidebar variant rendered.
2100
+ var hydrationUsername = detectLoggedInUsernameFromHydration();
2101
+ if (hydrationUsername) {
2102
+ return 'https://www.tiktok.com/@' + encodeURIComponent(hydrationUsername);
2103
+ }
2104
+
2105
+ if (overrideUsername) {
2106
+ return 'https://www.tiktok.com/@' + encodeURIComponent(overrideUsername);
2107
+ }
2108
+
2109
+ return '';
2110
+ }
2111
+
2112
+ function getProfileOwnershipSignals() {
2113
+ try {
2114
+ var visibleButtons = Array.prototype.slice.call(document.querySelectorAll('button, a, [role="button"]'))
2115
+ .filter(function(el) { return isVisibleElement(el); })
2116
+ .map(function(el) {
2117
+ return ((el.textContent || '') + ' ' + (el.getAttribute && el.getAttribute('aria-label') || '')).trim().toLowerCase();
2118
+ })
2119
+ .filter(Boolean);
2120
+ var joined = visibleButtons.join(' | ');
2121
+ var hasEditProfile = /edit profile|manage account|creator tools|profile settings/.test(joined);
2122
+ var hasVisitorFollow = /(^|\\b)follow(\\b|$)/.test(joined);
2123
+ var hasPrivateNotice = /this account is private|follow this account/.test((document.body && document.body.innerText || '').toLowerCase());
2124
+ return {
2125
+ hasEditProfile: hasEditProfile,
2126
+ hasVisitorFollow: hasVisitorFollow,
2127
+ hasPrivateNotice: hasPrivateNotice,
2128
+ looksOwned: hasEditProfile && !hasVisitorFollow
2129
+ };
2130
+ } catch(e) {
2131
+ return { hasEditProfile: false, hasVisitorFollow: false, hasPrivateNotice: false, looksOwned: false };
2132
+ }
2133
+ }
2134
+
2135
+ async function navigateToOwnProfile() {
2136
+ var overrideUsername = getProfileUsernameOverride();
2137
+ var currentUsername = getCurrentProfileUsername();
2138
+ debug('profile:navigate-start', {
2139
+ path: location.pathname,
2140
+ currentUsername: currentUsername || '',
2141
+ hasOverrideUsername: !!overrideUsername
2142
+ });
2143
+ if (
2144
+ isOwnProfilePath(location.pathname) &&
2145
+ (!overrideUsername || currentUsername.toLowerCase() === overrideUsername.toLowerCase())
2146
+ ) {
2147
+ debug('profile:navigate-already-on-profile', { path: location.pathname });
2148
+ return true;
2149
+ }
2150
+
2151
+ // Poll for an own-profile URL up to ~6s: TikTok's SPA bootstrap can lag
2152
+ // behind DOMContentLoaded, so the nav sidebar AND hydration scripts may
2153
+ // both be unavailable on first call. Re-checking every 300ms catches the
2154
+ // moment they appear without forcing a hard sleep.
2155
+ var ownProfileUrl = '';
2156
+ var pollAttempts = 0;
2157
+ var maxPollAttempts = 20;
2158
+ while (!ownProfileUrl && pollAttempts < maxPollAttempts) {
2159
+ ownProfileUrl = findOwnProfileUrl();
2160
+ if (ownProfileUrl) break;
2161
+ pollAttempts++;
2162
+ debug('profile:navigate-poll', {
2163
+ attempt: pollAttempts,
2164
+ hasUniversalData: !!document.getElementById('__UNIVERSAL_DATA_FOR_REHYDRATION__'),
2165
+ hasSigiState: !!document.getElementById('SIGI_STATE'),
2166
+ navAnchorCount: document.querySelectorAll('a[href*="/@"]').length,
2167
+ });
2168
+ await delay(300);
2169
+ }
2170
+ if (ownProfileUrl) {
2171
+ progress('profile', 25, 'Opening your TikTok profile...');
2172
+ debug('profile:navigate-route', { ownProfileUrl: ownProfileUrl });
2173
+ if (!routeToProfileUrl(ownProfileUrl)) {
2174
+ debug('profile:navigate-route-failed', { ownProfileUrl: ownProfileUrl });
2175
+ return false;
2176
+ }
2177
+ var routed = await waitForProfileRoute(overrideUsername, 7000);
2178
+ var ownership = getProfileOwnershipSignals();
2179
+ var ownershipUncertain = !!(overrideUsername && routed && !ownership.looksOwned);
2180
+ debug('profile:navigate-route-result', {
2181
+ routed: routed,
2182
+ path: location.pathname,
2183
+ ownership: ownership,
2184
+ ownershipUncertain: ownershipUncertain
2185
+ });
2186
+ if (routed && !overrideUsername) {
2187
+ return true;
2188
+ }
2189
+ if (routed && overrideUsername && ownership.looksOwned) {
2190
+ return true;
2191
+ }
2192
+ if (routed && overrideUsername) {
2193
+ // Do not hard-stop on web sessions where owner controls are hidden in RN WebView.
2194
+ // Continue with extraction while marking ownership as uncertain in debug logs.
2195
+ return true;
2196
+ }
2197
+ }
2198
+
2199
+ var clickTargets = Array.prototype.slice.call(document.querySelectorAll('[data-e2e="nav-profile"], [aria-label*="profile" i], [title*="profile" i]'));
2200
+ for (var i = 0; i < clickTargets.length; i++) {
2201
+ try {
2202
+ clickTargets[i].click();
2203
+ if (await waitForProfileRoute(overrideUsername, 5000)) {
2204
+ var clickedOwnership = getProfileOwnershipSignals();
2205
+ debug('profile:navigate-click-result', {
2206
+ success: true,
2207
+ index: i,
2208
+ path: location.pathname,
2209
+ ownership: clickedOwnership
2210
+ });
2211
+ if (!overrideUsername || clickedOwnership.looksOwned || clickedOwnership.hasEditProfile) {
2212
+ return true;
2213
+ }
2214
+ }
2215
+ } catch(e) {}
2216
+ }
2217
+
2218
+ debug('profile:navigate-failed', { path: location.pathname });
2219
+ return false;
2220
+ }
2221
+
2222
+ function mergeUniqueStrings(a, b) {
2223
+ var seen = {};
2224
+ return (Array.isArray(a) ? a : []).concat(Array.isArray(b) ? b : []).filter(function(value) {
2225
+ if (!value) return false;
2226
+ var key = String(value).toLowerCase();
2227
+ if (seen[key]) return false;
2228
+ seen[key] = true;
2229
+ return true;
2230
+ });
2231
+ }
2232
+
2233
+ function mergeVideo(base, extra) {
2234
+ if (!extra) return base;
2235
+ var mergedStats = Object.assign({}, base.stats || {}, extra.stats || {});
2236
+ return Object.assign({}, base, extra, {
2237
+ videoId: base.videoId || extra.videoId,
2238
+ url: base.url || extra.url,
2239
+ description: extra.description || base.description,
2240
+ caption: extra.caption || extra.description || base.caption || base.description,
2241
+ authorUsername: extra.authorUsername || base.authorUsername,
2242
+ authorDisplayName: extra.authorDisplayName || base.authorDisplayName,
2243
+ thumbnailUrl: extra.thumbnailUrl || base.thumbnailUrl,
2244
+ musicTitle: extra.musicTitle || base.musicTitle,
2245
+ musicAuthor: extra.musicAuthor || base.musicAuthor,
2246
+ stats: mergedStats,
2247
+ hashtags: mergeUniqueStrings(base.hashtags, extra.hashtags),
2248
+ source: base.source === extra.source ? base.source : [base.source, extra.source].filter(Boolean).join('+'),
2249
+ });
2250
+ }
2251
+
2252
+ function extractVideoDetailFromDocument(doc, videoUrl, fallbackAuthor) {
2253
+ var states = parseHydrationStates(doc);
2254
+ var stateVideos = extractFromStates(states, fallbackAuthor, 'detail-hydration').videos;
2255
+ var urlIdMatch = videoUrl.match(/\\/video\\/(\\d+)/);
2256
+ var urlAuthorMatch = videoUrl.match(/\\/(@[^/]+)\\/video\\//);
2257
+ var targetId = urlIdMatch ? urlIdMatch[1] : '';
2258
+ var best = null;
2259
+ for (var i = 0; i < stateVideos.length; i++) {
2260
+ if (!best || (targetId && stateVideos[i].videoId === targetId)) {
2261
+ best = stateVideos[i];
2262
+ }
2263
+ if (targetId && stateVideos[i].videoId === targetId) break;
2264
+ }
2265
+
2266
+ var metaDesc = attr('meta[property="og:description"]', 'content', doc) ||
2267
+ attr('meta[name="description"]', 'content', doc) ||
2268
+ attr('meta[property="twitter:description"]', 'content', doc);
2269
+ var metaTitle = attr('meta[property="og:title"]', 'content', doc) ||
2270
+ attr('meta[name="twitter:title"]', 'content', doc) ||
2271
+ text('title', doc);
2272
+ var imageUrl = attr('meta[property="og:image"]', 'content', doc) ||
2273
+ attr('meta[name="twitter:image"]', 'content', doc);
2274
+
2275
+ var cleanDesc = metaDesc || '';
2276
+ if (cleanDesc && metaTitle && cleanDesc === metaTitle) {
2277
+ cleanDesc = '';
2278
+ }
2279
+ var hashtags = cleanDesc ? ((cleanDesc.match(/#[\\w.-]+/g) || []).map(function(tag) { return tag.slice(1); })) : [];
2280
+ var authorUsername = urlAuthorMatch ? decodeURIComponent(urlAuthorMatch[1].replace(/^@/, '')) : fallbackAuthor;
2281
+
2282
+ var metaVideo = {
2283
+ videoId: targetId || (best && best.videoId) || videoUrl,
2284
+ description: cleanDesc || (best && best.description) || undefined,
2285
+ caption: cleanDesc || (best && (best.caption || best.description)) || undefined,
2286
+ authorUsername: authorUsername || (best && best.authorUsername) || undefined,
2287
+ authorDisplayName: best && best.authorDisplayName,
2288
+ url: videoUrl,
2289
+ thumbnailUrl: imageUrl || (best && best.thumbnailUrl) || undefined,
2290
+ musicTitle: best && best.musicTitle,
2291
+ musicAuthor: best && best.musicAuthor,
2292
+ stats: best && best.stats,
2293
+ hashtags: mergeUniqueStrings(best && best.hashtags, hashtags),
2294
+ source: best ? 'detail-meta+detail-hydration' : 'detail-meta',
2295
+ };
2296
+
2297
+ return mergeVideo(metaVideo, best);
2298
+ }
2299
+
2300
+ async function enrichVideosFromDetailPages(videos, maxDetails, startProgress, endProgress) {
2301
+ var enriched = [];
2302
+ var total = Math.min(videos.length, maxDetails);
2303
+ for (var i = 0; i < videos.length; i++) {
2304
+ var video = videos[i];
2305
+ if (i >= maxDetails || !video.url || video.url.indexOf('/video/') === -1) {
2306
+ enriched.push(video);
2307
+ continue;
2308
+ }
2309
+
2310
+ try {
2311
+ var pct = startProgress + Math.round(((i + 1) / Math.max(total, 1)) * (endProgress - startProgress));
2312
+ progress('liked-details', pct, 'Getting captions and hashtags (' + (i + 1) + '/' + total + ')...');
2313
+ var resp = await fetch(video.url, {
2314
+ method: 'GET',
2315
+ credentials: 'include',
2316
+ headers: { 'Accept': 'text/html,application/xhtml+xml' },
2317
+ });
2318
+ if (!resp.ok) {
2319
+ enriched.push(video);
2320
+ continue;
2321
+ }
2322
+ var html = await resp.text();
2323
+ var doc = new DOMParser().parseFromString(html, 'text/html');
2324
+ var detail = extractVideoDetailFromDocument(doc, video.url, video.authorUsername);
2325
+ enriched.push(mergeVideo(video, detail));
2326
+ await delay(150);
2327
+ } catch(e) {
2328
+ enriched.push(video);
2329
+ }
2330
+ }
2331
+ return enriched;
2332
+ }
2333
+
2334
+ function mergeProfiles() {
2335
+ for (var i = 0; i < arguments.length; i++) {
2336
+ var p = arguments[i];
2337
+ if (p) {
2338
+ var merged = {};
2339
+ for (var j = arguments.length - 1; j >= 0; j--) {
2340
+ if (arguments[j]) {
2341
+ Object.assign(merged, arguments[j]);
2342
+ merged.stats = Object.assign({}, arguments[j].stats || {}, merged.stats || {});
2343
+ }
2344
+ }
2345
+ return merged;
2346
+ }
2347
+ }
2348
+ return null;
2349
+ }
2350
+
2351
+ // ------------------------------------------------------------------
2352
+ // Direct port of the user-verified browser snippet. With desktop UA the
2353
+ // profile page exposes the same DOM the snippet relies on, so we use it
2354
+ // as the primary opener for the Liked tab and only fall back to the
2355
+ // older mobile-DOM strategies if it cannot find a tab.
2356
+ // ------------------------------------------------------------------
2357
+ function bs_clean(s) {
2358
+ return (s || '').replace(/\\s+/g, ' ').trim();
2359
+ }
2360
+ function bs_uniq(arr) {
2361
+ var seen = {};
2362
+ var out = [];
2363
+ for (var i = 0; i < arr.length; i++) {
2364
+ var v = arr[i];
2365
+ if (!v) continue;
2366
+ if (seen[v]) continue;
2367
+ seen[v] = true;
2368
+ out.push(v);
2369
+ }
2370
+ return out;
2371
+ }
2372
+ function bs_cleanUrl(url) {
2373
+ return String(url || '').split('?')[0];
2374
+ }
2375
+ function bs_isVisible(el) {
2376
+ try {
2377
+ var r = el && el.getBoundingClientRect ? el.getBoundingClientRect() : null;
2378
+ if (!r) return false;
2379
+ return r.width > 20 && r.height > 20 && r.bottom > 0 && r.top < window.innerHeight;
2380
+ } catch (e) { return false; }
2381
+ }
2382
+ function bs_getVideoAnchors() {
2383
+ var nodes = document.querySelectorAll('a[href*="/video/"]');
2384
+ var out = [];
2385
+ for (var i = 0; i < nodes.length; i++) {
2386
+ var a = nodes[i];
2387
+ if (!bs_isVisible(a)) continue;
2388
+ var r = a.getBoundingClientRect();
2389
+ if (r.width <= 80 || r.height <= 80) continue;
2390
+ out.push(a);
2391
+ }
2392
+ return out;
2393
+ }
2394
+ function bs_getVideoLinks() {
2395
+ return bs_uniq(bs_getVideoAnchors().map(function(a) { return bs_cleanUrl(a.href); }));
2396
+ }
2397
+ function bs_dumpPossibleTabs() {
2398
+ var nodes = document.querySelectorAll(
2399
+ '[role="tab"], button, a, div[data-e2e*="tab"], div[class*="Tab"], div[class*="tab"]'
2400
+ );
2401
+ var candidates = [];
2402
+ for (var i = 0; i < nodes.length; i++) {
2403
+ var el = nodes[i];
2404
+ if (!bs_isVisible(el)) continue;
2405
+ var text = bs_clean(el.innerText).slice(0, 80);
2406
+ var aria = el.getAttribute('aria-label') || '';
2407
+ var dataE2E = el.getAttribute('data-e2e') || '';
2408
+ var role = el.getAttribute('role') || '';
2409
+ var blob = (text + ' ' + aria + ' ' + dataE2E + ' ' + role).toLowerCase();
2410
+ if (!/video|post|repost|favorite|favourite|liked|like|heart/.test(blob)) continue;
2411
+ candidates.push({
2412
+ i: candidates.length,
2413
+ tag: el.tagName,
2414
+ role: role,
2415
+ dataE2E: dataE2E,
2416
+ aria: aria,
2417
+ text: text,
2418
+ el: el
2419
+ });
2420
+ }
2421
+ return candidates;
2422
+ }
2423
+ function bs_findActualLikedTab() {
2424
+ var candidates = bs_dumpPossibleTabs();
2425
+ // best case: TikTok exposes a liked tab-ish data attr / aria.
2426
+ for (var i = 0; i < candidates.length; i++) {
2427
+ var c = candidates[i];
2428
+ if (/liked/i.test((c.dataE2E || '') + ' ' + (c.aria || ''))) return c.el;
2429
+ }
2430
+ // next: visible tab whose text is exactly liked. NOT "likes".
2431
+ for (var j = 0; j < candidates.length; j++) {
2432
+ if (bs_clean(candidates[j].text).toLowerCase() === 'liked') return candidates[j].el;
2433
+ }
2434
+ // ordered profile tabs: videos, reposts, favorites, liked.
2435
+ var tabLike = [];
2436
+ for (var k = 0; k < candidates.length; k++) {
2437
+ var x = candidates[k];
2438
+ var blob = (x.text + ' ' + x.aria + ' ' + x.dataE2E + ' ' + x.role).toLowerCase();
2439
+ if (
2440
+ x.role === 'tab' ||
2441
+ /tab/.test(blob) ||
2442
+ /favorite|favourite|liked|heart|video|post|repost/.test(blob)
2443
+ ) {
2444
+ tabLike.push(x);
2445
+ }
2446
+ }
2447
+ for (var m = 0; m < tabLike.length; m++) {
2448
+ var y = tabLike[m];
2449
+ if (/heart|liked/.test(((y.aria || '') + ' ' + (y.dataE2E || '')).toLowerCase())) return y.el;
2450
+ }
2451
+ if (tabLike.length >= 3) return tabLike[tabLike.length - 1].el;
2452
+ return null;
2453
+ }
2454
+ function bs_describeCandidate(c) {
2455
+ return [
2456
+ c.tag,
2457
+ c.role || '-',
2458
+ c.dataE2E || '-',
2459
+ (c.aria || '').slice(0, 40),
2460
+ (c.text || '').slice(0, 40)
2461
+ ].join(' | ');
2462
+ }
2463
+ async function bs_clickLikedTab(username) {
2464
+ window.scrollTo(0, 0);
2465
+ await delay(1000);
2466
+
2467
+ var before = bs_getVideoLinks();
2468
+ var candidates = bs_dumpPossibleTabs();
2469
+ debug('liked:bs-candidates', {
2470
+ count: candidates.length,
2471
+ candidates: candidates.slice(0, 24).map(bs_describeCandidate),
2472
+ beforeCount: before.length
2473
+ });
2474
+
2475
+ var tab = bs_findActualLikedTab();
2476
+ if (!tab) {
2477
+ debug('liked:bs-no-tab', { count: candidates.length });
2478
+ return { opened: false, reason: 'NO_LIKED_TAB_CANDIDATE', before: before, after: before };
2479
+ }
2480
+
2481
+ debug('liked:bs-tab-found', {
2482
+ signature: getElementSignature(tab),
2483
+ rect: tab.getBoundingClientRect ? toRectString(tab.getBoundingClientRect()) : ''
2484
+ });
2485
+
2486
+ try { tab.click(); } catch (e) {
2487
+ debug('liked:bs-tab-click-error', { message: String(e && e.message ? e.message : e) });
2488
+ }
2489
+
2490
+ await delay(2500);
2491
+ window.scrollTo(0, 0);
2492
+ await delay(1500);
2493
+
2494
+ var after = bs_getVideoLinks();
2495
+ for (var i = 0; i < 10 && JSON.stringify(after.slice(0, 6)) === JSON.stringify(before.slice(0, 6)); i++) {
2496
+ await delay(700);
2497
+ after = bs_getVideoLinks();
2498
+ }
2499
+
2500
+ var handle = (username || '').toLowerCase();
2501
+ var ownVideoCount = 0;
2502
+ for (var j = 0; j < after.length; j++) {
2503
+ if (handle && after[j].toLowerCase().indexOf('/@' + handle + '/video/') !== -1) ownVideoCount++;
2504
+ }
2505
+ debug('liked:bs-tab-click-result', {
2506
+ beforeCount: before.length,
2507
+ afterCount: after.length,
2508
+ ownVideoCount: ownVideoCount,
2509
+ sample: after.slice(0, 4)
2510
+ });
2511
+
2512
+ if (after.length && ownVideoCount === after.length) {
2513
+ return { opened: false, reason: 'STILL_SHOWING_OWN_VIDEOS', before: before, after: after };
2514
+ }
2515
+ return { opened: true, before: before, after: after };
2516
+ }
2517
+ async function bs_collectLikedLinks(username, limit) {
2518
+ var clickResult = await bs_clickLikedTab(username);
2519
+ if (!clickResult.opened) {
2520
+ return { opened: false, reason: clickResult.reason || 'CLICK_FAILED', links: [] };
2521
+ }
2522
+ var links = clickResult.after.slice();
2523
+ for (var i = 0; i < 4 && links.length < limit; i++) {
2524
+ try { window.scrollBy(0, window.innerHeight * 0.7); } catch (e) {}
2525
+ await delay(1200);
2526
+ links = bs_uniq(links.concat(bs_getVideoLinks()));
2527
+ debug('liked:bs-scroll-tick', { tick: i + 1, count: links.length });
2528
+ }
2529
+ return { opened: true, links: links.slice(0, limit) };
2530
+ }
2531
+ function bs_buildVideoStubsFromLinks(links, username) {
2532
+ var stubs = [];
2533
+ var seen = {};
2534
+ for (var i = 0; i < links.length; i++) {
2535
+ var url = links[i];
2536
+ var match = url.match(/\\/video\\/(\\d+)/);
2537
+ var authorMatch = url.match(/\\/(@[^/]+)\\/video\\//);
2538
+ var id = match ? match[1] : url;
2539
+ if (!id || seen[id]) continue;
2540
+ seen[id] = true;
2541
+ var anchor = null;
2542
+ try {
2543
+ var anchors = document.querySelectorAll('a[href*="/video/' + id + '"]');
2544
+ for (var a = 0; a < anchors.length; a++) {
2545
+ if (bs_isVisible(anchors[a])) { anchor = anchors[a]; break; }
2546
+ }
2547
+ } catch (e) {}
2548
+ var img = anchor ? anchor.querySelector('img') : null;
2549
+ var desc = (anchor && anchor.getAttribute('title')) || (img && img.getAttribute('alt')) || '';
2550
+ var thumb = img ? (img.src || img.getAttribute('src') || '') : '';
2551
+ stubs.push({
2552
+ videoId: id,
2553
+ description: desc || undefined,
2554
+ caption: desc || undefined,
2555
+ authorUsername: authorMatch ? decodeURIComponent(authorMatch[1].replace(/^@/, '')) : (username || undefined),
2556
+ url: url,
2557
+ thumbnailUrl: thumb || undefined,
2558
+ stats: {},
2559
+ hashtags: desc ? (desc.match(/#[\\w.-]+/g) || []).map(function(t){return t.slice(1);}) : [],
2560
+ source: 'liked-dom-bs'
2561
+ });
2562
+ }
2563
+ return stubs;
2564
+ }
2565
+ async function openLikedTabBrowserStyle(username) {
2566
+ try {
2567
+ var collected = await bs_collectLikedLinks(username, 30);
2568
+ if (!collected.opened) {
2569
+ return { opened: false, reason: collected.reason || 'BS_FAILED' };
2570
+ }
2571
+ var stubs = bs_buildVideoStubsFromLinks(collected.links, username);
2572
+ if (!stubs.length) {
2573
+ return { opened: false, reason: 'BS_NO_STUBS' };
2574
+ }
2575
+ return {
2576
+ opened: true,
2577
+ videos: stubs,
2578
+ containerFound: false,
2579
+ coordinateTapped: true,
2580
+ coordinate: { mode: 'browser-script-port', linkCount: collected.links.length }
2581
+ };
2582
+ } catch (e) {
2583
+ debug('liked:bs-exception', { message: String(e && e.message ? e.message : e) });
2584
+ return { opened: false, reason: 'BS_EXCEPTION' };
2585
+ }
2586
+ }
2587
+
2588
+ async function openLikedTabAndExtract(username, options) {
2589
+ var manualMode = !!(options && options.manualMode);
2590
+ await resetProfileScrollToTabs();
2591
+ debug('liked:open-start', Object.assign({}, getLikedTabDebugState(), {
2592
+ privateNotice: getPrivateAccountNotice(),
2593
+ tabCandidates: collectLikedTabCandidates(),
2594
+ manualMode: manualMode
2595
+ }));
2596
+
2597
+ // PRIMARY: ported browser-side script. With desktop UA TikTok exposes
2598
+ // proper tab elements with click handlers and a real video grid for
2599
+ // liked videos.
2600
+ var bsResult = await openLikedTabBrowserStyle(username);
2601
+ if (bsResult && bsResult.opened) {
2602
+ debug('liked:open-browser-script-success', { count: bsResult.videos.length });
2603
+ return bsResult;
2604
+ }
2605
+ debug('liked:open-browser-script-failed', { reason: bsResult && bsResult.reason });
2606
+
2607
+ var apiLikedResult = await fetchLikedVideosViaApi(username, parseHydrationStates(document));
2608
+ if (apiLikedResult && apiLikedResult.opened) {
2609
+ return apiLikedResult;
2610
+ }
2611
+
2612
+ if (manualMode) {
2613
+ var manualContainer = findLikedVideoContainer();
2614
+ if (manualContainer) {
2615
+ var manualContainerVideos = extractVideosFromDom('liked-dom-manual-container', username, manualContainer);
2616
+ if (manualContainerVideos.length > 0 && !linksLookLikeOwnPosts(manualContainerVideos, username)) {
2617
+ return {
2618
+ opened: true,
2619
+ videos: manualContainerVideos,
2620
+ containerFound: true,
2621
+ coordinateTapped: true,
2622
+ coordinate: { mode: 'manual-current-container' }
2623
+ };
2624
+ }
2625
+ }
2626
+
2627
+ var manualDocumentVideos = extractVideosFromDom('liked-dom-manual-document', username);
2628
+ if (manualDocumentVideos.length > 0 && !linksLookLikeOwnPosts(manualDocumentVideos, username)) {
2629
+ return {
2630
+ opened: true,
2631
+ videos: manualDocumentVideos,
2632
+ containerFound: false,
2633
+ coordinateTapped: true,
2634
+ coordinate: { mode: 'manual-current-document' }
2635
+ };
2636
+ }
2637
+ }
2638
+
2639
+ var routeLikedResult = manualMode ? null : await tryExtractFromLikedRoute(username);
2640
+ if (routeLikedResult && routeLikedResult.opened) {
2641
+ debug('liked:open-route-liked-success', { coordinate: routeLikedResult.coordinate || null });
2642
+ return routeLikedResult;
2643
+ }
2644
+
2645
+ if (username && !manualMode) {
2646
+ routeToProfileUrl('https://www.tiktok.com/@' + encodeURIComponent(username));
2647
+ await delay(500);
2648
+ await resetProfileScrollToTabs();
2649
+ }
2650
+
2651
+ var tabReady = await waitForLikedTabReady(4500);
2652
+ debug('liked:open-tab-ready-check', tabReady.snapshot || {});
2653
+ var liked =
2654
+ (tabReady && (tabReady.exact || tabReady.textLiked || tabReady.generic)) ||
2655
+ findExactLikedTabButton() ||
2656
+ findTextLikedTabButton() ||
2657
+ findLikedTabButton();
2658
+ var firstGridTopAtStart = getFirstVideoGridTop();
2659
+ try {
2660
+ if (!liked) {
2661
+ var privateSignalWithoutTab = !!(tabReady && tabReady.snapshot && tabReady.snapshot.privateNotice && !tabReady.snapshot.hasExactLikedTab);
2662
+ if (privateSignalWithoutTab) {
2663
+ return {
2664
+ opened: false,
2665
+ videos: [],
2666
+ containerFound: false,
2667
+ reason: 'LIKED_TAB_UNAVAILABLE_PRIVATE_NOTICE',
2668
+ diagnostics: Object.assign({}, collectTabDiagnostics({ firstGridTop: firstGridTopAtStart }), {
2669
+ privateNotice: tabReady.snapshot.privateNotice,
2670
+ tabCandidates: tabReady.snapshot.tabCandidates || [],
2671
+ })
2672
+ };
2673
+ }
2674
+ debug('liked:open-no-direct-tab', { firstGridTopAtStart: firstGridTopAtStart });
2675
+ return tapMobileLikedTabByPosition(username);
2676
+ }
2677
+ debug('liked:open-direct-tab-found', {
2678
+ signature: getElementSignature(liked),
2679
+ beforeSelected: getTabSelectedState(liked),
2680
+ });
2681
+ var clickState = await clickLikedTabWithState(liked);
2682
+ debug('liked:open-direct-tab-click-state', clickState);
2683
+ await delay(1600);
2684
+ debug('liked:open-after-direct-click', getLikedTabDebugState());
2685
+
2686
+ var immediateLikedContainer = findLikedVideoContainer();
2687
+ if (immediateLikedContainer) {
2688
+ debug('liked:open-container-found-immediate', { signature: getElementSignature(immediateLikedContainer) });
2689
+ return {
2690
+ opened: true,
2691
+ videos: extractVideosFromDom('liked-dom-container', username, immediateLikedContainer),
2692
+ containerFound: true
2693
+ };
2694
+ }
2695
+
2696
+ var immediateVideos = extractVideosFromDom('liked-dom-document', username);
2697
+ if (immediateVideos.length > 0 && !linksLookLikeOwnPosts(immediateVideos, username)) {
2698
+ debug('liked:open-immediate-videos-found', { count: immediateVideos.length });
2699
+ return {
2700
+ opened: true,
2701
+ videos: immediateVideos,
2702
+ containerFound: false
2703
+ };
2704
+ }
2705
+
2706
+ await scrollLikedGrid();
2707
+
2708
+ var likedContainer = findLikedVideoContainer();
2709
+ if (likedContainer) {
2710
+ debug('liked:open-container-found-post-scroll', { signature: getElementSignature(likedContainer) });
2711
+ return {
2712
+ opened: true,
2713
+ videos: extractVideosFromDom('liked-dom-container', username, likedContainer),
2714
+ containerFound: true
2715
+ };
2716
+ }
2717
+
2718
+ var documentVideos = extractVideosFromDom('liked-dom-document', username);
2719
+ if (documentVideos.length > 0 && !linksLookLikeOwnPosts(documentVideos, username)) {
2720
+ debug('liked:open-document-videos-found-post-scroll', { count: documentVideos.length });
2721
+ return {
2722
+ opened: true,
2723
+ videos: documentVideos,
2724
+ containerFound: false
2725
+ };
2726
+ }
2727
+
2728
+ var candidateResult = await tryOpenLikedByTabCandidates(username);
2729
+ if (candidateResult && candidateResult.opened) {
2730
+ debug('liked:open-candidate-result-success', { coordinate: candidateResult.coordinate || null });
2731
+ return candidateResult;
2732
+ }
2733
+ debug('liked:open-candidate-result-failed', { coordinate: candidateResult && candidateResult.coordinate });
2734
+
2735
+ var coordinateResult = await tapMobileLikedTabByPosition(username);
2736
+ if (coordinateResult && coordinateResult.opened) {
2737
+ debug('liked:open-coordinate-success', { coordinate: coordinateResult.coordinate || null });
2738
+ return coordinateResult;
2739
+ }
2740
+ debug('liked:open-coordinate-failed', {
2741
+ coordinate: coordinateResult && coordinateResult.coordinate,
2742
+ state: getLikedTabDebugState()
2743
+ });
2744
+
2745
+ return {
2746
+ opened: false,
2747
+ videos: [],
2748
+ containerFound: false,
2749
+ reason: (tabReady && tabReady.snapshot && tabReady.snapshot.privateNotice && !tabReady.snapshot.hasExactLikedTab) ? 'LIKED_TAB_UNAVAILABLE_PRIVATE_NOTICE' : 'LIKED_TAB_NOT_OPENED',
2750
+ coordinate: coordinateResult && coordinateResult.coordinate,
2751
+ diagnostics: collectTabDiagnostics({ firstGridTop: firstGridTopAtStart })
2752
+ };
2753
+ } catch(e) {
2754
+ debug('liked:open-exception', { message: String(e && e.message ? e.message : e) });
2755
+ return false;
2756
+ }
2757
+ }
2758
+
2759
+ var manualDebugConfig = getManualDebugConfig();
2760
+ // Passive warmup is only useful when explicitly opted-in. After it
2761
+ // completes we ALWAYS continue into the active scrape so the user is
2762
+ // never stranded on the profile page (this is what was happening before:
2763
+ // passive warmup finished then waitForManualLikedContext re-engaged the
2764
+ // wait loop).
2765
+ var skipManualWaitAfterPassive = false;
2766
+ if (manualDebugConfig.enabled && manualDebugConfig.passiveLogOnly) {
2767
+ await runPassiveManualLogging(manualDebugConfig.passiveWarmupMs);
2768
+ debug('manual:passive-complete-start-scrape', {
2769
+ warmupMs: manualDebugConfig.passiveWarmupMs,
2770
+ path: location.pathname
2771
+ });
2772
+ skipManualWaitAfterPassive = true;
2773
+ }
2774
+
2775
+ progress('profile', 10, 'Finding your TikTok profile...');
2776
+
2777
+ var openedOwnProfile = await navigateToOwnProfile();
2778
+ if (!openedOwnProfile) {
2779
+ var diag = {
2780
+ path: location.pathname,
2781
+ hasUniversalData: !!document.getElementById('__UNIVERSAL_DATA_FOR_REHYDRATION__'),
2782
+ hasSigiState: !!document.getElementById('SIGI_STATE'),
2783
+ navAnchorCount: document.querySelectorAll('a[href*="/@"]').length,
2784
+ hydrationUsername: detectLoggedInUsernameFromHydration() || null,
2785
+ };
2786
+ debug('profile:navigate-final-fail', diag);
2787
+ postMsg({
2788
+ type: 'TIKTOK_EXPORT_ERROR',
2789
+ status: 'error',
2790
+ message: 'Could not identify your TikTok profile. Make sure you are logged into TikTok in this web view (tap the profile icon in the TikTok sidebar) and retry.',
2791
+ success: false,
2792
+ diagnostics: diag
2793
+ });
2794
+ return;
2795
+ }
2796
+
2797
+ var profileReady = await waitForProfileContentReady(5000);
2798
+ debug('profile:content-ready', profileReady);
2799
+
2800
+ var initialStates = parseHydrationStates(document);
2801
+ var initial = extractFromStates(initialStates, '', 'profile-hydration');
2802
+ var domProfile = extractProfileFromDom();
2803
+ var pathMatch = location.pathname.match(/^\\/@([^/]+)\\/?$/);
2804
+ var username = pathMatch ? decodeURIComponent(pathMatch[1]) : (domProfile && domProfile.username);
2805
+ var stateProfile = initial.users.find(function(user) {
2806
+ return user && username && user.username && user.username.toLowerCase() === username.toLowerCase();
2807
+ }) || null;
2808
+ var profile = mergeProfiles(domProfile, stateProfile);
2809
+ if (manualDebugConfig.enabled && !skipManualWaitAfterPassive) {
2810
+ progress('liked', 45, 'Manual debug mode: open profile + Liked tab now.');
2811
+ await waitForManualLikedContext(username, manualDebugConfig.timeoutMs);
2812
+ }
2813
+
2814
+ progress('liked', 50, 'Opening your Liked tab...');
2815
+ debug('liked:preflight-before-open', getLikedTabDebugState());
2816
+ // manualMode=false means: do not block on findLikedVideoContainer/
2817
+ // linksLookLikeOwnPosts in current DOM; instead actually try to open the
2818
+ // Liked tab (browser-script port, then API, then mobile fallbacks).
2819
+ var likedResult = await openLikedTabAndExtract(username, { manualMode: false });
2820
+ debug('liked:preflight-after-open', {
2821
+ opened: !!(likedResult && likedResult.opened),
2822
+ state: getLikedTabDebugState()
2823
+ });
2824
+
2825
+ progress('videos', 35, 'Collecting your visible TikTok videos...');
2826
+ var visibleVideos = extractVideosFromDom('visible-dom', username);
2827
+
2828
+ progress('liked', 65, 'Checking liked videos...');
2829
+ var clickedLiked = !!(likedResult && likedResult.opened);
2830
+ var likedDomVideos = likedResult && Array.isArray(likedResult.videos) ? likedResult.videos : [];
2831
+
2832
+ if (!clickedLiked || likedDomVideos.length === 0) {
2833
+ var failureDebug = {
2834
+ reason: likedResult && likedResult.reason,
2835
+ coordinate: likedResult && likedResult.coordinate,
2836
+ diagnostics: (likedResult && likedResult.diagnostics) || null
2837
+ };
2838
+ postMsg({
2839
+ type: 'TIKTOK_EXPORT_ERROR',
2840
+ status: 'error',
2841
+ message: 'Could not open a usable TikTok liked-videos tab. The page only exposed profile posts, so no data was stored. Debug: ' + JSON.stringify(failureDebug),
2842
+ success: false
2843
+ });
2844
+ return;
2845
+ }
2846
+
2847
+ var seenLiked = {};
2848
+ var likedVideos = likedDomVideos.filter(function(video) {
2849
+ if (!video || !video.videoId || seenLiked[video.videoId]) return false;
2850
+ seenLiked[video.videoId] = true;
2851
+ return true;
2852
+ }).slice(0, 80);
2853
+
2854
+ likedVideos = await enrichVideosFromDetailPages(likedVideos, 30, 72, 90);
2855
+
2856
+ var seenPosted = {};
2857
+ var postedVideos = visibleVideos.concat(initial.videos).filter(function(video) {
2858
+ if (!video || !video.videoId || seenPosted[video.videoId] || seenLiked[video.videoId]) return false;
2859
+ seenPosted[video.videoId] = true;
2860
+ return true;
2861
+ }).slice(0, 80);
2862
+
2863
+ profile = mergeProfiles(extractProfileFromDom(), domProfile, stateProfile, profile);
2864
+
2865
+ progress('complete', 95, 'Finishing TikTok export...');
2866
+
2867
+ postMsg({
2868
+ type: 'TIKTOK_EXPORT_COMPLETE',
2869
+ status: 'success',
2870
+ data: {
2871
+ likedVideos: likedVideos,
2872
+ postedVideos: postedVideos,
2873
+ profile: profile,
2874
+ rawStateSummary: {
2875
+ hydrationStateCount: initialStates.length,
2876
+ ownProfileDetected: openedOwnProfile,
2877
+ profilePath: location.pathname,
2878
+ likedTabClicked: clickedLiked,
2879
+ likedContainerFound: !!(likedResult && likedResult.containerFound),
2880
+ likedCoordinateTapped: !!(likedResult && likedResult.coordinateTapped),
2881
+ likedCoordinate: likedResult && likedResult.coordinate,
2882
+ visibleVideoCount: visibleVideos.length
2883
+ },
2884
+ summary: {
2885
+ likedVideosCount: likedVideos.length,
2886
+ postedVideosCount: postedVideos.length,
2887
+ hasProfile: !!profile,
2888
+ hasBio: !!(profile && profile.bio)
2889
+ }
2890
+ },
2891
+ success: true
2892
+ });
2893
+ } catch (error) {
2894
+ window.ReactNativeWebView.postMessage(JSON.stringify({
2895
+ type: 'TIKTOK_EXPORT_ERROR',
2896
+ status: 'error',
2897
+ message: error && error.message ? error.message : 'TikTok export failed',
2898
+ success: false
2899
+ }));
2900
+ }
2901
+ })();
2902
+ true;
2903
+ `;
2904
+ const TIKTOK_SUCCESS_SCRIPT = `
2905
+ (function() {
2906
+ console.log('[TIKTOK] Export successful');
2907
+ })();
2908
+ true;
2909
+ `;
2910
+ const TIKTOK_ERROR_SCRIPT = `
2911
+ (function() {
2912
+ console.log('[TIKTOK] Export failed');
2913
+ })();
2914
+ true;
2915
+ `;
2916
+ export {
2917
+ TIKTOK_ERROR_SCRIPT,
2918
+ TIKTOK_EXPORT_SCRIPT,
2919
+ TIKTOK_SUCCESS_SCRIPT
2920
+ };