@curlycode/storescreenshot 1.0.0 → 1.0.1

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.
package/README.md CHANGED
@@ -29,3 +29,7 @@ npx -y @curlycode/storescreenshot@latest send --app-name "My App" --description-
29
29
  ## Requirements
30
30
 
31
31
  Node 18 or newer. Capturing an iOS app needs macOS with Xcode.
32
+
33
+ ## Development
34
+
35
+ The CLI is written in TypeScript in `src/` and compiled to `dist/`, which is what npm ships. `npm run build` compiles it, and `npm publish` builds it automatically through `prepack`.
@@ -0,0 +1,262 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, extname, join } from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ const DEFAULT_API_URL = 'https://storescreenshot.app';
8
+ const API_URL = (process.env.STORESCREENSHOT_API_URL || DEFAULT_API_URL).replace(/\/$/, '');
9
+ function tokenFileName() {
10
+ if (API_URL === DEFAULT_API_URL) {
11
+ return 'token';
12
+ }
13
+ return `token-${new URL(API_URL).host.replace(/[^a-z0-9.-]/gi, '_')}`;
14
+ }
15
+ const TOKEN_FILE = join(homedir(), '.config', 'storescreenshot', tokenFileName());
16
+ const TOKEN = process.env.STORESCREENSHOT_TOKEN || (await readSavedToken());
17
+ const CLI_COMMAND = 'npx -y @curlycode/storescreenshot@latest';
18
+ const TOKEN_HELP = `Connect your StoreScreenshot account once with:
19
+ ${CLI_COMMAND} login`;
20
+ async function readSavedToken() {
21
+ try {
22
+ return (await readFile(TOKEN_FILE, 'utf8')).trim() || undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ const MIME_TYPES = {
29
+ '.png': 'image/png',
30
+ '.jpg': 'image/jpeg',
31
+ '.jpeg': 'image/jpeg',
32
+ '.webp': 'image/webp',
33
+ };
34
+ function fail(message) {
35
+ console.error(message);
36
+ process.exit(1);
37
+ }
38
+ function unreachable(error) {
39
+ const reason = error instanceof Error ? error.message : String(error);
40
+ fail(`Could not reach ${API_URL}: ${reason}\nRun the same command again to retry.`);
41
+ }
42
+ async function parseResponse(response) {
43
+ const text = await response.text();
44
+ return { status: response.status, body: text ? JSON.parse(text) : {} };
45
+ }
46
+ async function request(path, init = {}) {
47
+ if (!TOKEN) {
48
+ fail(`Not connected to StoreScreenshot yet.\n${TOKEN_HELP}`);
49
+ }
50
+ try {
51
+ const response = await fetch(`${API_URL}${path}`, {
52
+ ...init,
53
+ headers: {
54
+ Authorization: `Bearer ${TOKEN}`,
55
+ 'Content-Type': 'application/json',
56
+ ...init.headers,
57
+ },
58
+ });
59
+ return await parseResponse(response);
60
+ }
61
+ catch (error) {
62
+ unreachable(error);
63
+ }
64
+ }
65
+ async function postJson(path, payload) {
66
+ try {
67
+ const response = await fetch(`${API_URL}${path}`, {
68
+ method: 'POST',
69
+ headers: { 'Content-Type': 'application/json' },
70
+ body: JSON.stringify(payload),
71
+ });
72
+ return await parseResponse(response);
73
+ }
74
+ catch (error) {
75
+ unreachable(error);
76
+ }
77
+ }
78
+ async function me() {
79
+ const { status, body } = await request('/api/v1/me');
80
+ if (status === 401) {
81
+ fail(`The token was refused.\n${TOKEN_HELP}`);
82
+ }
83
+ if (status !== 200) {
84
+ fail(`Unexpected response (${status}): ${body.error ?? 'no details'}`);
85
+ }
86
+ console.log(`Signed in as ${body.email} on ${API_URL}`);
87
+ console.log(`Screenshot credits left: ${body.screenshotCredits}`);
88
+ if (!body.emailVerified) {
89
+ console.log('Your email is not verified yet. Verify it before sending screenshots.');
90
+ }
91
+ }
92
+ async function readStdin() {
93
+ const chunks = [];
94
+ for await (const chunk of process.stdin) {
95
+ chunks.push(chunk);
96
+ }
97
+ return Buffer.concat(chunks).toString('utf8').trim();
98
+ }
99
+ async function saveToken(token) {
100
+ await mkdir(dirname(TOKEN_FILE), { recursive: true });
101
+ await writeFile(TOKEN_FILE, `${token}\n`, { mode: 0o600 });
102
+ await chmod(TOKEN_FILE, 0o600);
103
+ }
104
+ const OPEN_COMMANDS = {
105
+ darwin: 'open',
106
+ win32: 'explorer',
107
+ };
108
+ function openInBrowser(url) {
109
+ const command = OPEN_COMMANDS[process.platform] ?? 'xdg-open';
110
+ try {
111
+ // A missing opener (no xdg-open on a server) is reported as an 'error' event, not thrown.
112
+ spawn(command, [url], { stdio: 'ignore', detached: true })
113
+ .on('error', () => undefined)
114
+ .unref();
115
+ }
116
+ catch {
117
+ return;
118
+ }
119
+ }
120
+ const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
121
+ const CODE_EXPIRED = 'The code expired before it was approved. Run login again to get a new one.';
122
+ const LOGIN_FAILURES = new Map([
123
+ ['access_denied', 'The request was denied in the browser. Run login again to retry.'],
124
+ ['expired_token', CODE_EXPIRED],
125
+ ['invalid_grant', 'This login request is no longer valid. Run login again.'],
126
+ ]);
127
+ async function waitForApproval({ deviceCode, interval, expiresIn, }) {
128
+ const deadline = Date.now() + expiresIn * 1000;
129
+ let delay = interval;
130
+ while (Date.now() < deadline) {
131
+ await sleep(delay);
132
+ const { status, body } = await postJson('/api/v1/cli/token', {
133
+ deviceCode,
134
+ });
135
+ if (status === 200 && body.token) {
136
+ return body.token;
137
+ }
138
+ if (body.error === 'slow_down') {
139
+ delay += 5;
140
+ continue;
141
+ }
142
+ if (body.error !== 'authorization_pending') {
143
+ const known = body.error === undefined ? undefined : LOGIN_FAILURES.get(body.error);
144
+ fail(known ?? `Login failed (${status}): ${body.error ?? 'no details'}`);
145
+ }
146
+ }
147
+ fail(CODE_EXPIRED);
148
+ }
149
+ async function loginInBrowser() {
150
+ const { status, body } = await postJson('/api/v1/cli/device-code', {});
151
+ const { deviceCode, userCode, verificationUrlComplete, interval, expiresIn } = body;
152
+ if (status !== 200 ||
153
+ deviceCode === undefined ||
154
+ verificationUrlComplete === undefined ||
155
+ interval === undefined ||
156
+ expiresIn === undefined) {
157
+ fail(`Could not start the login (${status}): ${body.error ?? 'no details'}`);
158
+ }
159
+ console.log('To connect StoreScreenshot, open this link and click Authorize:');
160
+ console.log(` ${verificationUrlComplete}`);
161
+ console.log(`Check that the page shows the code ${userCode}.`);
162
+ console.log('New to StoreScreenshot? The same page lets you sign up for free.');
163
+ openInBrowser(verificationUrlComplete);
164
+ console.log('Waiting for approval...');
165
+ const token = await waitForApproval({ deviceCode, interval, expiresIn });
166
+ await saveToken(token);
167
+ console.log(`Connected. Token saved to ${TOKEN_FILE}.`);
168
+ }
169
+ async function loginWithStdinToken() {
170
+ const token = await readStdin();
171
+ if (!token.startsWith('ss_')) {
172
+ fail(`That does not look like a StoreScreenshot token.\n${TOKEN_HELP}`);
173
+ }
174
+ await saveToken(token);
175
+ console.log(`Token saved to ${TOKEN_FILE}.`);
176
+ }
177
+ function login(argv) {
178
+ if (argv.includes('--token-stdin')) {
179
+ return loginWithStdinToken();
180
+ }
181
+ return loginInBrowser();
182
+ }
183
+ async function toScreenshot(path) {
184
+ const mimeType = MIME_TYPES[extname(path).toLowerCase()];
185
+ if (!mimeType) {
186
+ fail(`Unsupported file type: ${path}. Use PNG, JPEG or WebP.`);
187
+ }
188
+ const buffer = await readFile(path);
189
+ return { base64: buffer.toString('base64'), mimeType };
190
+ }
191
+ async function send(argv) {
192
+ const { values, positionals } = parseArgs({
193
+ args: argv,
194
+ allowPositionals: true,
195
+ options: {
196
+ 'app-name': { type: 'string' },
197
+ 'description-file': { type: 'string' },
198
+ description: { type: 'string' },
199
+ device: { type: 'string', default: 'iphone' },
200
+ },
201
+ });
202
+ const appName = values['app-name'];
203
+ if (!appName) {
204
+ fail('Missing --app-name.');
205
+ }
206
+ const descriptionFile = values['description-file'];
207
+ const prompt = descriptionFile
208
+ ? await readFile(descriptionFile, 'utf8')
209
+ : values.description;
210
+ if (!prompt?.trim()) {
211
+ fail('Missing --description-file or --description.');
212
+ }
213
+ if (positionals.length === 0) {
214
+ fail('Pass the screenshot files to send, in gallery order.');
215
+ }
216
+ const screenshots = await Promise.all(positionals.map(toScreenshot));
217
+ console.log(`Sending ${screenshots.length} screenshots for ${appName}...`);
218
+ const { status, body } = await request('/api/v1/projects', {
219
+ method: 'POST',
220
+ body: JSON.stringify({
221
+ appName,
222
+ prompt: prompt.trim(),
223
+ screenshots,
224
+ deviceFamily: values.device,
225
+ source: 'cli',
226
+ }),
227
+ });
228
+ if (status === 201) {
229
+ console.log(`Project created. ${body.creditsSpent} credits spent.`);
230
+ console.log(`Open it: ${body.studioUrl}`);
231
+ console.log('The screenshots appear frame by frame over the next minutes.');
232
+ return;
233
+ }
234
+ if (status === 401) {
235
+ fail(`The token was refused.\n${TOKEN_HELP}`);
236
+ }
237
+ if (status === 402) {
238
+ fail(`Not enough screenshot credits: ${body.creditsNeeded} needed, ${body.creditsAvailable} left.\n` +
239
+ `Buy credits at ${body.pricingUrl}, then run the same command again. Your captures are saved.`);
240
+ }
241
+ fail(`StoreScreenshot refused the request (${status}): ${body.error ?? 'no details'}`);
242
+ }
243
+ async function version() {
244
+ const packageJson = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
245
+ console.log(packageJson.version);
246
+ }
247
+ const COMMANDS = new Map([
248
+ ['login', (argv) => login(argv)],
249
+ ['me', () => me()],
250
+ ['send', (argv) => send(argv)],
251
+ ['--version', () => version()],
252
+ ]);
253
+ const [command, ...rest] = process.argv.slice(2);
254
+ if (API_URL !== DEFAULT_API_URL && command !== '--version') {
255
+ console.error(`Using ${API_URL} (set by STORESCREENSHOT_API_URL).`);
256
+ }
257
+ const run = command === undefined ? undefined : COMMANDS.get(command);
258
+ if (!run) {
259
+ fail(`Usage: ${CLI_COMMAND} login [--token-stdin] | me | send --app-name <name> --description-file <file> <screenshots...>\n` +
260
+ 'Full guide for coding agents: https://storescreenshot.app/setup.md');
261
+ }
262
+ await run(rest);
package/package.json CHANGED
@@ -1,17 +1,21 @@
1
1
  {
2
2
  "name": "@curlycode/storescreenshot",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Send your app's screens to StoreScreenshot from any coding agent and get designed App Store screenshots.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "storescreenshot": "bin/storescreenshot.mjs"
7
+ "storescreenshot": "dist/storescreenshot.js"
8
8
  },
9
9
  "files": [
10
- "bin"
10
+ "dist"
11
11
  ],
12
12
  "engines": {
13
13
  "node": ">=18"
14
14
  },
15
+ "scripts": {
16
+ "build": "tsc",
17
+ "prepack": "npm run build"
18
+ },
15
19
  "keywords": [
16
20
  "app store screenshots",
17
21
  "app store screenshot generator",
@@ -32,5 +36,9 @@
32
36
  "license": "MIT",
33
37
  "publishConfig": {
34
38
  "access": "public"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^18.19.130",
42
+ "typescript": "^7.0.2"
35
43
  }
36
44
  }
@@ -1,316 +0,0 @@
1
- #!/usr/bin/env node
2
- import { spawn } from 'node:child_process';
3
- import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
4
- import { homedir } from 'node:os';
5
- import { dirname, extname, join } from 'node:path';
6
- import { parseArgs } from 'node:util';
7
-
8
- const DEFAULT_API_URL = 'https://storescreenshot.app';
9
-
10
- const API_URL = (process.env.STORESCREENSHOT_API_URL || DEFAULT_API_URL).replace(
11
- /\/$/,
12
- '',
13
- );
14
-
15
- function tokenFileName() {
16
- if (API_URL === DEFAULT_API_URL) {
17
- return 'token';
18
- }
19
-
20
- return `token-${new URL(API_URL).host.replace(/[^a-z0-9.-]/gi, '_')}`;
21
- }
22
-
23
- const TOKEN_FILE = join(homedir(), '.config', 'storescreenshot', tokenFileName());
24
-
25
- const TOKEN = process.env.STORESCREENSHOT_TOKEN || (await readSavedToken());
26
-
27
- const CLI_COMMAND = 'npx -y @curlycode/storescreenshot@latest';
28
-
29
- const TOKEN_HELP = `Connect your StoreScreenshot account once with:
30
- ${CLI_COMMAND} login`;
31
-
32
- async function readSavedToken() {
33
- try {
34
- return (await readFile(TOKEN_FILE, 'utf8')).trim() || undefined;
35
- } catch {
36
- return undefined;
37
- }
38
- }
39
-
40
- const MIME_TYPES = {
41
- '.png': 'image/png',
42
- '.jpg': 'image/jpeg',
43
- '.jpeg': 'image/jpeg',
44
- '.webp': 'image/webp',
45
- };
46
-
47
- function fail(message) {
48
- console.error(message);
49
- process.exit(1);
50
- }
51
-
52
- async function request(path, init = {}) {
53
- if (!TOKEN) {
54
- fail(`Not connected to StoreScreenshot yet.\n${TOKEN_HELP}`);
55
- }
56
-
57
- try {
58
- const response = await fetch(`${API_URL}${path}`, {
59
- ...init,
60
- headers: {
61
- Authorization: `Bearer ${TOKEN}`,
62
- 'Content-Type': 'application/json',
63
- ...init.headers,
64
- },
65
- });
66
-
67
- const text = await response.text();
68
- const body = text ? JSON.parse(text) : null;
69
-
70
- return { status: response.status, body };
71
- } catch (error) {
72
- fail(`Could not reach ${API_URL}: ${error.message}\nRun the same command again to retry.`);
73
- }
74
- }
75
-
76
- async function me() {
77
- const { status, body } = await request('/api/v1/me');
78
-
79
- if (status === 401) {
80
- fail(`The token was refused.\n${TOKEN_HELP}`);
81
- }
82
-
83
- if (status !== 200) {
84
- fail(`Unexpected response (${status}): ${body?.error ?? 'no details'}`);
85
- }
86
-
87
- console.log(`Signed in as ${body.email} on ${API_URL}`);
88
- console.log(`Screenshot credits left: ${body.screenshotCredits}`);
89
-
90
- if (!body.emailVerified) {
91
- console.log('Your email is not verified yet. Verify it before sending screenshots.');
92
- }
93
- }
94
-
95
- async function readStdin() {
96
- const chunks = [];
97
- for await (const chunk of process.stdin) {
98
- chunks.push(chunk);
99
- }
100
- return Buffer.concat(chunks).toString('utf8').trim();
101
- }
102
-
103
- async function saveToken(token) {
104
- await mkdir(dirname(TOKEN_FILE), { recursive: true });
105
- await writeFile(TOKEN_FILE, `${token}\n`, { mode: 0o600 });
106
- await chmod(TOKEN_FILE, 0o600);
107
- }
108
-
109
- const OPEN_COMMANDS = { darwin: 'open', win32: 'explorer' };
110
-
111
- function openInBrowser(url) {
112
- const command = OPEN_COMMANDS[process.platform] ?? 'xdg-open';
113
-
114
- try {
115
- spawn(command, [url], { stdio: 'ignore', detached: true }).unref();
116
- } catch {
117
- return;
118
- }
119
- }
120
-
121
- async function postJson(path, payload) {
122
- try {
123
- const response = await fetch(`${API_URL}${path}`, {
124
- method: 'POST',
125
- headers: { 'Content-Type': 'application/json' },
126
- body: JSON.stringify(payload),
127
- });
128
- const text = await response.text();
129
-
130
- return { status: response.status, body: text ? JSON.parse(text) : null };
131
- } catch (error) {
132
- fail(`Could not reach ${API_URL}: ${error.message}\nRun the same command again to retry.`);
133
- }
134
- }
135
-
136
- const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
137
-
138
- const LOGIN_FAILURES = {
139
- access_denied: 'The request was denied in the browser. Run login again to retry.',
140
- expired_token: 'The code expired before it was approved. Run login again to get a new one.',
141
- invalid_grant: 'This login request is no longer valid. Run login again.',
142
- };
143
-
144
- async function waitForApproval({ deviceCode, interval, expiresIn }) {
145
- const deadline = Date.now() + expiresIn * 1000;
146
- let delay = interval;
147
-
148
- while (Date.now() < deadline) {
149
- await sleep(delay);
150
- const { status, body } = await postJson('/api/v1/cli/token', { deviceCode });
151
-
152
- if (status === 200 && body?.token) {
153
- return body.token;
154
- }
155
-
156
- if (body?.error === 'slow_down') {
157
- delay += 5;
158
- continue;
159
- }
160
-
161
- if (body?.error !== 'authorization_pending') {
162
- fail(LOGIN_FAILURES[body?.error] ?? `Login failed (${status}): ${body?.error ?? 'no details'}`);
163
- }
164
- }
165
-
166
- fail(LOGIN_FAILURES.expired_token);
167
- }
168
-
169
- async function loginInBrowser() {
170
- const { status, body } = await postJson('/api/v1/cli/device-code', {});
171
-
172
- if (status !== 200) {
173
- fail(`Could not start the login (${status}): ${body?.error ?? 'no details'}`);
174
- }
175
-
176
- console.log('To connect StoreScreenshot, open this link and click Authorize:');
177
- console.log(` ${body.verificationUrlComplete}`);
178
- console.log(`Check that the page shows the code ${body.userCode}.`);
179
- console.log('New to StoreScreenshot? The same page lets you sign up for free.');
180
- openInBrowser(body.verificationUrlComplete);
181
- console.log('Waiting for approval...');
182
-
183
- const token = await waitForApproval(body);
184
- await saveToken(token);
185
- console.log(`Connected. Token saved to ${TOKEN_FILE}.`);
186
- }
187
-
188
- async function loginWithStdinToken() {
189
- const token = await readStdin();
190
-
191
- if (!token.startsWith('ss_')) {
192
- fail(`That does not look like a StoreScreenshot token.\n${TOKEN_HELP}`);
193
- }
194
-
195
- await saveToken(token);
196
- console.log(`Token saved to ${TOKEN_FILE}.`);
197
- }
198
-
199
- function login(argv) {
200
- if (argv.includes('--token-stdin')) {
201
- return loginWithStdinToken();
202
- }
203
-
204
- return loginInBrowser();
205
- }
206
-
207
- async function toScreenshot(path) {
208
- const mimeType = MIME_TYPES[extname(path).toLowerCase()];
209
-
210
- if (!mimeType) {
211
- fail(`Unsupported file type: ${path}. Use PNG, JPEG or WebP.`);
212
- }
213
-
214
- const buffer = await readFile(path);
215
-
216
- return { base64: buffer.toString('base64'), mimeType };
217
- }
218
-
219
- async function send(argv) {
220
- const { values, positionals } = parseArgs({
221
- args: argv,
222
- allowPositionals: true,
223
- options: {
224
- 'app-name': { type: 'string' },
225
- 'description-file': { type: 'string' },
226
- description: { type: 'string' },
227
- device: { type: 'string', default: 'iphone' },
228
- },
229
- });
230
-
231
- const appName = values['app-name'];
232
-
233
- if (!appName) {
234
- fail('Missing --app-name.');
235
- }
236
-
237
- const descriptionFile = values['description-file'];
238
-
239
- const prompt = descriptionFile
240
- ? await readFile(descriptionFile, 'utf8')
241
- : values.description;
242
-
243
- if (!prompt?.trim()) {
244
- fail('Missing --description-file or --description.');
245
- }
246
-
247
- if (positionals.length === 0) {
248
- fail('Pass the screenshot files to send, in gallery order.');
249
- }
250
-
251
- const screenshots = await Promise.all(positionals.map(toScreenshot));
252
-
253
- console.log(`Sending ${screenshots.length} screenshots for ${appName}...`);
254
-
255
- const { status, body } = await request('/api/v1/projects', {
256
- method: 'POST',
257
- body: JSON.stringify({
258
- appName,
259
- prompt: prompt.trim(),
260
- screenshots,
261
- deviceFamily: values.device,
262
- source: 'cli',
263
- }),
264
- });
265
-
266
- if (status === 201) {
267
- console.log(`Project created. ${body.creditsSpent} credits spent.`);
268
- console.log(`Open it: ${body.studioUrl}`);
269
- console.log('The screenshots appear frame by frame over the next minutes.');
270
- return;
271
- }
272
-
273
- if (status === 401) {
274
- fail(`The token was refused.\n${TOKEN_HELP}`);
275
- }
276
-
277
- if (status === 402) {
278
- fail(
279
- `Not enough screenshot credits: ${body.creditsNeeded} needed, ${body.creditsAvailable} left.\n` +
280
- `Buy credits at ${body.pricingUrl}, then run the same command again. Your captures are saved.`,
281
- );
282
- }
283
-
284
- fail(`StoreScreenshot refused the request (${status}): ${body?.error ?? 'no details'}`);
285
- }
286
-
287
- async function version() {
288
- const packageJson = JSON.parse(
289
- await readFile(new URL('../package.json', import.meta.url), 'utf8'),
290
- );
291
-
292
- console.log(packageJson.version);
293
- }
294
-
295
- const COMMANDS = {
296
- login: (argv) => login(argv),
297
- me: () => me(),
298
- send: (argv) => send(argv),
299
- '--version': () => version(),
300
- };
301
-
302
- const [command, ...rest] = process.argv.slice(2);
303
-
304
- if (API_URL !== DEFAULT_API_URL && command !== '--version') {
305
- console.error(`Using ${API_URL} (set by STORESCREENSHOT_API_URL).`);
306
- }
307
- const run = COMMANDS[command];
308
-
309
- if (!run) {
310
- fail(
311
- `Usage: ${CLI_COMMAND} login [--token-stdin] | me | send --app-name <name> --description-file <file> <screenshots...>\n` +
312
- 'Full guide for coding agents: https://storescreenshot.app/setup.md',
313
- );
314
- }
315
-
316
- await run(rest);