thumbgate 1.4.2 → 1.4.4

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 (279) hide show
  1. package/.claude-plugin/README.md +45 -34
  2. package/.claude-plugin/marketplace.json +3 -3
  3. package/.claude-plugin/plugin.json +3 -3
  4. package/.well-known/llms.txt +1 -1
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +26 -2
  7. package/adapters/README.md +4 -1
  8. package/adapters/claude/.mcp.json +2 -2
  9. package/adapters/codex/config.toml +2 -2
  10. package/adapters/mcp/server-stdio.js +10 -4
  11. package/adapters/opencode/opencode.json +1 -1
  12. package/bin/cli.js +246 -90
  13. package/config/mcp-allowlists.json +11 -3
  14. package/package.json +184 -21
  15. package/scripts/audit-trail.js +25 -15
  16. package/scripts/auto-wire-hooks.js +127 -0
  17. package/scripts/cli-demo.js +102 -0
  18. package/scripts/cli-schema.js +285 -0
  19. package/scripts/cli-status.js +166 -0
  20. package/scripts/cross-encoder-reranker.js +235 -0
  21. package/scripts/explore-subcommands.js +277 -0
  22. package/scripts/explore.js +569 -0
  23. package/scripts/feedback-loop.js +20 -6
  24. package/scripts/lesson-inference.js +7 -1
  25. package/scripts/lesson-reranker.js +263 -0
  26. package/scripts/lesson-retrieval.js +34 -17
  27. package/scripts/lesson-search.js +69 -0
  28. package/scripts/perplexity-client.js +210 -0
  29. package/scripts/reflector-agent.js +2 -2
  30. package/scripts/statusline-local-stats.js +3 -1
  31. package/scripts/statusline.sh +12 -11
  32. package/src/api/server.js +178 -17
  33. package/src/index.js +3 -0
  34. package/.claude-plugin/bundle/icon.png +0 -0
  35. package/.claude-plugin/bundle/icon.svg +0 -18
  36. package/.claude-plugin/bundle/server/index.js +0 -24
  37. package/adapters/chatgpt/INSTALL.md +0 -138
  38. package/bin/memory.sh +0 -64
  39. package/bin/obsidian-sync.sh +0 -20
  40. package/plugins/amp-skill/INSTALL.md +0 -52
  41. package/plugins/amp-skill/SKILL.md +0 -64
  42. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +0 -22
  43. package/plugins/claude-codex-bridge/.mcp.json +0 -14
  44. package/plugins/claude-codex-bridge/INSTALL.md +0 -43
  45. package/plugins/claude-codex-bridge/README.md +0 -46
  46. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +0 -286
  47. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +0 -24
  48. package/plugins/claude-codex-bridge/skills/result/SKILL.md +0 -22
  49. package/plugins/claude-codex-bridge/skills/review/SKILL.md +0 -28
  50. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +0 -27
  51. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +0 -21
  52. package/plugins/claude-codex-bridge/skills/status/SKILL.md +0 -19
  53. package/plugins/claude-skill/INSTALL.md +0 -55
  54. package/plugins/claude-skill/SKILL.md +0 -46
  55. package/plugins/codex-profile/.codex-plugin/plugin.json +0 -43
  56. package/plugins/codex-profile/.mcp.json +0 -14
  57. package/plugins/codex-profile/AGENTS.md +0 -20
  58. package/plugins/codex-profile/INSTALL.md +0 -89
  59. package/plugins/codex-profile/README.md +0 -61
  60. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +0 -23
  61. package/plugins/cursor-marketplace/CHANGELOG.md +0 -30
  62. package/plugins/cursor-marketplace/LICENSE +0 -21
  63. package/plugins/cursor-marketplace/README.md +0 -124
  64. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +0 -31
  65. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  66. package/plugins/cursor-marketplace/commands/capture-feedback.md +0 -33
  67. package/plugins/cursor-marketplace/commands/check-gates.md +0 -25
  68. package/plugins/cursor-marketplace/commands/show-lessons.md +0 -27
  69. package/plugins/cursor-marketplace/hooks/hooks.json +0 -10
  70. package/plugins/cursor-marketplace/mcp.json +0 -14
  71. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +0 -34
  72. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +0 -30
  73. package/plugins/cursor-marketplace/rules/session-continuity.mdc +0 -28
  74. package/plugins/cursor-marketplace/scripts/gate-check.sh +0 -21
  75. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +0 -48
  76. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +0 -31
  77. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +0 -30
  78. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +0 -33
  79. package/plugins/gemini-extension/INSTALL.md +0 -92
  80. package/plugins/gemini-extension/gemini_prompt.txt +0 -14
  81. package/plugins/gemini-extension/tool_contract.json +0 -45
  82. package/plugins/opencode-profile/INSTALL.md +0 -57
  83. package/public/assets/instagram-card.png +0 -0
  84. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  85. package/public/blog.html +0 -474
  86. package/public/compare/mem0.html +0 -189
  87. package/public/compare/speclock.html +0 -180
  88. package/public/compare.html +0 -310
  89. package/public/dashboard.html +0 -1100
  90. package/public/guide.html +0 -317
  91. package/public/guides/claude-code-prevent-repeated-mistakes.html +0 -161
  92. package/public/guides/codex-cli-guardrails.html +0 -158
  93. package/public/guides/cursor-prevent-repeated-mistakes.html +0 -161
  94. package/public/guides/pre-action-gates.html +0 -162
  95. package/public/guides/stop-repeated-ai-agent-mistakes.html +0 -159
  96. package/public/index.html +0 -1128
  97. package/public/js/buyer-intent.js +0 -252
  98. package/public/learn/agent-harness-pattern.html +0 -180
  99. package/public/learn/ai-agent-persistent-memory.html +0 -203
  100. package/public/learn/learn.css +0 -45
  101. package/public/learn/mcp-pre-action-gates-explained.html +0 -172
  102. package/public/learn/stop-ai-agent-force-push.html +0 -134
  103. package/public/learn/vibe-coding-safety-net.html +0 -142
  104. package/public/learn.html +0 -274
  105. package/public/lessons.html +0 -967
  106. package/public/llm-context.md +0 -140
  107. package/public/pro.html +0 -1087
  108. package/public/vercel.json +0 -8
  109. package/scripts/a2ui-engine.js +0 -73
  110. package/scripts/adk-consolidator.js +0 -274
  111. package/scripts/agent-security-hardening.js +0 -225
  112. package/scripts/ai-search-visibility.js +0 -142
  113. package/scripts/autonomous-sales-agent.js +0 -39
  114. package/scripts/autoresearch-runner.js +0 -216
  115. package/scripts/background-agent-governance.js +0 -229
  116. package/scripts/behavioral-extraction.js +0 -93
  117. package/scripts/budget-enforcer.js +0 -173
  118. package/scripts/budget-guard.js +0 -173
  119. package/scripts/build-claude-mcpb.js +0 -255
  120. package/scripts/build-codex-plugin.js +0 -152
  121. package/scripts/capture-railway-diagnostics.sh +0 -97
  122. package/scripts/changeset-check.js +0 -372
  123. package/scripts/check-congruence.js +0 -443
  124. package/scripts/computer-use-firewall.js +0 -280
  125. package/scripts/content-engine/linkedin-content-generator.js +0 -154
  126. package/scripts/content-engine/output/linkedin-memento-validation.md +0 -17
  127. package/scripts/content-engine/output/linkedin-posts-2026-04-09.md +0 -175
  128. package/scripts/content-engine/reddit-thread-finder.js +0 -154
  129. package/scripts/context-engine.js +0 -710
  130. package/scripts/daily-digest.js +0 -11
  131. package/scripts/data-governance.js +0 -173
  132. package/scripts/deploy-gcp.sh +0 -44
  133. package/scripts/deploy-policy.js +0 -249
  134. package/scripts/disagreement-mining.js +0 -315
  135. package/scripts/dpo-optimizer.js +0 -206
  136. package/scripts/ensure-repo-bootstrap.js +0 -130
  137. package/scripts/ephemeral-agent-store.js +0 -212
  138. package/scripts/eval-harness.js +0 -56
  139. package/scripts/export-kto-pairs.js +0 -309
  140. package/scripts/export-training.js +0 -446
  141. package/scripts/feedback-fallback.js +0 -111
  142. package/scripts/feedback-inbox-read.js +0 -162
  143. package/scripts/feedback-root-consolidator.js +0 -233
  144. package/scripts/feedback-to-memory.js +0 -185
  145. package/scripts/gate-satisfy.js +0 -42
  146. package/scripts/generate-paperbanana-diagrams.sh +0 -99
  147. package/scripts/generate-pretool-hook.sh +0 -40
  148. package/scripts/github-about.js +0 -430
  149. package/scripts/github-outreach.js +0 -65
  150. package/scripts/gtm-revenue-loop.js +0 -535
  151. package/scripts/hallucination-detector.js +0 -226
  152. package/scripts/hf-papers.js +0 -317
  153. package/scripts/hook-auto-capture.sh +0 -100
  154. package/scripts/hook-stop-pr-thread-check.sh +0 -68
  155. package/scripts/hook-stop-self-score.sh +0 -51
  156. package/scripts/hook-stop-verify-deploy.sh +0 -31
  157. package/scripts/hook-verify-before-done.sh +0 -20
  158. package/scripts/managed-dpo-export.js +0 -91
  159. package/scripts/markdown-escape.js +0 -12
  160. package/scripts/marketing-experiment.js +0 -657
  161. package/scripts/memalign-recall.js +0 -111
  162. package/scripts/memory-migration.js +0 -296
  163. package/scripts/meta-policy.js +0 -190
  164. package/scripts/metered-billing.js +0 -16
  165. package/scripts/model-tier-router.js +0 -310
  166. package/scripts/money-watcher.js +0 -218
  167. package/scripts/multi-hop-recall.js +0 -240
  168. package/scripts/per-step-scoring.js +0 -163
  169. package/scripts/perplexity-marketing.js +0 -466
  170. package/scripts/pii-scanner.js +0 -153
  171. package/scripts/plan-gate.js +0 -154
  172. package/scripts/post-everywhere.js +0 -341
  173. package/scripts/post-to-x-retry.sh +0 -22
  174. package/scripts/post-to-x.js +0 -369
  175. package/scripts/pr-manager.js +0 -421
  176. package/scripts/principle-extractor.js +0 -162
  177. package/scripts/pro-features.js +0 -41
  178. package/scripts/prompt-dlp.js +0 -222
  179. package/scripts/prove-adapters.js +0 -860
  180. package/scripts/prove-attribution.js +0 -361
  181. package/scripts/prove-automation.js +0 -651
  182. package/scripts/prove-autoresearch.js +0 -304
  183. package/scripts/prove-claim-verification.js +0 -277
  184. package/scripts/prove-cloudflare-sandbox.js +0 -161
  185. package/scripts/prove-data-pipeline.js +0 -408
  186. package/scripts/prove-data-quality.js +0 -227
  187. package/scripts/prove-evolution.js +0 -352
  188. package/scripts/prove-harnesses.js +0 -287
  189. package/scripts/prove-intelligence.js +0 -257
  190. package/scripts/prove-lancedb.js +0 -425
  191. package/scripts/prove-local-intelligence.js +0 -340
  192. package/scripts/prove-loop-closure.js +0 -263
  193. package/scripts/prove-packaged-runtime.js +0 -326
  194. package/scripts/prove-predictive-insights.js +0 -355
  195. package/scripts/prove-runtime.js +0 -363
  196. package/scripts/prove-seo-gsd.js +0 -234
  197. package/scripts/prove-settings.js +0 -279
  198. package/scripts/prove-subway-upgrades.js +0 -277
  199. package/scripts/prove-tessl.js +0 -229
  200. package/scripts/prove-training-export.js +0 -325
  201. package/scripts/prove-workflow-contract.js +0 -112
  202. package/scripts/prove-xmemory.js +0 -332
  203. package/scripts/publish-decision.js +0 -159
  204. package/scripts/ralph-loop.js +0 -376
  205. package/scripts/ralph-mode-ci.js +0 -331
  206. package/scripts/reddit-dm-outreach.js +0 -192
  207. package/scripts/reddit-monitor-cron.sh +0 -26
  208. package/scripts/reminder-engine.js +0 -132
  209. package/scripts/revenue-status.js +0 -472
  210. package/scripts/rotate-stripe-webhook-secret.js +0 -314
  211. package/scripts/schedule-manager.js +0 -249
  212. package/scripts/self-healing-check.js +0 -193
  213. package/scripts/shieldcortex-memory-firewall-runner.mjs +0 -53
  214. package/scripts/skill-exporter.js +0 -260
  215. package/scripts/skill-materializer.js +0 -134
  216. package/scripts/skill-packs.js +0 -136
  217. package/scripts/skill-proposer.js +0 -99
  218. package/scripts/skill-quality-tracker.js +0 -282
  219. package/scripts/slow-loop.js +0 -72
  220. package/scripts/social-analytics/db/analytics.sqlite +0 -0
  221. package/scripts/social-analytics/db/schema.sql +0 -32
  222. package/scripts/social-analytics/digest.js +0 -256
  223. package/scripts/social-analytics/engagement-audit.js +0 -185
  224. package/scripts/social-analytics/generate-instagram-card.js +0 -97
  225. package/scripts/social-analytics/instagram-thumbgate-post.js +0 -111
  226. package/scripts/social-analytics/install-growth-automation.js +0 -114
  227. package/scripts/social-analytics/load-env.js +0 -77
  228. package/scripts/social-analytics/mcp-server.js +0 -289
  229. package/scripts/social-analytics/normalizer.js +0 -580
  230. package/scripts/social-analytics/notify.js +0 -162
  231. package/scripts/social-analytics/poll-all.js +0 -107
  232. package/scripts/social-analytics/pollers/github.js +0 -195
  233. package/scripts/social-analytics/pollers/instagram.js +0 -253
  234. package/scripts/social-analytics/pollers/linkedin.js +0 -340
  235. package/scripts/social-analytics/pollers/plausible.js +0 -245
  236. package/scripts/social-analytics/pollers/reddit.js +0 -306
  237. package/scripts/social-analytics/pollers/threads.js +0 -233
  238. package/scripts/social-analytics/pollers/tiktok.js +0 -203
  239. package/scripts/social-analytics/pollers/x.js +0 -227
  240. package/scripts/social-analytics/pollers/youtube.js +0 -304
  241. package/scripts/social-analytics/pollers/zernio.js +0 -183
  242. package/scripts/social-analytics/publish-instagram-thumbgate.js +0 -104
  243. package/scripts/social-analytics/publish-thumbgate-launch.js +0 -322
  244. package/scripts/social-analytics/publishers/devto.js +0 -122
  245. package/scripts/social-analytics/publishers/instagram.js +0 -317
  246. package/scripts/social-analytics/publishers/linkedin.js +0 -294
  247. package/scripts/social-analytics/publishers/reddit.js +0 -385
  248. package/scripts/social-analytics/publishers/threads.js +0 -275
  249. package/scripts/social-analytics/publishers/tiktok.js +0 -217
  250. package/scripts/social-analytics/publishers/x.js +0 -259
  251. package/scripts/social-analytics/publishers/youtube.js +0 -223
  252. package/scripts/social-analytics/publishers/zernio.js +0 -539
  253. package/scripts/social-analytics/reconcile-thumbgate-campaign.js +0 -165
  254. package/scripts/social-analytics/run-digest.js +0 -34
  255. package/scripts/social-analytics/schedule-thumbgate-campaign.js +0 -275
  256. package/scripts/social-analytics/store.js +0 -455
  257. package/scripts/social-analytics/sync-launch-assets.js +0 -185
  258. package/scripts/social-analytics/utm.js +0 -143
  259. package/scripts/social-pipeline.js +0 -2626
  260. package/scripts/social-post-hourly.js +0 -228
  261. package/scripts/social-quality-gate.js +0 -134
  262. package/scripts/social-reply-monitor.js +0 -592
  263. package/scripts/status-dashboard.js +0 -155
  264. package/scripts/stripe-live-status.js +0 -115
  265. package/scripts/subagent-profiles.js +0 -79
  266. package/scripts/sync-branch-protection.js +0 -340
  267. package/scripts/sync-gh-secrets-from-env.sh +0 -70
  268. package/scripts/sync-github-about.js +0 -55
  269. package/scripts/sync-version.js +0 -479
  270. package/scripts/synthetic-dpo.js +0 -234
  271. package/scripts/tessl-export.js +0 -369
  272. package/scripts/test-coverage.js +0 -128
  273. package/scripts/thumbgate_session_start.sh +0 -32
  274. package/scripts/train_from_feedback.py +0 -929
  275. package/scripts/validate-feedback.js +0 -581
  276. package/scripts/verify-obsidian-setup.sh +0 -269
  277. package/scripts/verify-run.js +0 -269
  278. package/scripts/weekly-auto-post.js +0 -124
  279. package/scripts/x-autonomous-marketing.js +0 -139
@@ -1,539 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * zernio.js
5
- * Unified publisher via Zernio API.
6
- *
7
- * Required env vars:
8
- * ZERNIO_API_KEY — Bearer token for https://zernio.com/api/v1
9
- */
10
-
11
- const fs = require('node:fs');
12
- const path = require('node:path');
13
- const crypto = require('node:crypto');
14
- const { tagUrlsInText } = require('../utm');
15
- const { loadLocalEnv } = require('../load-env');
16
-
17
- const ZERNIO_UTM = { source: 'zernio', medium: 'social', campaign: 'organic' };
18
-
19
- const ZERNIO_BASE = 'https://zernio.com/api/v1';
20
- const DEFAULT_DEDUP_LOG_PATH = path.join(__dirname, '..', '..', '..', '.thumbgate', 'zernio-dedup-log.json');
21
-
22
- loadLocalEnv();
23
-
24
- /**
25
- * Content-hash dedup: prevents the same content from being posted to the same
26
- * platform twice within a 24-hour window.
27
- */
28
- function getDedupLogPath() {
29
- return process.env.THUMBGATE_DEDUP_LOG_PATH || DEFAULT_DEDUP_LOG_PATH;
30
- }
31
-
32
- function buildDedupKey(content, platform) {
33
- const hash = crypto.createHash('sha256').update(content.trim()).digest('hex').slice(0, 16);
34
- return `${platform}::${hash}`;
35
- }
36
-
37
- function loadDedupLog() {
38
- const logPath = getDedupLogPath();
39
- try {
40
- if (fs.existsSync(logPath)) {
41
- return JSON.parse(fs.readFileSync(logPath, 'utf8'));
42
- }
43
- } catch { /* ignore corrupt log */ }
44
- return {};
45
- }
46
-
47
- function saveDedupLog(log) {
48
- const logPath = getDedupLogPath();
49
- const dir = path.dirname(logPath);
50
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
51
- fs.writeFileSync(logPath, JSON.stringify(log, null, 2));
52
- }
53
-
54
- function isDuplicate(content, platform) {
55
- const log = loadDedupLog();
56
- const key = buildDedupKey(content, platform);
57
- const entry = log[key];
58
- if (!entry) return false;
59
- const ageMs = Date.now() - new Date(entry.postedAt).getTime();
60
- return ageMs < 24 * 60 * 60 * 1000; // 24-hour dedup window
61
- }
62
-
63
- function recordPost(content, platform) {
64
- const log = loadDedupLog();
65
- const key = buildDedupKey(content, platform);
66
- log[key] = { platform, postedAt: new Date().toISOString() };
67
- // Prune entries older than 7 days
68
- const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
69
- for (const [k, v] of Object.entries(log)) {
70
- if (new Date(v.postedAt).getTime() < cutoff) delete log[k];
71
- }
72
- saveDedupLog(log);
73
- }
74
-
75
- function requireApiKey() {
76
- const key = process.env.ZERNIO_API_KEY;
77
- if (!key) {
78
- throw new Error('ZERNIO_API_KEY environment variable is required');
79
- }
80
- return key;
81
- }
82
-
83
- class ZernioQuotaError extends Error {
84
- constructor(message, details = {}) {
85
- super(message);
86
- this.name = 'ZernioQuotaError';
87
- this.code = 'ZERNIO_POST_LIMIT_REACHED';
88
- this.billingPeriod = details.billingPeriod || null;
89
- this.current = Number.isFinite(details.current) ? details.current : null;
90
- this.endpoint = details.endpoint || null;
91
- this.limit = Number.isFinite(details.limit) ? details.limit : null;
92
- this.method = details.method || null;
93
- this.planName = details.planName || null;
94
- this.status = details.status || null;
95
- }
96
- }
97
-
98
- function parseZernioErrorText(errorText) {
99
- if (!errorText || typeof errorText !== 'string') return null;
100
- try {
101
- const parsed = JSON.parse(errorText);
102
- return parsed && typeof parsed === 'object' ? parsed : null;
103
- } catch {
104
- return null;
105
- }
106
- }
107
-
108
- function isZernioQuotaError(error) {
109
- return Boolean(
110
- error &&
111
- (error instanceof ZernioQuotaError || error.code === 'ZERNIO_POST_LIMIT_REACHED')
112
- );
113
- }
114
-
115
- function isZernioQuotaPayload(status, payload, errorText) {
116
- const message = String(payload?.error || payload?.message || errorText || '');
117
- return status === 403 && /post limit reached/i.test(message);
118
- }
119
-
120
- function resolveAccountId(account) {
121
- if (!account || typeof account !== 'object') {
122
- return '';
123
- }
124
- return String(account.accountId || account._id || account.id || '').trim();
125
- }
126
-
127
- function normalizeAccount(account) {
128
- if (!account || typeof account !== 'object') {
129
- return null;
130
- }
131
- const platform = String(account.platform || '').trim();
132
- const accountId = resolveAccountId(account);
133
- return {
134
- ...account,
135
- platform,
136
- accountId,
137
- };
138
- }
139
-
140
- function normalizePlatforms(platforms) {
141
- return platforms
142
- .map(normalizeAccount)
143
- .filter(Boolean)
144
- .map((platform) => ({
145
- platform: platform.platform,
146
- accountId: platform.accountId,
147
- }));
148
- }
149
-
150
- function groupAccountsByPlatform(accounts) {
151
- const groups = new Map();
152
- for (const account of accounts) {
153
- if (!account || !account.platform || !account.accountId) {
154
- continue;
155
- }
156
- const existing = groups.get(account.platform) || [];
157
- existing.push({
158
- platform: account.platform,
159
- accountId: account.accountId,
160
- });
161
- groups.set(account.platform, existing);
162
- }
163
- return groups;
164
- }
165
-
166
- function inferContentType(filePath) {
167
- const ext = path.extname(String(filePath || '')).toLowerCase();
168
- if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
169
- if (ext === '.png') return 'image/png';
170
- if (ext === '.webp') return 'image/webp';
171
- if (ext === '.gif') return 'image/gif';
172
- if (ext === '.mp4') return 'video/mp4';
173
- if (ext === '.mov') return 'video/quicktime';
174
- if (ext === '.webm') return 'video/webm';
175
- return 'application/octet-stream';
176
- }
177
-
178
- function inferMediaType(contentType) {
179
- if (String(contentType || '').startsWith('video/')) {
180
- return 'video';
181
- }
182
- return 'image';
183
- }
184
-
185
- function normalizePostResult(payload) {
186
- const data = payload && typeof payload === 'object' ? (payload.data ?? payload) : {};
187
- const post = data.post && typeof data.post === 'object' ? data.post : null;
188
- const id = data.id || data._id || post?._id || post?.id || null;
189
- return {
190
- ...data,
191
- id,
192
- post: post || data.post,
193
- };
194
- }
195
-
196
- async function zernioFetch(method, endpoint, body = null) {
197
- const apiKey = requireApiKey();
198
- const url = `${ZERNIO_BASE}${endpoint}`;
199
-
200
- const options = {
201
- method,
202
- headers: {
203
- Authorization: `Bearer ${apiKey}`,
204
- 'Content-Type': 'application/json',
205
- },
206
- };
207
-
208
- if (body !== null) {
209
- options.body = JSON.stringify(body);
210
- }
211
-
212
- const res = await fetch(url, options);
213
-
214
- if (!res.ok) {
215
- const errorText = await res.text().catch(() => '');
216
- const payload = parseZernioErrorText(errorText);
217
- if (isZernioQuotaPayload(res.status, payload, errorText)) {
218
- throw new ZernioQuotaError(payload?.error || 'Zernio post limit reached', {
219
- billingPeriod: payload?.billingPeriod,
220
- current: Number(payload?.current),
221
- endpoint,
222
- limit: Number(payload?.limit),
223
- method,
224
- planName: payload?.planName,
225
- status: res.status,
226
- });
227
- }
228
- throw new Error(`Zernio API ${res.status} for ${method} ${endpoint}: ${errorText}`);
229
- }
230
-
231
- return res.json();
232
- }
233
-
234
- async function listPosts(options = {}) {
235
- const query = new URLSearchParams();
236
- if (options.limit) query.set('limit', String(options.limit));
237
- if (options.page) query.set('page', String(options.page));
238
- if (options.status) query.set('status', String(options.status));
239
-
240
- const suffix = query.toString() ? `?${query.toString()}` : '';
241
- const json = await zernioFetch('GET', `/posts${suffix}`);
242
- return Array.isArray(json.posts) ? json.posts : (json.data?.posts || json.data || []);
243
- }
244
-
245
- async function deletePost(postId) {
246
- if (!postId) throw new Error('deletePost: postId is required');
247
- const json = await zernioFetch('DELETE', `/posts/${encodeURIComponent(String(postId).trim())}`);
248
- return json.data ?? json;
249
- }
250
-
251
- async function requestMediaPresign(filename, contentType, size) {
252
- if (!filename) throw new Error('requestMediaPresign: filename is required');
253
- if (!contentType) throw new Error('requestMediaPresign: contentType is required');
254
-
255
- const json = await zernioFetch('POST', '/media/presign', {
256
- filename,
257
- contentType,
258
- size,
259
- });
260
-
261
- return json.data ?? json;
262
- }
263
-
264
- async function uploadLocalMedia(filePath, options = {}) {
265
- const resolvedPath = path.resolve(String(filePath || ''));
266
- if (!fs.existsSync(resolvedPath)) {
267
- throw new Error(`uploadLocalMedia: file not found at ${resolvedPath}`);
268
- }
269
-
270
- const stats = fs.statSync(resolvedPath);
271
- const filename = options.filename || path.basename(resolvedPath);
272
- const contentType = options.contentType || inferContentType(resolvedPath);
273
- const presign = await requestMediaPresign(filename, contentType, stats.size);
274
-
275
- if (!presign.uploadUrl || !presign.publicUrl) {
276
- throw new Error('uploadLocalMedia: presign response missing uploadUrl or publicUrl');
277
- }
278
-
279
- const uploadResponse = await fetch(presign.uploadUrl, {
280
- method: 'PUT',
281
- headers: {
282
- 'Content-Type': contentType,
283
- },
284
- body: fs.readFileSync(resolvedPath),
285
- });
286
-
287
- if (!uploadResponse.ok) {
288
- const errorText = await uploadResponse.text().catch(() => '');
289
- throw new Error(`uploadLocalMedia: upload failed with ${uploadResponse.status}: ${errorText}`);
290
- }
291
-
292
- return {
293
- contentType,
294
- key: presign.key || '',
295
- size: stats.size,
296
- type: presign.type || inferMediaType(contentType),
297
- url: presign.publicUrl,
298
- };
299
- }
300
-
301
- /**
302
- * Publishes a post immediately to one or more platforms.
303
- * @param {string} content
304
- * @param {Array<{platform: string, accountId: string}>} platforms
305
- * @returns {Promise<object>}
306
- */
307
- async function publishPost(content, platforms, options = {}) {
308
- if (!content) throw new Error('publishPost: content is required');
309
- if (!Array.isArray(platforms) || platforms.length === 0) {
310
- throw new Error('publishPost: platforms must be a non-empty array');
311
- }
312
-
313
- const normalizedPlatforms = normalizePlatforms(platforms);
314
- if (normalizedPlatforms.length === 0 || normalizedPlatforms.some((entry) => !entry.platform || !entry.accountId)) {
315
- throw new Error('publishPost: each platform entry requires platform and accountId');
316
- }
317
-
318
- // Tag trackable URLs with Zernio UTM parameters before publishing
319
- content = tagUrlsInText(content, options.utm || ZERNIO_UTM);
320
-
321
- const qualityGate = require('../../social-quality-gate');
322
- const gateResult = qualityGate.gatePost(content);
323
- if (!gateResult.allowed) {
324
- const reasons = gateResult.findings.map(f => f.reason).join(', ');
325
- console.error(`[zernio:publisher] BLOCKED by quality gate: ${reasons}`);
326
- return { blocked: true, reasons: gateResult.findings };
327
- }
328
-
329
- // Dedup: filter out platforms where identical content was posted in last 24h
330
- const dedupedPlatforms = normalizedPlatforms.filter((p) => {
331
- if (isDuplicate(content, p.platform)) {
332
- console.log(`[zernio:publisher] SKIPPED ${p.platform} — duplicate content within 24h`);
333
- return false;
334
- }
335
- return true;
336
- });
337
-
338
- if (dedupedPlatforms.length === 0) {
339
- console.log('[zernio:publisher] All platforms skipped (duplicate content)');
340
- return { blocked: true, reasons: [{ reason: 'duplicate_content_all_platforms' }] };
341
- }
342
-
343
- console.log(`[zernio:publisher] Publishing to ${dedupedPlatforms.length} platform(s): ${dedupedPlatforms.map((p) => p.platform).join(', ')}`);
344
-
345
- const json = await zernioFetch('POST', '/posts', {
346
- content,
347
- firstComment: options.firstComment,
348
- mediaItems: options.mediaItems,
349
- publishNow: true,
350
- platforms: dedupedPlatforms,
351
- });
352
-
353
- const data = normalizePostResult(json);
354
- // Record each platform to prevent future dupes
355
- for (const p of dedupedPlatforms) {
356
- recordPost(content, p.platform);
357
- }
358
- console.log(`[zernio:publisher] Post published. id=${data.id ?? 'unknown'}`);
359
- return data;
360
- }
361
-
362
- /**
363
- * Schedules a post for future publication.
364
- * @param {string} content
365
- * @param {Array<{platform: string, accountId: string}>} platforms
366
- * @param {string} scheduledFor ISO 8601 datetime
367
- * @param {string} timezone IANA timezone string
368
- * @returns {Promise<object>}
369
- */
370
- async function schedulePost(content, platforms, scheduledFor, timezone, options = {}) {
371
- if (!content) throw new Error('schedulePost: content is required');
372
- if (!Array.isArray(platforms) || platforms.length === 0) {
373
- throw new Error('schedulePost: platforms must be a non-empty array');
374
- }
375
- if (!scheduledFor) throw new Error('schedulePost: scheduledFor is required');
376
- if (!timezone) throw new Error('schedulePost: timezone is required');
377
-
378
- const normalizedPlatforms = normalizePlatforms(platforms);
379
- if (normalizedPlatforms.length === 0 || normalizedPlatforms.some((entry) => !entry.platform || !entry.accountId)) {
380
- throw new Error('schedulePost: each platform entry requires platform and accountId');
381
- }
382
-
383
- content = tagUrlsInText(content, options.utm || ZERNIO_UTM);
384
-
385
- // Dedup: filter out platforms where identical content was scheduled in last 24h
386
- const dedupedPlatforms = normalizedPlatforms.filter((p) => {
387
- if (isDuplicate(content, p.platform)) {
388
- console.log(`[zernio:publisher] SKIPPED ${p.platform} schedule — duplicate content within 24h`);
389
- return false;
390
- }
391
- return true;
392
- });
393
-
394
- if (dedupedPlatforms.length === 0) {
395
- console.log('[zernio:publisher] All platforms skipped (duplicate content)');
396
- return { blocked: true, reasons: [{ reason: 'duplicate_content_all_platforms' }] };
397
- }
398
-
399
- console.log(`[zernio:publisher] Scheduling post for ${scheduledFor} (${timezone}) to ${dedupedPlatforms.length} platform(s)`);
400
-
401
- const json = await zernioFetch('POST', '/posts', {
402
- content,
403
- firstComment: options.firstComment,
404
- mediaItems: options.mediaItems,
405
- publishNow: false,
406
- platforms: dedupedPlatforms,
407
- scheduledFor,
408
- timezone,
409
- });
410
-
411
- const data = normalizePostResult(json);
412
- for (const p of dedupedPlatforms) {
413
- recordPost(content, p.platform);
414
- }
415
- console.log(`[zernio:publisher] Post scheduled. id=${data.id ?? 'unknown'}`);
416
- return data;
417
- }
418
-
419
- /**
420
- * Fetches all connected platform accounts from Zernio.
421
- * @returns {Promise<Array<{platform: string, accountId: string, name: string}>>}
422
- */
423
- async function getConnectedAccounts() {
424
- console.log('[zernio:publisher] Fetching connected accounts');
425
-
426
- const json = await zernioFetch('GET', '/accounts');
427
- const accounts = (Array.isArray(json) ? json : (json.data ?? json.accounts ?? []))
428
- .map(normalizeAccount)
429
- .filter((account) => account && account.platform && account.accountId);
430
-
431
- console.log(`[zernio:publisher] ${accounts.length} connected account(s) found`);
432
- return accounts;
433
- }
434
-
435
- /**
436
- * Publishes a post to all connected Zernio accounts in one call.
437
- * @param {string} content
438
- * @returns {Promise<{ published: object[], errors: object[] }>}
439
- */
440
- async function publishToAllPlatforms(content, options = {}) {
441
- if (!content) throw new Error('publishToAllPlatforms: content is required');
442
-
443
- console.log('[zernio:publisher] Fetching all connected accounts for bulk publish');
444
- const accounts = await getConnectedAccounts();
445
-
446
- if (accounts.length === 0) {
447
- console.warn('[zernio:publisher] No connected accounts found — nothing to publish');
448
- return { published: [], errors: [] };
449
- }
450
-
451
- const published = [];
452
- const errors = [];
453
- const requestedPlatforms = Array.isArray(options.platforms) && options.platforms.length > 0
454
- ? new Set(options.platforms.map((platform) => String(platform || '').trim()).filter(Boolean))
455
- : null;
456
- const groupedAccounts = groupAccountsByPlatform(accounts);
457
-
458
- for (const [platform, platformAccounts] of groupedAccounts.entries()) {
459
- if (requestedPlatforms && !requestedPlatforms.has(platform)) {
460
- continue;
461
- }
462
-
463
- try {
464
- const result = await publishPost(content, platformAccounts, {
465
- utm: {
466
- source: platform,
467
- medium: options.medium || ZERNIO_UTM.medium,
468
- campaign: options.campaign || ZERNIO_UTM.campaign,
469
- },
470
- });
471
- published.push({ platform, result });
472
- } catch (err) {
473
- console.error(`[zernio:publisher] Bulk publish failed for ${platform}: ${err.message}`);
474
- errors.push({ error: err.message, platform });
475
- }
476
- }
477
-
478
- console.log(`[zernio:publisher] Bulk publish complete. published=${published.length} errors=${errors.length}`);
479
- return { published, errors };
480
- }
481
-
482
- module.exports = {
483
- buildDedupKey,
484
- deletePost,
485
- isDuplicate,
486
- isZernioQuotaError,
487
- listPosts,
488
- ZernioQuotaError,
489
- publishPost,
490
- recordPost,
491
- schedulePost,
492
- publishToAllPlatforms,
493
- getConnectedAccounts,
494
- groupAccountsByPlatform,
495
- inferContentType,
496
- inferMediaType,
497
- normalizeAccount,
498
- normalizePlatforms,
499
- normalizePostResult,
500
- requestMediaPresign,
501
- resolveAccountId,
502
- uploadLocalMedia,
503
- };
504
-
505
- if (require.main === module) {
506
- const args = process.argv.slice(2);
507
-
508
- function getArg(flag) {
509
- const prefix = `${flag}=`;
510
- const entry = args.find((a) => a.startsWith(prefix));
511
- return entry ? entry.slice(prefix.length) : null;
512
- }
513
-
514
- const text = getArg('--text');
515
- const schedule = getArg('--schedule');
516
- const timezone = getArg('--timezone') || 'UTC';
517
-
518
- if (!text) {
519
- console.error('Usage: node zernio.js --text="..." [--schedule="2026-04-01T10:00:00Z" --timezone="America/New_York"]');
520
- process.exit(1);
521
- }
522
-
523
- (async () => {
524
- try {
525
- if (schedule) {
526
- const accounts = await getConnectedAccounts();
527
- const platforms = accounts.map((a) => ({ platform: a.platform, accountId: a.accountId }));
528
- const result = await schedulePost(text, platforms, schedule, timezone);
529
- console.log(`[zernio:publisher] Scheduled. id=${result.id ?? 'unknown'}`);
530
- } else {
531
- const result = await publishToAllPlatforms(text);
532
- console.log(`[zernio:publisher] Done. published=${result.published.length} errors=${result.errors.length}`);
533
- }
534
- } catch (err) {
535
- console.error('[zernio:publisher] Failed:', err.message);
536
- process.exit(1);
537
- }
538
- })();
539
- }
@@ -1,165 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- const {
5
- buildCampaignEntries,
6
- defaultCampaignSchedule,
7
- } = require('./publish-thumbgate-launch');
8
- const {
9
- deletePost,
10
- listPosts,
11
- } = require('./publishers/zernio');
12
- const {
13
- buildScheduleKey,
14
- DEFAULT_STATE_PATH,
15
- writeScheduleState,
16
- } = require('./schedule-thumbgate-campaign');
17
-
18
- const CAMPAIGN_MARKERS = {
19
- proof_pack: 'campaign_proof_pack',
20
- free_local: 'campaign_free_local',
21
- checkout_path: 'campaign_checkout_path',
22
- };
23
-
24
- function parseArgs(argv = []) {
25
- const options = {
26
- cancelDuplicates: false,
27
- limit: 50,
28
- scheduleTimes: [],
29
- statePath: DEFAULT_STATE_PATH,
30
- };
31
-
32
- for (let index = 0; index < argv.length; index += 1) {
33
- const token = argv[index];
34
- if (token === '--cancel-duplicates') {
35
- options.cancelDuplicates = true;
36
- continue;
37
- }
38
- if (token.startsWith('--limit=')) {
39
- options.limit = Number(token.slice('--limit='.length)) || options.limit;
40
- continue;
41
- }
42
- if (token.startsWith('--times=')) {
43
- options.scheduleTimes = token.slice('--times='.length).split(',').map((value) => value.trim()).filter(Boolean);
44
- continue;
45
- }
46
- if (token.startsWith('--state-path=')) {
47
- options.statePath = token.slice('--state-path='.length).trim() || DEFAULT_STATE_PATH;
48
- }
49
- }
50
-
51
- return options;
52
- }
53
-
54
- function normalizePlatform(post) {
55
- return String(post?.platforms?.[0]?.platform || '').trim().toLowerCase();
56
- }
57
-
58
- function selectCanonicalPost(posts = []) {
59
- return [...posts].sort((left, right) => {
60
- const leftCreated = new Date(left.createdAt || 0).getTime();
61
- const rightCreated = new Date(right.createdAt || 0).getTime();
62
- return leftCreated - rightCreated;
63
- })[0] || null;
64
- }
65
-
66
- async function reconcileCampaignState(options = {}, api = {}) {
67
- const zernio = {
68
- deletePost: api.deletePost || deletePost,
69
- listPosts: api.listPosts || listPosts,
70
- };
71
- const scheduleTimes = options.scheduleTimes && options.scheduleTimes.length > 0
72
- ? options.scheduleTimes
73
- : defaultCampaignSchedule();
74
- const posts = await zernio.listPosts({ limit: options.limit || 50 });
75
- const scheduled = {};
76
- const duplicates = [];
77
- const kept = [];
78
- const entries = buildCampaignEntries();
79
-
80
- for (let index = 0; index < entries.length; index += 1) {
81
- const entry = entries[index];
82
- const scheduleLocal = scheduleTimes[index];
83
- if (!scheduleLocal) {
84
- continue;
85
- }
86
-
87
- const scheduledForUtc = new Date(scheduleLocal).toISOString();
88
-
89
- for (const platform of Object.keys(entry.posts)) {
90
- const marker = CAMPAIGN_MARKERS[entry.slug];
91
- const matchingPosts = posts.filter((post) => (
92
- post.status === 'scheduled' &&
93
- normalizePlatform(post) === platform &&
94
- String(post.content || '').includes(`utm_content=${marker}`) &&
95
- String(post.scheduledFor || '') === scheduledForUtc
96
- ));
97
-
98
- if (matchingPosts.length === 0) {
99
- continue;
100
- }
101
-
102
- const canonical = selectCanonicalPost(matchingPosts);
103
- if (!canonical) {
104
- continue;
105
- }
106
-
107
- const scheduleKey = buildScheduleKey({
108
- slug: entry.slug,
109
- platform,
110
- scheduledFor: scheduleLocal,
111
- });
112
- scheduled[scheduleKey] = {
113
- id: canonical._id,
114
- scheduledFor: scheduleLocal,
115
- slug: entry.slug,
116
- platform,
117
- recordedAt: new Date().toISOString(),
118
- };
119
- kept.push({
120
- key: scheduleKey,
121
- id: canonical._id,
122
- });
123
-
124
- const extras = matchingPosts.filter((post) => post._id !== canonical._id);
125
- for (const duplicate of extras) {
126
- const duplicateRecord = {
127
- key: scheduleKey,
128
- id: duplicate._id,
129
- platform,
130
- slug: entry.slug,
131
- };
132
- if (options.cancelDuplicates) {
133
- duplicateRecord.cancelled = await zernio.deletePost(duplicate._id);
134
- }
135
- duplicates.push(duplicateRecord);
136
- }
137
- }
138
- }
139
-
140
- writeScheduleState(options.statePath || DEFAULT_STATE_PATH, { scheduled });
141
- return {
142
- duplicates,
143
- kept,
144
- statePath: options.statePath || DEFAULT_STATE_PATH,
145
- };
146
- }
147
-
148
- if (require.main === module) {
149
- reconcileCampaignState(parseArgs(process.argv.slice(2)))
150
- .then((result) => {
151
- process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
152
- })
153
- .catch((error) => {
154
- console.error(error && error.message ? error.message : error);
155
- process.exit(1);
156
- });
157
- }
158
-
159
- module.exports = {
160
- CAMPAIGN_MARKERS,
161
- normalizePlatform,
162
- parseArgs,
163
- reconcileCampaignState,
164
- selectCanonicalPost,
165
- };