quizmill 0.3.76 → 0.3.77

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
@@ -21,6 +21,7 @@ npx quizmill build my-topic # static app in my-topic-app/ — deploy anywhe
21
21
  | `run [dir\|owner/repo]` | activate a pack and start the app |
22
22
  | `build [dir\|owner/repo]` | emit a deployable static app in `<pack-id>-app/` |
23
23
  | `bundle <dir> [--out file]` | validate + write one `<pack-id>.bundle.json` (images inside) that any quizmill app inserts at `/packs` |
24
+ | `share <dir>` | validate + bundle + upload to the unlock service; prints a `…/unlock#key=…` link that installs the pack in one tap (`--new-key [label]`, `--list`, `--revoke <key>`, `--app`, `--endpoint`) |
24
25
  | `list` | published packs you can install |
25
26
  | `upgrade` | update the cached engine in `~/.quizmill` |
26
27
 
package/bin/quizmill.js CHANGED
@@ -13,6 +13,7 @@
13
13
  * npx quizmill run owner/repo ...straight from a GitHub pack repo
14
14
  * npx quizmill build my-topic static site in <pack-id>-app/
15
15
  * npx quizmill bundle my-topic one <pack-id>.bundle.json to hand over
16
+ * npx quizmill share my-topic upload the bundle to the unlock service, print the link
16
17
  * npx quizmill list published packs
17
18
  * npx quizmill upgrade update the cached engine
18
19
  */
@@ -91,7 +92,10 @@ function engineSha() {
91
92
  }
92
93
  }
93
94
 
94
- function engineNpm(args) {
95
+ /** Run one of the engine's npm scripts. `quiet` swallows its stdout (the
96
+ * caller prints its own summary); stderr — the validator's errors — is
97
+ * always passed through. */
98
+ function engineNpm(args, { quiet = false } = {}) {
95
99
  ensureEngine();
96
100
  const env = { ...process.env };
97
101
  // Stamp the build with the CLI version, which always matches the pinned
@@ -102,7 +106,7 @@ function engineNpm(args) {
102
106
  if (!process.env.QUIZMILL_ENGINE && !env.NEXT_PUBLIC_APP_VERSION) {
103
107
  env.NEXT_PUBLIC_APP_VERSION = CLI_VERSION;
104
108
  }
105
- run('npm', args, { cwd: ENGINE, env });
109
+ run('npm', args, { cwd: ENGINE, env, ...(quiet ? { stdio: ['inherit', 'pipe', 'inherit'] } : {}) });
106
110
  }
107
111
 
108
112
  /** Resolve a pack argument: absolute path for dirs, verbatim otherwise
@@ -238,6 +242,186 @@ function cmdBundle(arg, rest) {
238
242
  engineNpm(['run', 'pack:bundle', '--', src, '--out', target]);
239
243
  }
240
244
 
245
+ // ── share: a private pack behind a licence key ──────────────────────────
246
+ //
247
+ // `share` is `bundle` with the file going to the unlock service instead
248
+ // of the desk: the engine validates and bundles the pack, the CLI PUTs
249
+ // the bundle to `<endpoint>/v1/packs/<id>` with the admin token, and the
250
+ // service answers with the pack's licence keys — minting the first one
251
+ // on the first upload. Each key becomes a link to the home app
252
+ // (`<app>/unlock#key=…`): tapping it on a phone fetches the bundle with
253
+ // the key, inserts the pack and makes it active, no file picker. The
254
+ // key rides in the fragment, which no server or log ever sees.
255
+ // Re-running `share` replaces the bundle and leaves the keys alone, so
256
+ // links keep working and (same pack id) learners keep their progress.
257
+ //
258
+ // Settings live in ~/.quizmill/config.json:
259
+ // { "unlock": { "endpoint": "https://sync.quizmill.dev",
260
+ // "app": "https://app.quizmill.dev", "token": "QT-…" } }
261
+ // `endpoint` and `app` have defaults; `token` is the service's
262
+ // UNLOCK_ADMIN_TOKEN and has none.
263
+
264
+ const CONFIG_FILE = path.join(HOME, 'config.json');
265
+ const DEFAULT_UNLOCK_ENDPOINT = 'https://sync.quizmill.dev';
266
+ const DEFAULT_UNLOCK_APP = 'https://app.quizmill.dev';
267
+
268
+ /** The `unlock` block of the config file, `{}` when there is none. */
269
+ function readUnlockConfig() {
270
+ try {
271
+ const parsed = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
272
+ return parsed && typeof parsed.unlock === 'object' && parsed.unlock ? parsed.unlock : {};
273
+ } catch {
274
+ return {};
275
+ }
276
+ }
277
+
278
+ /** An origin typed without a scheme (`app.quizmill.dev`) means https. */
279
+ function withScheme(origin) {
280
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(origin) ? origin : `https://${origin}`;
281
+ }
282
+
283
+ function parseShareArgs(arg, rest) {
284
+ const opts = { dir: null, list: false, newKey: null, revoke: null, app: null, endpoint: null };
285
+ const argv = arg === undefined ? rest : [arg, ...rest];
286
+ const usage =
287
+ 'usage: quizmill share <dir> [--new-key [label]] [--list] [--app <origin>] [--endpoint <url>]\n' +
288
+ ' quizmill share --revoke <key>';
289
+ for (let i = 0; i < argv.length; i++) {
290
+ const a = argv[i];
291
+ const value = (flag) => {
292
+ const v = argv[++i];
293
+ if (v === undefined || v.startsWith('--')) die(`${flag} needs a value — ${usage}`);
294
+ return v;
295
+ };
296
+ if (a === '--list') opts.list = true;
297
+ else if (a === '--new-key') {
298
+ // The label is optional: the next word is one unless it is a flag.
299
+ opts.newKey = argv[i + 1] !== undefined && !argv[i + 1].startsWith('--') ? argv[++i] : '';
300
+ } else if (a.startsWith('--new-key=')) opts.newKey = a.slice('--new-key='.length);
301
+ else if (a === '--revoke') opts.revoke = value('--revoke');
302
+ else if (a.startsWith('--revoke=')) opts.revoke = a.slice('--revoke='.length);
303
+ else if (a === '--app') opts.app = value('--app');
304
+ else if (a.startsWith('--app=')) opts.app = a.slice('--app='.length);
305
+ else if (a === '--endpoint') opts.endpoint = value('--endpoint');
306
+ else if (a.startsWith('--endpoint=')) opts.endpoint = a.slice('--endpoint='.length);
307
+ else if (a.startsWith('-')) die(`unknown option "${a}" — ${usage}`);
308
+ else if (opts.dir === null) opts.dir = a;
309
+ else die(`unexpected argument "${a}" — ${usage}`);
310
+ }
311
+ if (opts.dir === null && opts.revoke === null) die(usage);
312
+ return opts;
313
+ }
314
+
315
+ /** One request to the unlock service's admin routes; dies with the
316
+ * service's own words on anything but a 2xx. */
317
+ async function unlockApi(cfg, method, route, body) {
318
+ const url = `${cfg.endpoint.replace(/\/+$/, '')}${route}`;
319
+ let res;
320
+ try {
321
+ res = await fetch(url, {
322
+ method,
323
+ headers: {
324
+ authorization: `Bearer ${cfg.token}`,
325
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
326
+ },
327
+ ...(body !== undefined ? { body } : {}),
328
+ });
329
+ } catch (err) {
330
+ die(`could not reach ${cfg.endpoint}: ${err.cause ? err.cause.message : err.message}`);
331
+ }
332
+ let data = null;
333
+ try {
334
+ data = await res.json();
335
+ } catch {
336
+ // a non-JSON answer: reported by status below
337
+ }
338
+ if (res.status === 401) {
339
+ die(`${cfg.endpoint} refused the token in ${CONFIG_FILE} (unlock.token)`);
340
+ }
341
+ if (!res.ok) {
342
+ die(`${method} ${route} → HTTP ${res.status}${data && data.error ? `: ${data.error}` : ''}`);
343
+ }
344
+ return data;
345
+ }
346
+
347
+ const unlockLink = (cfg, key) => `${cfg.app.replace(/\/+$/, '')}/unlock#key=${key}`;
348
+
349
+ /** `--list`: every key of the pack, spent and revoked ones included. */
350
+ function printKeys(cfg, id, keys) {
351
+ if (keys.length === 0) {
352
+ log(`${id}: no licence keys yet — run \`quizmill share <dir>\` to upload and mint one`);
353
+ return;
354
+ }
355
+ log(`${id} — ${keys.length} licence key${keys.length === 1 ? '' : 's'}`);
356
+ for (const k of keys) {
357
+ const uses = k.maxUses === null ? `${k.uses} use${k.uses === 1 ? '' : 's'}` : `${k.uses}/${k.maxUses} uses`;
358
+ const state = k.revokedAt
359
+ ? `revoked ${k.revokedAt.slice(0, 10)}`
360
+ : k.maxUses !== null && k.uses >= k.maxUses
361
+ ? 'spent'
362
+ : unlockLink(cfg, k.key);
363
+ log(` ${k.key} ${k.label ? `${k.label} ` : ''}${uses} ${state}`);
364
+ }
365
+ }
366
+
367
+ async function cmdShare(arg, rest) {
368
+ const opts = parseShareArgs(arg, rest);
369
+ const file = readUnlockConfig();
370
+ const cfg = {
371
+ endpoint: opts.endpoint || file.endpoint || DEFAULT_UNLOCK_ENDPOINT,
372
+ app: withScheme(opts.app || file.app || DEFAULT_UNLOCK_APP),
373
+ token: typeof file.token === 'string' ? file.token.trim() : '',
374
+ };
375
+ if (!cfg.token) {
376
+ die(
377
+ `no unlock token — put the service's UNLOCK_ADMIN_TOKEN in ${CONFIG_FILE}:\n` +
378
+ ` { "unlock": { "endpoint": "${cfg.endpoint}", "app": "${cfg.app}", "token": "…" } }`,
379
+ );
380
+ }
381
+
382
+ if (opts.revoke !== null) {
383
+ const data = await unlockApi(cfg, 'DELETE', `/v1/keys/${encodeURIComponent(opts.revoke)}`);
384
+ const k = data.key || {};
385
+ log(`✓ revoked ${k.key || opts.revoke}${k.packId ? ` (${k.packId})` : ''} — its link no longer unlocks anything`);
386
+ return;
387
+ }
388
+
389
+ const src = packSource(opts.dir);
390
+ if (!fs.existsSync(src)) die(`not a directory: ${opts.dir}`);
391
+ const id = packIdOf(src);
392
+ if (!id) die(`${opts.dir}/pack.json has no readable "id" — run \`quizmill validate ${opts.dir}\``);
393
+
394
+ if (opts.list) {
395
+ const data = await unlockApi(cfg, 'GET', `/v1/packs/${id}/keys`);
396
+ printKeys(cfg, id, data.keys || []);
397
+ return;
398
+ }
399
+ if (opts.newKey !== null) {
400
+ const data = await unlockApi(cfg, 'POST', `/v1/packs/${id}/keys`, JSON.stringify({ label: opts.newKey }));
401
+ log(`✓ new licence key for ${id}${opts.newKey ? ` (${opts.newKey})` : ''}`);
402
+ log(unlockLink(cfg, data.key.key));
403
+ return;
404
+ }
405
+
406
+ // Validate + bundle via the engine (it refuses an invalid pack, with the
407
+ // validator's errors on stderr), through a scratch file the engine
408
+ // writes and the CLI reads straight back — nothing is left on disk.
409
+ const scratch = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'quizmill-share-')), `${id}.json`);
410
+ let text;
411
+ try {
412
+ engineNpm(['run', 'pack:bundle', '--', src, '--out', scratch], { quiet: true });
413
+ text = fs.readFileSync(scratch, 'utf8');
414
+ } finally {
415
+ fs.rmSync(path.dirname(scratch), { recursive: true, force: true });
416
+ }
417
+ const data = await unlockApi(cfg, 'PUT', `/v1/packs/${id}`, text);
418
+ const kib = Math.round(Buffer.byteLength(text) / 1024);
419
+ log(`Uploaded ${id} (${data.questions} question${data.questions === 1 ? '' : 's'}, ${kib} KiB)`);
420
+ const live = (data.keys || []).filter((k) => !k.revokedAt && (k.maxUses === null || k.uses < k.maxUses));
421
+ for (const k of live) log(`${unlockLink(cfg, k.key)}${k.label ? ` (${k.label})` : ''}`);
422
+ if (live.length === 0) log(`(no live licence key — mint one with \`quizmill share ${opts.dir} --new-key\`)`);
423
+ }
424
+
241
425
  function cmdUpgrade() {
242
426
  if (process.env.QUIZMILL_ENGINE) {
243
427
  ensureEngine();
@@ -263,6 +447,8 @@ usage:
263
447
  quizmill run [dir|owner/repo] activate a pack (default: current/demo) and start the app
264
448
  quizmill build [dir|owner/repo] build a static app into <pack-id>-app/
265
449
  quizmill bundle <dir> [--out file] one <pack-id>.bundle.json, images inside — insert it at /packs
450
+ quizmill share <dir> upload the bundle to the unlock service; prints the licence-key link
451
+ --new-key [label] | --list | --revoke <key> | --app <origin> | --endpoint <url>
266
452
  quizmill list published packs you can install
267
453
  quizmill upgrade update the cached engine (~/.quizmill)
268
454
  quizmill --version print the CLI version (stamped into builds)
@@ -279,6 +465,13 @@ try {
279
465
  case 'run': cmdRun(arg); break;
280
466
  case 'build': cmdBuild(arg); break;
281
467
  case 'bundle': cmdBundle(arg, rest); break;
468
+ case 'share':
469
+ // The only async command (it talks HTTP); failures end the process
470
+ // the same way the synchronous ones do.
471
+ cmdShare(arg, rest).catch((err) => {
472
+ process.exit(typeof err.status === 'number' ? err.status : 1);
473
+ });
474
+ break;
282
475
  case 'list': engineNpm(['run', 'pack:list']); break;
283
476
  case 'upgrade': cmdUpgrade(); break;
284
477
  case 'version':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quizmill",
3
- "version": "0.3.76",
3
+ "version": "0.3.77",
4
4
  "description": "Turn a folder of JSON into an installable, offline-first practice app. The mill that grinds questions into knowledge.",
5
5
  "bin": {
6
6
  "quizmill": "bin/quizmill.js"