lexisync 0.2.0 → 1.0.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 CHANGED
@@ -1,8 +1,11 @@
1
1
  # lexisync
2
2
 
3
- Official **CLI**, **i18next backend**, and HTTP client for [LexiSync](https://lexisync-six.vercel.app) — API-first, Locize-style translation management.
3
+ Official **CLI**, **i18next backend**, and HTTP client for [LexiSync](https://github.com/sanderpost/lexisync) — open-source, self-hosted, Locize-style translation management.
4
4
 
5
- [Docs](https://lexisync-six.vercel.app/docs) · [API discovery](https://lexisync-six.vercel.app/api/v1) · [OpenAPI](https://lexisync-six.vercel.app/api/v1/openapi.json)
5
+ [Self-hosting](https://github.com/sanderpost/lexisync/blob/main/docker/README.md) · API discovery: `{your-instance}/api/v1` · OpenAPI: `{your-instance}/api/v1/openapi.json`
6
+
7
+ > **1.0 breaking change:** there is no hosted default any more. Pass `apiUrl` (or set
8
+ > `LEXISYNC_API_URL` / `lexisync config api-url`) pointing at your own LexiSync instance.
6
9
 
7
10
  ## Install
8
11
 
@@ -16,40 +19,45 @@ npm install i18next
16
19
  npx lexisync --help
17
20
  ```
18
21
 
19
- Requires **Node.js ≥ 18**.
22
+ Requires **Node.js ≥ 20**.
20
23
 
21
24
  ## Quick start
22
25
 
23
- 1. Create an org + project at [lexisync-six.vercel.app](https://lexisync-six.vercel.app/onboarding/1)
26
+ 1. Run your own instance ([Docker guide](https://github.com/sanderpost/lexisync/blob/main/docker/README.md)) and create a project
24
27
  2. Copy **project id** and secret API key (`sk_…`)
25
28
  3. Sync source strings, translate, publish a version, load from CDN
26
29
 
27
30
  ```bash
28
- export LEXISYNC_API_KEY=sk_your_secret
31
+ npx lexisync config api-url https://lexisync.example.com
32
+ npx lexisync config api-key sk_your_secret
29
33
  npx lexisync sync -p YOUR_PROJECT_ID -f ./locales/en.json -l en
30
34
  npx lexisync publish -p YOUR_PROJECT_ID -v production
31
35
  npx lexisync pull -p YOUR_PROJECT_ID -n common -l en -v production -o ./locales/en.json
32
36
  ```
33
37
 
34
- Config is stored in `~/.lexisync/config.json`. Override API host with `LEXISYNC_API_URL` (default: `https://lexisync-six.vercel.app`).
38
+ Config is stored in `~/.lexisync/config.json`. The server URL comes from `LEXISYNC_API_URL` or `lexisync config api-url` (**required — no default**). The CDN defaults to `{apiUrl}/cdn`; override with `LEXISYNC_CDN_URL` if you serve catalogs from a dedicated host.
35
39
 
36
40
  ## Locize-style workflow
37
41
 
38
- | Step | What |
39
- |------|------|
40
- | 1. Keys | Dashboard → `projectId` + `sk_…` / `pub_…` |
42
+ | Step | What |
43
+ | --------------- | ----------------------------------------------------------------- |
44
+ | 1. Keys | Dashboard → `projectId` + `sk_…` / `pub_…` |
41
45
  | 2. Working copy | `lexisync sync` and/or `saveMissing: true` → version **`latest`** |
42
- | 3. Translate | Dashboard → project → Translate & publish |
43
- | 4. Publish | `lexisync publish -v production` freezes CDN catalogs |
44
- | 5. Ship | App loads `version: "production"` (immutable) or `latest` (dev) |
46
+ | 3. Translate | Dashboard → project → Translate & publish |
47
+ | 4. Publish | `lexisync publish -v production` → PublicationManifest + CDN tag |
48
+ | 5. Ship | App loads `version: "production"` (live tag) or `latest` (dev) |
49
+ | 6. Rollback | Dashboard **Releases** → Restore to CDN (working copy untouched) |
50
+
51
+ See the in-app docs on your instance (`/docs`).
45
52
 
46
53
  **CDN (no auth):**
47
54
 
48
55
  ```
49
- GET {apiUrl}/api/cdn/{projectId}/{version}/{lng}/{namespace}
56
+ GET {apiUrl}/cdn/{projectId}/{version}/{lng}/{namespace}
57
+ GET {apiUrl}/cdn/{projectId}/{version}/languages
50
58
  ```
51
59
 
52
- Example: `https://lexisync-six.vercel.app/api/cdn/<id>/production/en/common`
60
+ With a dedicated CDN host (`cdnUrl`): `{cdnUrl}/{projectId}/{version}/{lng}/{namespace}.json`
53
61
 
54
62
  ## CLI
55
63
 
@@ -76,7 +84,8 @@ await i18next.use(LexiSyncBackend).init({
76
84
  backend: {
77
85
  projectId: 'YOUR_PROJECT_ID',
78
86
  apiKey: process.env.LEXISYNC_API_KEY, // needed for saveMissing
79
- apiUrl: 'https://lexisync-six.vercel.app',
87
+ apiUrl: 'https://lexisync.example.com', // required — your LexiSync instance
88
+ // cdnUrl: 'https://cdn.lexisync.example.com', // optional — default `${apiUrl}/cdn`
80
89
  version: 'latest', // use "production" after publish
81
90
  },
82
91
  saveMissing: true, // only writes when version === "latest"
@@ -104,9 +113,10 @@ const {
104
113
  downloadCatalog,
105
114
  reportMissing,
106
115
  publishVersion,
116
+ cdnUrl,
107
117
  } = require('lexisync/client');
108
118
 
109
- const apiUrl = 'https://lexisync-six.vercel.app';
119
+ const apiUrl = 'https://lexisync.example.com'; // your instance
110
120
  const apiKey = process.env.LEXISYNC_API_KEY;
111
121
 
112
122
  await discoverApi({ apiUrl });
@@ -119,69 +129,12 @@ await downloadCatalog({
119
129
  version: 'latest',
120
130
  format: 'nested', // or "flat"
121
131
  });
122
- await reportMissing({
123
- apiUrl,
124
- apiKey,
125
- projectId: '…',
126
- namespace: 'common',
127
- languageCode: 'en',
128
- keys: { new_cta: 'Try now' },
129
- });
130
- await publishVersion({ apiUrl, apiKey, projectId: '…', version: 'production' });
131
- ```
132
-
133
- Full machine-readable map: `GET /api/v1` · OpenAPI: `GET /api/v1/openapi.json`.
134
132
 
135
- ## React
136
-
137
- ```bash
138
- npm install lexisync-react i18next react-i18next
133
+ // Build a public CDN URL
134
+ cdnUrl({ apiUrl, projectId: '…', version: 'production', language: 'en', namespace: 'common' });
135
+ // → https://lexisync.example.com/cdn/…/production/en/common
139
136
  ```
140
137
 
141
- ```tsx
142
- import { LexiSyncProvider, useT } from 'lexisync-react';
143
-
144
- function App() {
145
- return (
146
- <LexiSyncProvider
147
- projectId="…"
148
- apiKey={import.meta.env.VITE_LEXISYNC_API_KEY}
149
- version="latest"
150
- saveMissing
151
- >
152
- <Page />
153
- </LexiSyncProvider>
154
- );
155
- }
156
-
157
- function Page() {
158
- const t = useT();
159
- return <h1>{t('hello')}</h1>;
160
- }
161
- ```
162
-
163
- `lexisync-react` is a separate package on npm when published.
164
-
165
- ## Environment
166
-
167
- | Variable | Description |
168
- |----------|-------------|
169
- | `LEXISYNC_API_URL` | API host (default production URL) |
170
- | `LEXISYNC_API_KEY` | Secret key for CLI write ops |
171
-
172
- ## Security
173
-
174
- - Use **secret** keys (`sk_…`) only server-side or in trusted CLI environments.
175
- - Use **public** keys (`pub_…`) for read-only clients when possible.
176
- - Never commit API keys. Prefer env vars or `~/.lexisync/config.json` (local).
177
-
178
- ## Links
179
-
180
- - Product: https://lexisync-six.vercel.app
181
- - Documentation: https://lexisync-six.vercel.app/docs
182
- - API v1: https://lexisync-six.vercel.app/api/v1
183
- - Source: https://github.com/sanderpost/lexisync (package under `packages/lexisync`)
184
-
185
138
  ## License
186
139
 
187
140
  MIT
package/bin/lexisync.js CHANGED
@@ -18,13 +18,20 @@ const config = createConfig();
18
18
  const program = new Command();
19
19
 
20
20
  function apiBase() {
21
- return resolveApiUrl(process.env.LEXISYNC_API_URL || config.get('apiUrl'));
21
+ const url = process.env.LEXISYNC_API_URL || config.get('apiUrl');
22
+ if (!url) {
23
+ throw new Error(
24
+ 'No LexiSync server configured. Run `lexisync config api-url https://your-instance` ' +
25
+ 'or set LEXISYNC_API_URL.',
26
+ );
27
+ }
28
+ return resolveApiUrl(url);
22
29
  }
23
30
 
24
31
  program
25
32
  .name('lexisync')
26
33
  .description('LexiSync CLI — sync, pull, publish versioned catalogs (Locize-style)')
27
- .version('0.2.0');
34
+ .version(require('../package.json').version);
28
35
 
29
36
  program
30
37
  .command('init')
@@ -65,7 +72,9 @@ program
65
72
  const apiKey = config.get('apiKey');
66
73
  const projectId = options.project || config.get('projectId');
67
74
  if (!apiKey) {
68
- console.error('Error: Not authenticated. Run lexisync init or set apiKey in ~/.lexisync/config.json');
75
+ console.error(
76
+ 'Error: Not authenticated. Run lexisync init or set apiKey in ~/.lexisync/config.json',
77
+ );
69
78
  process.exitCode = 1;
70
79
  return;
71
80
  }
@@ -83,7 +92,7 @@ program
83
92
  const response = await axios.post(
84
93
  `${apiBase()}/api/sync`,
85
94
  { projectId, languageCode: options.lang, data },
86
- { headers: { 'x-api-key': apiKey } }
95
+ { headers: { 'x-api-key': apiKey } },
87
96
  );
88
97
 
89
98
  console.log('Sync complete:', response.data);
@@ -119,9 +128,7 @@ program
119
128
  const outPath = path.resolve(options.out);
120
129
  fs.mkdirSync(path.dirname(outPath), { recursive: true });
121
130
  fs.writeFileSync(outPath, JSON.stringify(resource, null, 2) + '\n');
122
- console.log(
123
- `Wrote ${Object.keys(resource).length} keys → ${outPath} (v=${options.version})`
124
- );
131
+ console.log(`Wrote ${Object.keys(resource).length} keys → ${outPath} (v=${options.version})`);
125
132
  console.log(
126
133
  'CDN URL:',
127
134
  cdnUrl({
@@ -130,7 +137,7 @@ program
130
137
  version: options.version,
131
138
  language: options.lang,
132
139
  namespace: options.namespace,
133
- })
140
+ }),
134
141
  );
135
142
  } catch (err) {
136
143
  console.error(`Error: ${err.message}`);
@@ -185,4 +192,385 @@ program
185
192
  }
186
193
  });
187
194
 
188
- program.parse(process.argv);
195
+ program
196
+ .command('config')
197
+ .description('Manage local CLI configuration (~/.lexisync/config.json)')
198
+ .argument('<key>', 'Configuration key (e.g. reference-language)')
199
+ .argument('[value]', 'Value to set; omit to read')
200
+ .action((key, value) => {
201
+ // Normalize kebab aliases → camelCase storage keys.
202
+ const map = {
203
+ 'reference-language': 'referenceLanguage',
204
+ 'source-language': 'referenceLanguage', // deprecated alias
205
+ 'project-id': 'projectId',
206
+ 'api-key': 'apiKey',
207
+ 'api-url': 'apiUrl',
208
+ };
209
+ const storeKey = map[key] || key;
210
+ if (value === undefined) {
211
+ const cur = config.get(storeKey);
212
+ if (cur === undefined || cur === null) {
213
+ console.log(`${key} (unset)`);
214
+ } else {
215
+ console.log(`${key} = ${cur}`);
216
+ }
217
+ } else {
218
+ config.set(storeKey, value);
219
+ // Keep deprecated sourceLanguage mirrored when setting reference.
220
+ if (storeKey === 'referenceLanguage') {
221
+ config.set('sourceLanguage', value);
222
+ }
223
+ console.log(`${key} = ${value}`);
224
+ }
225
+ });
226
+
227
+ program
228
+ .command('project')
229
+ .description('Create a new project under the current organization')
230
+ .option('-n, --name <name>', 'Project name (required)', '')
231
+ .option(
232
+ '-r, --reference-language <lng>',
233
+ 'Reference language (Locize-style; where defaultValues / saveMissing land)',
234
+ 'en',
235
+ )
236
+ .option('-s, --source-language <lng>', 'Deprecated alias of --reference-language', '')
237
+ .option('-l, --languages <codes>', 'Comma-separated extra languages to enable')
238
+ .action(async (options) => {
239
+ const apiKey = config.get('apiKey');
240
+ if (!apiKey) {
241
+ console.error("Error: Not authenticated. Run 'lexisync init' first.");
242
+ process.exitCode = 1;
243
+ return;
244
+ }
245
+ if (!options.name.trim()) {
246
+ console.error('Error: --name <name> is required.');
247
+ process.exitCode = 1;
248
+ return;
249
+ }
250
+ const isRealLang = (c) => /^[a-z]{2,3}(-[a-zA-Z0-9]{2,8})?$/i.test(String(c || '').trim());
251
+ const refRaw = options.referenceLanguage || options.sourceLanguage || 'en';
252
+ if (!isRealLang(refRaw)) {
253
+ console.error('Error: --reference-language must be a valid BCP-47 tag (e.g. en, nl, en-US).');
254
+ process.exitCode = 1;
255
+ return;
256
+ }
257
+ const referenceLng = String(refRaw).toLowerCase();
258
+ const extraLangs = (options.languages || '')
259
+ .split(',')
260
+ .map((s) => s.trim().toLowerCase())
261
+ .filter(Boolean);
262
+
263
+ try {
264
+ const body = {
265
+ name: options.name.trim(),
266
+ referenceLng,
267
+ languages: extraLangs,
268
+ };
269
+ const response = await axios.post(`${apiBase()}/api/v1/projects`, body, {
270
+ headers: { 'x-api-key': apiKey },
271
+ });
272
+ const p = response.data?.data || response.data;
273
+ console.log('Project created:');
274
+ console.log(` id ${p.id}`);
275
+ console.log(` name ${p.name}`);
276
+ console.log(` referenceLng ${p.referenceLng}`);
277
+ console.log(` languages ${(p.languages || []).join(', ')}`);
278
+ console.log('');
279
+ console.log('Now: lexisync config set reference-language ' + p.referenceLng);
280
+ console.log(' lexisync config set project-id ' + p.id);
281
+ config.set('referenceLanguage', p.referenceLng);
282
+ // Keep deprecated key mirrored for older scripts.
283
+ config.set('sourceLanguage', p.referenceLng);
284
+ config.set('projectId', p.id);
285
+ } catch (err) {
286
+ console.error('Error:', err.response?.data?.error || err.message);
287
+ process.exitCode = 1;
288
+ }
289
+ });
290
+
291
+ // ─── Phase 2: quality gates ───────────────────────────────────────────
292
+
293
+ function projectIdOrDie() {
294
+ const id = config.get('projectId');
295
+ if (!id) {
296
+ console.error('Error: projectId not set. Run: lexisync config set project-id <id>');
297
+ process.exit(1);
298
+ }
299
+ return id;
300
+ }
301
+
302
+ function authHeaders() {
303
+ const apiKey = config.get('apiKey');
304
+ if (!apiKey) {
305
+ console.error("Error: Not authenticated. Run 'lexisync init' first.");
306
+ process.exit(1);
307
+ }
308
+ return { 'x-api-key': apiKey, 'Content-Type': 'application/json' };
309
+ }
310
+
311
+ program
312
+ .command('check')
313
+ .description('Run localization quality checks (CI-friendly; exit 1 if not ready)')
314
+ .option('-e, --environment <env>', 'Environment label (preview|production)', 'preview')
315
+ .option('-l, --language <codes>', 'Comma-separated languages to check')
316
+ .option('--json', 'Print full JSON report')
317
+ .action(async (options) => {
318
+ const projectId = projectIdOrDie();
319
+ const languages = options.language
320
+ ? options.language
321
+ .split(',')
322
+ .map((s) => s.trim())
323
+ .filter(Boolean)
324
+ : undefined;
325
+ try {
326
+ const version = options.environment === 'production' ? 'production' : undefined;
327
+ const res = await axios.post(
328
+ `${apiBase()}/api/v1/projects/${projectId}/check`,
329
+ { languages, version, persist: true },
330
+ { headers: authHeaders() },
331
+ );
332
+ const data = res.data?.data || res.data;
333
+ if (options.json) {
334
+ console.log(JSON.stringify(data, null, 2));
335
+ } else {
336
+ console.log(`ready: ${data.ready ? 'yes' : 'NO'}`);
337
+ console.log(`checked: ${data.checked}`);
338
+ console.log(`blocking: ${data.blockingCount}`);
339
+ if (data.byCode) {
340
+ console.log('by code:');
341
+ for (const [k, v] of Object.entries(data.byCode)) {
342
+ console.log(` ${k}: ${v}`);
343
+ }
344
+ }
345
+ if (data.blocking?.length) {
346
+ console.log('top blockers:');
347
+ for (const b of data.blocking.slice(0, 15)) {
348
+ console.log(
349
+ ` [${b.severity}] ${b.code} ${b.namespace}/${b.identifier} @${b.languageCode}: ${b.message}`,
350
+ );
351
+ }
352
+ }
353
+ }
354
+ if (!data.ready) process.exitCode = 1;
355
+ } catch (err) {
356
+ console.error('Error:', err.response?.data?.error || err.message);
357
+ process.exitCode = 1;
358
+ }
359
+ });
360
+
361
+ program
362
+ .command('status')
363
+ .description('Readiness summary per language')
364
+ .option('-l, --language <code>', 'Single language')
365
+ .option('--json', 'Print JSON')
366
+ .action(async (options) => {
367
+ const projectId = projectIdOrDie();
368
+ try {
369
+ const q = options.language ? `?language=${encodeURIComponent(options.language)}` : '';
370
+ const res = await axios.get(`${apiBase()}/api/v1/projects/${projectId}/status${q}`, {
371
+ headers: authHeaders(),
372
+ });
373
+ const data = res.data?.data || res.data;
374
+ if (options.json) {
375
+ console.log(JSON.stringify(data, null, 2));
376
+ return;
377
+ }
378
+ if (data.language) {
379
+ const l = data.language;
380
+ console.log(
381
+ `${l.language}${l.isReference ? ' (reference)' : ''}: ready=${l.ready} filled=${l.filled}/${l.keys} empty=${l.empty} stale=${l.stale} errors=${l.errors} unapproved=${l.unapproved}`,
382
+ );
383
+ if (!l.ready) process.exitCode = 1;
384
+ return;
385
+ }
386
+ console.log(`reference: ${data.referenceLng} overall ready: ${data.ready ? 'yes' : 'NO'}`);
387
+ for (const l of data.languages || []) {
388
+ const mark = l.ready ? '✓' : '✗';
389
+ console.log(
390
+ ` ${mark} ${l.language.padEnd(8)} filled ${String(l.filled).padStart(4)}/${l.keys} empty ${l.empty} stale ${l.stale} err ${l.errors} unapproved ${l.unapproved}`,
391
+ );
392
+ }
393
+ if (!data.ready) process.exitCode = 1;
394
+ } catch (err) {
395
+ console.error('Error:', err.response?.data?.error || err.message);
396
+ process.exitCode = 1;
397
+ }
398
+ });
399
+
400
+ program
401
+ .command('diff')
402
+ .description('Working copy changes since a published version')
403
+ .option('--since <version>', 'Published version tag', 'production')
404
+ .option('--json', 'Print JSON')
405
+ .action(async (options) => {
406
+ const projectId = projectIdOrDie();
407
+ try {
408
+ const res = await axios.get(
409
+ `${apiBase()}/api/v1/projects/${projectId}/diff?since=${encodeURIComponent(options.since)}`,
410
+ { headers: authHeaders() },
411
+ );
412
+ const data = res.data?.data || res.data;
413
+ if (options.json) {
414
+ console.log(JSON.stringify(data, null, 2));
415
+ return;
416
+ }
417
+ console.log(
418
+ `since ${data.version}: +${data.counts.added} ~${data.counts.changed} -${data.counts.removed}`,
419
+ );
420
+ for (const c of (data.changed || []).slice(0, 30)) {
421
+ console.log(` ~ ${c.namespace}/${c.identifier} @${c.languageCode}`);
422
+ }
423
+ for (const a of (data.added || []).slice(0, 20)) {
424
+ console.log(` + ${a.namespace}/${a.identifier} @${a.languageCode}`);
425
+ }
426
+ for (const r of (data.removed || []).slice(0, 20)) {
427
+ console.log(` - ${r.namespace}/${r.identifier} @${r.languageCode}`);
428
+ }
429
+ } catch (err) {
430
+ console.error('Error:', err.response?.data?.error || err.message);
431
+ process.exitCode = 1;
432
+ }
433
+ });
434
+
435
+ program
436
+ .command('review')
437
+ .description('Review-lite: approve|reject|reopen a translation')
438
+ .argument('<action>', 'approve|reject|reopen')
439
+ .requiredOption('--key <identifier>', 'Key identifier')
440
+ .requiredOption('--lang <code>', 'Language code')
441
+ .option('--namespace <ns>', 'Namespace', 'common')
442
+ .action(async (action, options) => {
443
+ const projectId = projectIdOrDie();
444
+ if (!['approve', 'reject', 'reopen'].includes(action)) {
445
+ console.error('action must be approve|reject|reopen');
446
+ process.exitCode = 1;
447
+ return;
448
+ }
449
+ try {
450
+ const res = await axios.post(
451
+ `${apiBase()}/api/v1/projects/${projectId}/review`,
452
+ {
453
+ action,
454
+ identifier: options.key,
455
+ namespace: options.namespace,
456
+ languageCode: options.lang,
457
+ },
458
+ { headers: authHeaders() },
459
+ );
460
+ console.log(JSON.stringify(res.data?.data || res.data, null, 2));
461
+ } catch (err) {
462
+ console.error('Error:', err.response?.data?.error || err.message);
463
+ process.exitCode = 1;
464
+ }
465
+ });
466
+
467
+ // ─── CLI OAuth auth ────────────────────────────────────────────────────────
468
+
469
+ const crypto = require('crypto');
470
+ const http = require('http');
471
+ const { exec } = require('child_process');
472
+
473
+ function openBrowser(target) {
474
+ const cmd =
475
+ process.platform === 'darwin'
476
+ ? `open ${JSON.stringify(target)}`
477
+ : process.platform === 'win32'
478
+ ? `start "" ${JSON.stringify(target)}`
479
+ : `xdg-open ${JSON.stringify(target)}`;
480
+ exec(cmd);
481
+ }
482
+
483
+ function base64Url(buf) {
484
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
485
+ }
486
+
487
+ program
488
+ .command('auth')
489
+ .description('Authenticate the CLI via browser OAuth (stores API key in config)')
490
+ .argument('<url>', 'LexiSync base URL (e.g. http://localhost:3000)')
491
+ .action(async (url) => {
492
+ try {
493
+ const base = String(url).replace(/\/$/, '');
494
+ config.set('apiUrl', base);
495
+
496
+ const verifier = base64Url(crypto.randomBytes(32));
497
+ const challenge = base64Url(crypto.createHash('sha256').update(verifier).digest());
498
+ const state = base64Url(crypto.randomBytes(16));
499
+
500
+ const port = 8765;
501
+ const redirectUri = `http://localhost:${port}/callback`;
502
+
503
+ const code = await new Promise((resolve, reject) => {
504
+ const server = http.createServer((req, res) => {
505
+ const u = new URL(req.url, `http://localhost:${port}`);
506
+ if (u.pathname !== '/callback') {
507
+ res.statusCode = 404;
508
+ res.end('Not found');
509
+ return;
510
+ }
511
+ const err = u.searchParams.get('error');
512
+ const c = u.searchParams.get('code');
513
+ const st = u.searchParams.get('state');
514
+ if (err) {
515
+ res.end(`Auth error: ${err}`);
516
+ server.close();
517
+ reject(new Error(err));
518
+ return;
519
+ }
520
+ if (!c || st !== state) {
521
+ res.statusCode = 400;
522
+ res.end('Invalid callback');
523
+ return;
524
+ }
525
+ res.end('Authentication successful. You can close this window.');
526
+ server.close();
527
+ resolve(c);
528
+ });
529
+ server.listen(port, () => {
530
+ const authUrl = `${base}/api/cli/authorize?redirect_uri=${encodeURIComponent(
531
+ redirectUri,
532
+ )}&state=${encodeURIComponent(state)}&code_challenge=${encodeURIComponent(
533
+ challenge,
534
+ )}&code_challenge_method=S256`;
535
+ console.log('Opening browser for authentication...');
536
+ console.log(authUrl);
537
+ openBrowser(authUrl);
538
+ });
539
+ setTimeout(
540
+ () => {
541
+ server.close();
542
+ reject(new Error('Timed out waiting for auth callback'));
543
+ },
544
+ 5 * 60 * 1000,
545
+ );
546
+ });
547
+
548
+ const tokenRes = await axios.post(`${base}/api/cli/token`, {
549
+ code,
550
+ code_verifier: verifier,
551
+ redirect_uri: redirectUri,
552
+ });
553
+ const token = tokenRes.data.token;
554
+ if (!token) throw new Error('No token returned');
555
+ config.set('apiKey', token);
556
+ console.log('Authenticated. API key stored in config.');
557
+ } catch (err) {
558
+ console.error(`Error: ${err.response?.data?.error || err.message}`);
559
+ process.exitCode = 1;
560
+ }
561
+ });
562
+
563
+ program
564
+ .command('auth-token')
565
+ .description('Print the stored API token (like gh auth token)')
566
+ .action(() => {
567
+ const token = config.get('apiKey');
568
+ if (!token) {
569
+ console.error('Error: Not authenticated. Run lexisync auth <url>.');
570
+ process.exitCode = 1;
571
+ return;
572
+ }
573
+ console.log(token);
574
+ });
575
+
576
+ program.parse(process.argv);