thumbgate 1.4.3 → 1.4.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 (270) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.well-known/llms.txt +12 -8
  4. package/.well-known/mcp/server-card.json +1 -1
  5. package/README.md +18 -8
  6. package/adapters/README.md +1 -1
  7. package/adapters/claude/.mcp.json +2 -2
  8. package/adapters/codex/config.toml +2 -2
  9. package/adapters/mcp/server-stdio.js +1 -1
  10. package/adapters/opencode/opencode.json +1 -1
  11. package/config/github-about.json +2 -2
  12. package/package.json +158 -10
  13. package/scripts/billing.js +5 -2
  14. package/scripts/statusline.sh +1 -0
  15. package/src/api/server.js +113 -16
  16. package/src/index.js +3 -0
  17. package/.claude-plugin/bundle/icon.png +0 -0
  18. package/.claude-plugin/bundle/icon.svg +0 -18
  19. package/.claude-plugin/bundle/server/index.js +0 -24
  20. package/adapters/chatgpt/INSTALL.md +0 -158
  21. package/adapters/perplexity/.mcp.json +0 -36
  22. package/adapters/perplexity/config.toml +0 -16
  23. package/adapters/perplexity/opencode.json +0 -29
  24. package/bin/memory.sh +0 -64
  25. package/bin/obsidian-sync.sh +0 -20
  26. package/plugins/amp-skill/INSTALL.md +0 -52
  27. package/plugins/amp-skill/SKILL.md +0 -64
  28. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +0 -22
  29. package/plugins/claude-codex-bridge/.mcp.json +0 -14
  30. package/plugins/claude-codex-bridge/INSTALL.md +0 -43
  31. package/plugins/claude-codex-bridge/README.md +0 -46
  32. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +0 -286
  33. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +0 -24
  34. package/plugins/claude-codex-bridge/skills/result/SKILL.md +0 -22
  35. package/plugins/claude-codex-bridge/skills/review/SKILL.md +0 -28
  36. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +0 -27
  37. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +0 -21
  38. package/plugins/claude-codex-bridge/skills/status/SKILL.md +0 -19
  39. package/plugins/claude-skill/INSTALL.md +0 -55
  40. package/plugins/claude-skill/SKILL.md +0 -46
  41. package/plugins/codex-profile/.codex-plugin/plugin.json +0 -43
  42. package/plugins/codex-profile/.mcp.json +0 -14
  43. package/plugins/codex-profile/AGENTS.md +0 -20
  44. package/plugins/codex-profile/INSTALL.md +0 -89
  45. package/plugins/codex-profile/README.md +0 -61
  46. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +0 -23
  47. package/plugins/cursor-marketplace/CHANGELOG.md +0 -30
  48. package/plugins/cursor-marketplace/LICENSE +0 -21
  49. package/plugins/cursor-marketplace/README.md +0 -124
  50. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +0 -31
  51. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  52. package/plugins/cursor-marketplace/commands/capture-feedback.md +0 -33
  53. package/plugins/cursor-marketplace/commands/check-gates.md +0 -25
  54. package/plugins/cursor-marketplace/commands/show-lessons.md +0 -27
  55. package/plugins/cursor-marketplace/hooks/hooks.json +0 -10
  56. package/plugins/cursor-marketplace/mcp.json +0 -14
  57. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +0 -34
  58. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +0 -30
  59. package/plugins/cursor-marketplace/rules/session-continuity.mdc +0 -28
  60. package/plugins/cursor-marketplace/scripts/gate-check.sh +0 -21
  61. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +0 -48
  62. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +0 -31
  63. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +0 -30
  64. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +0 -33
  65. package/plugins/gemini-extension/INSTALL.md +0 -92
  66. package/plugins/gemini-extension/gemini_prompt.txt +0 -14
  67. package/plugins/gemini-extension/tool_contract.json +0 -45
  68. package/plugins/opencode-profile/INSTALL.md +0 -57
  69. package/public/assets/instagram-card.png +0 -0
  70. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  71. package/public/blog.html +0 -474
  72. package/public/compare/mem0.html +0 -189
  73. package/public/compare/speclock.html +0 -180
  74. package/public/compare.html +0 -310
  75. package/public/dashboard.html +0 -1100
  76. package/public/guide.html +0 -317
  77. package/public/guides/claude-code-prevent-repeated-mistakes.html +0 -161
  78. package/public/guides/codex-cli-guardrails.html +0 -158
  79. package/public/guides/cursor-prevent-repeated-mistakes.html +0 -161
  80. package/public/guides/pre-action-gates.html +0 -162
  81. package/public/guides/stop-repeated-ai-agent-mistakes.html +0 -159
  82. package/public/index.html +0 -1225
  83. package/public/js/buyer-intent.js +0 -252
  84. package/public/learn/agent-harness-pattern.html +0 -180
  85. package/public/learn/ai-agent-persistent-memory.html +0 -203
  86. package/public/learn/learn.css +0 -45
  87. package/public/learn/mcp-pre-action-gates-explained.html +0 -172
  88. package/public/learn/stop-ai-agent-force-push.html +0 -134
  89. package/public/learn/vibe-coding-safety-net.html +0 -142
  90. package/public/learn.html +0 -274
  91. package/public/lessons.html +0 -967
  92. package/public/llm-context.md +0 -156
  93. package/public/pro.html +0 -1087
  94. package/public/vercel.json +0 -8
  95. package/scripts/a2ui-engine.js +0 -73
  96. package/scripts/adk-consolidator.js +0 -274
  97. package/scripts/agent-security-hardening.js +0 -225
  98. package/scripts/ai-search-visibility.js +0 -116
  99. package/scripts/autonomous-sales-agent.js +0 -39
  100. package/scripts/autoresearch-runner.js +0 -216
  101. package/scripts/background-agent-governance.js +0 -229
  102. package/scripts/behavioral-extraction.js +0 -93
  103. package/scripts/budget-enforcer.js +0 -173
  104. package/scripts/budget-guard.js +0 -173
  105. package/scripts/build-claude-mcpb.js +0 -255
  106. package/scripts/build-codex-plugin.js +0 -152
  107. package/scripts/capture-railway-diagnostics.sh +0 -97
  108. package/scripts/changeset-check.js +0 -372
  109. package/scripts/check-congruence.js +0 -443
  110. package/scripts/computer-use-firewall.js +0 -280
  111. package/scripts/content-engine/linkedin-content-generator.js +0 -154
  112. package/scripts/content-engine/output/linkedin-memento-validation.md +0 -17
  113. package/scripts/content-engine/output/linkedin-posts-2026-04-09.md +0 -175
  114. package/scripts/content-engine/reddit-thread-finder.js +0 -154
  115. package/scripts/context-engine.js +0 -710
  116. package/scripts/daily-digest.js +0 -11
  117. package/scripts/data-governance.js +0 -173
  118. package/scripts/deploy-gcp.sh +0 -44
  119. package/scripts/deploy-policy.js +0 -249
  120. package/scripts/disagreement-mining.js +0 -315
  121. package/scripts/dpo-optimizer.js +0 -206
  122. package/scripts/ensure-repo-bootstrap.js +0 -130
  123. package/scripts/ephemeral-agent-store.js +0 -212
  124. package/scripts/eval-harness.js +0 -56
  125. package/scripts/export-kto-pairs.js +0 -309
  126. package/scripts/export-training.js +0 -446
  127. package/scripts/feedback-fallback.js +0 -111
  128. package/scripts/feedback-inbox-read.js +0 -162
  129. package/scripts/feedback-root-consolidator.js +0 -233
  130. package/scripts/feedback-to-memory.js +0 -185
  131. package/scripts/gate-satisfy.js +0 -42
  132. package/scripts/generate-paperbanana-diagrams.sh +0 -99
  133. package/scripts/generate-pretool-hook.sh +0 -40
  134. package/scripts/github-about.js +0 -430
  135. package/scripts/github-outreach.js +0 -65
  136. package/scripts/gtm-revenue-loop.js +0 -535
  137. package/scripts/hallucination-detector.js +0 -226
  138. package/scripts/hf-papers.js +0 -317
  139. package/scripts/hook-auto-capture.sh +0 -100
  140. package/scripts/hook-stop-pr-thread-check.sh +0 -68
  141. package/scripts/hook-stop-self-score.sh +0 -51
  142. package/scripts/hook-stop-verify-deploy.sh +0 -31
  143. package/scripts/hook-verify-before-done.sh +0 -20
  144. package/scripts/managed-dpo-export.js +0 -91
  145. package/scripts/markdown-escape.js +0 -12
  146. package/scripts/marketing-experiment.js +0 -657
  147. package/scripts/memalign-recall.js +0 -111
  148. package/scripts/memory-migration.js +0 -296
  149. package/scripts/meta-policy.js +0 -190
  150. package/scripts/metered-billing.js +0 -16
  151. package/scripts/model-tier-router.js +0 -310
  152. package/scripts/money-watcher.js +0 -218
  153. package/scripts/multi-hop-recall.js +0 -240
  154. package/scripts/per-step-scoring.js +0 -163
  155. package/scripts/perplexity-command-center.js +0 -644
  156. package/scripts/perplexity-marketing.js +0 -454
  157. package/scripts/pii-scanner.js +0 -153
  158. package/scripts/plan-gate.js +0 -154
  159. package/scripts/post-everywhere.js +0 -341
  160. package/scripts/post-to-x-retry.sh +0 -22
  161. package/scripts/post-to-x.js +0 -369
  162. package/scripts/pr-manager.js +0 -421
  163. package/scripts/principle-extractor.js +0 -162
  164. package/scripts/pro-features.js +0 -41
  165. package/scripts/prompt-dlp.js +0 -222
  166. package/scripts/prove-adapters.js +0 -860
  167. package/scripts/prove-attribution.js +0 -361
  168. package/scripts/prove-automation.js +0 -651
  169. package/scripts/prove-autoresearch.js +0 -304
  170. package/scripts/prove-claim-verification.js +0 -277
  171. package/scripts/prove-cloudflare-sandbox.js +0 -161
  172. package/scripts/prove-data-pipeline.js +0 -408
  173. package/scripts/prove-data-quality.js +0 -227
  174. package/scripts/prove-evolution.js +0 -352
  175. package/scripts/prove-harnesses.js +0 -287
  176. package/scripts/prove-intelligence.js +0 -257
  177. package/scripts/prove-lancedb.js +0 -425
  178. package/scripts/prove-local-intelligence.js +0 -340
  179. package/scripts/prove-loop-closure.js +0 -263
  180. package/scripts/prove-packaged-runtime.js +0 -327
  181. package/scripts/prove-predictive-insights.js +0 -355
  182. package/scripts/prove-runtime.js +0 -363
  183. package/scripts/prove-seo-gsd.js +0 -234
  184. package/scripts/prove-settings.js +0 -279
  185. package/scripts/prove-subway-upgrades.js +0 -277
  186. package/scripts/prove-tessl.js +0 -229
  187. package/scripts/prove-training-export.js +0 -325
  188. package/scripts/prove-workflow-contract.js +0 -112
  189. package/scripts/prove-xmemory.js +0 -332
  190. package/scripts/publish-decision.js +0 -159
  191. package/scripts/ralph-loop.js +0 -376
  192. package/scripts/ralph-mode-ci.js +0 -434
  193. package/scripts/reddit-dm-outreach.js +0 -192
  194. package/scripts/reddit-monitor-cron.sh +0 -26
  195. package/scripts/reminder-engine.js +0 -132
  196. package/scripts/revenue-status.js +0 -472
  197. package/scripts/rotate-stripe-webhook-secret.js +0 -314
  198. package/scripts/schedule-manager.js +0 -249
  199. package/scripts/self-healing-check.js +0 -193
  200. package/scripts/session-analyzer.js +0 -533
  201. package/scripts/shieldcortex-memory-firewall-runner.mjs +0 -53
  202. package/scripts/skill-exporter.js +0 -260
  203. package/scripts/skill-materializer.js +0 -134
  204. package/scripts/skill-packs.js +0 -136
  205. package/scripts/skill-proposer.js +0 -99
  206. package/scripts/skill-quality-tracker.js +0 -282
  207. package/scripts/slow-loop.js +0 -72
  208. package/scripts/social-analytics/db/marketing-db.js +0 -179
  209. package/scripts/social-analytics/db/schema.sql +0 -55
  210. package/scripts/social-analytics/digest.js +0 -256
  211. package/scripts/social-analytics/engagement-audit.js +0 -185
  212. package/scripts/social-analytics/generate-instagram-card.js +0 -123
  213. package/scripts/social-analytics/generate-slides.js +0 -268
  214. package/scripts/social-analytics/instagram-thumbgate-post.js +0 -111
  215. package/scripts/social-analytics/install-growth-automation.js +0 -114
  216. package/scripts/social-analytics/load-env.js +0 -77
  217. package/scripts/social-analytics/mcp-server.js +0 -289
  218. package/scripts/social-analytics/normalizer.js +0 -580
  219. package/scripts/social-analytics/notify.js +0 -162
  220. package/scripts/social-analytics/poll-all.js +0 -107
  221. package/scripts/social-analytics/pollers/github.js +0 -195
  222. package/scripts/social-analytics/pollers/instagram.js +0 -253
  223. package/scripts/social-analytics/pollers/linkedin.js +0 -340
  224. package/scripts/social-analytics/pollers/plausible.js +0 -245
  225. package/scripts/social-analytics/pollers/reddit.js +0 -306
  226. package/scripts/social-analytics/pollers/threads.js +0 -233
  227. package/scripts/social-analytics/pollers/tiktok.js +0 -203
  228. package/scripts/social-analytics/pollers/x.js +0 -227
  229. package/scripts/social-analytics/pollers/youtube.js +0 -304
  230. package/scripts/social-analytics/pollers/zernio.js +0 -183
  231. package/scripts/social-analytics/post-video.js +0 -316
  232. package/scripts/social-analytics/publish-instagram-thumbgate.js +0 -104
  233. package/scripts/social-analytics/publish-thumbgate-launch.js +0 -322
  234. package/scripts/social-analytics/publishers/devto.js +0 -122
  235. package/scripts/social-analytics/publishers/instagram.js +0 -317
  236. package/scripts/social-analytics/publishers/linkedin.js +0 -294
  237. package/scripts/social-analytics/publishers/reddit.js +0 -385
  238. package/scripts/social-analytics/publishers/threads.js +0 -275
  239. package/scripts/social-analytics/publishers/tiktok.js +0 -217
  240. package/scripts/social-analytics/publishers/x.js +0 -259
  241. package/scripts/social-analytics/publishers/youtube.js +0 -223
  242. package/scripts/social-analytics/publishers/zernio.js +0 -568
  243. package/scripts/social-analytics/reconcile-thumbgate-campaign.js +0 -165
  244. package/scripts/social-analytics/run-digest.js +0 -34
  245. package/scripts/social-analytics/schedule-thumbgate-campaign.js +0 -275
  246. package/scripts/social-analytics/store.js +0 -455
  247. package/scripts/social-analytics/sync-launch-assets.js +0 -185
  248. package/scripts/social-analytics/utm.js +0 -143
  249. package/scripts/social-pipeline.js +0 -2626
  250. package/scripts/social-post-hourly.js +0 -228
  251. package/scripts/social-quality-gate.js +0 -134
  252. package/scripts/social-reply-monitor.js +0 -592
  253. package/scripts/status-dashboard.js +0 -155
  254. package/scripts/stripe-live-status.js +0 -115
  255. package/scripts/subagent-profiles.js +0 -79
  256. package/scripts/sync-branch-protection.js +0 -340
  257. package/scripts/sync-gh-secrets-from-env.sh +0 -70
  258. package/scripts/sync-github-about.js +0 -55
  259. package/scripts/sync-version.js +0 -479
  260. package/scripts/synthetic-dpo.js +0 -234
  261. package/scripts/tessl-export.js +0 -369
  262. package/scripts/test-coverage.js +0 -128
  263. package/scripts/thumbgate-bench.js +0 -494
  264. package/scripts/thumbgate_session_start.sh +0 -32
  265. package/scripts/train_from_feedback.py +0 -929
  266. package/scripts/validate-feedback.js +0 -581
  267. package/scripts/verify-obsidian-setup.sh +0 -269
  268. package/scripts/verify-run.js +0 -269
  269. package/scripts/weekly-auto-post.js +0 -124
  270. package/scripts/x-autonomous-marketing.js +0 -139
@@ -1,2626 +0,0 @@
1
- 'use strict';
2
-
3
- const cp = require('child_process');
4
- const crypto = require('crypto');
5
- const { once } = require('events');
6
- const fs = require('fs');
7
- const net = require('net');
8
- const os = require('os');
9
- const path = require('path');
10
- const { pathToFileURL } = require('url');
11
- const { ensureDir } = require('./fs-utils');
12
-
13
- const REPO_ROOT = path.resolve(__dirname, '..');
14
- const DEFAULT_ASSET_HTML = path.join(
15
- REPO_ROOT,
16
- 'docs',
17
- 'marketing',
18
- 'assets',
19
- 'pre-action-gates-instagram-carousel.html'
20
- );
21
- const DEFAULT_CAPTION_PATH = path.join(
22
- REPO_ROOT,
23
- 'docs',
24
- 'marketing',
25
- 'assets',
26
- 'pre-action-gates-caption.txt'
27
- );
28
- const DEFAULT_OUTPUT_ROOT = path.join(REPO_ROOT, '.artifacts', 'social');
29
- const DEFAULT_QUEUE_PATH = path.join(REPO_ROOT, '.thumbgate', 'social-post-queue.json');
30
- const DEFAULT_HISTORY_PATH = path.join(REPO_ROOT, '.thumbgate', 'social-post-history.jsonl');
31
- const DEFAULT_LAUNCHD_LABEL = 'io.github.IgorGanapolsky.thumbgate.social';
32
- const DEFAULT_SCHEDULE_INTERVAL_MINUTES = 15;
33
- const DEFAULT_CHROME_PROFILE_ROOT = path.join(
34
- os.homedir(),
35
- 'Library',
36
- 'Application Support',
37
- 'Google',
38
- 'Chrome'
39
- );
40
- const DEFAULT_CHROME_PROFILE_DIR = 'Default';
41
- const DEFAULT_EXPECTED_SLIDE_COUNT = 5;
42
- const DEFAULT_EXPECTED_SLIDE_WIDTH = 1080;
43
- const DEFAULT_EXPECTED_SLIDE_HEIGHT = 1080;
44
- const DEFAULT_CHROME_CDP_TIMEOUT_MS = 60_000;
45
- const DEFAULT_CHROME_EXIT_TIMEOUT_MS = 5000;
46
- const DEFAULT_DIRECTORY_RETRY_ATTEMPTS = 12;
47
- const DEFAULT_DIRECTORY_RETRY_DELAY_MS = 250;
48
- const INSTAGRAM_URL = 'https://www.instagram.com/';
49
- const TIKTOK_UPLOAD_URL = 'https://www.tiktok.com/tiktokstudio/upload?lang=en';
50
- const TIKTOK_CONTENT_URL = 'https://www.tiktok.com/tiktokstudio/content';
51
- const INSTAGRAM_ACCEPT_PREFIX = 'image/';
52
-
53
- function parseArgs(argv) {
54
- const args = { _: [] };
55
- for (let index = 0; index < argv.length; index += 1) {
56
- const token = argv[index];
57
- if (!token.startsWith('--')) {
58
- args._.push(token);
59
- continue;
60
- }
61
-
62
- const eqIndex = token.indexOf('=');
63
- if (eqIndex !== -1) {
64
- args[token.slice(2, eqIndex)] = token.slice(eqIndex + 1);
65
- continue;
66
- }
67
-
68
- const key = token.slice(2);
69
- const next = argv[index + 1];
70
- if (!next || next.startsWith('--')) {
71
- args[key] = true;
72
- continue;
73
- }
74
-
75
- args[key] = next;
76
- index += 1;
77
- }
78
- return args;
79
- }
80
-
81
-
82
- function readText(filePath) {
83
- return fs.readFileSync(filePath, 'utf8');
84
- }
85
-
86
- function writeText(filePath, content) {
87
- ensureDir(path.dirname(filePath));
88
- fs.writeFileSync(filePath, content);
89
- }
90
-
91
- function readJson(filePath, fallback) {
92
- if (!fs.existsSync(filePath)) {
93
- return fallback;
94
- }
95
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
96
- }
97
-
98
- function writeJson(filePath, value) {
99
- ensureDir(path.dirname(filePath));
100
- fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
101
- }
102
-
103
- function appendJsonLine(filePath, value) {
104
- ensureDir(path.dirname(filePath));
105
- fs.appendFileSync(filePath, `${JSON.stringify(value)}\n`);
106
- }
107
-
108
- function loadJsonLines(filePath) {
109
- if (!fs.existsSync(filePath)) {
110
- return [];
111
- }
112
- return fs.readFileSync(filePath, 'utf8')
113
- .split('\n')
114
- .filter(Boolean)
115
- .map((line) => JSON.parse(line));
116
- }
117
-
118
- function slugify(input) {
119
- return String(input || '')
120
- .trim()
121
- .toLowerCase()
122
- .replace(/[^a-z0-9]+/g, '-')
123
- .replace(/^-+|-+$/g, '') || 'social-post';
124
- }
125
-
126
- function resolvePath(input, fallback) {
127
- const target = input || fallback;
128
- if (!target) {
129
- return null;
130
- }
131
- return path.isAbsolute(target) ? target : path.resolve(REPO_ROOT, target);
132
- }
133
-
134
- function resolveChromeProfileRoot(input = DEFAULT_CHROME_PROFILE_ROOT) {
135
- if (!input) {
136
- return null;
137
- }
138
- return path.isAbsolute(input) ? input : path.resolve(REPO_ROOT, input);
139
- }
140
-
141
- function sleep(ms) {
142
- return new Promise((resolve) => setTimeout(resolve, ms));
143
- }
144
-
145
- function hashText(value) {
146
- return crypto.createHash('sha256').update(String(value || ''), 'utf8').digest('hex');
147
- }
148
-
149
- function hashFile(filePath) {
150
- return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
151
- }
152
-
153
- function mimeTypeForPath(filePath) {
154
- const ext = path.extname(filePath).toLowerCase();
155
- if (ext === '.png') return 'image/png';
156
- if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
157
- if (ext === '.webp') return 'image/webp';
158
- if (ext === '.mp4') return 'video/mp4';
159
- if (ext === '.mov') return 'video/quicktime';
160
- return 'application/octet-stream';
161
- }
162
-
163
- function readPngDimensions(filePath) {
164
- const buffer = fs.readFileSync(filePath);
165
- const pngSignature = '89504e470d0a1a0a';
166
- if (buffer.length < 24 || buffer.subarray(0, 8).toString('hex') !== pngSignature) {
167
- throw new Error(`Expected a PNG file at ${filePath}`);
168
- }
169
- return {
170
- width: buffer.readUInt32BE(16),
171
- height: buffer.readUInt32BE(20),
172
- };
173
- }
174
-
175
- function validateSlideImages(
176
- slideImagePaths,
177
- {
178
- expectedCount = DEFAULT_EXPECTED_SLIDE_COUNT,
179
- expectedWidth = DEFAULT_EXPECTED_SLIDE_WIDTH,
180
- expectedHeight = DEFAULT_EXPECTED_SLIDE_HEIGHT,
181
- } = {}
182
- ) {
183
- if (!Array.isArray(slideImagePaths) || slideImagePaths.length !== expectedCount) {
184
- throw new Error(`Expected ${expectedCount} rendered slide images, received ${slideImagePaths ? slideImagePaths.length : 0}.`);
185
- }
186
-
187
- return slideImagePaths.map((slidePath, index) => {
188
- if (!fs.existsSync(slidePath)) {
189
- throw new Error(`Rendered slide ${index + 1} is missing at ${slidePath}`);
190
- }
191
-
192
- const stats = fs.statSync(slidePath);
193
- if (stats.size <= 0) {
194
- throw new Error(`Rendered slide ${index + 1} is empty at ${slidePath}`);
195
- }
196
-
197
- const { width, height } = readPngDimensions(slidePath);
198
- if (width !== expectedWidth || height !== expectedHeight) {
199
- throw new Error(
200
- `Rendered slide ${index + 1} must be ${expectedWidth}x${expectedHeight}; received ${width}x${height} at ${slidePath}`
201
- );
202
- }
203
-
204
- return {
205
- path: slidePath,
206
- sha256: hashFile(slidePath),
207
- sizeBytes: stats.size,
208
- width,
209
- height,
210
- };
211
- });
212
- }
213
-
214
- function extractHeadContent(html) {
215
- const match = html.match(/<head[^>]*>([\s\S]*?)<\/head>/i);
216
- if (!match) {
217
- throw new Error('Unable to locate <head> content in carousel HTML.');
218
- }
219
- return match[1];
220
- }
221
-
222
- function extractSlideBlocks(html) {
223
- const blocks = [];
224
- let searchIndex = 0;
225
-
226
- while (searchIndex < html.length) {
227
- const start = html.indexOf('<div class="slide', searchIndex);
228
- if (start === -1) {
229
- break;
230
- }
231
-
232
- let cursor = start;
233
- let depth = 0;
234
- let end = -1;
235
-
236
- while (cursor < html.length) {
237
- const nextOpen = html.indexOf('<div', cursor);
238
- const nextClose = html.indexOf('</div', cursor);
239
-
240
- if (nextClose === -1) {
241
- throw new Error('Unable to parse slide HTML. Found unbalanced <div> tags.');
242
- }
243
-
244
- if (nextOpen !== -1 && nextOpen < nextClose) {
245
- depth += 1;
246
- cursor = html.indexOf('>', nextOpen);
247
- if (cursor === -1) {
248
- throw new Error('Unable to parse opening <div> tag while extracting slide blocks.');
249
- }
250
- cursor += 1;
251
- continue;
252
- }
253
-
254
- depth -= 1;
255
- cursor = html.indexOf('>', nextClose);
256
- if (cursor === -1) {
257
- throw new Error('Unable to parse closing </div> tag while extracting slide blocks.');
258
- }
259
- cursor += 1;
260
- if (depth === 0) {
261
- end = cursor;
262
- break;
263
- }
264
- }
265
-
266
- if (end === -1) {
267
- throw new Error('Unable to resolve the end of a slide block.');
268
- }
269
-
270
- blocks.push(html.slice(start, end));
271
- searchIndex = end;
272
- }
273
-
274
- return blocks;
275
- }
276
-
277
- function buildIsolatedSlideDocument(headContent, slideHtml) {
278
- const exportStyles = [
279
- '<style>',
280
- 'html, body { width: 1080px; height: 1080px; margin: 0; padding: 0; overflow: hidden; background: #111; }',
281
- 'body { display: block; }',
282
- '.slide-label { display: none !important; }',
283
- '.slide { margin: 0 !important; }',
284
- '</style>',
285
- ].join('');
286
-
287
- return [
288
- '<!DOCTYPE html>',
289
- '<html lang="en">',
290
- '<head>',
291
- headContent,
292
- exportStyles,
293
- '</head>',
294
- '<body>',
295
- slideHtml,
296
- '</body>',
297
- '</html>',
298
- ].join('');
299
- }
300
-
301
- function writeIsolatedSlideDocuments({ sourceHtmlPath, outputDir }) {
302
- const html = readText(sourceHtmlPath);
303
- const headContent = extractHeadContent(html);
304
- const slides = extractSlideBlocks(html);
305
-
306
- if (slides.length === 0) {
307
- throw new Error('No .slide blocks found in carousel HTML.');
308
- }
309
-
310
- ensureDir(outputDir);
311
- const slideDocuments = slides.map((slideHtml, index) => {
312
- const slidePath = path.join(outputDir, `slide-${String(index + 1).padStart(2, '0')}.html`);
313
- writeText(slidePath, buildIsolatedSlideDocument(headContent, slideHtml));
314
- return slidePath;
315
- });
316
-
317
- return slideDocuments;
318
- }
319
-
320
- function resolveCaptionSource({ sourceDir, captionPath, captionText }) {
321
- if (captionText !== undefined && captionText !== null) {
322
- const inlineCaptionPath = path.join(sourceDir, 'caption-source.txt');
323
- writeText(inlineCaptionPath, `${String(captionText).trim()}\n`);
324
- return {
325
- captionPath: inlineCaptionPath,
326
- caption: String(captionText).trim(),
327
- source: 'inline',
328
- };
329
- }
330
-
331
- const resolvedCaptionPath = resolvePath(captionPath, DEFAULT_CAPTION_PATH);
332
- return {
333
- captionPath: resolvedCaptionPath,
334
- caption: readText(resolvedCaptionPath).trim(),
335
- source: 'file',
336
- };
337
- }
338
-
339
- function findExecutable(candidates) {
340
- for (const candidate of candidates) {
341
- if (!candidate) {
342
- continue;
343
- }
344
-
345
- if (candidate.includes(path.sep) && fs.existsSync(candidate)) {
346
- return candidate;
347
- }
348
-
349
- const result = cp.spawnSync('which', [candidate], { encoding: 'utf8' });
350
- if (result.status === 0) {
351
- const resolved = result.stdout.trim();
352
- if (resolved) {
353
- return resolved;
354
- }
355
- }
356
- }
357
- return null;
358
- }
359
-
360
- function resolveChromeBinary() {
361
- const chrome = findExecutable([
362
- process.env.CHROME_BIN,
363
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
364
- 'Google Chrome',
365
- 'google-chrome',
366
- 'chromium',
367
- 'chromium-browser',
368
- ]);
369
- if (!chrome) {
370
- throw new Error('Google Chrome binary not found. Set CHROME_BIN or install Google Chrome.');
371
- }
372
- return chrome;
373
- }
374
-
375
- function resolveFfmpegBinary() {
376
- const ffmpeg = findExecutable([process.env.FFMPEG_BIN, 'ffmpeg']);
377
- if (!ffmpeg) {
378
- throw new Error('ffmpeg binary not found. Set FFMPEG_BIN or install ffmpeg.');
379
- }
380
- return ffmpeg;
381
- }
382
-
383
- function renderSlides({ slideDocuments, outputDir, chromeBin, dryRun = false }) {
384
- ensureDir(outputDir);
385
- const slidePaths = slideDocuments.map((_, index) => (
386
- path.join(outputDir, `slide-${String(index + 1).padStart(2, '0')}.png`)
387
- ));
388
-
389
- if (dryRun) {
390
- return slidePaths;
391
- }
392
-
393
- for (let index = 0; index < slideDocuments.length; index += 1) {
394
- cp.execFileSync(chromeBin, [
395
- '--headless=new',
396
- '--disable-gpu',
397
- '--hide-scrollbars',
398
- '--allow-file-access-from-files',
399
- '--window-size=1080,1080',
400
- '--virtual-time-budget=5000',
401
- `--screenshot=${slidePaths[index]}`,
402
- pathToFileURL(slideDocuments[index]).href,
403
- ], { stdio: 'ignore' });
404
- }
405
-
406
- return slidePaths;
407
- }
408
-
409
- function buildFfmpegConcatManifest(slidePaths, durationSeconds) {
410
- const lines = [];
411
- for (const slidePath of slidePaths) {
412
- lines.push(`file '${slidePath.replace(/'/g, "'\\''")}'`);
413
- lines.push(`duration ${durationSeconds}`);
414
- }
415
- lines.push(`file '${slidePaths[slidePaths.length - 1].replace(/'/g, "'\\''")}'`);
416
- return `${lines.join('\n')}\n`;
417
- }
418
-
419
- function normalizeTikTokCaption(caption) {
420
- return String(caption || '')
421
- .replace(/[“”]/g, '"')
422
- .replace(/[’]/g, '\'')
423
- .replace(/[—–]/g, '-')
424
- .replace(/\s+/g, ' ')
425
- .trim();
426
- }
427
-
428
- function renderTikTokVideo({
429
- slidePaths,
430
- outputPath,
431
- slideDurationSeconds = 2.4,
432
- ffmpegBin,
433
- dryRun = false,
434
- }) {
435
- if (!slidePaths || slidePaths.length === 0) {
436
- throw new Error('TikTok fallback video requires at least one slide image.');
437
- }
438
-
439
- ensureDir(path.dirname(outputPath));
440
- if (dryRun) {
441
- return outputPath;
442
- }
443
-
444
- const concatPath = path.join(path.dirname(outputPath), 'tiktok-slides.txt');
445
- writeText(concatPath, buildFfmpegConcatManifest(slidePaths, slideDurationSeconds));
446
-
447
- cp.execFileSync(ffmpegBin, [
448
- '-y',
449
- '-f', 'concat',
450
- '-safe', '0',
451
- '-i', concatPath,
452
- '-f', 'lavfi',
453
- '-t', String(slidePaths.length * slideDurationSeconds + 0.5),
454
- '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000',
455
- '-vf', 'fps=30,scale=1080:1080:flags=lanczos,pad=1080:1920:0:420:color=0x241f4f,format=yuv420p',
456
- '-c:v', 'libx264',
457
- '-preset', 'medium',
458
- '-profile:v', 'high',
459
- '-level', '4.1',
460
- '-pix_fmt', 'yuv420p',
461
- '-c:a', 'aac',
462
- '-b:a', '128k',
463
- '-shortest',
464
- '-movflags', '+faststart',
465
- outputPath,
466
- ], { stdio: 'ignore' });
467
-
468
- return outputPath;
469
- }
470
-
471
- function buildBundleManifest({
472
- id,
473
- sourceHtmlPath,
474
- captionPath,
475
- outputDir,
476
- slideDocumentPaths,
477
- slideImagePaths,
478
- slideImageMetadata,
479
- tiktokVideoPath,
480
- instagramCaptionPath,
481
- tiktokCaptionPath,
482
- instagramCaptionHash,
483
- tiktokCaptionHash,
484
- tiktokVideoHash,
485
- createdAt,
486
- }) {
487
- return {
488
- id,
489
- createdAt,
490
- sourceHtmlPath,
491
- captionPath,
492
- outputDir,
493
- slideDocumentPaths,
494
- slideImagePaths,
495
- slideImageMetadata,
496
- instagramCaptionPath,
497
- tiktokCaptionPath,
498
- tiktokVideoPath,
499
- hashes: {
500
- instagramCaptionSha256: instagramCaptionHash,
501
- tiktokCaptionSha256: tiktokCaptionHash,
502
- tiktokVideoSha256: tiktokVideoHash,
503
- },
504
- platforms: {
505
- instagram: {
506
- type: 'carousel',
507
- assetPaths: slideImagePaths,
508
- },
509
- tiktok: {
510
- preferredType: 'photo-carousel',
511
- photoAssetPaths: slideImagePaths,
512
- videoAssetPath: tiktokVideoPath,
513
- assetPath: tiktokVideoPath,
514
- },
515
- },
516
- };
517
- }
518
-
519
- function prepareBundle({
520
- sourceHtmlPath,
521
- captionPath,
522
- captionText,
523
- outputDir,
524
- slug,
525
- slideDurationSeconds = 2.4,
526
- chromeBin,
527
- ffmpegBin,
528
- dryRun = false,
529
- renderSlidesFn = renderSlides,
530
- renderTikTokVideoFn = renderTikTokVideo,
531
- }) {
532
- const bundleId = slugify(slug || path.basename(sourceHtmlPath, path.extname(sourceHtmlPath)));
533
- const bundleRoot = outputDir || path.join(DEFAULT_OUTPUT_ROOT, bundleId);
534
- const sourceDir = path.join(bundleRoot, 'source');
535
- const slidesDir = path.join(bundleRoot, 'slides');
536
- const captionsDir = path.join(bundleRoot, 'captions');
537
- const videoDir = path.join(bundleRoot, 'video');
538
-
539
- ensureDir(bundleRoot);
540
- ensureDir(sourceDir);
541
- ensureDir(slidesDir);
542
- ensureDir(captionsDir);
543
- ensureDir(videoDir);
544
-
545
- const resolvedChromeBin = chromeBin || (dryRun ? 'dry-run-chrome' : resolveChromeBinary());
546
- const resolvedFfmpegBin = ffmpegBin || (dryRun ? 'dry-run-ffmpeg' : resolveFfmpegBinary());
547
-
548
- const slideDocumentPaths = writeIsolatedSlideDocuments({
549
- sourceHtmlPath,
550
- outputDir: sourceDir,
551
- });
552
- const slideImagePaths = renderSlidesFn({
553
- slideDocuments: slideDocumentPaths,
554
- outputDir: slidesDir,
555
- chromeBin: resolvedChromeBin,
556
- dryRun,
557
- });
558
- const slideImageMetadata = validateSlideImages(slideImagePaths);
559
-
560
- const resolvedCaptionSource = resolveCaptionSource({
561
- sourceDir,
562
- captionPath,
563
- captionText,
564
- });
565
- const caption = resolvedCaptionSource.caption;
566
- const instagramCaptionPath = path.join(captionsDir, 'instagram.txt');
567
- const tiktokCaptionPath = path.join(captionsDir, 'tiktok.txt');
568
- writeText(instagramCaptionPath, `${caption}\n`);
569
- writeText(tiktokCaptionPath, `${normalizeTikTokCaption(caption)}\n`);
570
-
571
- const tiktokVideoPath = renderTikTokVideoFn({
572
- slidePaths: slideImagePaths,
573
- outputPath: path.join(videoDir, 'tiktok-fallback.mp4'),
574
- slideDurationSeconds,
575
- ffmpegBin: resolvedFfmpegBin,
576
- dryRun,
577
- });
578
-
579
- const manifest = buildBundleManifest({
580
- id: bundleId,
581
- createdAt: new Date().toISOString(),
582
- sourceHtmlPath,
583
- captionPath: resolvedCaptionSource.captionPath,
584
- outputDir: bundleRoot,
585
- slideDocumentPaths,
586
- slideImagePaths,
587
- slideImageMetadata,
588
- tiktokVideoPath,
589
- instagramCaptionPath,
590
- tiktokCaptionPath,
591
- instagramCaptionHash: hashFile(instagramCaptionPath),
592
- tiktokCaptionHash: hashFile(tiktokCaptionPath),
593
- tiktokVideoHash: hashFile(tiktokVideoPath),
594
- });
595
-
596
- const manifestPath = path.join(bundleRoot, 'bundle.json');
597
- writeJson(manifestPath, manifest);
598
- return { manifest, manifestPath };
599
- }
600
-
601
- function loadQueueState(queuePath = DEFAULT_QUEUE_PATH) {
602
- return readJson(queuePath, { entries: [] });
603
- }
604
-
605
- function saveQueueState(queuePath, queueState) {
606
- writeJson(queuePath, queueState);
607
- }
608
-
609
- function normalizePlatformList(platforms = []) {
610
- return [...new Set((platforms || []).map((platform) => String(platform).trim()).filter(Boolean))].sort();
611
- }
612
-
613
- function enqueueBundle({
614
- queuePath = DEFAULT_QUEUE_PATH,
615
- bundlePath,
616
- scheduledAt,
617
- platforms = ['instagram', 'tiktok'],
618
- }) {
619
- const bundle = readJson(bundlePath, null);
620
- if (!bundle) {
621
- throw new Error(`Bundle manifest not found at ${bundlePath}`);
622
- }
623
-
624
- const queueState = loadQueueState(queuePath);
625
- const normalizedScheduledAt = new Date(scheduledAt).toISOString();
626
- const normalizedPlatforms = normalizePlatformList(platforms);
627
- const existingEntry = (queueState.entries || []).find((entry) => (
628
- entry.status === 'pending' &&
629
- entry.bundlePath === bundlePath &&
630
- entry.scheduledAt === normalizedScheduledAt &&
631
- JSON.stringify(normalizePlatformList(entry.platforms)) === JSON.stringify(normalizedPlatforms)
632
- ));
633
-
634
- if (existingEntry) {
635
- return existingEntry;
636
- }
637
-
638
- const entry = {
639
- id: `social_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
640
- bundlePath,
641
- bundleId: bundle.id,
642
- scheduledAt: normalizedScheduledAt,
643
- platforms: normalizedPlatforms,
644
- status: 'pending',
645
- attempts: [],
646
- createdAt: new Date().toISOString(),
647
- };
648
-
649
- queueState.entries.push(entry);
650
- saveQueueState(queuePath, queueState);
651
- return entry;
652
- }
653
-
654
- function getDueEntries(queueState, now = new Date()) {
655
- return (queueState.entries || []).filter((entry) => (
656
- entry.status === 'pending' && new Date(entry.scheduledAt).getTime() <= now.getTime()
657
- ));
658
- }
659
-
660
- function loadPublishHistory(historyPath = DEFAULT_HISTORY_PATH) {
661
- return loadJsonLines(historyPath);
662
- }
663
-
664
- function buildPublishFingerprint({ platform, captionText, assetPaths = [] }) {
665
- const fingerprintPayload = {
666
- platform,
667
- captionSha256: hashText(captionText),
668
- assetHashes: assetPaths.map((assetPath) => ({
669
- path: path.basename(assetPath),
670
- sha256: hashFile(assetPath),
671
- })),
672
- };
673
- return hashText(JSON.stringify(fingerprintPayload));
674
- }
675
-
676
- function assertPublishNotDuplicated({ historyPath = DEFAULT_HISTORY_PATH, fingerprint, platform }) {
677
- const existing = loadPublishHistory(historyPath).find((entry) => (
678
- entry.platform === platform &&
679
- entry.status === 'published' &&
680
- entry.fingerprint === fingerprint
681
- ));
682
-
683
- if (existing) {
684
- throw new Error(
685
- `Duplicate ${platform} publish blocked. Matching content was already published at ${existing.publishedAt}. Use --force to bypass.`
686
- );
687
- }
688
- }
689
-
690
- function createPublishAttempt(bundle, platform) {
691
- const attemptId = `${platform}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
692
- const attemptDir = path.join(bundle.outputDir, 'publish-attempts', attemptId);
693
- ensureDir(attemptDir);
694
- return {
695
- attemptId,
696
- attemptDir,
697
- recordPath: path.join(attemptDir, 'attempt.json'),
698
- };
699
- }
700
-
701
- function writePublishAttemptRecord(recordPath, payload) {
702
- writeJson(recordPath, payload);
703
- }
704
-
705
- function appendPublishAttemptEvent(recordPath, event) {
706
- const existing = readJson(recordPath, {});
707
- const events = Array.isArray(existing.events) ? existing.events.slice() : [];
708
- events.push(event);
709
- writeJson(recordPath, {
710
- ...existing,
711
- lastEventAt: event.recordedAt || new Date().toISOString(),
712
- events,
713
- });
714
- }
715
-
716
- async function removeDirectoryWithRetries(
717
- dirPath,
718
- {
719
- attempts = DEFAULT_DIRECTORY_RETRY_ATTEMPTS,
720
- delayMs = DEFAULT_DIRECTORY_RETRY_DELAY_MS,
721
- } = {}
722
- ) {
723
- if (!dirPath) {
724
- return;
725
- }
726
-
727
- let lastError = null;
728
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
729
- try {
730
- fs.rmSync(dirPath, { recursive: true, force: true });
731
- return;
732
- } catch (error) {
733
- lastError = error;
734
- if (!['EBUSY', 'EMFILE', 'ENFILE', 'ENOTEMPTY', 'EPERM'].includes(error.code) || attempt === attempts) {
735
- throw error;
736
- }
737
- await sleep(delayMs);
738
- }
739
- }
740
-
741
- if (lastError) {
742
- throw lastError;
743
- }
744
- }
745
-
746
- async function waitForProcessExit(processHandle, timeoutMs = DEFAULT_CHROME_EXIT_TIMEOUT_MS) {
747
- if (!processHandle) {
748
- return 0;
749
- }
750
- if (processHandle.exitCode !== null || processHandle.signalCode !== null) {
751
- return processHandle.exitCode;
752
- }
753
-
754
- await Promise.race([
755
- Promise.race([
756
- once(processHandle, 'exit'),
757
- once(processHandle, 'close'),
758
- ]),
759
- sleep(timeoutMs).then(() => {
760
- throw new Error(`Timed out waiting for process ${processHandle.pid || 'unknown'} to exit.`);
761
- }),
762
- ]);
763
- return processHandle.exitCode;
764
- }
765
-
766
- async function stopChromeProcess(processHandle, timeoutMs = DEFAULT_CHROME_EXIT_TIMEOUT_MS) {
767
- if (!processHandle || processHandle.exitCode !== null || processHandle.signalCode !== null) {
768
- return;
769
- }
770
-
771
- processHandle.kill('SIGTERM');
772
- try {
773
- await waitForProcessExit(processHandle, timeoutMs);
774
- } catch (error) {
775
- if (processHandle.exitCode !== null || processHandle.signalCode !== null) {
776
- return;
777
- }
778
- processHandle.kill('SIGKILL');
779
- await waitForProcessExit(processHandle, timeoutMs);
780
- throw error;
781
- }
782
- }
783
-
784
- async function waitForChildExit(child, timeoutMs = DEFAULT_CHROME_EXIT_TIMEOUT_MS) {
785
- return waitForProcessExit(child, timeoutMs);
786
- }
787
-
788
- async function removeDirWithRetries(dirPath, {
789
- retries = DEFAULT_DIRECTORY_RETRY_ATTEMPTS,
790
- delayMs = DEFAULT_DIRECTORY_RETRY_DELAY_MS,
791
- } = {}) {
792
- return removeDirectoryWithRetries(dirPath, { attempts: retries, delayMs });
793
- }
794
-
795
- function resolveTikTokPublishTarget(bundle, readyState = {}) {
796
- const photoAssetPaths = bundle.platforms?.tiktok?.photoAssetPaths || bundle.slideImagePaths || [];
797
- const videoAssetPath = bundle.platforms?.tiktok?.videoAssetPath || bundle.platforms?.tiktok?.assetPath || bundle.tiktokVideoPath;
798
- const hasPhotoSurface = readyState.state === 'photo-upload-ready';
799
-
800
- if (hasPhotoSurface && photoAssetPaths.length > 0) {
801
- return {
802
- type: 'photo-carousel',
803
- assetPaths: photoAssetPaths,
804
- captionPath: bundle.tiktokCaptionPath,
805
- };
806
- }
807
-
808
- if (!videoAssetPath) {
809
- throw new Error('TikTok publish requires either photo assets or a fallback MP4 asset.');
810
- }
811
-
812
- return {
813
- type: 'video',
814
- assetPaths: [videoAssetPath],
815
- captionPath: bundle.tiktokCaptionPath,
816
- };
817
- }
818
-
819
- function parseBrowserResult(raw) {
820
- if (typeof raw !== 'string') {
821
- return raw;
822
- }
823
- try {
824
- return JSON.parse(raw);
825
- } catch {
826
- return raw;
827
- }
828
- }
829
-
830
- function escapeRegex(value) {
831
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
832
- }
833
-
834
- function buildClickByTextScript(label) {
835
- return `
836
- (() => {
837
- const pattern = new RegExp('^\\\\s*' + ${JSON.stringify(escapeRegex(label))} + '\\\\s*$', 'i');
838
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
839
- const target = [...document.querySelectorAll('button,[role=button],a')].find((element) => pattern.test(text(element)));
840
- if (!target) {
841
- return JSON.stringify({ clicked: false });
842
- }
843
- target.click();
844
- return JSON.stringify({ clicked: true, label: text(target) });
845
- })()
846
- `;
847
- }
848
-
849
- function shouldCopyChromePath(relativePath) {
850
- const normalized = String(relativePath || '').replace(/\\/g, '/');
851
- return ![
852
- 'Cache',
853
- 'Code Cache',
854
- 'GPUCache',
855
- 'GrShaderCache',
856
- 'ShaderCache',
857
- 'Crashpad',
858
- 'DawnGraphiteCache',
859
- 'DawnWebGPUCache',
860
- 'Service Worker/CacheStorage',
861
- 'Service Worker/ScriptCache',
862
- ].some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`));
863
- }
864
-
865
- function copyChromeProfileForAutomation({
866
- profileRoot = DEFAULT_CHROME_PROFILE_ROOT,
867
- profileDir = DEFAULT_CHROME_PROFILE_DIR,
868
- }) {
869
- const resolvedProfileRoot = resolveChromeProfileRoot(profileRoot);
870
- const sourceProfileDir = path.join(resolvedProfileRoot, profileDir);
871
- if (!fs.existsSync(sourceProfileDir)) {
872
- throw new Error(`Chrome profile directory not found: ${sourceProfileDir}`);
873
- }
874
-
875
- const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'social-chrome-profile-'));
876
- const localStatePath = path.join(resolvedProfileRoot, 'Local State');
877
- if (fs.existsSync(localStatePath)) {
878
- fs.copyFileSync(localStatePath, path.join(tempRoot, 'Local State'));
879
- }
880
-
881
- const destinationProfileDir = path.join(tempRoot, profileDir);
882
- fs.cpSync(sourceProfileDir, destinationProfileDir, {
883
- recursive: true,
884
- force: true,
885
- filter: (sourcePath) => {
886
- const relativePath = path.relative(sourceProfileDir, sourcePath);
887
- return shouldCopyChromePath(relativePath);
888
- },
889
- });
890
-
891
- return {
892
- tempRoot,
893
- profileDir,
894
- };
895
- }
896
-
897
- function getAvailablePort() {
898
- return new Promise((resolve, reject) => {
899
- const server = net.createServer();
900
- server.listen(0, '127.0.0.1', () => {
901
- const address = server.address();
902
- const port = address && address.port;
903
- server.close((error) => {
904
- if (error) {
905
- reject(error);
906
- return;
907
- }
908
- resolve(port);
909
- });
910
- });
911
- server.on('error', reject);
912
- });
913
- }
914
-
915
- async function waitForChromeCdp(port, timeoutMs = DEFAULT_CHROME_CDP_TIMEOUT_MS) {
916
- const start = Date.now();
917
- while (Date.now() - start < timeoutMs) {
918
- try {
919
- const response = await fetch(`http://127.0.0.1:${port}/json/version`);
920
- if (response.ok) {
921
- return response.json();
922
- }
923
- } catch {
924
- // Keep polling until Chrome exposes CDP.
925
- }
926
- await sleep(250);
927
- }
928
- throw new Error(`Timed out waiting for Chrome DevTools on port ${port}`);
929
- }
930
-
931
- function createAppleScriptBrowserSession() {
932
- return {
933
- name: 'apple-events',
934
- async healthCheck() {
935
- executeChromeJavaScript({
936
- urlPrefix: 'chrome://newtab/',
937
- openUrl: 'chrome://newtab/',
938
- js: 'JSON.stringify({ ok: true, href: location.href })',
939
- });
940
- },
941
- async evaluate(spec) {
942
- return executeChromeJavaScript(spec);
943
- },
944
- async poll(spec) {
945
- return pollChromeState(spec);
946
- },
947
- async screenshot() {
948
- return null;
949
- },
950
- async setInputFiles() {
951
- return null;
952
- },
953
- async clickText({ urlPrefix, openUrl, text }) {
954
- return parseBrowserResult(executeChromeJavaScript({
955
- urlPrefix,
956
- openUrl,
957
- js: buildClickByTextScript(text),
958
- }));
959
- },
960
- async close() {
961
- return null;
962
- },
963
- };
964
- }
965
-
966
- async function createPlaywrightBrowserSession({
967
- chromeBin,
968
- profileRoot = DEFAULT_CHROME_PROFILE_ROOT,
969
- profileDir = DEFAULT_CHROME_PROFILE_DIR,
970
- headless = false,
971
- }) {
972
- const { chromium } = require('playwright-core');
973
- const { tempRoot } = copyChromeProfileForAutomation({
974
- profileRoot,
975
- profileDir,
976
- });
977
- const port = await getAvailablePort();
978
- const chromeArgs = [
979
- `--remote-debugging-port=${port}`,
980
- `--user-data-dir=${tempRoot}`,
981
- `--profile-directory=${profileDir}`,
982
- '--disable-blink-features=AutomationControlled',
983
- '--allow-file-access-from-files',
984
- '--disable-background-networking',
985
- '--no-default-browser-check',
986
- '--no-first-run',
987
- '--no-sandbox',
988
- ];
989
- if (headless) {
990
- chromeArgs.push('--headless=new', '--disable-gpu', '--hide-scrollbars');
991
- }
992
- chromeArgs.push('about:blank');
993
-
994
- const chromeProcess = cp.spawn(chromeBin, chromeArgs, {
995
- stdio: ['ignore', 'ignore', 'pipe'],
996
- });
997
-
998
- let stderr = '';
999
- chromeProcess.stderr.on('data', (chunk) => {
1000
- stderr += chunk.toString('utf8');
1001
- });
1002
-
1003
- let browser = null;
1004
- try {
1005
- await waitForChromeCdp(port);
1006
- browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
1007
- } catch (error) {
1008
- await stopChromeProcess(chromeProcess).catch(() => {});
1009
- await removeDirectoryWithRetries(tempRoot).catch(() => {});
1010
- throw new Error(`Failed to launch copied-profile Chrome automation session: ${error.message}${stderr ? `\n${stderr.trim()}` : ''}`);
1011
- }
1012
- const context = browser.contexts()[0];
1013
- if (!context) {
1014
- await browser.close();
1015
- await stopChromeProcess(chromeProcess).catch(() => {});
1016
- await removeDirectoryWithRetries(tempRoot).catch(() => {});
1017
- throw new Error(`Chrome launched without a CDP context. stderr: ${stderr.trim()}`);
1018
- }
1019
-
1020
- async function getPage({ urlPrefix, openUrl }) {
1021
- let page = context.pages().find((candidate) => candidate.url().startsWith(urlPrefix));
1022
- if (!page) {
1023
- page = await context.newPage();
1024
- await page.goto(openUrl || urlPrefix, {
1025
- waitUntil: 'domcontentloaded',
1026
- });
1027
- } else {
1028
- await page.bringToFront();
1029
- }
1030
- await page.waitForLoadState('domcontentloaded');
1031
- return page;
1032
- }
1033
-
1034
- async function setInputFiles({ urlPrefix, openUrl, files, accept = 'any', multiple = false }) {
1035
- const page = await getPage({ urlPrefix, openUrl });
1036
- const handles = await page.locator('input[type=file]').elementHandles();
1037
- for (const handle of handles) {
1038
- const acceptAttribute = (await handle.getAttribute('accept')) || '';
1039
- const allowsMultiple = (await handle.getAttribute('multiple')) !== null;
1040
- const matchesAccept = accept === 'any' ||
1041
- (accept === 'image' && (/image\//i.test(acceptAttribute) || allowsMultiple)) ||
1042
- (accept === 'video' && /video\//i.test(acceptAttribute));
1043
- const matchesMultiple = !multiple || allowsMultiple;
1044
- if (!matchesAccept || !matchesMultiple) {
1045
- continue;
1046
- }
1047
- await handle.setInputFiles(files);
1048
- return {
1049
- ok: true,
1050
- filesLength: files.length,
1051
- accept: acceptAttribute,
1052
- multiple: allowsMultiple,
1053
- };
1054
- }
1055
- return {
1056
- ok: false,
1057
- reason: 'no-matching-file-input',
1058
- filesLength: 0,
1059
- };
1060
- }
1061
-
1062
- async function clickText({ urlPrefix, openUrl, text }) {
1063
- const page = await getPage({ urlPrefix, openUrl });
1064
- const exactPattern = new RegExp(`^\\s*${escapeRegex(text)}\\s*$`, 'i');
1065
- const locatorCandidates = [
1066
- page.getByRole('button', { name: exactPattern }).first(),
1067
- page.locator('button,[role=button],a').filter({ hasText: exactPattern }).first(),
1068
- ];
1069
-
1070
- for (const locator of locatorCandidates) {
1071
- const count = await locator.count().catch(() => 0);
1072
- if (!count) {
1073
- continue;
1074
- }
1075
- await locator.click();
1076
- return { clicked: true, label: text };
1077
- }
1078
-
1079
- return { clicked: false, label: text };
1080
- }
1081
-
1082
- return {
1083
- name: 'playwright',
1084
- async healthCheck() {
1085
- const page = await getPage({
1086
- urlPrefix: 'chrome://newtab/',
1087
- openUrl: 'chrome://newtab/',
1088
- });
1089
- await page.evaluate(() => document.title);
1090
- },
1091
- async evaluate(spec) {
1092
- const page = await getPage(spec);
1093
- return page.evaluate((script) => window.eval(script), spec.js);
1094
- },
1095
- async poll({ urlPrefix, openUrl, js, timeoutMs = 20000, intervalMs = 1000, isReady }) {
1096
- const start = Date.now();
1097
- while (Date.now() - start < timeoutMs) {
1098
- const parsed = parseBrowserResult(await this.evaluate({ urlPrefix, openUrl, js }));
1099
- if (isReady(parsed)) {
1100
- return parsed;
1101
- }
1102
- await sleep(intervalMs);
1103
- }
1104
- throw new Error(`Timed out waiting for browser state on ${urlPrefix}`);
1105
- },
1106
- async screenshot({ urlPrefix, openUrl, outputPath }) {
1107
- const page = await getPage({ urlPrefix, openUrl });
1108
- ensureDir(path.dirname(outputPath));
1109
- await page.screenshot({ path: outputPath, fullPage: false });
1110
- return outputPath;
1111
- },
1112
- async setInputFiles(spec) {
1113
- return setInputFiles(spec);
1114
- },
1115
- async clickText(spec) {
1116
- return clickText(spec);
1117
- },
1118
- async close() {
1119
- const closeErrors = [];
1120
- try {
1121
- await browser.close();
1122
- } catch (error) {
1123
- closeErrors.push(new Error(`browser.close failed: ${error.message}`));
1124
- }
1125
-
1126
- try {
1127
- await stopChromeProcess(chromeProcess);
1128
- } catch (error) {
1129
- closeErrors.push(new Error(`chromeProcess.kill failed: ${error.message}`));
1130
- }
1131
-
1132
- try {
1133
- await removeDirectoryWithRetries(tempRoot);
1134
- } catch (error) {
1135
- closeErrors.push(new Error(`temp profile cleanup failed: ${error.message}`));
1136
- }
1137
-
1138
- if (closeErrors.length > 0) {
1139
- throw new Error(closeErrors.map((error) => error.message).join('; '));
1140
- }
1141
- },
1142
- };
1143
- }
1144
-
1145
- async function createBrowserSession({
1146
- browserBackend = 'auto',
1147
- chromeBin = resolveChromeBinary(),
1148
- profileRoot = DEFAULT_CHROME_PROFILE_ROOT,
1149
- profileDir = DEFAULT_CHROME_PROFILE_DIR,
1150
- headless = false,
1151
- } = {}) {
1152
- if (browserBackend === 'apple-events') {
1153
- const session = createAppleScriptBrowserSession();
1154
- await session.healthCheck();
1155
- return session;
1156
- }
1157
-
1158
- if (browserBackend === 'playwright') {
1159
- return createPlaywrightBrowserSession({
1160
- chromeBin,
1161
- profileRoot,
1162
- profileDir,
1163
- headless,
1164
- });
1165
- }
1166
-
1167
- const appleEventsSession = createAppleScriptBrowserSession();
1168
- try {
1169
- await appleEventsSession.healthCheck();
1170
- return appleEventsSession;
1171
- } catch {
1172
- return createPlaywrightBrowserSession({
1173
- chromeBin,
1174
- profileRoot,
1175
- profileDir,
1176
- headless,
1177
- });
1178
- }
1179
- }
1180
-
1181
- async function captureAttemptScreenshot(session, attempt, name, spec) {
1182
- if (!attempt || !session || typeof session.screenshot !== 'function') {
1183
- return null;
1184
- }
1185
- const outputPath = path.join(attempt.attemptDir, `${name}.png`);
1186
- try {
1187
- return await session.screenshot({
1188
- ...spec,
1189
- outputPath,
1190
- });
1191
- } catch {
1192
- return null;
1193
- }
1194
- }
1195
-
1196
- function escapeAppleScriptString(value) {
1197
- return `"${String(value)
1198
- .replace(/\\/g, '\\\\')
1199
- .replace(/"/g, '\\"')
1200
- .replace(/\n/g, '\\n')}"`;
1201
- }
1202
-
1203
- function runAppleScript(script) {
1204
- if (process.platform !== 'darwin') {
1205
- throw new Error('Chrome social automation requires macOS and AppleScript.');
1206
- }
1207
-
1208
- return cp.execFileSync('osascript', ['-'], {
1209
- encoding: 'utf8',
1210
- input: script,
1211
- }).trim();
1212
- }
1213
-
1214
- function buildChromeJavaScriptAppleScript({ urlPrefix, openUrl, tempJsPath }) {
1215
- return [
1216
- 'tell application "Google Chrome"',
1217
- ' activate',
1218
- ` set targetPrefix to ${escapeAppleScriptString(urlPrefix)}`,
1219
- ` set openTarget to ${escapeAppleScriptString(openUrl || urlPrefix)}`,
1220
- ' set targetWindow to missing value',
1221
- ' set targetTabIndex to 0',
1222
- ' set targetTab to missing value',
1223
- ' repeat with w in windows',
1224
- ' set currentTabIndex to 1',
1225
- ' repeat with t in tabs of w',
1226
- ' if (URL of t starts with targetPrefix) then',
1227
- ' set targetWindow to w',
1228
- ' set targetTabIndex to currentTabIndex',
1229
- ' exit repeat',
1230
- ' end if',
1231
- ' set currentTabIndex to currentTabIndex + 1',
1232
- ' end repeat',
1233
- ' if targetWindow is not missing value then exit repeat',
1234
- ' end repeat',
1235
- ' if targetWindow is not missing value then',
1236
- ' if (index of targetWindow) is not 1 then set index of targetWindow to 1',
1237
- ' if (active tab index of targetWindow) is not targetTabIndex then set active tab index of targetWindow to targetTabIndex',
1238
- ' set targetTab to active tab of targetWindow',
1239
- ' end if',
1240
- ' if targetTab is missing value then',
1241
- ' if (count of windows) = 0 then make new window',
1242
- ' tell window 1',
1243
- ' set targetTab to make new tab with properties {URL:openTarget}',
1244
- ' set active tab index to index of targetTab',
1245
- ' end tell',
1246
- ' delay 1',
1247
- ' end if',
1248
- ` set jsCode to read POSIX file ${escapeAppleScriptString(tempJsPath)}`,
1249
- ' return execute targetTab javascript jsCode',
1250
- 'end tell',
1251
- ].join('\n');
1252
- }
1253
-
1254
- function executeChromeJavaScript({ urlPrefix, openUrl, js }) {
1255
- const tempJsPath = path.join(
1256
- os.tmpdir(),
1257
- `social-pipeline-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.js`
1258
- );
1259
- writeText(tempJsPath, js);
1260
-
1261
- const appleScript = buildChromeJavaScriptAppleScript({
1262
- urlPrefix,
1263
- openUrl,
1264
- tempJsPath,
1265
- });
1266
-
1267
- try {
1268
- return runAppleScript(appleScript);
1269
- } finally {
1270
- fs.rmSync(tempJsPath, { force: true });
1271
- }
1272
- }
1273
-
1274
- async function pollChromeState({ urlPrefix, openUrl, js, timeoutMs = 20000, intervalMs = 1000, isReady }) {
1275
- const start = Date.now();
1276
- while (Date.now() - start < timeoutMs) {
1277
- const raw = executeChromeJavaScript({ urlPrefix, openUrl, js });
1278
- let parsed = raw;
1279
- try {
1280
- parsed = JSON.parse(raw);
1281
- } catch {
1282
- // Keep raw string if it is not JSON.
1283
- }
1284
- if (isReady(parsed)) {
1285
- return parsed;
1286
- }
1287
- await sleep(intervalMs);
1288
- }
1289
- throw new Error(`Timed out waiting for Chrome state on ${urlPrefix}`);
1290
- }
1291
-
1292
- function buildBrowserUploadScript(filePaths) {
1293
- const files = filePaths.map((filePath) => ({
1294
- name: path.basename(filePath),
1295
- type: mimeTypeForPath(filePath),
1296
- b64: fs.readFileSync(filePath).toString('base64'),
1297
- }));
1298
-
1299
- return `
1300
- (async () => {
1301
- const input = document.querySelector('input[type=file]');
1302
- if (!input) {
1303
- return JSON.stringify({ ok: false, reason: 'no-file-input' });
1304
- }
1305
- const files = ${JSON.stringify(files)};
1306
- const dt = new DataTransfer();
1307
- for (const entry of files) {
1308
- const binary = atob(entry.b64);
1309
- const bytes = new Uint8Array(binary.length);
1310
- for (let index = 0; index < binary.length; index += 1) {
1311
- bytes[index] = binary.charCodeAt(index);
1312
- }
1313
- dt.items.add(new File([bytes], entry.name, { type: entry.type, lastModified: Date.now() }));
1314
- }
1315
- input.files = dt.files;
1316
- input.dispatchEvent(new Event('input', { bubbles: true }));
1317
- input.dispatchEvent(new Event('change', { bubbles: true }));
1318
- await new Promise((resolve) => setTimeout(resolve, 1500));
1319
- return JSON.stringify({
1320
- ok: true,
1321
- filesLength: input.files ? input.files.length : 0,
1322
- body: document.body ? document.body.innerText.slice(0, 2400) : ''
1323
- });
1324
- })()
1325
- `;
1326
- }
1327
-
1328
- const INSTAGRAM_COMPOSER_JS = `
1329
- (() => {
1330
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1331
- if (document.querySelector('input[type=file][multiple]')) {
1332
- return JSON.stringify({ state: 'ready' });
1333
- }
1334
- const post = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^post$/i.test(text(element)));
1335
- if (post) {
1336
- post.click();
1337
- return JSON.stringify({ state: 'clicked-post' });
1338
- }
1339
- const create = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^create$/i.test(text(element)));
1340
- if (create) {
1341
- create.click();
1342
- return JSON.stringify({ state: 'clicked-create' });
1343
- }
1344
- return JSON.stringify({ state: 'waiting', title: document.title });
1345
- })()
1346
- `;
1347
-
1348
- const INSTAGRAM_EDITOR_JS = `
1349
- (() => {
1350
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1351
- const editor = document.querySelector('textarea,[contenteditable=true]');
1352
- const share = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^share$/i.test(text(element)));
1353
- const next = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^next$/i.test(text(element)));
1354
- const cancel = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^cancel$/i.test(text(element)));
1355
- const body = document.body ? document.body.innerText.slice(0, 2400) : '';
1356
- return JSON.stringify({
1357
- hasEditor: Boolean(editor),
1358
- shareVisible: Boolean(share),
1359
- nextVisible: Boolean(next),
1360
- discardModalVisible: Boolean(cancel) && /discard post\?/i.test(body),
1361
- hasError: /something went wrong|try again/i.test(body),
1362
- body,
1363
- });
1364
- })()
1365
- `;
1366
-
1367
- const INSTAGRAM_PREFLIGHT_JS = `
1368
- (() => {
1369
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1370
- const post = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^post$/i.test(text(element)));
1371
- const create = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^create$/i.test(text(element)));
1372
- const multiInput = document.querySelector('input[type=file][multiple]');
1373
- const loginInput = document.querySelector('input[name="username"], input[name="password"], input[autocomplete="username"], input[autocomplete="current-password"]');
1374
- const body = document.body ? document.body.innerText.slice(0, 2400) : '';
1375
- return JSON.stringify({
1376
- url: location.href,
1377
- title: document.title,
1378
- body,
1379
- loggedOut: Boolean(loginInput) || location.pathname.startsWith('/accounts/login'),
1380
- state: multiInput ? 'ready' : post ? 'post-visible' : create ? 'create-visible' : 'waiting',
1381
- });
1382
- })()
1383
- `;
1384
-
1385
- function buildInstagramCaptionScript(caption) {
1386
- return `
1387
- (() => {
1388
- const caption = ${JSON.stringify(caption)};
1389
- const textarea = document.querySelector('textarea');
1390
- if (textarea) {
1391
- textarea.focus();
1392
- textarea.value = caption;
1393
- textarea.dispatchEvent(new Event('input', { bubbles: true }));
1394
- return JSON.stringify({ ok: true, mode: 'textarea' });
1395
- }
1396
- const editor = document.querySelector('[contenteditable=true]');
1397
- if (!editor) {
1398
- return JSON.stringify({ ok: false, reason: 'no-caption-editor' });
1399
- }
1400
- editor.focus();
1401
- document.execCommand('selectAll', false);
1402
- document.execCommand('insertText', false, caption);
1403
- editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: caption }));
1404
- return JSON.stringify({ ok: true, mode: 'contenteditable', text: editor.innerText.slice(0, 400) });
1405
- })()
1406
- `;
1407
- }
1408
-
1409
- function buildContentEditableCaptionScript(caption) {
1410
- return `
1411
- (() => {
1412
- const caption = ${JSON.stringify(caption)};
1413
- const editor = document.querySelector('[contenteditable=true]');
1414
- if (!editor) {
1415
- return JSON.stringify({ ok: false, reason: 'no-editor' });
1416
- }
1417
- editor.focus();
1418
- document.execCommand('selectAll', false);
1419
- document.execCommand('insertText', false, caption);
1420
- editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: caption }));
1421
- return JSON.stringify({ ok: true, text: editor.innerText.slice(0, 400) });
1422
- })()
1423
- `;
1424
- }
1425
-
1426
- const INSTAGRAM_NEXT_JS = `
1427
- (() => {
1428
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1429
- const next = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^next$/i.test(text(element)));
1430
- if (!next) {
1431
- return JSON.stringify({ clicked: false });
1432
- }
1433
- next.click();
1434
- return JSON.stringify({ clicked: true });
1435
- })()
1436
- `;
1437
-
1438
- const INSTAGRAM_DISMISS_DISCARD_MODAL_JS = `
1439
- (() => {
1440
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1441
- const discard = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^discard$/i.test(text(element)));
1442
- if (!discard) {
1443
- return JSON.stringify({ clicked: false });
1444
- }
1445
- discard.click();
1446
- return JSON.stringify({ clicked: true });
1447
- })()
1448
- `;
1449
-
1450
- const INSTAGRAM_SHARE_JS = `
1451
- (() => {
1452
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1453
- const share = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^share$/i.test(text(element)));
1454
- if (!share) {
1455
- return JSON.stringify({ clicked: false });
1456
- }
1457
- share.click();
1458
- return JSON.stringify({ clicked: true });
1459
- })()
1460
- `;
1461
-
1462
- const INSTAGRAM_CLOSE_JS = `
1463
- (() => {
1464
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1465
- const close = [...document.querySelectorAll('button,[role=button],svg')].find((element) => /close/i.test(text(element)));
1466
- if (close && close.closest('button')) {
1467
- close.closest('button').click();
1468
- return JSON.stringify({ closed: true });
1469
- }
1470
- const discard = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^discard$/i.test(text(element)));
1471
- if (discard) {
1472
- discard.click();
1473
- return JSON.stringify({ discarded: true });
1474
- }
1475
- return JSON.stringify({ closed: false });
1476
- })()
1477
- `;
1478
-
1479
- const TIKTOK_READY_JS = `
1480
- (() => {
1481
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1482
- const buttons = [...document.querySelectorAll('button,[role=button],a')];
1483
- const gotIt = buttons.find((element) => /^got it$/i.test(text(element)));
1484
- if (gotIt) {
1485
- gotIt.click();
1486
- }
1487
- const retry = buttons.find((element) => /^retry$/i.test(text(element)));
1488
- if (retry) {
1489
- retry.click();
1490
- return JSON.stringify({ state: 'clicked-retry' });
1491
- }
1492
- const continueButton = buttons.find((element) => /^continue$/i.test(text(element)));
1493
- if (continueButton) {
1494
- continueButton.click();
1495
- return JSON.stringify({ state: 'clicked-continue' });
1496
- }
1497
- if (document.querySelector('[contenteditable=true]')) {
1498
- return JSON.stringify({ state: 'editor-ready' });
1499
- }
1500
- const photoInput = [...document.querySelectorAll('input[type=file]')].find((element) => /image\\//i.test(element.accept || '') || element.multiple);
1501
- if (photoInput) {
1502
- return JSON.stringify({ state: 'photo-upload-ready', accept: photoInput.accept || '', multiple: !!photoInput.multiple });
1503
- }
1504
- const videoInput = [...document.querySelectorAll('input[type=file]')].find((element) => /video\\//i.test(element.accept || ''));
1505
- if (videoInput) {
1506
- return JSON.stringify({ state: 'video-upload-ready', accept: videoInput.accept || '', multiple: !!videoInput.multiple });
1507
- }
1508
- return JSON.stringify({ state: 'waiting', body: document.body ? document.body.innerText.slice(0, 1600) : '' });
1509
- })()
1510
- `;
1511
-
1512
- const TIKTOK_PREFLIGHT_JS = `
1513
- (() => {
1514
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1515
- const body = document.body ? document.body.innerText.slice(0, 2400) : '';
1516
- const loginInput = document.querySelector('input[name="username"], input[type="password"], input[autocomplete="username"], input[autocomplete="current-password"]');
1517
- const buttons = [...document.querySelectorAll('button,[role=button],a')];
1518
- const editor = document.querySelector('[contenteditable=true]');
1519
- const photoInput = [...document.querySelectorAll('input[type=file]')].find((element) => /image\\//i.test(element.accept || '') || element.multiple);
1520
- const videoInput = [...document.querySelectorAll('input[type=file]')].find((element) => /video\\//i.test(element.accept || ''));
1521
- const loginButton = buttons.find((element) => /^(log in|login|sign up)$/i.test(text(element)));
1522
- const state = editor ? 'editor-ready' : photoInput ? 'photo-upload-ready' : videoInput ? 'video-upload-ready' : 'waiting';
1523
- return JSON.stringify({
1524
- url: location.href,
1525
- title: document.title,
1526
- body,
1527
- state,
1528
- accept: (photoInput || videoInput || {}).accept || '',
1529
- multiple: Boolean(photoInput && photoInput.multiple),
1530
- loggedOut: Boolean(loginInput) || (Boolean(loginButton) && !editor && !photoInput && !videoInput),
1531
- });
1532
- })()
1533
- `;
1534
-
1535
- const TIKTOK_FOCUS_EDITOR_JS = `
1536
- (() => {
1537
- const editor = document.querySelector('[contenteditable=true]');
1538
- if (!editor) {
1539
- return JSON.stringify({ ok: false, reason: 'no-editor' });
1540
- }
1541
- editor.focus();
1542
- return JSON.stringify({ ok: true, text: editor.innerText.slice(0, 400) });
1543
- })()
1544
- `;
1545
-
1546
- const TIKTOK_SET_FOLLOWERS_JS = `
1547
- (() => {
1548
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1549
- const buttons = [...document.querySelectorAll('button,[role=button],a,[role=combobox],div')];
1550
- const openControl = buttons.find((element) => /^(followers|friends|only you|only me)$/i.test(text(element)));
1551
- if (!openControl) {
1552
- return JSON.stringify({ state: 'missing-privacy-control' });
1553
- }
1554
- if (/^followers$/i.test(text(openControl))) {
1555
- return JSON.stringify({ state: 'already-followers' });
1556
- }
1557
- openControl.click();
1558
- const option = [...document.querySelectorAll('button,[role=button],a,div,span')].find((element) => /^followers$/i.test(text(element)));
1559
- if (option) {
1560
- option.click();
1561
- return JSON.stringify({ state: 'selected-followers' });
1562
- }
1563
- return JSON.stringify({ state: 'privacy-menu-opened' });
1564
- })()
1565
- `;
1566
-
1567
- const TIKTOK_POST_JS = `
1568
- (() => {
1569
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1570
- const post = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^post$/i.test(text(element)));
1571
- if (!post) {
1572
- return JSON.stringify({ clicked: false });
1573
- }
1574
- post.click();
1575
- return JSON.stringify({ clicked: true });
1576
- })()
1577
- `;
1578
-
1579
- const TIKTOK_DISCARD_JS = `
1580
- (() => {
1581
- const text = (element) => (element.innerText || element.getAttribute('aria-label') || '').trim();
1582
- const discard = [...document.querySelectorAll('button,[role=button],a')].find((element) => /^discard$/i.test(text(element)));
1583
- if (!discard) {
1584
- return JSON.stringify({ discarded: false });
1585
- }
1586
- discard.click();
1587
- return JSON.stringify({ discarded: true });
1588
- })()
1589
- `;
1590
-
1591
- async function preflightInstagramSession(session, attempt = null) {
1592
- const state = await session.poll({
1593
- urlPrefix: INSTAGRAM_URL,
1594
- openUrl: INSTAGRAM_URL,
1595
- js: INSTAGRAM_PREFLIGHT_JS,
1596
- isReady: (value) => value && (value.loggedOut || typeof value.body === 'string'),
1597
- });
1598
- if (attempt) {
1599
- writePublishAttemptRecord(attempt.recordPath, {
1600
- attemptId: attempt.attemptId,
1601
- platform: 'instagram',
1602
- status: 'preflight',
1603
- recordedAt: new Date().toISOString(),
1604
- state,
1605
- });
1606
- }
1607
- if (state.loggedOut) {
1608
- throw new Error('Instagram session unavailable in the selected Chrome profile.');
1609
- }
1610
- return state;
1611
- }
1612
-
1613
- async function preflightTikTokSession(session, attempt = null) {
1614
- const startedAt = new Date().toISOString();
1615
- try {
1616
- const state = await session.poll({
1617
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1618
- openUrl: TIKTOK_UPLOAD_URL,
1619
- js: TIKTOK_PREFLIGHT_JS,
1620
- isReady: (value) => value && (
1621
- value.loggedOut ||
1622
- value.state === 'editor-ready' ||
1623
- value.state === 'photo-upload-ready' ||
1624
- value.state === 'video-upload-ready'
1625
- ),
1626
- });
1627
- if (attempt) {
1628
- writePublishAttemptRecord(attempt.recordPath, {
1629
- attemptId: attempt.attemptId,
1630
- platform: 'tiktok',
1631
- status: 'preflight',
1632
- recordedAt: new Date().toISOString(),
1633
- state,
1634
- });
1635
- }
1636
- if (state.loggedOut) {
1637
- throw new Error('TikTok session unavailable in the selected Chrome profile.');
1638
- }
1639
- return state;
1640
- } catch (error) {
1641
- let fallbackState = null;
1642
- const timedOut = /Timed out waiting for browser state/.test(error.message || '');
1643
- try {
1644
- fallbackState = parseBrowserResult(await session.evaluate({
1645
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1646
- openUrl: TIKTOK_UPLOAD_URL,
1647
- js: TIKTOK_PREFLIGHT_JS,
1648
- }));
1649
- } catch {
1650
- // Preserve the original error if the page is unavailable.
1651
- }
1652
-
1653
- if (attempt) {
1654
- writePublishAttemptRecord(attempt.recordPath, {
1655
- attemptId: attempt.attemptId,
1656
- platform: 'tiktok',
1657
- status: timedOut ? 'preflight-timeout' : 'preflight-failed',
1658
- recordedAt: new Date().toISOString(),
1659
- startedAt,
1660
- error: error.message,
1661
- state: fallbackState,
1662
- });
1663
- }
1664
-
1665
- if (fallbackState && fallbackState.loggedOut) {
1666
- throw new Error('TikTok session unavailable in the selected Chrome profile.');
1667
- }
1668
-
1669
- if (fallbackState) {
1670
- throw new Error(`TikTok did not reach an authenticated upload surface: ${JSON.stringify(timedOut ? fallbackState : {
1671
- url: fallbackState.url,
1672
- title: fallbackState.title,
1673
- state: fallbackState.state,
1674
- body: fallbackState.body,
1675
- })}`);
1676
- }
1677
-
1678
- if (timedOut) {
1679
- throw new Error(`TikTok did not reach an authenticated upload surface: ${JSON.stringify({ error: error.message })}`);
1680
- }
1681
-
1682
- throw error;
1683
- }
1684
- }
1685
-
1686
- async function prepareInstagramDraft(bundle, session, { dryRun = false, attempt = null }) {
1687
- const instagramAssets = bundle.platforms.instagram.assetPaths;
1688
- if (!instagramAssets || instagramAssets.length === 0) {
1689
- throw new Error('Instagram publish requires slide image assets.');
1690
- }
1691
-
1692
- if (dryRun) {
1693
- return {
1694
- platform: 'instagram',
1695
- mode: 'dry-run',
1696
- assetCount: instagramAssets.length,
1697
- };
1698
- }
1699
-
1700
- await session.poll({
1701
- urlPrefix: INSTAGRAM_URL,
1702
- openUrl: INSTAGRAM_URL,
1703
- js: INSTAGRAM_COMPOSER_JS,
1704
- isReady: (state) => state && state.state === 'ready',
1705
- });
1706
-
1707
- const uploadState = session.setInputFiles
1708
- ? await session.setInputFiles({
1709
- urlPrefix: INSTAGRAM_URL,
1710
- openUrl: INSTAGRAM_URL,
1711
- files: instagramAssets,
1712
- accept: 'image',
1713
- multiple: true,
1714
- })
1715
- : parseBrowserResult(await session.evaluate({
1716
- urlPrefix: INSTAGRAM_URL,
1717
- openUrl: INSTAGRAM_URL,
1718
- js: buildBrowserUploadScript(instagramAssets),
1719
- }));
1720
-
1721
- if (!uploadState.ok || uploadState.filesLength !== instagramAssets.length) {
1722
- throw new Error(`Instagram upload failed: ${JSON.stringify(uploadState)}`);
1723
- }
1724
- if (attempt) {
1725
- appendPublishAttemptEvent(attempt.recordPath, {
1726
- platform: 'instagram',
1727
- type: 'upload-complete',
1728
- recordedAt: new Date().toISOString(),
1729
- uploadState,
1730
- });
1731
- }
1732
- await captureAttemptScreenshot(session, attempt, 'instagram-uploaded', {
1733
- urlPrefix: INSTAGRAM_URL,
1734
- openUrl: INSTAGRAM_URL,
1735
- });
1736
-
1737
- await sleep(5000);
1738
-
1739
- let editorState = null;
1740
- const editorStepStates = [];
1741
- for (let index = 0; index < 5; index += 1) {
1742
- editorState = parseBrowserResult(await session.evaluate({
1743
- urlPrefix: INSTAGRAM_URL,
1744
- openUrl: INSTAGRAM_URL,
1745
- js: INSTAGRAM_EDITOR_JS,
1746
- }));
1747
- const stepState = {
1748
- step: index + 1,
1749
- recordedAt: new Date().toISOString(),
1750
- state: editorState,
1751
- };
1752
- editorStepStates.push(stepState);
1753
- if (attempt) {
1754
- appendPublishAttemptEvent(attempt.recordPath, {
1755
- platform: 'instagram',
1756
- type: 'editor-state',
1757
- ...stepState,
1758
- });
1759
- }
1760
- if (editorState.hasEditor || editorState.shareVisible) {
1761
- break;
1762
- }
1763
- if (editorState.discardModalVisible) {
1764
- await session.evaluate({
1765
- urlPrefix: INSTAGRAM_URL,
1766
- openUrl: INSTAGRAM_URL,
1767
- js: INSTAGRAM_DISMISS_DISCARD_MODAL_JS,
1768
- });
1769
- if (attempt) {
1770
- appendPublishAttemptEvent(attempt.recordPath, {
1771
- platform: 'instagram',
1772
- type: 'editor-discard-dismissed',
1773
- recordedAt: new Date().toISOString(),
1774
- step: index + 1,
1775
- });
1776
- }
1777
- await sleep(750);
1778
- continue;
1779
- }
1780
- if (editorState.hasError) {
1781
- break;
1782
- }
1783
- if (!editorState.nextVisible) {
1784
- await sleep(2000);
1785
- continue;
1786
- }
1787
- const clickState = session.clickText
1788
- ? await session.clickText({
1789
- urlPrefix: INSTAGRAM_URL,
1790
- openUrl: INSTAGRAM_URL,
1791
- text: 'Next',
1792
- })
1793
- : parseBrowserResult(await session.evaluate({
1794
- urlPrefix: INSTAGRAM_URL,
1795
- openUrl: INSTAGRAM_URL,
1796
- js: INSTAGRAM_NEXT_JS,
1797
- }));
1798
- if (attempt) {
1799
- appendPublishAttemptEvent(attempt.recordPath, {
1800
- platform: 'instagram',
1801
- type: 'editor-next-click',
1802
- recordedAt: new Date().toISOString(),
1803
- step: index + 1,
1804
- clickState,
1805
- });
1806
- }
1807
- await captureAttemptScreenshot(session, attempt, `instagram-step-${index + 1}`, {
1808
- urlPrefix: INSTAGRAM_URL,
1809
- openUrl: INSTAGRAM_URL,
1810
- });
1811
- await sleep(4000);
1812
- }
1813
-
1814
- if (!editorState || (!editorState.hasEditor && !editorState.shareVisible)) {
1815
- if (attempt) {
1816
- writePublishAttemptRecord(attempt.recordPath, {
1817
- attemptId: attempt.attemptId,
1818
- platform: 'instagram',
1819
- status: editorState && editorState.hasError ? 'editor-error' : 'editor-timeout',
1820
- recordedAt: new Date().toISOString(),
1821
- uploadState,
1822
- editorState,
1823
- editorStepStates,
1824
- events: readJson(attempt.recordPath, {}).events || [],
1825
- });
1826
- }
1827
- throw new Error(`Instagram editor did not become ready: ${JSON.stringify(editorState)}`);
1828
- }
1829
-
1830
- const caption = readText(bundle.instagramCaptionPath).trim();
1831
- const captionState = parseBrowserResult(await session.evaluate({
1832
- urlPrefix: INSTAGRAM_URL,
1833
- openUrl: INSTAGRAM_URL,
1834
- js: buildInstagramCaptionScript(caption),
1835
- }));
1836
-
1837
- if (!captionState.ok) {
1838
- throw new Error(`Instagram caption write failed: ${JSON.stringify(captionState)}`);
1839
- }
1840
- await captureAttemptScreenshot(session, attempt, 'instagram-draft-ready', {
1841
- urlPrefix: INSTAGRAM_URL,
1842
- openUrl: INSTAGRAM_URL,
1843
- });
1844
-
1845
- const result = {
1846
- platform: 'instagram',
1847
- mode: 'draft-ready',
1848
- assetCount: instagramAssets.length,
1849
- };
1850
- if (attempt) {
1851
- writePublishAttemptRecord(attempt.recordPath, {
1852
- attemptId: attempt.attemptId,
1853
- platform: 'instagram',
1854
- status: 'draft-ready',
1855
- recordedAt: new Date().toISOString(),
1856
- uploadState,
1857
- captionState,
1858
- result,
1859
- });
1860
- }
1861
- return result;
1862
- }
1863
-
1864
- async function publishInstagram(bundle, session, { dryRun = false, noShare = false, attempt = null }) {
1865
- const draftState = await prepareInstagramDraft(bundle, session, { dryRun, attempt });
1866
- if (dryRun || noShare) {
1867
- return draftState;
1868
- }
1869
-
1870
- const shareState = session.clickText
1871
- ? await session.clickText({
1872
- urlPrefix: INSTAGRAM_URL,
1873
- openUrl: INSTAGRAM_URL,
1874
- text: 'Share',
1875
- })
1876
- : parseBrowserResult(await session.evaluate({
1877
- urlPrefix: INSTAGRAM_URL,
1878
- openUrl: INSTAGRAM_URL,
1879
- js: INSTAGRAM_SHARE_JS,
1880
- }));
1881
-
1882
- if (!shareState.clicked) {
1883
- throw new Error('Instagram share button was not available.');
1884
- }
1885
-
1886
- await sleep(4000);
1887
- const confirmationState = parseBrowserResult(await session.evaluate({
1888
- urlPrefix: INSTAGRAM_URL,
1889
- openUrl: INSTAGRAM_URL,
1890
- js: `(() => JSON.stringify({
1891
- url: location.href,
1892
- title: document.title,
1893
- body: document.body ? document.body.innerText.slice(0, 800) : ''
1894
- }))()`,
1895
- }));
1896
- await captureAttemptScreenshot(session, attempt, 'instagram-published', {
1897
- urlPrefix: INSTAGRAM_URL,
1898
- openUrl: INSTAGRAM_URL,
1899
- });
1900
- const result = {
1901
- platform: 'instagram',
1902
- mode: 'published',
1903
- finalUrl: confirmationState.url,
1904
- confirmationState,
1905
- };
1906
- if (attempt) {
1907
- writePublishAttemptRecord(attempt.recordPath, {
1908
- attemptId: attempt.attemptId,
1909
- platform: 'instagram',
1910
- status: 'published',
1911
- recordedAt: new Date().toISOString(),
1912
- shareState,
1913
- result,
1914
- });
1915
- }
1916
- return result;
1917
- }
1918
-
1919
- async function cleanupInstagramDraft(session) {
1920
- await session.evaluate({
1921
- urlPrefix: INSTAGRAM_URL,
1922
- openUrl: INSTAGRAM_URL,
1923
- js: INSTAGRAM_CLOSE_JS,
1924
- });
1925
- await sleep(500);
1926
- await session.evaluate({
1927
- urlPrefix: INSTAGRAM_URL,
1928
- openUrl: INSTAGRAM_URL,
1929
- js: INSTAGRAM_CLOSE_JS,
1930
- });
1931
- }
1932
-
1933
- async function prepareTikTokDraft(bundle, session, {
1934
- dryRun = false,
1935
- attempt = null,
1936
- readyState = { state: 'video-upload-ready' },
1937
- } = {}) {
1938
- const previewTarget = resolveTikTokPublishTarget(bundle, readyState);
1939
- if (dryRun) {
1940
- return {
1941
- platform: 'tiktok',
1942
- mode: 'dry-run',
1943
- publishType: previewTarget.type,
1944
- assetPaths: previewTarget.assetPaths,
1945
- };
1946
- }
1947
-
1948
- await session.poll({
1949
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1950
- openUrl: TIKTOK_UPLOAD_URL,
1951
- js: TIKTOK_READY_JS,
1952
- isReady: (state) => state && (
1953
- state.state === 'photo-upload-ready' ||
1954
- state.state === 'video-upload-ready' ||
1955
- state.state === 'editor-ready'
1956
- ),
1957
- });
1958
-
1959
- const freshReadyState = parseBrowserResult(await session.evaluate({
1960
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1961
- openUrl: TIKTOK_UPLOAD_URL,
1962
- js: TIKTOK_READY_JS,
1963
- }));
1964
- const target = resolveTikTokPublishTarget(bundle, freshReadyState);
1965
-
1966
- if (freshReadyState.state !== 'editor-ready') {
1967
- const uploadState = session.setInputFiles
1968
- ? await session.setInputFiles({
1969
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1970
- openUrl: TIKTOK_UPLOAD_URL,
1971
- files: target.assetPaths,
1972
- accept: target.type === 'photo-carousel' ? 'image' : 'video',
1973
- multiple: target.type === 'photo-carousel',
1974
- })
1975
- : parseBrowserResult(await session.evaluate({
1976
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1977
- openUrl: TIKTOK_UPLOAD_URL,
1978
- js: buildBrowserUploadScript(target.assetPaths),
1979
- }));
1980
- if (!uploadState.ok || uploadState.filesLength !== target.assetPaths.length) {
1981
- throw new Error(`TikTok upload failed: ${JSON.stringify(uploadState)}`);
1982
- }
1983
- await captureAttemptScreenshot(session, attempt, 'tiktok-uploaded', {
1984
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
1985
- openUrl: TIKTOK_UPLOAD_URL,
1986
- });
1987
- if (attempt) {
1988
- writePublishAttemptRecord(attempt.recordPath, {
1989
- attemptId: attempt.attemptId,
1990
- platform: 'tiktok',
1991
- status: 'upload-complete',
1992
- recordedAt: new Date().toISOString(),
1993
- readyState: freshReadyState,
1994
- uploadState,
1995
- target,
1996
- });
1997
- }
1998
- }
1999
-
2000
- await session.poll({
2001
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2002
- openUrl: TIKTOK_UPLOAD_URL,
2003
- js: TIKTOK_READY_JS,
2004
- isReady: (state) => state && state.state === 'editor-ready',
2005
- });
2006
-
2007
- await session.evaluate({
2008
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2009
- openUrl: TIKTOK_UPLOAD_URL,
2010
- js: TIKTOK_FOCUS_EDITOR_JS,
2011
- });
2012
- const captionState = parseBrowserResult(await session.evaluate({
2013
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2014
- openUrl: TIKTOK_UPLOAD_URL,
2015
- js: buildContentEditableCaptionScript(readText(bundle.tiktokCaptionPath).trim()),
2016
- }));
2017
- if (!captionState.ok) {
2018
- throw new Error(`TikTok caption write failed: ${JSON.stringify(captionState)}`);
2019
- }
2020
-
2021
- await session.evaluate({
2022
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2023
- openUrl: TIKTOK_UPLOAD_URL,
2024
- js: TIKTOK_SET_FOLLOWERS_JS,
2025
- });
2026
- await captureAttemptScreenshot(session, attempt, 'tiktok-draft-ready', {
2027
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2028
- openUrl: TIKTOK_UPLOAD_URL,
2029
- });
2030
-
2031
- const result = {
2032
- platform: 'tiktok',
2033
- mode: 'draft-ready',
2034
- publishType: target.type,
2035
- assetPaths: target.assetPaths,
2036
- };
2037
- if (attempt) {
2038
- writePublishAttemptRecord(attempt.recordPath, {
2039
- attemptId: attempt.attemptId,
2040
- platform: 'tiktok',
2041
- status: 'draft-ready',
2042
- recordedAt: new Date().toISOString(),
2043
- readyState: freshReadyState,
2044
- captionState,
2045
- result,
2046
- });
2047
- }
2048
- return result;
2049
- }
2050
-
2051
- async function publishTikTok(bundle, session, {
2052
- dryRun = false,
2053
- noShare = false,
2054
- attempt = null,
2055
- readyState = { state: 'video-upload-ready' },
2056
- } = {}) {
2057
- const draftState = await prepareTikTokDraft(bundle, session, { dryRun, attempt, readyState });
2058
- if (dryRun || noShare) {
2059
- return draftState;
2060
- }
2061
-
2062
- const postState = parseBrowserResult(await session.evaluate({
2063
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2064
- openUrl: TIKTOK_UPLOAD_URL,
2065
- js: TIKTOK_POST_JS,
2066
- }));
2067
-
2068
- if (!postState.clicked) {
2069
- throw new Error('TikTok post button was not available.');
2070
- }
2071
-
2072
- await session.poll({
2073
- urlPrefix: TIKTOK_CONTENT_URL,
2074
- openUrl: TIKTOK_CONTENT_URL,
2075
- js: `
2076
- (() => JSON.stringify({
2077
- url: location.href,
2078
- body: document.body ? document.body.innerText.slice(0, 2600) : ''
2079
- }))()
2080
- `,
2081
- timeoutMs: 30000,
2082
- intervalMs: 2000,
2083
- isReady: (state) => state && typeof state.body === 'string' && state.body.includes(bundle.id.split('-').join(' ')) === false
2084
- ? state.body.includes('Followers') && state.body.includes(readText(bundle.tiktokCaptionPath).trim().slice(0, 60))
2085
- : state && typeof state.body === 'string' && state.body.includes(readText(bundle.tiktokCaptionPath).trim().slice(0, 60)),
2086
- });
2087
-
2088
- const confirmationState = parseBrowserResult(await session.evaluate({
2089
- urlPrefix: TIKTOK_CONTENT_URL,
2090
- openUrl: TIKTOK_CONTENT_URL,
2091
- js: `
2092
- (() => JSON.stringify({
2093
- url: location.href,
2094
- title: document.title,
2095
- body: document.body ? document.body.innerText.slice(0, 2400) : ''
2096
- }))()
2097
- `,
2098
- }));
2099
- await captureAttemptScreenshot(session, attempt, 'tiktok-published', {
2100
- urlPrefix: TIKTOK_CONTENT_URL,
2101
- openUrl: TIKTOK_CONTENT_URL,
2102
- });
2103
- const result = {
2104
- platform: 'tiktok',
2105
- mode: 'published',
2106
- publishType: draftState.publishType,
2107
- finalUrl: confirmationState.url,
2108
- confirmationState,
2109
- };
2110
- if (attempt) {
2111
- writePublishAttemptRecord(attempt.recordPath, {
2112
- attemptId: attempt.attemptId,
2113
- platform: 'tiktok',
2114
- status: 'published',
2115
- recordedAt: new Date().toISOString(),
2116
- postState,
2117
- result,
2118
- });
2119
- }
2120
- return result;
2121
- }
2122
-
2123
- async function cleanupTikTokDraft(session) {
2124
- await session.evaluate({
2125
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2126
- openUrl: TIKTOK_UPLOAD_URL,
2127
- js: TIKTOK_DISCARD_JS,
2128
- });
2129
- }
2130
-
2131
- async function publishBundle(bundlePath, options = {}) {
2132
- const bundle = readJson(bundlePath, null);
2133
- if (!bundle) {
2134
- throw new Error(`Bundle manifest not found: ${bundlePath}`);
2135
- }
2136
-
2137
- const platformSet = new Set(
2138
- String(options.platforms || 'instagram,tiktok')
2139
- .split(',')
2140
- .map((value) => value.trim())
2141
- .filter(Boolean)
2142
- );
2143
-
2144
- const historyPath = options.historyPath || DEFAULT_HISTORY_PATH;
2145
- const attempts = {};
2146
- const fingerprints = {};
2147
- const completedPlatforms = new Set();
2148
- const results = [];
2149
- let session = null;
2150
- let publishError = null;
2151
-
2152
- if (platformSet.has('instagram')) {
2153
- attempts.instagram = createPublishAttempt(bundle, 'instagram');
2154
- fingerprints.instagram = buildPublishFingerprint({
2155
- platform: 'instagram',
2156
- captionText: readText(bundle.instagramCaptionPath).trim(),
2157
- assetPaths: bundle.platforms.instagram.assetPaths,
2158
- });
2159
- writePublishAttemptRecord(attempts.instagram.recordPath, {
2160
- attemptId: attempts.instagram.attemptId,
2161
- platform: 'instagram',
2162
- status: 'started',
2163
- fingerprint: fingerprints.instagram,
2164
- recordedAt: new Date().toISOString(),
2165
- });
2166
- }
2167
-
2168
- if (platformSet.has('tiktok')) {
2169
- attempts.tiktok = createPublishAttempt(bundle, 'tiktok');
2170
- fingerprints.tiktok = buildPublishFingerprint({
2171
- platform: 'tiktok',
2172
- captionText: readText(bundle.tiktokCaptionPath).trim(),
2173
- assetPaths: bundle.platforms.tiktok.photoAssetPaths || bundle.slideImagePaths || [],
2174
- });
2175
- writePublishAttemptRecord(attempts.tiktok.recordPath, {
2176
- attemptId: attempts.tiktok.attemptId,
2177
- platform: 'tiktok',
2178
- status: 'started',
2179
- fingerprint: fingerprints.tiktok,
2180
- recordedAt: new Date().toISOString(),
2181
- });
2182
- }
2183
-
2184
- if (!options.force && !options.dryRun && !options.noShare) {
2185
- if (platformSet.has('instagram')) {
2186
- assertPublishNotDuplicated({
2187
- historyPath,
2188
- fingerprint: fingerprints.instagram,
2189
- platform: 'instagram',
2190
- });
2191
- }
2192
- if (platformSet.has('tiktok')) {
2193
- assertPublishNotDuplicated({
2194
- historyPath,
2195
- fingerprint: fingerprints.tiktok,
2196
- platform: 'tiktok',
2197
- });
2198
- }
2199
- }
2200
-
2201
- if (options.dryRun) {
2202
- if (platformSet.has('instagram')) {
2203
- results.push({
2204
- platform: 'instagram',
2205
- mode: 'dry-run',
2206
- assetCount: bundle.platforms.instagram.assetPaths.length,
2207
- });
2208
- }
2209
- if (platformSet.has('tiktok')) {
2210
- const previewTarget = resolveTikTokPublishTarget(bundle, { state: 'video-upload-ready' });
2211
- results.push({
2212
- platform: 'tiktok',
2213
- mode: 'dry-run',
2214
- publishType: previewTarget.type,
2215
- assetPaths: previewTarget.assetPaths,
2216
- });
2217
- }
2218
- return results;
2219
- }
2220
-
2221
- try {
2222
- session = await createBrowserSession({
2223
- browserBackend: options.browserBackend || 'auto',
2224
- chromeBin: options.chromeBin || resolveChromeBinary(),
2225
- profileRoot: options.profileRoot || DEFAULT_CHROME_PROFILE_ROOT,
2226
- profileDir: options.profileDir || DEFAULT_CHROME_PROFILE_DIR,
2227
- headless: Boolean(options.headless),
2228
- });
2229
-
2230
- const preflightState = {};
2231
- if (platformSet.has('instagram')) {
2232
- preflightState.instagram = await preflightInstagramSession(session, attempts.instagram);
2233
- await captureAttemptScreenshot(session, attempts.instagram, 'instagram-preflight', {
2234
- urlPrefix: INSTAGRAM_URL,
2235
- openUrl: INSTAGRAM_URL,
2236
- });
2237
- }
2238
- if (platformSet.has('tiktok')) {
2239
- preflightState.tiktok = await preflightTikTokSession(session, attempts.tiktok);
2240
- await captureAttemptScreenshot(session, attempts.tiktok, 'tiktok-preflight', {
2241
- urlPrefix: 'https://www.tiktok.com/tiktokstudio/',
2242
- openUrl: TIKTOK_UPLOAD_URL,
2243
- });
2244
- }
2245
-
2246
- if (platformSet.has('instagram')) {
2247
- const result = await publishInstagram(bundle, session, { ...options, attempt: attempts.instagram });
2248
- appendJsonLine(historyPath, {
2249
- platform: 'instagram',
2250
- bundleId: bundle.id,
2251
- fingerprint: fingerprints.instagram,
2252
- status: result.mode,
2253
- publishedAt: new Date().toISOString(),
2254
- attemptId: attempts.instagram.attemptId,
2255
- attemptDir: attempts.instagram.attemptDir,
2256
- finalUrl: result.finalUrl || null,
2257
- browserBackend: session.name,
2258
- });
2259
- completedPlatforms.add('instagram');
2260
- results.push(result);
2261
- }
2262
-
2263
- if (platformSet.has('tiktok')) {
2264
- const result = await publishTikTok(bundle, session, {
2265
- ...options,
2266
- attempt: attempts.tiktok,
2267
- readyState: preflightState.tiktok,
2268
- });
2269
- appendJsonLine(historyPath, {
2270
- platform: 'tiktok',
2271
- bundleId: bundle.id,
2272
- fingerprint: fingerprints.tiktok,
2273
- status: result.mode,
2274
- publishType: result.publishType || null,
2275
- publishedAt: new Date().toISOString(),
2276
- attemptId: attempts.tiktok.attemptId,
2277
- attemptDir: attempts.tiktok.attemptDir,
2278
- finalUrl: result.finalUrl || null,
2279
- browserBackend: session.name,
2280
- });
2281
- completedPlatforms.add('tiktok');
2282
- results.push(result);
2283
- }
2284
-
2285
- if (options.noShare && options.cleanupDrafts && !options.dryRun) {
2286
- if (platformSet.has('instagram')) {
2287
- await cleanupInstagramDraft(session);
2288
- }
2289
- if (platformSet.has('tiktok')) {
2290
- await cleanupTikTokDraft(session);
2291
- }
2292
- }
2293
-
2294
- return results;
2295
- } catch (error) {
2296
- publishError = error;
2297
- if (platformSet.has('instagram') && !completedPlatforms.has('instagram')) {
2298
- appendJsonLine(historyPath, {
2299
- platform: 'instagram',
2300
- bundleId: bundle.id,
2301
- fingerprint: fingerprints.instagram || null,
2302
- status: 'failed',
2303
- publishedAt: new Date().toISOString(),
2304
- attemptId: attempts.instagram ? attempts.instagram.attemptId : null,
2305
- attemptDir: attempts.instagram ? attempts.instagram.attemptDir : null,
2306
- browserBackend: session ? session.name : options.browserBackend || 'auto',
2307
- error: error.message,
2308
- });
2309
- }
2310
- if (platformSet.has('tiktok') && !completedPlatforms.has('tiktok')) {
2311
- appendJsonLine(historyPath, {
2312
- platform: 'tiktok',
2313
- bundleId: bundle.id,
2314
- fingerprint: fingerprints.tiktok || null,
2315
- status: 'failed',
2316
- publishedAt: new Date().toISOString(),
2317
- attemptId: attempts.tiktok ? attempts.tiktok.attemptId : null,
2318
- attemptDir: attempts.tiktok ? attempts.tiktok.attemptDir : null,
2319
- browserBackend: session ? session.name : options.browserBackend || 'auto',
2320
- error: error.message,
2321
- });
2322
- }
2323
- throw error;
2324
- } finally {
2325
- if (session) {
2326
- try {
2327
- await session.close();
2328
- } catch (closeError) {
2329
- if (!publishError) {
2330
- throw closeError;
2331
- }
2332
- console.error(`[social-pipeline] session cleanup warning: ${closeError.message}`);
2333
- }
2334
- }
2335
- }
2336
- }
2337
-
2338
- async function publishDueQueueEntries({
2339
- queuePath = DEFAULT_QUEUE_PATH,
2340
- historyPath = DEFAULT_HISTORY_PATH,
2341
- dryRun = false,
2342
- noShare = false,
2343
- cleanupDrafts = false,
2344
- force = false,
2345
- browserBackend = 'auto',
2346
- profileRoot = DEFAULT_CHROME_PROFILE_ROOT,
2347
- profileDir = DEFAULT_CHROME_PROFILE_DIR,
2348
- headless = false,
2349
- now = new Date(),
2350
- }) {
2351
- const queueState = loadQueueState(queuePath);
2352
- const dueEntries = getDueEntries(queueState, now);
2353
- const results = [];
2354
-
2355
- for (const entry of dueEntries) {
2356
- try {
2357
- const publishResults = await publishBundle(entry.bundlePath, {
2358
- platforms: entry.platforms.join(','),
2359
- historyPath,
2360
- dryRun,
2361
- noShare,
2362
- cleanupDrafts,
2363
- force,
2364
- browserBackend,
2365
- profileRoot,
2366
- profileDir,
2367
- headless,
2368
- });
2369
- entry.status = dryRun || noShare ? 'prepared' : 'published';
2370
- entry.publishedAt = new Date().toISOString();
2371
- entry.attempts.push({
2372
- at: entry.publishedAt,
2373
- ok: true,
2374
- results: publishResults,
2375
- });
2376
- results.push({ entry, publishResults });
2377
- } catch (error) {
2378
- entry.status = 'failed';
2379
- entry.attempts.push({
2380
- at: new Date().toISOString(),
2381
- ok: false,
2382
- error: error.message,
2383
- });
2384
- results.push({ entry, error: error.message });
2385
- }
2386
- }
2387
-
2388
- saveQueueState(queuePath, queueState);
2389
- return results;
2390
- }
2391
-
2392
- function buildLaunchAgentPlist({
2393
- label = DEFAULT_LAUNCHD_LABEL,
2394
- repoRoot = REPO_ROOT,
2395
- queuePath = DEFAULT_QUEUE_PATH,
2396
- intervalMinutes = DEFAULT_SCHEDULE_INTERVAL_MINUTES,
2397
- nodeBin = process.execPath,
2398
- scriptPath = path.join(REPO_ROOT, 'scripts', 'social-pipeline.js'),
2399
- }) {
2400
- const intervalSeconds = Number(intervalMinutes) * 60;
2401
- return `<?xml version="1.0" encoding="UTF-8"?>
2402
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2403
- <plist version="1.0">
2404
- <dict>
2405
- <key>Label</key>
2406
- <string>${label}</string>
2407
- <key>ProgramArguments</key>
2408
- <array>
2409
- <string>${nodeBin}</string>
2410
- <string>${scriptPath}</string>
2411
- <string>publish-queue</string>
2412
- <string>--queue</string>
2413
- <string>${queuePath}</string>
2414
- </array>
2415
- <key>WorkingDirectory</key>
2416
- <string>${repoRoot}</string>
2417
- <key>StartInterval</key>
2418
- <integer>${intervalSeconds}</integer>
2419
- <key>RunAtLoad</key>
2420
- <true/>
2421
- <key>StandardOutPath</key>
2422
- <string>${path.join(repoRoot, '.artifacts', 'social', 'launchd.stdout.log')}</string>
2423
- <key>StandardErrorPath</key>
2424
- <string>${path.join(repoRoot, '.artifacts', 'social', 'launchd.stderr.log')}</string>
2425
- </dict>
2426
- </plist>
2427
- `;
2428
- }
2429
-
2430
- function installLaunchAgent({
2431
- label = DEFAULT_LAUNCHD_LABEL,
2432
- intervalMinutes = DEFAULT_SCHEDULE_INTERVAL_MINUTES,
2433
- queuePath = DEFAULT_QUEUE_PATH,
2434
- dryRun = false,
2435
- }) {
2436
- const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${label}.plist`);
2437
- const plist = buildLaunchAgentPlist({
2438
- label,
2439
- intervalMinutes,
2440
- queuePath,
2441
- });
2442
-
2443
- if (dryRun) {
2444
- return { plistPath, plist };
2445
- }
2446
-
2447
- writeText(plistPath, plist);
2448
- try {
2449
- cp.execFileSync('launchctl', ['unload', plistPath], { stdio: 'ignore' });
2450
- } catch {
2451
- // Ignore if not loaded yet.
2452
- }
2453
- cp.execFileSync('launchctl', ['load', '-w', plistPath], { stdio: 'ignore' });
2454
- return { plistPath, plist };
2455
- }
2456
-
2457
- async function main(argv = process.argv.slice(2)) {
2458
- const args = parseArgs(argv);
2459
- const command = args._[0] || 'status';
2460
-
2461
- if (command === 'prepare') {
2462
- const sourceHtmlPath = resolvePath(args.source, DEFAULT_ASSET_HTML);
2463
- const outputDir = resolvePath(args.output, path.join(DEFAULT_OUTPUT_ROOT, slugify(args.slug || 'pre-action-gates')));
2464
- const { manifestPath, manifest } = prepareBundle({
2465
- sourceHtmlPath,
2466
- captionPath: resolvePath(args.caption, DEFAULT_CAPTION_PATH),
2467
- captionText: args['caption-text'],
2468
- outputDir,
2469
- slug: args.slug || 'pre-action-gates',
2470
- slideDurationSeconds: Number(args['slide-seconds'] || 2.4),
2471
- dryRun: Boolean(args['dry-run']),
2472
- });
2473
- console.log(JSON.stringify({ manifestPath, manifest }, null, 2));
2474
- return;
2475
- }
2476
-
2477
- if (command === 'post') {
2478
- const sourceHtmlPath = resolvePath(args.source, DEFAULT_ASSET_HTML);
2479
- const slug = args.slug || path.basename(sourceHtmlPath, path.extname(sourceHtmlPath));
2480
- const outputDir = resolvePath(args.output, path.join(DEFAULT_OUTPUT_ROOT, slugify(slug)));
2481
- const { manifestPath, manifest } = prepareBundle({
2482
- sourceHtmlPath,
2483
- captionPath: resolvePath(args.caption, DEFAULT_CAPTION_PATH),
2484
- captionText: args['caption-text'],
2485
- outputDir,
2486
- slug,
2487
- slideDurationSeconds: Number(args['slide-seconds'] || 2.4),
2488
- dryRun: Boolean(args['dry-run']),
2489
- });
2490
- const results = await publishBundle(manifestPath, {
2491
- platforms: args.platforms || 'instagram,tiktok',
2492
- historyPath: resolvePath(args.history, DEFAULT_HISTORY_PATH),
2493
- dryRun: Boolean(args['dry-run']),
2494
- noShare: Boolean(args['no-share']),
2495
- cleanupDrafts: Boolean(args['cleanup-drafts']),
2496
- force: Boolean(args.force),
2497
- browserBackend: args.backend || 'auto',
2498
- profileRoot: resolveChromeProfileRoot(args['profile-root'] || DEFAULT_CHROME_PROFILE_ROOT),
2499
- profileDir: args['profile-dir'] || DEFAULT_CHROME_PROFILE_DIR,
2500
- headless: Boolean(args.headless),
2501
- });
2502
- console.log(JSON.stringify({ manifestPath, manifest, results }, null, 2));
2503
- return;
2504
- }
2505
-
2506
- if (command === 'queue') {
2507
- const entry = enqueueBundle({
2508
- queuePath: resolvePath(args.queue, DEFAULT_QUEUE_PATH),
2509
- bundlePath: resolvePath(args.bundle),
2510
- scheduledAt: args.when || args.at,
2511
- platforms: String(args.platforms || 'instagram,tiktok').split(',').map((value) => value.trim()).filter(Boolean),
2512
- });
2513
- console.log(JSON.stringify(entry, null, 2));
2514
- return;
2515
- }
2516
-
2517
- if (command === 'publish') {
2518
- const results = await publishBundle(resolvePath(args.bundle), {
2519
- platforms: args.platforms || 'instagram,tiktok',
2520
- historyPath: resolvePath(args.history, DEFAULT_HISTORY_PATH),
2521
- dryRun: Boolean(args['dry-run']),
2522
- noShare: Boolean(args['no-share']),
2523
- cleanupDrafts: Boolean(args['cleanup-drafts']),
2524
- force: Boolean(args.force),
2525
- browserBackend: args.backend || 'auto',
2526
- profileRoot: resolveChromeProfileRoot(args['profile-root'] || DEFAULT_CHROME_PROFILE_ROOT),
2527
- profileDir: args['profile-dir'] || DEFAULT_CHROME_PROFILE_DIR,
2528
- headless: Boolean(args.headless),
2529
- });
2530
- console.log(JSON.stringify(results, null, 2));
2531
- return;
2532
- }
2533
-
2534
- if (command === 'publish-queue') {
2535
- const results = await publishDueQueueEntries({
2536
- queuePath: resolvePath(args.queue, DEFAULT_QUEUE_PATH),
2537
- historyPath: resolvePath(args.history, DEFAULT_HISTORY_PATH),
2538
- dryRun: Boolean(args['dry-run']),
2539
- noShare: Boolean(args['no-share']),
2540
- cleanupDrafts: Boolean(args['cleanup-drafts']),
2541
- force: Boolean(args.force),
2542
- browserBackend: args.backend || 'auto',
2543
- profileRoot: resolveChromeProfileRoot(args['profile-root'] || DEFAULT_CHROME_PROFILE_ROOT),
2544
- profileDir: args['profile-dir'] || DEFAULT_CHROME_PROFILE_DIR,
2545
- headless: Boolean(args.headless),
2546
- now: args.now ? new Date(args.now) : new Date(),
2547
- });
2548
- console.log(JSON.stringify(results, null, 2));
2549
- return;
2550
- }
2551
-
2552
- if (command === 'install-scheduler') {
2553
- const result = installLaunchAgent({
2554
- label: args.label || DEFAULT_LAUNCHD_LABEL,
2555
- intervalMinutes: Number(args['interval-minutes'] || DEFAULT_SCHEDULE_INTERVAL_MINUTES),
2556
- queuePath: resolvePath(args.queue, DEFAULT_QUEUE_PATH),
2557
- dryRun: Boolean(args['dry-run']),
2558
- });
2559
- console.log(JSON.stringify(result, null, 2));
2560
- return;
2561
- }
2562
-
2563
- if (command === 'status') {
2564
- const queuePath = resolvePath(args.queue, DEFAULT_QUEUE_PATH);
2565
- const queueState = loadQueueState(queuePath);
2566
- console.log(JSON.stringify({
2567
- queuePath,
2568
- historyPath: resolvePath(args.history, DEFAULT_HISTORY_PATH),
2569
- publishHistory: loadPublishHistory(resolvePath(args.history, DEFAULT_HISTORY_PATH)),
2570
- entries: queueState.entries || [],
2571
- }, null, 2));
2572
- return;
2573
- }
2574
-
2575
- throw new Error(`Unknown command "${command}"`);
2576
- }
2577
-
2578
- module.exports = {
2579
- DEFAULT_ASSET_HTML,
2580
- DEFAULT_CAPTION_PATH,
2581
- DEFAULT_CHROME_PROFILE_DIR,
2582
- DEFAULT_CHROME_PROFILE_ROOT,
2583
- DEFAULT_HISTORY_PATH,
2584
- DEFAULT_QUEUE_PATH,
2585
- DEFAULT_LAUNCHD_LABEL,
2586
- assertPublishNotDuplicated,
2587
- buildBundleManifest,
2588
- buildPublishFingerprint,
2589
- buildChromeJavaScriptAppleScript,
2590
- buildFfmpegConcatManifest,
2591
- buildIsolatedSlideDocument,
2592
- buildLaunchAgentPlist,
2593
- buildBrowserUploadScript,
2594
- buildContentEditableCaptionScript,
2595
- appendPublishAttemptEvent,
2596
- enqueueBundle,
2597
- extractHeadContent,
2598
- extractSlideBlocks,
2599
- getDueEntries,
2600
- loadQueueState,
2601
- loadPublishHistory,
2602
- normalizePlatformList,
2603
- mimeTypeForPath,
2604
- normalizeTikTokCaption,
2605
- preflightTikTokSession,
2606
- prepareBundle,
2607
- publishBundle,
2608
- resolveChromeProfileRoot,
2609
- removeDirectoryWithRetries,
2610
- renderSlides,
2611
- renderTikTokVideo,
2612
- resolveTikTokPublishTarget,
2613
- saveQueueState,
2614
- slugify,
2615
- stopChromeProcess,
2616
- validateSlideImages,
2617
- waitForProcessExit,
2618
- writeIsolatedSlideDocuments,
2619
- };
2620
-
2621
- if (require.main === module) {
2622
- main().catch((error) => {
2623
- console.error(error.message);
2624
- process.exit(1);
2625
- });
2626
- }