@gepetto/cli 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.
- package/README.md +29 -2
- package/bin/gepetto.mjs +337 -0
- package/package.json +27 -4
package/README.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @gepetto/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Gepetto API v2 from the terminal: real estate photo editing (enhance, declutter, furnish, sky, creative restyle, walls
|
|
4
|
+
and floors, upscale). Made so that a person, or a coding agent such as Claude Code, can go from an empty project to a
|
|
5
|
+
first render without leaving the terminal. Needs Node 18 or later. Formerly `gepetto-cli`.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx @gepetto/cli login # opens a page: check the code, click "Authorize"
|
|
9
|
+
npx @gepetto/cli init # writes GEPETTO_API_KEY (test key, 200 free renders) to .env
|
|
10
|
+
npx @gepetto/cli run declutter --image ./room.jpg --out empty.png
|
|
11
|
+
npx @gepetto/cli run furnish --image ./room.jpg --roomId bedroom --styleId modern
|
|
12
|
+
npx @gepetto/cli run enhance --image ./room.jpg --straighten
|
|
13
|
+
npx @gepetto/cli list rooms # valid ids (also: styles, furnitures, skies, surfaces)
|
|
14
|
+
npx @gepetto/cli job <id> # one job; jobs --failed lists the latest failures with their reason
|
|
15
|
+
npx @gepetto/cli usage # renders and consumption of the period
|
|
16
|
+
npx @gepetto/cli webhook test http://localhost:3000/api/gepetto # sends a signed success and failure to your endpoint
|
|
17
|
+
npx @gepetto/cli secret # your webhook signing secret
|
|
18
|
+
npx @gepetto/cli keys # your test and live keys, masked (--show to print them in full)
|
|
19
|
+
npx @gepetto/cli subscribe # payment link; the live key is written to .env.production.local once paid
|
|
20
|
+
npx @gepetto/cli whoami # or logout
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`run` passes any API parameter as is: `--keepFireplace`, `--straighten`, `--skyId sunny`, `--resolution 4k`... A local `--image` or
|
|
24
|
+
`--mask` file is uploaded first.
|
|
25
|
+
|
|
26
|
+
Every command accepts `--json`. The API key is read from `--key`, then `GEPETTO_API_KEY`, then `.env.local` /
|
|
27
|
+
`.env`, then the test key of the signed-in account.
|
|
28
|
+
|
|
29
|
+
API: `https://europe-west1-gepettoai.cloudfunctions.net/v2`, header `Authorization: Bearer <key>`.
|
|
30
|
+
Documentation: https://docs.gepettoapp.com
|
package/bin/gepetto.mjs
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @gepetto/cli (ex gepetto-cli) : connecter un projet à l'API Gepetto v2 depuis le terminal, pour une personne ou pour son agent de code.
|
|
3
|
+
// Aucune dépendance (Node 18 ou plus). Toutes les commandes acceptent --json pour une sortie lisible par une machine.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
|
|
10
|
+
const VERSION = '0.2.0';
|
|
11
|
+
const API = (process.env.GEPETTO_API_URL || 'https://europe-west1-gepettoai.cloudfunctions.net/v2').replace(/\/$/, '');
|
|
12
|
+
// The keys go wherever GEPETTO_API_URL points: https only (http allowed for a local server)
|
|
13
|
+
{
|
|
14
|
+
let ok = false;
|
|
15
|
+
try { const u = new URL(API); ok = u.protocol === 'https:' || (u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)); } catch { /* invalid */ }
|
|
16
|
+
if (!ok) { console.error(`Error (invalid_api_url): GEPETTO_API_URL must be an https URL (or http://localhost), not "${API}".`); process.exit(1); }
|
|
17
|
+
}
|
|
18
|
+
/** The only sites the CLI opens in the browser: the approval page and the payment page. */
|
|
19
|
+
const BROWSER_HOSTS = ['app.gepettoapp.com', 'pay.gepettoapp.com', 'checkout.stripe.com'];
|
|
20
|
+
const CONFIG_DIR = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'gepetto');
|
|
21
|
+
const CREDENTIALS = path.join(CONFIG_DIR, 'credentials.json');
|
|
22
|
+
const TOOLS = ['declutter', 'furnish', 'sunshine', 'creative-redesign', 'surfaces', 'enhance', 'upscale'];
|
|
23
|
+
const LISTS = ['rooms', 'styles', 'furnitures', 'skies', 'surfaces'];
|
|
24
|
+
|
|
25
|
+
// --- arguments ---
|
|
26
|
+
|
|
27
|
+
const argv = process.argv.slice(2);
|
|
28
|
+
const positional = [];
|
|
29
|
+
const flags = {};
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const a = argv[i];
|
|
32
|
+
if (a.startsWith('--')) {
|
|
33
|
+
const [rawName, inline] = a.slice(2).split(/=(.*)/s, 2);
|
|
34
|
+
const name = rawName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
35
|
+
if (inline !== undefined) flags[name] = inline;
|
|
36
|
+
else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[name] = argv[++i];
|
|
37
|
+
else flags[name] = true;
|
|
38
|
+
} else positional.push(a);
|
|
39
|
+
}
|
|
40
|
+
const JSON_OUT = flags.json === true;
|
|
41
|
+
delete flags.json;
|
|
42
|
+
|
|
43
|
+
// --- sortie ---
|
|
44
|
+
|
|
45
|
+
const out = (human, data) => {
|
|
46
|
+
if (JSON_OUT) console.log(JSON.stringify(data ?? { message: human }));
|
|
47
|
+
else if (human) console.log(human);
|
|
48
|
+
};
|
|
49
|
+
function fail(code, message, extra = {}) {
|
|
50
|
+
if (JSON_OUT) console.log(JSON.stringify({ status: 'error', code, message, ...extra }));
|
|
51
|
+
else console.error(`Error (${code}): ${message}`);
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// --- HTTP ---
|
|
56
|
+
|
|
57
|
+
async function api(method, route, { token, body, raw, contentType, query } = {}) {
|
|
58
|
+
const url = new URL(API + route);
|
|
59
|
+
for (const [k, v] of Object.entries(query || {})) if (v !== undefined) url.searchParams.set(k, String(v));
|
|
60
|
+
const headers = { 'User-Agent': `gepetto-cli/${VERSION}` };
|
|
61
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
62
|
+
let payload;
|
|
63
|
+
if (raw) { payload = raw; headers['Content-Type'] = contentType; }
|
|
64
|
+
else if (body) { payload = JSON.stringify(body); headers['Content-Type'] = 'application/json'; }
|
|
65
|
+
let res;
|
|
66
|
+
try {
|
|
67
|
+
res = await fetch(url, { method, headers, body: payload });
|
|
68
|
+
} catch (e) {
|
|
69
|
+
fail('network_error', `Could not reach ${API} (${e.message}).`);
|
|
70
|
+
}
|
|
71
|
+
const text = await res.text();
|
|
72
|
+
let json;
|
|
73
|
+
try { json = JSON.parse(text); } catch { json = { status: 'error', code: `http_${res.status}`, message: text.slice(0, 300) }; }
|
|
74
|
+
if (!res.ok) fail(json.code || `http_${res.status}`, json.message || `HTTP ${res.status}`, json.id ? { id: json.id } : {});
|
|
75
|
+
return json;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// --- identifiants ---
|
|
79
|
+
|
|
80
|
+
const readCredentials = () => { try { return JSON.parse(fs.readFileSync(CREDENTIALS, 'utf8')); } catch { return null; } };
|
|
81
|
+
function writeCredentials(data) {
|
|
82
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
83
|
+
fs.writeFileSync(CREDENTIALS, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
84
|
+
// The modes above only apply to new files: forced, in case they existed with wider rights
|
|
85
|
+
try { fs.chmodSync(CONFIG_DIR, 0o700); fs.chmodSync(CREDENTIALS, 0o600); } catch { /* Windows */ }
|
|
86
|
+
}
|
|
87
|
+
function session() {
|
|
88
|
+
const c = readCredentials();
|
|
89
|
+
if (!c?.token) fail('cli_login_required', 'Not signed in: run `npx @gepetto/cli login` first.');
|
|
90
|
+
return c.token;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** GEPETTO_API_KEY from a dotenv file of the current directory. */
|
|
94
|
+
function keyFromEnvFiles() {
|
|
95
|
+
for (const file of ['.env.local', '.env']) {
|
|
96
|
+
try {
|
|
97
|
+
const line = fs.readFileSync(file, 'utf8').split('\n').find((l) => /^\s*GEPETTO_API_KEY\s*=/.test(l));
|
|
98
|
+
if (line) return line.split('=').slice(1).join('=').trim().replace(/^["']|["']$/g, '');
|
|
99
|
+
} catch { /* no file */ }
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The API key: --key, then GEPETTO_API_KEY, then .env.local / .env, then the test key of the signed-in account. */
|
|
105
|
+
async function apiKey() {
|
|
106
|
+
if (typeof flags.key === 'string') return flags.key;
|
|
107
|
+
if (process.env.GEPETTO_API_KEY) return process.env.GEPETTO_API_KEY;
|
|
108
|
+
const fromFile = keyFromEnvFiles();
|
|
109
|
+
if (fromFile) return fromFile;
|
|
110
|
+
if (readCredentials()?.token) return (await api('GET', '/cli/keys', { token: session() })).test_key;
|
|
111
|
+
fail('missing_api_key', 'No API key: run `npx @gepetto/cli login` then `npx @gepetto/cli init`, or set GEPETTO_API_KEY.');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Sets NAME=value in a dotenv file (replaced if present), and makes sure git ignores the file. */
|
|
115
|
+
function writeEnv(file, name, value) {
|
|
116
|
+
let content = '';
|
|
117
|
+
try { content = fs.readFileSync(file, 'utf8'); } catch { /* new file */ }
|
|
118
|
+
const line = `${name}=${value}`;
|
|
119
|
+
const re = new RegExp(`^\\s*${name}\\s*=.*$`, 'm');
|
|
120
|
+
content = re.test(content) ? content.replace(re, line) : `${content}${content && !content.endsWith('\n') ? '\n' : ''}${line}\n`;
|
|
121
|
+
fs.writeFileSync(file, content, { mode: 0o600 });
|
|
122
|
+
let gitignore = '';
|
|
123
|
+
try { gitignore = fs.readFileSync('.gitignore', 'utf8'); } catch { /* none */ }
|
|
124
|
+
const ignored = gitignore.split('\n').map((l) => l.trim()).some((l) => l === file || l === `/${file}` || l === '.env*' || (file.startsWith('.env') && l === '.env*.local' && file.endsWith('.local')));
|
|
125
|
+
if (!ignored) fs.appendFileSync('.gitignore', `${gitignore && !gitignore.endsWith('\n') ? '\n' : ''}${file}\n`);
|
|
126
|
+
return !ignored;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Opens a Gepetto or Stripe page in the browser, without going through a shell (the link is printed anyway). */
|
|
130
|
+
function openBrowser(url) {
|
|
131
|
+
if (flags.noBrowser) return;
|
|
132
|
+
let target;
|
|
133
|
+
try { target = new URL(url); } catch { return; }
|
|
134
|
+
if (target.protocol !== 'https:' || !BROWSER_HOSTS.includes(target.hostname)) return;
|
|
135
|
+
const href = target.toString();
|
|
136
|
+
const [cmd, args] = process.platform === 'darwin' ? ['open', [href]]
|
|
137
|
+
: process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', href]]
|
|
138
|
+
: ['xdg-open', [href]];
|
|
139
|
+
try { spawn(cmd, args, { stdio: 'ignore', detached: true, shell: false }).on('error', () => {}).unref(); } catch { /* printed anyway */ }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
143
|
+
const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.heic': 'image/heic', '.heif': 'image/heic' };
|
|
144
|
+
|
|
145
|
+
/** A local file is sent with POST /v2/uploads; a URL is kept as it is. */
|
|
146
|
+
async function imageUrl(value, key, label) {
|
|
147
|
+
if (/^https?:\/\//i.test(value)) return value;
|
|
148
|
+
if (!fs.existsSync(value)) fail('file_not_found', `${label}: no file "${value}".`);
|
|
149
|
+
const type = MIME[path.extname(value).toLowerCase()];
|
|
150
|
+
if (!type) fail('unsupported_image', `${label}: use a JPEG, PNG, WebP or HEIC file.`);
|
|
151
|
+
const data = fs.readFileSync(value);
|
|
152
|
+
if (data.length > 10 * 1024 * 1024) fail('file_too_large', `${label}: 10 MB at most for an upload; give a public URL instead.`);
|
|
153
|
+
return (await api('POST', '/uploads', { token: key, raw: data, contentType: type })).url;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// --- commandes ---
|
|
157
|
+
|
|
158
|
+
const commands = {
|
|
159
|
+
async login() {
|
|
160
|
+
const device = await api('POST', '/cli/device', { body: { client: `@gepetto/cli ${VERSION}`, host: os.hostname() } });
|
|
161
|
+
if (JSON_OUT) console.log(JSON.stringify({ event: 'authorize', url: device.verification_url, code: device.user_code, expires_in: device.expires_in }));
|
|
162
|
+
else console.log(`Open ${device.verification_url} and check that the code is ${device.user_code}, then click "Authorize".\nWaiting for the authorization…`);
|
|
163
|
+
openBrowser(device.verification_url);
|
|
164
|
+
const deadline = Date.now() + device.expires_in * 1000;
|
|
165
|
+
while (Date.now() < deadline) {
|
|
166
|
+
await sleep((device.interval || 3) * 1000);
|
|
167
|
+
const r = await api('POST', '/cli/token', { body: { device_code: device.device_code } });
|
|
168
|
+
if (r.status === 'approved') {
|
|
169
|
+
writeCredentials({ token: r.token, email: r.email, created_at: new Date().toISOString() });
|
|
170
|
+
return out(`Signed in as ${r.email}. Next: npx @gepetto/cli init`, { event: 'logged_in', email: r.email });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
fail('code_expired', 'The code expired before it was approved. Run the command again.');
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
async logout() {
|
|
177
|
+
const c = readCredentials();
|
|
178
|
+
let revoked = false;
|
|
179
|
+
if (c?.token) {
|
|
180
|
+
// The session is revoked on the server, not only forgotten here
|
|
181
|
+
try {
|
|
182
|
+
const r = await fetch(`${API}/cli/logout`, { method: 'POST', headers: { Authorization: `Bearer ${c.token}`, 'User-Agent': `gepetto-cli/${VERSION}` } });
|
|
183
|
+
revoked = r.ok || r.status === 401;
|
|
184
|
+
} catch { /* offline */ }
|
|
185
|
+
}
|
|
186
|
+
try { fs.unlinkSync(CREDENTIALS); } catch { /* already out */ }
|
|
187
|
+
out(revoked || !c?.token ? 'Signed out.' : 'Signed out here, but the server could not be reached to revoke the session: run logout again when online, or wait for it to expire (90 days).',
|
|
188
|
+
{ status: 'signed_out', revoked });
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
async whoami() {
|
|
192
|
+
const c = readCredentials();
|
|
193
|
+
if (!c?.token) fail('cli_login_required', 'Not signed in: run `npx @gepetto/cli login`.');
|
|
194
|
+
out(`Signed in as ${c.email}.`, { email: c.email });
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
async init() {
|
|
198
|
+
const keys = await api('GET', '/cli/keys', { token: session() });
|
|
199
|
+
const file = typeof flags.env === 'string' ? flags.env : '.env';
|
|
200
|
+
const added = writeEnv(file, 'GEPETTO_API_KEY', keys.test_key);
|
|
201
|
+
out(`Test key written to ${file} (GEPETTO_API_KEY)${added ? `, ${file} added to .gitignore` : ''}.\nTest keys make 200 free renders. For production: npx @gepetto/cli subscribe`,
|
|
202
|
+
{ status: 'ok', file, key_type: 'test', gitignore_updated: added });
|
|
203
|
+
},
|
|
204
|
+
|
|
205
|
+
/** The keys of the account, masked unless --show (a key printed in a terminal ends up in logs and in agents' context). */
|
|
206
|
+
async keys() {
|
|
207
|
+
const k = await api('GET', '/cli/keys', { token: session() });
|
|
208
|
+
const show = flags.show === true;
|
|
209
|
+
const mask = (key) => (key ? (show ? key : `${key.slice(0, 9)}…${key.slice(-4)}`) : null);
|
|
210
|
+
if (JSON_OUT) return console.log(JSON.stringify({ email: k.email, test_key: mask(k.test_key), live_key: mask(k.live_key), masked: !show }));
|
|
211
|
+
console.log(`Account ${k.email}\n test ${mask(k.test_key)}\n live ${mask(k.live_key) ?? '(none: npx @gepetto/cli subscribe)'}${show ? '' : '\nAdd --show to print them in full.'}`);
|
|
212
|
+
},
|
|
213
|
+
|
|
214
|
+
async subscribe() {
|
|
215
|
+
const token = session();
|
|
216
|
+
const { url } = await api('POST', '/cli/subscribe', { token });
|
|
217
|
+
if (JSON_OUT) console.log(JSON.stringify({ event: 'checkout', url }));
|
|
218
|
+
else console.log(`API subscription: €100 excl. tax per month including €100 of renders, then pay as you go, plus a one-time €50 activation fee.\nPayment: ${url}\nWaiting for the payment…`);
|
|
219
|
+
openBrowser(url);
|
|
220
|
+
const file = typeof flags.env === 'string' ? flags.env : '.env.production.local';
|
|
221
|
+
const deadline = Date.now() + 30 * 60 * 1000;
|
|
222
|
+
while (Date.now() < deadline) {
|
|
223
|
+
await sleep(5000);
|
|
224
|
+
const keys = await api('GET', '/cli/keys', { token });
|
|
225
|
+
if (keys.live_key) {
|
|
226
|
+
const added = writeEnv(file, 'GEPETTO_API_KEY', keys.live_key);
|
|
227
|
+
return out(`Payment received. Live key written to ${file} (GEPETTO_API_KEY)${added ? `, ${file} added to .gitignore` : ''}.`, { event: 'subscribed', file });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
fail('payment_timeout', 'No payment after 30 minutes. Run the command again once paid: the key will be written.');
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async run() {
|
|
234
|
+
const tool = positional[1];
|
|
235
|
+
if (!TOOLS.includes(tool)) fail('unknown_tool', `Tool: ${TOOLS.join(', ')}. Example: npx @gepetto/cli run declutter --image ./room.jpg`);
|
|
236
|
+
const key = await apiKey();
|
|
237
|
+
const { image, mask, out: outFile, key: _k, noBrowser: _n, ...rest } = flags;
|
|
238
|
+
if (typeof image !== 'string') fail('missing_parameter', '--image is required (a local file or a URL).');
|
|
239
|
+
const body = { ...rest, url: await imageUrl(image, key, '--image') };
|
|
240
|
+
if (typeof mask === 'string') body.mask = await imageUrl(mask, key, '--mask');
|
|
241
|
+
if (!JSON_OUT) console.log(body.webhook ? 'Sending the job…' : 'Rendering (about 15 to 60 s)…');
|
|
242
|
+
const job = await api('POST', `/${tool}`, { token: key, body });
|
|
243
|
+
if (job.status !== 'success') return out(`Job ${job.id}: ${job.status}. Follow it with: npx @gepetto/cli job ${job.id}`, job);
|
|
244
|
+
// Default name built from what the server sent: only letters, digits, - and _, and an image extension
|
|
245
|
+
const ext = path.extname(new URL(job.output).pathname).toLowerCase();
|
|
246
|
+
const safeId = String(job.id).replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64) || 'output';
|
|
247
|
+
const target = typeof outFile === 'string' ? outFile : `${tool}-${safeId}${['.jpg', '.jpeg', '.png', '.webp'].includes(ext) ? ext : '.jpg'}`;
|
|
248
|
+
fs.writeFileSync(target, Buffer.from(await (await fetch(job.output)).arrayBuffer()));
|
|
249
|
+
out(`Done in ${job.createdAt && job.finishedAt ? Math.round((Date.parse(job.finishedAt) - Date.parse(job.createdAt)) / 1000) + ' s' : '—'}: ${target} (${job.test ? 'test key' : `${job.priceCents} cents`})`, { ...job, file: target });
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
async job() {
|
|
253
|
+
const id = positional[1];
|
|
254
|
+
if (!id) fail('missing_parameter', 'Usage: npx @gepetto/cli job <id>');
|
|
255
|
+
const job = await api('GET', `/job/${encodeURIComponent(id)}`, { token: await apiKey() });
|
|
256
|
+
out(`${job.id} ${job.tool} ${job.status}${job.output ? ' ' + job.output : ''}${job.error ? ` (${job.error.code}: ${job.error.message})` : ''}`, job);
|
|
257
|
+
},
|
|
258
|
+
|
|
259
|
+
async jobs() {
|
|
260
|
+
const list = await api('GET', '/jobs', { token: await apiKey(), query: { status: flags.failed ? 'error' : undefined, limit: flags.limit } });
|
|
261
|
+
if (JSON_OUT) return console.log(JSON.stringify(list));
|
|
262
|
+
if (!list.length) return console.log('No job.');
|
|
263
|
+
for (const j of list) console.log(`${j.createdAt?.slice(0, 16).replace('T', ' ')} ${j.id} ${j.tool.padEnd(17)} ${j.status.padEnd(10)} ${j.error ? `${j.error.code}: ${j.error.message}` : j.output ?? ''}`);
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
async usage() {
|
|
267
|
+
const u = await api('GET', '/usage', { token: await apiKey() });
|
|
268
|
+
if (JSON_OUT) return console.log(JSON.stringify(u));
|
|
269
|
+
const tools = Object.entries(u.byTool).map(([t, n]) => `${t} ${n}`).join(', ') || 'none';
|
|
270
|
+
if (u.key_type === 'test') return console.log(`Test key: ${u.testRenders.used} of ${u.testRenders.limit} free renders used. This month: ${u.renders} renders (${tools}).`);
|
|
271
|
+
console.log(`Since ${u.periodStart.slice(0, 10)}: ${u.renders} renders (${tools}), €${(u.consumedCents / 100).toFixed(2)} used of the €${(u.includedCents / 100).toFixed(2)} included${u.overageCents ? `, €${(u.overageCents / 100).toFixed(2)} over` : ''}.`);
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
async list() {
|
|
275
|
+
const what = positional[1];
|
|
276
|
+
if (!LISTS.includes(what)) fail('unknown_list', `List: ${LISTS.join(', ')}`);
|
|
277
|
+
const data = await api('GET', `/${what}`, { token: await apiKey() });
|
|
278
|
+
if (JSON_OUT) return console.log(JSON.stringify(data));
|
|
279
|
+
const show = (items) => items.map((x) => ` ${x.id}${x.name_en || x.name ? ` (${x.name_en || x.name})` : ''}${x.modes ? ` modes: ${x.modes.join(', ')}` : ''}`).join('\n');
|
|
280
|
+
if (Array.isArray(data)) console.log(show(data));
|
|
281
|
+
else for (const [group, items] of Object.entries(data)) console.log(`${group}:\n${show(items)}`);
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
async webhook() {
|
|
285
|
+
if (positional[1] !== 'test' || !positional[2]) fail('missing_parameter', 'Usage: npx @gepetto/cli webhook test <url> (for example http://localhost:3000/api/gepetto)');
|
|
286
|
+
const account = await api('GET', '/account', { token: await apiKey() });
|
|
287
|
+
const now = new Date().toISOString();
|
|
288
|
+
const samples = {
|
|
289
|
+
success: { id: 'job_test_success', status: 'success', tool: 'declutter', mode: 'zone', output: 'https://assets.gepettoapp.com/samples/pavillon/sejour.png', error: null, priceCents: 0, test: true, createdAt: now, finishedAt: now },
|
|
290
|
+
error: { id: 'job_test_error', status: 'error', tool: 'declutter', mode: 'zone', output: null, error: { code: 'render_failed', message: 'The render failed. You were not charged.' }, priceCents: 0, test: true, createdAt: now, finishedAt: now },
|
|
291
|
+
};
|
|
292
|
+
const results = {};
|
|
293
|
+
for (const [name, payload] of Object.entries(samples)) {
|
|
294
|
+
const body = JSON.stringify(payload);
|
|
295
|
+
const t = Math.floor(Date.now() / 1000);
|
|
296
|
+
const v1 = crypto.createHmac('sha256', account.webhook_secret).update(`${t}.${body}`).digest('hex');
|
|
297
|
+
try {
|
|
298
|
+
const r = await fetch(positional[2], { method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'Gepetto-Webhooks/2', 'Gepetto-Signature': `t=${t},v1=${v1}` }, body });
|
|
299
|
+
results[name] = r.status;
|
|
300
|
+
} catch (e) {
|
|
301
|
+
results[name] = `unreachable (${e.message})`;
|
|
302
|
+
}
|
|
303
|
+
if (!JSON_OUT) console.log(`render ${name.padEnd(8)} -> ${typeof results[name] === 'number' ? `HTTP ${results[name]}` : results[name]}`);
|
|
304
|
+
}
|
|
305
|
+
if (JSON_OUT) console.log(JSON.stringify({ results }));
|
|
306
|
+
else console.log('Signature: header Gepetto-Signature "t=<unix time>,v1=<hex>", HMAC-SHA256 of "<t>.<raw body>" with your webhook secret (npx @gepetto/cli secret).');
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
async secret() {
|
|
310
|
+
const account = await api('GET', '/account', { token: await apiKey() });
|
|
311
|
+
out(account.webhook_secret, { webhook_secret: account.webhook_secret });
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
help() {
|
|
315
|
+
console.log(`@gepetto/cli ${VERSION}: Gepetto API v2 (real estate photo editing) from the terminal.
|
|
316
|
+
|
|
317
|
+
login Sign in with your Gepetto account (opens a page, you click "Authorize")
|
|
318
|
+
init [--env .env] Write your test key (200 free renders) to .env as GEPETTO_API_KEY
|
|
319
|
+
keys [--show] Your test and live keys (masked unless --show)
|
|
320
|
+
run <tool> --image <file|url> [--mask <file|url>] [--out file] [--<param> value]
|
|
321
|
+
Tools: ${TOOLS.join(', ')}
|
|
322
|
+
e.g. run furnish --image room.jpg --roomId bedroom --styleId modern
|
|
323
|
+
list <${LISTS.join('|')}> Valid ids for the parameters
|
|
324
|
+
job <id> | jobs [--failed] A job, or the latest ones (with the reason of a failure)
|
|
325
|
+
usage Renders and consumption of the period
|
|
326
|
+
webhook test <url> Send a signed success and failure to your webhook endpoint
|
|
327
|
+
secret Your webhook signing secret
|
|
328
|
+
subscribe Payment link of the subscription; writes the live key once paid
|
|
329
|
+
logout | whoami
|
|
330
|
+
|
|
331
|
+
Every command accepts --json. Docs: https://docs.gepettoapp.com`);
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
const name = positional[0] || 'help';
|
|
336
|
+
if (!commands[name] || name === 'help' || flags.help) commands.help();
|
|
337
|
+
else commands[name]().catch((e) => fail('cli_error', e.message));
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gepetto/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Gepetto API v2 from the terminal: sign in, get an API key, render real estate photos (enhance, declutter, furnish, sky, restyle, walls and floors, upscale), subscribe.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"gepetto": "bin/gepetto.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=18"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"gepetto",
|
|
18
|
+
"real-estate",
|
|
19
|
+
"virtual-staging",
|
|
20
|
+
"photo-editing",
|
|
21
|
+
"api",
|
|
22
|
+
"cli"
|
|
23
|
+
],
|
|
24
|
+
"homepage": "https://docs.gepettoapp.com",
|
|
25
|
+
"license": "UNLICENSED",
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
}
|
|
29
|
+
}
|