usebecky 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,52 @@
1
+ import { type Ui } from './ui.ts';
2
+ export interface ApiError {
3
+ code: string;
4
+ message: string;
5
+ hint?: string;
6
+ status: number;
7
+ details?: any;
8
+ }
9
+ export interface SocialContext {
10
+ cwd: string;
11
+ ui: Ui;
12
+ /** The arguments after "social". */
13
+ args: string[];
14
+ help: boolean;
15
+ ref: string | null;
16
+ /** A token is already there (no question will be asked). */
17
+ signedIn: boolean;
18
+ signIn: () => Promise<boolean>;
19
+ /** The platform API under /projects/<ref>/social. */
20
+ api: <T = any>(method: string, path: string, body?: unknown, extra?: {
21
+ headers?: Record<string, string>;
22
+ raw?: Uint8Array;
23
+ }) => Promise<{
24
+ data: T | null;
25
+ error: ApiError | null;
26
+ }>;
27
+ noProject: () => number;
28
+ /** Tests: instead of waiting. */
29
+ sleep?: (ms: number) => Promise<void>;
30
+ /** How often a video is asked about before giving up (every 2 seconds). */
31
+ maxPolls?: number;
32
+ }
33
+ interface Options {
34
+ words: string[];
35
+ caption?: string;
36
+ title?: string;
37
+ link?: string;
38
+ networks?: string;
39
+ network?: string;
40
+ at?: string;
41
+ perDay?: string;
42
+ from?: string;
43
+ count?: string;
44
+ state?: string;
45
+ json?: boolean;
46
+ all?: boolean;
47
+ allowDuplicate?: boolean;
48
+ needsReview?: boolean;
49
+ }
50
+ export declare function parseSocialArgs(args: string[]): Options;
51
+ export declare function socialCommand(ctx: SocialContext): Promise<number>;
52
+ export {};
@@ -0,0 +1,532 @@
1
+ // `npx usebecky social <command>`: fill the posting pipeline of the linked project (Social). Not in the help while Social is
2
+ // not open to everyone, and the how-to (`social guide`) comes from the server, so the package says nothing about it.
3
+ // It talks to the platform API with your login (or USEBECKY_ACCESS_TOKEN).
4
+ //
5
+ // `add` never puts a video on an account a second time: before anything is sent it asks which posts already use these
6
+ // bytes (GET /posts?sha256=). It uploads every video first and plans them only when all of them passed the check, in the
7
+ // order given. Each post gets an Idempotency-Key from the file's hash and the text.
8
+ import crypto from 'node:crypto';
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { c } from "./ui.js";
12
+ const HELP = `
13
+ ${c.bold('npx usebecky social <command>')}: plan videos and have them posted.
14
+
15
+ ${c.cyan('guide')} How to fill the pipeline (read this first)
16
+ ${c.cyan('status')} Accounts, posting times, next free places
17
+ ${c.cyan('slots')} [--network n] [--count n]
18
+ ${c.cyan('upload')} <file> Add a video without planning it
19
+ ${c.cyan('add')} <files…> Upload videos and plan them, in the order given
20
+ --caption <text> --title <text> --link <url> --networks instagram,… --per-day <n>
21
+ --from <YYYY-MM-DD|tomorrow> --at <time with zone> --allow-duplicate (with --networks)
22
+ ${c.cyan('list')} [--state a,b] [--network n] [--all]
23
+ ${c.cyan('show')} <post id> One post with its history
24
+ ${c.cyan('cancel')} <post id> Remove a post that has not gone out
25
+ ${c.cyan('retry')} <post id> [--network n] [--needs-review]
26
+
27
+ Every command takes ${c.bold('--json')} and ${c.bold('--project <ref>')}.
28
+ `;
29
+ const VALUE_FLAGS = { '--caption': 'caption', '--title': 'title', '--link': 'link', '--networks': 'networks', '--network': 'network', '--at': 'at', '--per-day': 'perDay', '--from': 'from', '--count': 'count', '--state': 'state' };
30
+ const SWITCHES = { '--json': 'json', '--all': 'all', '--allow-duplicate': 'allowDuplicate', '--needs-review': 'needsReview' };
31
+ /** A command that cannot go on; printed once, at the top. */
32
+ class Failure extends Error {
33
+ code;
34
+ hint;
35
+ status;
36
+ constructor(message, opts = {}) {
37
+ super(message);
38
+ this.code = opts.code ?? 'cli_error';
39
+ this.hint = opts.hint;
40
+ this.status = opts.status ?? 0;
41
+ }
42
+ }
43
+ export function parseSocialArgs(args) {
44
+ const o = { words: [] };
45
+ for (let i = 0; i < args.length; i++) {
46
+ const a = args[i];
47
+ if (!a.startsWith('--')) {
48
+ o.words.push(a);
49
+ continue;
50
+ }
51
+ const eq = a.indexOf('=');
52
+ const name = eq > 0 ? a.slice(0, eq) : a;
53
+ if (VALUE_FLAGS[name]) {
54
+ const value = eq > 0 ? a.slice(eq + 1) : args[++i];
55
+ if (value === undefined)
56
+ throw new Failure(`${name} needs a value.`);
57
+ o[VALUE_FLAGS[name]] = value;
58
+ }
59
+ else if (SWITCHES[name] && eq < 0)
60
+ o[SWITCHES[name]] = true;
61
+ else
62
+ throw new Failure(`Unknown option "${name}".`, { hint: 'See `npx usebecky social help`.' });
63
+ }
64
+ return o;
65
+ }
66
+ const ALL_STATES = 'scheduled,preparing,ready,publishing,published,failed,canceled,needs_review';
67
+ const CONTENT_TYPES = { '.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime' };
68
+ const NO_TEXT_WARNING = 'No --caption was given: these posts go out without text.';
69
+ const POLL_MS = 2000;
70
+ /** About 20 minutes: a gigabyte put together and checked takes far less. */
71
+ const MAX_POLLS = 600;
72
+ const RETRIES = [2000, 4000, 8000];
73
+ export async function socialCommand(ctx) {
74
+ const { ui } = ctx;
75
+ const asJson = ctx.args.includes('--json');
76
+ try {
77
+ const o = parseSocialArgs(ctx.args);
78
+ const command = o.words[0] ?? 'help';
79
+ if (ctx.help || command === 'help') {
80
+ ui.write(HELP);
81
+ return 0;
82
+ }
83
+ const commands = { guide, status, slots, upload, add, list, show, cancel, retry };
84
+ const run = Object.hasOwn(commands, command) ? commands[command] : undefined;
85
+ if (!run)
86
+ throw new Failure(`Unknown command "social ${command}".`, { hint: 'See `npx usebecky social help`.' });
87
+ if (!ctx.ref) {
88
+ if (!asJson)
89
+ return ctx.noProject();
90
+ throw new Failure('No linked project found.', { code: 'no_project', hint: 'Run `npx usebecky init` in your app folder, or pass --project <ref>.' });
91
+ }
92
+ // With --json nothing may ask a question: the output is read by a program.
93
+ if (asJson && !ctx.signedIn)
94
+ throw new Failure('Not signed in.', { code: 'not_signed_in', hint: 'Run `npx usebecky login` first (or set USEBECKY_ACCESS_TOKEN).', status: 401 });
95
+ if (!(await ctx.signIn()))
96
+ return 1;
97
+ return await run(o);
98
+ }
99
+ catch (err) {
100
+ if (!(err instanceof Failure))
101
+ throw err;
102
+ if (asJson)
103
+ json({ error: { code: err.code, message: err.message, ...(err.hint ? { hint: err.hint } : {}) } });
104
+ else {
105
+ ui.error(err.message);
106
+ if (err.hint)
107
+ ui.write(` ${c.dim(err.hint)}`);
108
+ if (err.status === 401)
109
+ ui.write(` ${c.dim('Your login expired. Run `npx usebecky login` again.')}`);
110
+ }
111
+ return 1;
112
+ }
113
+ // ---- helpers ----------------------------------------------------------------------------------------
114
+ function json(value) {
115
+ ui.write(JSON.stringify(value, null, 2));
116
+ }
117
+ function failure(e) {
118
+ if (e.status === 404 && e.code === 'route_not_found')
119
+ return new Failure('Social is not available for this project.', { code: 'social_not_available', status: 404 });
120
+ return new Failure(e.message, { code: e.code, hint: e.hint, status: e.status });
121
+ }
122
+ async function call(method, p, body, extra) {
123
+ const r = await ctx.api(method, p, body, extra);
124
+ if (r.error)
125
+ throw failure(r.error);
126
+ return r.data;
127
+ }
128
+ function wait(ms) {
129
+ return ctx.sleep ? ctx.sleep(ms) : new Promise((resolve) => setTimeout(resolve, ms));
130
+ }
131
+ /** "Thu 26 Nov, 12:00" in the project's zone. */
132
+ function when(iso, zone) {
133
+ return new Intl.DateTimeFormat('en-GB', { timeZone: zone ?? 'UTC', weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(new Date(iso));
134
+ }
135
+ // Function declarations only below the `return` above: a `const` there would never be set.
136
+ function zoneName(zone) {
137
+ return zone ?? 'UTC (no time zone set)';
138
+ }
139
+ function targetText(t, zone) {
140
+ return `${t.network} ${when(t.slot_at, zone)}${t.state === 'scheduled' ? '' : ` (${t.state.replace('_', ' ')})`}`;
141
+ }
142
+ async function timezone() {
143
+ return (await call('GET', '/rhythm')).timezone;
144
+ }
145
+ function oneWord(o, what) {
146
+ if (o.words.length !== 2)
147
+ throw new Failure(`Say which ${what}: npx usebecky social ${o.words[0]} <${what}>`);
148
+ return o.words[1];
149
+ }
150
+ function number(value, flag) {
151
+ const n = Number(value);
152
+ if (!Number.isInteger(n) || n < 1)
153
+ throw new Failure(`${flag} needs a whole number from 1.`);
154
+ return n;
155
+ }
156
+ function checkFile(file) {
157
+ const full = path.resolve(ctx.cwd, file);
158
+ let stat;
159
+ try {
160
+ stat = fs.statSync(full);
161
+ }
162
+ catch {
163
+ throw new Failure(`There is no file "${file}".`, { code: 'file_not_found' });
164
+ }
165
+ if (!stat.isFile() || !stat.size)
166
+ throw new Failure(`"${file}" is not a video file.`, { code: 'file_not_found' });
167
+ return { path: full, bytes: stat.size };
168
+ }
169
+ async function describe(file) {
170
+ const { path: full, bytes } = checkFile(file);
171
+ const hash = crypto.createHash('sha256');
172
+ for await (const chunk of fs.createReadStream(full))
173
+ hash.update(chunk);
174
+ return { file, name: path.basename(full).slice(0, 200), path: full, bytes, sha256: hash.digest('hex') };
175
+ }
176
+ async function sendPart(id, n, bytes) {
177
+ for (let tries = 0;; tries++) {
178
+ const r = await ctx.api('PUT', `/media/${id}/parts/${n}`, undefined, { raw: bytes });
179
+ if (!r.error)
180
+ return;
181
+ const passing = r.error.status === 0 || r.error.status === 429 || r.error.status >= 500;
182
+ if (!passing || tries >= RETRIES.length)
183
+ throw failure(r.error);
184
+ await wait(RETRIES[tries]);
185
+ }
186
+ }
187
+ /** The parts the server does not have yet, then `complete`. */
188
+ async function sendFile(v, id, partBytes, have) {
189
+ const fd = fs.openSync(v.path, 'r');
190
+ try {
191
+ for (let n = 1; (n - 1) * partBytes < v.bytes; n++) {
192
+ if (have.includes(n))
193
+ continue;
194
+ const size = Math.min(partBytes, v.bytes - (n - 1) * partBytes);
195
+ const buf = Buffer.alloc(size);
196
+ for (let got = 0; got < size;) {
197
+ const read = fs.readSync(fd, buf, got, size - got, (n - 1) * partBytes + got);
198
+ if (!read)
199
+ throw new Failure(`"${v.file}" changed while it was being sent.`);
200
+ got += read;
201
+ }
202
+ await sendPart(id, n, buf);
203
+ }
204
+ }
205
+ finally {
206
+ fs.closeSync(fd);
207
+ }
208
+ await call('POST', `/media/${id}/complete`);
209
+ }
210
+ async function checked(v, id) {
211
+ for (let i = 0; i < (ctx.maxPolls ?? MAX_POLLS); i++) {
212
+ const { media } = await call('GET', `/media/${id}`);
213
+ if (media.status === 'ready')
214
+ return media;
215
+ if (media.status === 'rejected')
216
+ throw new Failure(`"${v.file}" was turned down: ${media.reject_reason ?? 'it is not a video that can be posted.'}`, { code: 'media_rejected', hint: 'See "The video" in `npx usebecky social guide`.' });
217
+ if (media.status === 'purged')
218
+ throw new Failure(`"${v.file}" was deleted while it was being checked.`, { code: 'media_not_ready' });
219
+ await wait(POLL_MS);
220
+ }
221
+ throw new Failure(`"${v.file}" is still being checked.`, { code: 'media_not_ready', hint: 'Run the same command again in a few minutes: the upload is not sent twice.' });
222
+ }
223
+ /** The video on the server: the one that is already there, an upload that stopped half way, or a new upload. */
224
+ async function ensureUploaded(v, say) {
225
+ const { media } = await call('GET', '/media');
226
+ const ready = media.find((m) => m.status === 'ready' && m.sha256 === v.sha256);
227
+ if (ready)
228
+ return ready;
229
+ const open = media.find((m) => (m.status === 'uploading' || m.status === 'assembling') && m.filename === v.name && m.bytes === v.bytes);
230
+ if (open) {
231
+ say(`Continuing the upload of ${v.file}`);
232
+ if (open.status === 'uploading')
233
+ await sendFile(v, open.id, open.upload.part_bytes, open.upload.received);
234
+ const done = await checked(v, open.id);
235
+ if (done.sha256 === v.sha256)
236
+ return done;
237
+ // Same name and size, other bytes: not this video. It is removed and sent from the start.
238
+ await call('DELETE', `/media/${open.id}`);
239
+ }
240
+ say(`Uploading ${v.file}`);
241
+ const created = await call('POST', '/media', { filename: v.name, bytes: v.bytes, content_type: CONTENT_TYPES[path.extname(v.name).toLowerCase()] ?? 'video/mp4' });
242
+ await sendFile(v, created.id, created.part_bytes, []);
243
+ return checked(v, created.id);
244
+ }
245
+ // ---- commands ---------------------------------------------------------------------------------------
246
+ async function guide(o) {
247
+ const text = await call('GET', '/guide');
248
+ if (o.json)
249
+ json({ guide: text });
250
+ else
251
+ ui.write(String(text).trimEnd());
252
+ return 0;
253
+ }
254
+ async function status(o) {
255
+ const s = await call('GET', '/status?slots=3');
256
+ if (o.json) {
257
+ json(s);
258
+ return 0;
259
+ }
260
+ ui.write(`${c.bold('Time zone:')} ${zoneName(s.timezone)}`);
261
+ for (const n of s.networks) {
262
+ if (!n.available) {
263
+ ui.write(`${n.name.padEnd(10)} ${c.dim('not available yet')}`);
264
+ continue;
265
+ }
266
+ if (!n.connection) {
267
+ ui.write(`${n.name.padEnd(10)} ${c.dim('not connected (Social → Accounts in the dashboard)')}`);
268
+ continue;
269
+ }
270
+ const account = n.connection.handle ? `@${n.connection.handle}` : (n.connection.display_name ?? 'connected');
271
+ const days = n.rhythm.days.length === 7 ? 'every day' : n.rhythm.days.map((d) => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d]).join(' ');
272
+ const times = n.rhythm.days.length && n.rhythm.times.length ? `${days} at ${n.rhythm.times.join(', ')}` : 'no posting times set';
273
+ ui.write(`${n.name.padEnd(10)} ${account} ${c.dim(times)}${n.connection.status === 'active' ? '' : c.yellow(' has to be connected again')}`);
274
+ if (n.next_slots?.length)
275
+ ui.write(` Next free: ${n.next_slots.map((t) => when(t, s.timezone)).join(' · ')}`);
276
+ }
277
+ for (const w of s.warnings ?? [])
278
+ ui.warn(w);
279
+ return 0;
280
+ }
281
+ async function slots(o) {
282
+ const q = new URLSearchParams();
283
+ if (o.network)
284
+ q.set('network', o.network);
285
+ if (o.count)
286
+ q.set('count', String(number(o.count, '--count')));
287
+ if (o.perDay)
288
+ q.set('max_per_day', String(number(o.perDay, '--per-day')));
289
+ if (o.from)
290
+ q.set('not_before', o.from);
291
+ const s = await call('GET', `/slots?${q}`);
292
+ if (o.json) {
293
+ json(s);
294
+ return 0;
295
+ }
296
+ ui.write(`${c.bold('Time zone:')} ${zoneName(s.timezone)}`);
297
+ if (!s.slots.length)
298
+ ui.info('No account is connected.');
299
+ for (const a of s.slots) {
300
+ ui.write(c.bold(a.network));
301
+ if (a.problem)
302
+ ui.warn(a.problem);
303
+ for (const t of a.times)
304
+ ui.write(` ${when(t, s.timezone)} ${c.dim(t)}`);
305
+ }
306
+ return 0;
307
+ }
308
+ async function upload(o) {
309
+ const v = await describe(oneWord(o, 'file'));
310
+ const media = await ensureUploaded(v, (s) => void (o.json || ui.info(s)));
311
+ if (o.json)
312
+ json({ media });
313
+ else {
314
+ ui.success(`${v.file} is ready ${c.dim(media.id)}`);
315
+ for (const w of media.warnings ?? [])
316
+ ui.warn(w);
317
+ }
318
+ return 0;
319
+ }
320
+ async function add(o) {
321
+ const files = o.words.slice(1);
322
+ if (!files.length)
323
+ throw new Failure('Say which videos to add: npx usebecky social add <file…>');
324
+ if (o.at && files.length > 1)
325
+ throw new Failure('--at sets the time of one post: call add once per file.');
326
+ if (o.at && (o.perDay || o.from))
327
+ throw new Failure('--at sets an exact time: leave out --per-day and --from.');
328
+ if (o.caption?.includes('{link}') && !o.link)
329
+ throw new Failure('Say where {link} leads: --link https://…', { code: 'link_required' });
330
+ if (o.link && !/^https?:\/\/\S+$/i.test(o.link))
331
+ throw new Failure('--link must be a web address, like https://example.com/offer.', { code: 'invalid_link' });
332
+ const perDay = o.perDay === undefined ? undefined : number(o.perDay, '--per-day');
333
+ // Every file is looked at before anything is sent, so a typo does not leave half a batch behind.
334
+ for (const f of files)
335
+ checkFile(f);
336
+ const state = await call('GET', '/status');
337
+ const zone = state.timezone;
338
+ const named = o.networks?.split(',').map((n) => n.trim().toLowerCase()).filter(Boolean);
339
+ const usable = state.networks.filter((n) => n.available && n.connection?.status === 'active').map((n) => n.network);
340
+ const wanted = named?.length ? [...new Set(named)] : usable;
341
+ if (!wanted.length)
342
+ throw new Failure('No account is connected.', { code: 'no_account', hint: 'Connect one in the dashboard: Social → Accounts.' });
343
+ // A wrong network, day or number is said now, not after the uploads.
344
+ const unusable = wanted.find((n) => !usable.includes(n));
345
+ if (unusable)
346
+ throw new Failure(`There is no connected account to post to on "${unusable}".`, { code: 'network_not_connected', hint: usable.length ? `Connected: ${usable.join(', ')}.` : 'Connect one in the dashboard: Social → Accounts.' });
347
+ if (o.from || perDay)
348
+ await call('GET', `/slots?${new URLSearchParams({ count: '1', ...(o.from ? { not_before: o.from } : {}), ...(perDay ? { max_per_day: String(perDay) } : {}) })}`);
349
+ // It skips the question "is it there already?" for every network it posts to: with several accounts they must be named.
350
+ if (o.allowDuplicate && !named?.length && wanted.length > 1)
351
+ throw new Failure('Say where the video should be added again: --allow-duplicate needs --networks.', { code: 'networks_required', hint: `Name only the networks that should get it a second time (connected: ${wanted.join(', ')}).` });
352
+ const say = (s) => void (o.json || ui.info(s));
353
+ const results = [];
354
+ const jobs = [];
355
+ const seen = new Map();
356
+ // 1. What is already there, and the uploads of the rest. A video that is turned down ends the run before anything
357
+ // is planned.
358
+ for (const file of files) {
359
+ const v = await describe(file);
360
+ const result = { file, status: 'skipped', post_id: null, targets: [], already: [], warnings: [] };
361
+ results.push(result);
362
+ const twin = seen.get(v.sha256);
363
+ if (twin) {
364
+ result.warnings.push(`The same video as ${twin}: added once.`);
365
+ continue;
366
+ }
367
+ seen.set(v.sha256, file);
368
+ if (!o.allowDuplicate) {
369
+ const { posts } = await call('GET', `/posts?${new URLSearchParams({ sha256: v.sha256, state: ALL_STATES, limit: '500' })}`);
370
+ for (const network of wanted) {
371
+ const found = posts.flatMap((p) => p.targets.filter((t) => t.network === network).map((t) => ({ network, post_id: p.id, state: t.state, slot_at: t.slot_at })));
372
+ // A post that is planned or out says more than one that was removed or failed.
373
+ const best = found.find((t) => t.state !== 'canceled' && t.state !== 'failed') ?? found.find((t) => t.state === 'failed') ?? found[0];
374
+ if (best)
375
+ result.already.push(best);
376
+ }
377
+ }
378
+ const missing = wanted.filter((n) => !result.already.some((a) => a.network === n));
379
+ if (!missing.length)
380
+ continue;
381
+ const media = await ensureUploaded(v, say);
382
+ jobs.push({ v, result, missing: [...missing].sort(), mediaId: media.id });
383
+ }
384
+ // 2. The posts, in the order of the files: each takes the next free place after the one before.
385
+ let stopped = null;
386
+ for (const job of jobs) {
387
+ // The link counts only when one is given, so a run without one asks under the same key as before.
388
+ const key = o.allowDuplicate ? crypto.randomUUID() : crypto.createHash('sha256').update(JSON.stringify([job.v.sha256, o.caption ?? '', o.title ?? '', job.missing, ...(o.link ? [o.link] : [])])).digest('hex');
389
+ const body = {
390
+ media_id: job.mediaId,
391
+ caption: o.caption ?? '',
392
+ ...(o.title ? { title: o.title } : {}),
393
+ ...(o.link ? { link: o.link } : {}),
394
+ networks: job.missing,
395
+ ...(o.at ? { slot_at: o.at } : {}),
396
+ ...(perDay ? { max_per_day: perDay } : {}),
397
+ ...(o.from ? { not_before: o.from } : {}),
398
+ ...(o.allowDuplicate ? { allow_duplicate: true } : {}),
399
+ };
400
+ const r = await ctx.api('POST', '/posts', body, { headers: { 'idempotency-key': `cli-${key}` } });
401
+ if (r.error) {
402
+ // Somebody else (or an earlier run) added it in between.
403
+ if (r.error.code === 'already_scheduled' || r.error.code === 'idempotency_conflict') {
404
+ job.result.warnings.push(r.error.message);
405
+ continue;
406
+ }
407
+ stopped = failure(r.error);
408
+ break;
409
+ }
410
+ const post = r.data.post;
411
+ job.result.post_id = post.id;
412
+ job.result.targets = post.targets.map((t) => ({ network: t.network, slot_at: t.slot_at, state: t.state }));
413
+ job.result.warnings.push(...post.warnings);
414
+ job.result.status = r.data.replay ? 'skipped' : 'added';
415
+ if (!o.caption && !r.data.replay)
416
+ job.result.warnings.push(NO_TEXT_WARNING);
417
+ }
418
+ const added = results.filter((r) => r.status === 'added').length;
419
+ if (o.json) {
420
+ // Videos that were not reached when a post could not be planned say so.
421
+ json({ timezone: zone, added, results, ...(stopped ? { error: { code: stopped.code, message: stopped.message, ...(stopped.hint ? { hint: stopped.hint } : {}) } } : {}) });
422
+ return stopped ? 1 : 0;
423
+ }
424
+ for (const r of results) {
425
+ if (r.status === 'added')
426
+ ui.success(`${r.file} → ${r.targets.map((t) => targetText(t, zone)).join(', ')} ${c.dim(r.post_id)}`);
427
+ else if (r.targets.length)
428
+ ui.info(`${r.file} was added before: ${r.targets.map((t) => targetText(t, zone)).join(', ')} ${c.dim(r.post_id)}`);
429
+ for (const a of r.already) {
430
+ if (a.state === 'canceled')
431
+ ui.warn(`${r.file} was removed from ${a.network} earlier and was not added again. (--allow-duplicate adds it anyway.)`);
432
+ else if (a.state === 'failed')
433
+ ui.warn(`${r.file} failed on ${a.network} earlier. Try that post again: npx usebecky social retry ${a.post_id}`);
434
+ else
435
+ ui.info(`${r.file} is already in the pipeline: ${targetText(a, zone)} ${c.dim(a.post_id)}`);
436
+ }
437
+ }
438
+ for (const w of new Set(results.flatMap((r) => r.warnings)))
439
+ ui.warn(w);
440
+ if (stopped) {
441
+ ui.error(`${added} of ${results.length} videos were added, then it stopped.`);
442
+ throw stopped;
443
+ }
444
+ ui.write(`\n${added} added, ${results.length - added} not added. Times are ${zoneName(zone)}.`);
445
+ return 0;
446
+ }
447
+ async function list(o) {
448
+ const q = new URLSearchParams({ limit: '500' });
449
+ if (o.state)
450
+ q.set('state', o.state);
451
+ if (o.network)
452
+ q.set('network', o.network);
453
+ // The last seven days and everything ahead. --all: older ones too; the newest are asked for (the answer has a limit)
454
+ // and shown in the order of time like the rest.
455
+ if (o.all)
456
+ q.set('order', 'desc');
457
+ else
458
+ q.set('from', new Date(Date.now() - 7 * 86400_000).toISOString());
459
+ const zone = await timezone();
460
+ const { posts } = await call('GET', `/posts?${q}`);
461
+ if (o.all)
462
+ posts.reverse();
463
+ if (o.json) {
464
+ json({ timezone: zone, posts });
465
+ return 0;
466
+ }
467
+ ui.write(`${c.bold('Time zone:')} ${zoneName(zone)}`);
468
+ if (!posts.length)
469
+ ui.info('Nothing here.');
470
+ for (const p of posts) {
471
+ const line = String(p.caption).split('\n')[0].slice(0, 60);
472
+ const text = line ? `"${line}"` : p.targets.some((t) => t.caption) ? '(a text per network)' : '(no text)';
473
+ ui.write(`${p.targets.map((t) => targetText(t, zone)).join(', ')} ${c.bold(p.media.filename)} ${text} ${c.dim(p.id)}`);
474
+ }
475
+ return 0;
476
+ }
477
+ async function show(o) {
478
+ const id = oneWord(o, 'post id');
479
+ const zone = await timezone();
480
+ const r = await call('GET', `/posts/${encodeURIComponent(id)}`);
481
+ if (o.json) {
482
+ json({ timezone: zone, ...r });
483
+ return 0;
484
+ }
485
+ ui.write(`${c.bold(r.post.media.filename)} ${c.dim(r.post.id)}`);
486
+ if (r.post.caption)
487
+ ui.write(r.post.caption);
488
+ for (const t of r.post.targets) {
489
+ ui.write(` ${targetText(t, zone)}${t.permalink ? ` ${t.permalink}` : ''}${t.short_link ? ` ${c.dim(`link: ${t.short_link}`)}` : ''}`);
490
+ if (t.error)
491
+ ui.warn(t.error);
492
+ }
493
+ for (const w of r.post.warnings)
494
+ ui.warn(w);
495
+ ui.write(c.bold('History'));
496
+ for (const e of r.events)
497
+ ui.write(` ${c.dim(when(e.at, zone))} ${e.network}: ${e.detail ?? e.to_state}`);
498
+ return 0;
499
+ }
500
+ async function cancel(o) {
501
+ const r = await call('DELETE', `/posts/${encodeURIComponent(oneWord(o, 'post id'))}`);
502
+ const waiting = r.post.targets.filter((t) => t.cancel_requested);
503
+ if (o.json)
504
+ json(r);
505
+ else if (waiting.length)
506
+ ui.info('The post is being prepared. It stops before it is posted.');
507
+ else
508
+ ui.success('Removed from the pipeline.');
509
+ return 0;
510
+ }
511
+ async function retry(o) {
512
+ const id = encodeURIComponent(oneWord(o, 'post id'));
513
+ const { post } = await call('GET', `/posts/${id}`);
514
+ const targets = post.targets.filter((t) => !o.network || t.network === o.network);
515
+ const doubtful = targets.filter((t) => t.state === 'needs_review');
516
+ const again = targets.filter((t) => t.state === 'failed' || (o.needsReview && t.state === 'needs_review'));
517
+ // Retrying a post that may be online would post it twice: only when somebody looked (--needs-review).
518
+ if (!again.length) {
519
+ if (doubtful.length)
520
+ throw new Failure('It is not clear whether this post went out.', { code: 'needs_review', hint: 'Look at the account. Only if it is not there: add --needs-review. If it is there, choose "Mark as posted" in the dashboard.' });
521
+ throw new Failure('Nothing to try again: no part of this post failed.', { code: 'target_state' });
522
+ }
523
+ let last = post;
524
+ for (const t of again)
525
+ last = (await call('POST', `/posts/${id}/targets/${t.network}/retry`)).post;
526
+ if (o.json)
527
+ json({ post: last });
528
+ else
529
+ ui.success(`Trying again on ${again.map((t) => t.network).join(', ')}.`);
530
+ return 0;
531
+ }
532
+ }
@@ -0,0 +1,28 @@
1
+ import { type Ui } from './ui.ts';
2
+ type ApiResult<T> = {
3
+ data: T | null;
4
+ error: {
5
+ code: string;
6
+ message: string;
7
+ hint?: string;
8
+ status: number;
9
+ details?: any;
10
+ } | null;
11
+ };
12
+ export interface TokensContext {
13
+ ui: Ui;
14
+ args: string[];
15
+ ref: string | null;
16
+ yes: boolean;
17
+ api: <T = any>(method: string, path: string, body?: unknown) => Promise<ApiResult<T>>;
18
+ signIn: () => Promise<boolean>;
19
+ printError: (e: {
20
+ message: string;
21
+ hint?: string;
22
+ status?: number;
23
+ }) => number;
24
+ noProject: () => number;
25
+ }
26
+ export declare const SCOPE_TEXT: Record<string, string>;
27
+ export declare function tokensCommand(ctx: TokensContext): Promise<number>;
28
+ export {};