guessit-js 4.6.0 → 4.7.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
@@ -6,6 +6,7 @@ Extract metadata (title, year, season, episode, codec, language, etc.) from medi
6
6
  [![Tests](https://github.com/opensubtitles/guessit-js/actions/workflows/ci.yml/badge.svg)](https://github.com/opensubtitles/guessit-js/actions/workflows/ci.yml)
7
7
  [![License: LGPL-3.0](https://img.shields.io/badge/License-LGPL--3.0-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0)
8
8
  [![Python guessit compat](https://img.shields.io/badge/guessit_compat-100%25_(1342%2F1342)-brightgreen)](https://github.com/guessit-io/guessit)
9
+ [![Coverage](https://img.shields.io/badge/coverage-97%25-brightgreen)](https://github.com/opensubtitles/guessit-js/actions/workflows/ci.yml)
9
10
 
10
11
  **[Live Demo](https://opensubtitles.github.io/guessit-js)** · **[API Docs](https://opensubtitles.github.io/guessit-js/docs)** · **[npm](https://www.npmjs.com/package/guessit-js)**
11
12
 
@@ -53,6 +54,14 @@ Parsing options match the Python CLI: `-n` name-only, `-Y`/`-D` date order,
53
54
  `~/.config/guessit/options.json` (`.yaml`/`.yml` too; disable with
54
55
  `--no-user-config`), plus explicit `-c <file>`. See `npx guessit-js --help`.
55
56
 
57
+ Extras beyond the Python CLI:
58
+
59
+ ```bash
60
+ npx guessit-js --serve 3847 # instant REST API (see below)
61
+ npx guessit-js --benchmark 1000 "Movie.2020.1080p.mkv" # throughput report
62
+ eval "$(npx guessit-js --completion bash)" # shell completion (bash/zsh)
63
+ ```
64
+
56
65
  ## Usage
57
66
 
58
67
  ```typescript
@@ -135,11 +144,20 @@ Regenerate the schema (after parsing changes) with `npm run schema`. A test (`te
135
144
 
136
145
  ## REST API
137
146
 
147
+ No install needed beyond the package itself:
148
+
138
149
  ```bash
139
- npm start # port 3847
150
+ npx guessit-js --serve # port 3847 (or --serve 8080 / PORT env)
140
151
  curl "http://localhost:3847/api/guessit?filename=Movie.2024.1080p.mkv"
152
+ curl -X POST http://localhost:3847/api/guessit \
153
+ -H 'Content-Type: application/json' \
154
+ -d '{"filenames": ["A.2020.mkv", "B.S01E02.mkv"], "options": {"type": "episode"}}'
141
155
  ```
142
156
 
157
+ CLI parsing flags become server defaults: `guessit-js --serve -t episode -L en`.
158
+ The repo also ships a fuller dev server (`npm start`) with the demo page,
159
+ Swagger UI at `/docs`, and static WASM serving.
160
+
143
161
  ## WASM
144
162
 
145
163
  For non-JS environments (Rust, Go, C++, edge compute). Uses [Javy](https://github.com/bytecodealliance/javy) (QuickJS → WASM).
package/bin/cli.mjs CHANGED
@@ -66,6 +66,14 @@ Information:
66
66
  -V, --values Display property values that can be guessed
67
67
  --version Display the guessit-js version banner
68
68
 
69
+ Extras (not in the Python CLI):
70
+ --serve [PORT] Start a REST API server (default port 3847;
71
+ GET /api/guessit?filename=..., POST {filename|filenames})
72
+ --benchmark [N] Parse the given filenames N times (default 1000)
73
+ and report throughput
74
+ --completion SHELL Print a bash or zsh completion script
75
+ (eval "$(guessit-js --completion bash)")
76
+
69
77
  Exit codes: 0 success, 1 processing error, 2 usage error.`;
70
78
 
71
79
  function fail(msg) {
@@ -123,6 +131,10 @@ let listProperties = false;
123
131
  let listValues = false;
124
132
  let noUserConfig = false;
125
133
  let endOfOptions = false;
134
+ let serve = false;
135
+ let servePort = 3847;
136
+ let benchmark = 0;
137
+ let completionShell = null;
126
138
 
127
139
  const needsValue = (a, i) => {
128
140
  if (i + 1 >= args.length) fail(`option ${a} requires a value`);
@@ -171,6 +183,15 @@ for (let i = 0; i < args.length; i++) {
171
183
  case '--no-default-config': cliOptions.no_default_config = true; break;
172
184
  case '-p': case '--properties': listProperties = true; break;
173
185
  case '-V': case '--values': listValues = true; break;
186
+ case '--serve':
187
+ serve = true;
188
+ if (args[i + 1] && /^\d+$/.test(args[i + 1])) { servePort = Number(args[++i]); }
189
+ else if (process.env.PORT) servePort = Number(process.env.PORT);
190
+ break;
191
+ case '--benchmark':
192
+ benchmark = args[i + 1] && /^\d+$/.test(args[i + 1]) ? Number(args[++i]) : 1000;
193
+ break;
194
+ case '--completion': completionShell = needsValue(a, i); i++; break;
174
195
  case '--version': {
175
196
  console.log('+-------------------------------------------------------+');
176
197
  console.log(`+ GuessIt-JS ${version}`.padEnd(56) + '+');
@@ -310,12 +331,116 @@ if (listProperties || listValues) {
310
331
  process.exit(0);
311
332
  }
312
333
 
334
+ // ---- shell completion -------------------------------------------------------
335
+ if (completionShell) {
336
+ const flags = '-t --type -n --name-only -Y --date-year-first -D --date-day-first -L --allowed-languages -C --allowed-countries -E --episode-prefer-number -T --expected-title -G --expected-group --includes --excludes -f --input-file -v --verbose -P --show-property -a --advanced -s --single-value -j --json --jsonl -y --yaml -i --output-input-string -c --config --no-user-config --no-default-config -p --properties -V --values --version --serve --benchmark --completion -h --help';
337
+ if (completionShell === 'bash') {
338
+ console.log(`_guessit_js() {
339
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
340
+ if [[ "$cur" == -* ]]; then
341
+ COMPREPLY=( $(compgen -W "${flags}" -- "$cur") )
342
+ else
343
+ COMPREPLY=( $(compgen -f -- "$cur") )
344
+ fi
345
+ }
346
+ complete -F _guessit_js guessit-js guessit`);
347
+ } else if (completionShell === 'zsh') {
348
+ console.log(`#compdef guessit-js guessit
349
+ _arguments '*: :{ _alternative "flags:flag:(${flags})" "files:filename:_files" }'`);
350
+ } else {
351
+ fail(`unsupported shell "${completionShell}": use bash or zsh`);
352
+ }
353
+ process.exit(0);
354
+ }
355
+
356
+ // ---- REST API server --------------------------------------------------------
357
+ if (serve) {
358
+ const { createServer } = await import('http');
359
+ const baseOptions = options;
360
+ const sendJson = (res, status, data) => {
361
+ res.writeHead(status, {
362
+ 'Content-Type': 'application/json; charset=utf-8',
363
+ 'Access-Control-Allow-Origin': '*',
364
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
365
+ 'Access-Control-Allow-Headers': 'Content-Type',
366
+ });
367
+ res.end(JSON.stringify(data, null, 2));
368
+ };
369
+ const server = createServer((req, res) => {
370
+ const url = new URL(req.url || '/', `http://localhost:${servePort}`);
371
+ if (req.method === 'OPTIONS') { sendJson(res, 204, {}); return; }
372
+ if (url.pathname === '/api/health') { sendJson(res, 200, { status: 'ok', version }); return; }
373
+ if (url.pathname !== '/api/guessit' && url.pathname !== '/') {
374
+ sendJson(res, 404, { error: 'Not found — use /api/guessit' });
375
+ return;
376
+ }
377
+ if (req.method === 'GET') {
378
+ const filename = url.searchParams.get('filename');
379
+ if (!filename) {
380
+ sendJson(res, 400, {
381
+ error: 'Missing required parameter: filename',
382
+ usage: `GET /api/guessit?filename=Movie.2020.1080p.mkv[&type=movie|episode] · POST /api/guessit {"filename": "..."} or {"filenames": ["..."]}`,
383
+ });
384
+ return;
385
+ }
386
+ const opts = { ...baseOptions };
387
+ const type = url.searchParams.get('type');
388
+ if (type === 'movie' || type === 'episode') opts.type = type;
389
+ try { sendJson(res, 200, display(guessit(filename, opts), 'json')); }
390
+ catch (e) { sendJson(res, 500, { error: String((e && e.message) || e) }); }
391
+ return;
392
+ }
393
+ if (req.method === 'POST') {
394
+ const chunks = [];
395
+ let size = 0;
396
+ req.on('data', (c) => { size += c.length; if (size > 1 << 20) req.destroy(); else chunks.push(c); });
397
+ req.on('end', () => {
398
+ try {
399
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
400
+ const opts = { ...baseOptions, ...(body.options || {}) };
401
+ if (Array.isArray(body.filenames)) {
402
+ sendJson(res, 200, body.filenames.map((f) => display(guessit(String(f), opts), 'json')));
403
+ } else if (typeof body.filename === 'string') {
404
+ sendJson(res, 200, display(guessit(body.filename, opts), 'json'));
405
+ } else {
406
+ sendJson(res, 400, { error: 'Body must contain "filename" (string) or "filenames" (array)' });
407
+ }
408
+ } catch (e) { sendJson(res, 400, { error: String((e && e.message) || e) }); }
409
+ });
410
+ return;
411
+ }
412
+ sendJson(res, 405, { error: 'Method not allowed' });
413
+ });
414
+ server.listen(servePort, () => {
415
+ console.log(`guessit-js ${version} API listening on http://localhost:${servePort}`);
416
+ console.log(` GET /api/guessit?filename=Movie.2020.1080p.mkv`);
417
+ console.log(` POST /api/guessit {"filename": "..."} or {"filenames": ["...", "..."]}`);
418
+ console.log(` GET /api/health`);
419
+ });
420
+ } else {
421
+
313
422
  // ---- main -------------------------------------------------------------------
314
423
  if (!process.stdin.isTTY && !filenames.length) {
315
424
  filenames.push(...readLines('-'));
316
425
  }
317
426
  if (!filenames.length) fail('usage: guessit-js [options] <filename> — see --help');
318
427
 
428
+ if (benchmark > 0) {
429
+ guessit(filenames[0], options); // warm up (builds the pattern matcher)
430
+ const t0 = performance.now();
431
+ for (let n = 0; n < benchmark; n++) {
432
+ for (const f of filenames) guessit(f, options);
433
+ }
434
+ const elapsed = performance.now() - t0;
435
+ const total = benchmark * filenames.length;
436
+ console.log(`guessit-js ${version} benchmark`);
437
+ console.log(` ${total} parses (${filenames.length} filename${filenames.length > 1 ? 's' : ''} × ${benchmark} iterations)`);
438
+ console.log(` total: ${(elapsed / 1000).toFixed(2)} s`);
439
+ console.log(` per parse: ${(elapsed / total).toFixed(3)} ms`);
440
+ console.log(` throughput: ${Math.round(total / (elapsed / 1000))} parses/s`);
441
+ process.exit(0);
442
+ }
443
+
319
444
  let hadError = false;
320
445
  for (const filename of filenames) {
321
446
  let result;
@@ -362,3 +487,4 @@ for (const filename of filenames) {
362
487
  }
363
488
 
364
489
  process.exit(hadError ? 1 : 0);
490
+ } // end of non-serve mode