create-nevela 0.4.1 → 0.4.2

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
@@ -45,8 +45,10 @@ npm install -g create-nevela
45
45
  ```
46
46
 
47
47
  ```sh
48
- nevela new my-app # anywhere: create an app
48
+ nevela # anywhere: everything it can do
49
+ nevela new my-app # anywhere: create an app (leave the name off and it asks)
49
50
  nevela update # anywhere: update the nevela command itself
51
+ nevela version # anywhere: the command's version, and the app's when in one
50
52
  nevela dev # inside an app: run the API and the dashboard
51
53
  nevela upgrade # inside an app: bring it to the latest Nevela
52
54
  ```
package/banner.mjs ADDED
@@ -0,0 +1,50 @@
1
+ // The name, large, at the top of the commands you run from anywhere: new, update, help.
2
+ //
3
+ // The same block letters as the Laravel installer and Grit, in Nevela's colours, one
4
+ // colour to a row so the name runs from blue through indigo to pink.
5
+
6
+ const LETTERS = {
7
+ N: ['███╗ ██╗', '████╗ ██║', '██╔██╗ ██║', '██║╚██╗██║', '██║ ╚████║', '╚═╝ ╚═══╝'],
8
+ E: ['███████╗', '██╔════╝', '█████╗ ', '██╔══╝ ', '███████╗', '╚══════╝'],
9
+ V: ['██╗ ██╗', '██║ ██║', '██║ ██║', '╚██╗ ██╔╝', ' ╚████╔╝ ', ' ╚═══╝ '],
10
+ L: ['██╗ ', '██║ ', '██║ ', '██║ ', '███████╗', '╚══════╝'],
11
+ A: [' █████╗ ', '██╔══██╗', '███████║', '██╔══██║', '██║ ██║', '╚═╝ ╚═╝'],
12
+ };
13
+
14
+ /** "NEVELA", six rows of the same width. */
15
+ export const ROWS = [0, 1, 2, 3, 4, 5].map((row) => [...'NEVELA'].map((letter) => LETTERS[letter][row]).join(''));
16
+ export const WIDTH = ROWS[0].length;
17
+
18
+ export const TAGLINE = 'Describe a resource. Get the API and the dashboard.';
19
+
20
+ /** A colour for each row, top to bottom, for what the terminal can show. */
21
+ const GRADIENT = {
22
+ // 16.7 million colours
23
+ 24: ['38;2;79;123;255', '38;2;99;102;241', '38;2;124;92;246', '38;2;168;85;247', '38;2;217;70;239', '38;2;244;114;182'],
24
+ // 256 colours
25
+ 8: ['38;5;69', '38;5;63', '38;5;99', '38;5;135', '38;5;171', '38;5;205'],
26
+ // 16 colours: blue above, magenta below
27
+ 4: ['94', '94', '94', '95', '95', '95'],
28
+ };
29
+
30
+ /**
31
+ * The banner, as text to print.
32
+ *
33
+ * @param {object} options
34
+ * @param {string} options.version
35
+ * @param {number} options.depth Bits of colour the terminal has: 24, 8, 4, 1 for none,
36
+ * and 0 when the output isn't a terminal at all.
37
+ * @param {number} [options.columns] How wide the terminal is
38
+ * @param {boolean} [options.compact] The name on one line, whatever the terminal can show
39
+ */
40
+ export function banner({ version, depth, columns = 80, compact = false }) {
41
+ const paint = (code, text) => (depth > 1 ? `\x1b[${code}m${text}\x1b[0m` : text);
42
+ // Into a file or a pipe, or a terminal too narrow for the letters: the name on one line.
43
+ if (compact || depth === 0 || columns < WIDTH + 4) {
44
+ // Indigo where there are 256 colours to pick it from; magenta where there are 16.
45
+ return `\n ${paint(depth >= 8 ? '1;38;5;99' : '1;95', 'Nevela')} ${paint(2, `v${version}`)}\n`;
46
+ }
47
+ const colours = GRADIENT[depth >= 24 ? 24 : depth >= 8 ? 8 : 4];
48
+ const rows = ROWS.map((row, index) => ` ${paint(colours[index], row)}`);
49
+ return `\n${rows.join('\n')}\n\n ${paint(2, `${TAGLINE} v${version}`)}\n`;
50
+ }
package/index.mjs CHANGED
@@ -13,11 +13,12 @@ import os from 'node:os';
13
13
  import path from 'node:path';
14
14
  import readline from 'node:readline/promises';
15
15
  import { fileURLToPath } from 'node:url';
16
+ import { banner } from './banner.mjs';
16
17
  import { isNewer, latestRelease, onPackagist } from './packagist.mjs';
17
18
  import { COMMANDS, findProject, forward, upgrade } from './project.mjs';
18
19
  import { shellLine, spawnCommand, windows } from './shell.mjs';
19
20
  import { latestVersion, newerVersion, runVersion } from './selfupdate.mjs';
20
- import { globalInstall, INSTALL_COMMAND } from './tool.mjs';
21
+ import { copiesOnPath, globalInstall, INSTALL_COMMAND, removeCommand } from './tool.mjs';
21
22
  import { copyLaravelPackage, copyWebTemplate, fromRepository, templateRecord } from './template.mjs';
22
23
 
23
24
  const here = path.dirname(fileURLToPath(import.meta.url));
@@ -31,24 +32,39 @@ const DOCS = 'https://nevela-docs.vercel.app';
31
32
  */
32
33
  const ADMIN = { name: 'Admin', email: 'admin@example.com', password: 'password' };
33
34
 
34
- const colour = (code) => (text) => (process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text);
35
+ /** Bits of colour the terminal has: 24, 8, 4, 1 for none, and 0 when this isn't going to a terminal. */
36
+ const depth = process.stdout.isTTY ? process.stdout.getColorDepth() : 0;
37
+ const colour = (code) => (text) => (depth > 1 ? `\x1b[${code}m${text}\x1b[0m` : text);
35
38
  const bold = colour(1);
36
39
  const dim = colour(2);
37
40
  const green = colour(32);
38
41
  const red = colour(31);
39
- const indigo = colour('38;5;99');
42
+ // Indigo where there are 256 colours to pick it from; magenta where there are 16.
43
+ const indigo = colour(depth >= 8 ? '38;5;99' : '95');
40
44
 
41
- const HELP = `
42
- ${bold('create-nevela')} ${dim(`v${VERSION}`)}
45
+ /**
46
+ * Whether `nevela` was typed, as opposed to create-nevela (`pnpm create nevela`). Kept in
47
+ * the environment so a newer installer this one hands over to knows it too.
48
+ */
49
+ const startedAsNevela = /^nevela(\.mjs)?$/.test(path.basename(process.argv[1] ?? ''));
50
+ const typedNevela = startedAsNevela || process.env.NEVELA_TYPED === 'nevela';
51
+ if (typedNevela) process.env.NEVELA_TYPED = 'nevela';
43
52
 
44
- Create a new Nevela app: a Laravel API and a Next.js dashboard.
53
+ /** The name, large. Once per run: an installer that handed over to a newer one has shown it. */
54
+ function showTitle() {
55
+ console.log(banner({ version: VERSION, depth, columns: process.stdout.columns ?? 80, compact: Boolean(process.env.NEVELA_HANDED_OVER) }));
56
+ }
57
+
58
+ const HELP = ` Create a new Nevela app: a Laravel API and a Next.js dashboard.
45
59
 
46
60
  ${bold('Get the nevela command')} (once; everything below is then this short)
47
61
  npm install -g create-nevela
48
62
 
49
63
  ${bold('Anywhere')}
50
- nevela new <name> [options] Create an app. Without the command: pnpm create nevela <name>
64
+ nevela new [name] [options] Create an app. It asks for the name if you leave it off.
65
+ Without the command: pnpm create nevela <name>
51
66
  nevela update Update the nevela command itself to the latest version
67
+ nevela version Which version the nevela command is, and this app when in one
52
68
 
53
69
  ${bold('Inside an app')}
54
70
  nevela upgrade Bring this app to the latest Nevela: the package and the dashboard
@@ -176,6 +192,7 @@ function parseArgs(argv) {
176
192
  for (let i = 0; i < argv.length; i++) {
177
193
  const arg = argv[i];
178
194
  if (arg === '-h' || arg === '--help') {
195
+ showTitle();
179
196
  console.log(HELP);
180
197
  process.exit(0);
181
198
  } else if (arg === '-v' || arg === '--version') {
@@ -210,6 +227,8 @@ function phpIsTypeable() {
210
227
 
211
228
  /** `nevela <command>` as someone should type it here: through PHP, or through the package manager. */
212
229
  function nevelaCommand(pm) {
230
+ // Typed as `nevela`, so the command is installed, and it is the shortest of the three.
231
+ if (typedNevela) return 'nevela';
213
232
  if (phpIsTypeable()) return 'php nevela';
214
233
  return { pnpm: 'pnpm nevela', yarn: 'yarn nevela', bun: 'bun run nevela' }[pm] ?? 'npm run nevela';
215
234
  }
@@ -330,9 +349,8 @@ Docs: ${DOCS}
330
349
  async function inProject(name, args) {
331
350
  const project = findProject(process.cwd());
332
351
  if (!project) {
333
- fail(`"${name}" runs inside a Nevela app, and this folder isn't in one.`, `To create an app: pnpm create nevela my-app`);
352
+ fail(`"${name}" runs inside a Nevela app, and this folder isn't in one.`, `To create an app: ${typedNevela ? 'nevela new my-app' : 'pnpm create nevela my-app'}`);
334
353
  }
335
- if (name === 'version') console.log(`create-nevela ${VERSION}`);
336
354
  if (name !== 'upgrade') process.exit(forward(project, name, args));
337
355
 
338
356
  // Upgrading is the one command that must not run on stale code itself: it is the newest
@@ -351,6 +369,85 @@ async function inProject(name, args) {
351
369
  process.exit(status);
352
370
  }
353
371
 
372
+ /**
373
+ * Say so when the nevela command is installed more than once. Only the first on the PATH
374
+ * ever runs, so an update to one of the others looks like an update that did nothing.
375
+ */
376
+ function otherCopies() {
377
+ const copies = copiesOnPath();
378
+ if (copies.length < 2) return;
379
+ console.log(`\n ${red('!')} The nevela command is installed ${copies.length} times. Typing ${bold('nevela')} runs the first of these:`);
380
+ for (const dir of copies) console.log(` ${dir}`);
381
+ console.log(` Keep that one and remove the rest, so there is one to keep up to date:`);
382
+ for (const dir of copies.slice(1)) console.log(` ${bold(removeCommand(dir))}`);
383
+ }
384
+
385
+ /** The version of Nevela an app has installed, read from the package, or null. */
386
+ function appVersion(project) {
387
+ try {
388
+ const source = fs.readFileSync(path.join(project.api, 'vendor', 'nevela', 'laravel', 'src', 'Nevela.php'), 'utf8');
389
+ return /const VERSION = '([^']+)'/.exec(source)?.[1] ?? null;
390
+ } catch {
391
+ return null;
392
+ }
393
+ }
394
+
395
+ /** `nevela version`, from anywhere: the command's version, and the app's when in one. */
396
+ function showVersion() {
397
+ const project = findProject(process.cwd());
398
+ const install = fromRepository ? null : globalInstall(here);
399
+ console.log(`\n ${indigo(bold('Nevela command'))} ${bold(`v${VERSION}`)}${install ? ` ${dim(`installed with ${install.manager}`)}` : ''}`);
400
+ if (project) {
401
+ const app = appVersion(project);
402
+ if (app === null) {
403
+ console.log(` ${indigo(bold('This app'))} ${dim("Nevela isn't installed in it yet. Run: cd apps/api && composer install")}`);
404
+ } else {
405
+ const behind = isNewer(VERSION, app);
406
+ console.log(` ${indigo(bold('This app'))} ${bold(`v${app}`)}${behind ? ` ${dim('To bring it to the latest:')} ${bold('nevela upgrade')}` : ''}`);
407
+ }
408
+ }
409
+ otherCopies();
410
+ console.log('');
411
+ }
412
+
413
+ /**
414
+ * Why `name` can't be the new app's name, or null when it can.
415
+ */
416
+ function nameProblem(name) {
417
+ if (name === '') return 'Type a name, for example my-app.';
418
+ if (!/^[a-z0-9][a-z0-9-_]*$/.test(name)) {
419
+ return `"${name}" can't be used as a name. Use lowercase letters, numbers and dashes, for example my-app.`;
420
+ }
421
+ const root = path.resolve(process.cwd(), name);
422
+ if (fs.existsSync(root) && fs.readdirSync(root).length > 0) return `${root} already exists and isn't empty.`;
423
+ return null;
424
+ }
425
+
426
+ /**
427
+ * Ask what the app is called, until the answer is a name that can be used. The only
428
+ * question this ever asks, and only when the name was left off.
429
+ */
430
+ async function askName() {
431
+ const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
432
+ // Ctrl+C or the end of input, at the question: leave, having created nothing.
433
+ const closed = new Promise((resolve) => prompt.once('close', () => resolve(null)));
434
+ prompt.on('SIGINT', () => prompt.close());
435
+ try {
436
+ for (;;) {
437
+ const answer = await Promise.race([prompt.question(` ${green('What is the name of your app?')} `).catch(() => null), closed]);
438
+ if (answer === null) {
439
+ console.log('\n');
440
+ process.exit(130);
441
+ }
442
+ const problem = nameProblem(answer.trim());
443
+ if (problem === null) return answer.trim();
444
+ console.log(` ${red('✖')} ${problem}\n`);
445
+ }
446
+ } finally {
447
+ prompt.close();
448
+ }
449
+ }
450
+
354
451
  /**
355
452
  * `nevela update`, from anywhere: update the nevela command itself.
356
453
  *
@@ -373,14 +470,16 @@ async function updateTool(args) {
373
470
  console.log(`\n ${dim(`"update" now updates the nevela command, and an app is brought up to date with "upgrade". Upgrading this app.`)}`);
374
471
  await inProject('upgrade', args);
375
472
  }
376
- console.log(`\n ${indigo(bold('Nevela'))} ${dim(`v${VERSION}`)}\n`);
473
+ showTitle();
377
474
  console.log(` The nevela command isn't installed on this computer, so there is nothing to update.`);
378
475
  console.log(` To install it: ${bold(INSTALL_COMMAND)}`);
379
476
  console.log(` Then, anywhere: ${bold('nevela new my-app')} and inside an app: ${bold('nevela upgrade')}, ${bold('nevela dev')}\n`);
380
477
  return;
381
478
  }
382
479
 
383
- console.log(`\n ${indigo(bold('Nevela'))} ${dim('update')}\n`);
480
+ showTitle();
481
+ console.log(` ${indigo(`Nevela self-update — current: v${VERSION}`)}\n`);
482
+ console.log(` ${dim('→ Checking npm for the latest release…')}\n`);
384
483
  const latest = await latestVersion();
385
484
  const newer = latest !== null && isNewer(latest, VERSION) ? latest : null;
386
485
  if (latest === null) {
@@ -389,16 +488,17 @@ async function updateTool(args) {
389
488
  console.log(` Try again when you are online, or run: ${install.command.join(' ')}`);
390
489
  process.exitCode = 1;
391
490
  } else if (!newer) {
392
- console.log(` ${green('✔')} nevela ${bold(VERSION)} is the latest.`);
491
+ console.log(` ${green(`✔ Already on the latest version (v${VERSION}). Nothing to do.`)}`);
393
492
  } else {
394
- console.log(` Updating the nevela command ${bold(VERSION)} → ${bold(newer)} ${dim(`(${install.command.join(' ')})`)}\n`);
493
+ console.log(` Updating v${VERSION} → ${bold(`v${newer}`)} ${dim(`(${install.command.join(' ')})`)}\n`);
395
494
  const [command, ...rest] = install.command;
396
495
  const result = spawnCommand(command, rest, { stdio: 'inherit' });
397
496
  if (result.error || result.status !== 0) {
398
497
  fail(`Couldn't update the nevela command.`, `Run it yourself to see why: ${install.command.join(' ')}`);
399
498
  }
400
- console.log(`\n ${green('✔')} nevela is now ${bold(newer)}.`);
499
+ console.log(`\n ${green(`✔ Updated to v${newer}.`)} ${dim('Every nevela command, and every app you create from now on, uses it.')}`);
401
500
  }
501
+ otherCopies();
402
502
  if (project) {
403
503
  console.log(` ${dim('This app is not changed by that. To bring it to the latest Nevela:')} ${bold('nevela upgrade')}`);
404
504
  }
@@ -409,10 +509,18 @@ async function main() {
409
509
  const argv = process.argv.slice(2);
410
510
  if (argv[0] === 'new') argv.shift();
411
511
  else if (argv[0] === 'update') return updateTool(argv.slice(1));
512
+ else if (argv[0] === 'version') return showVersion();
412
513
  else if (COMMANDS.includes(argv[0])) await inProject(argv[0], argv.slice(1));
514
+ else if (argv[0] === 'help' || (startedAsNevela && argv.length === 0)) {
515
+ // `nevela` on its own says what it can do. `pnpm create nevela` on its own starts an
516
+ // app, and so does a newer installer that an older `nevela new` handed over to.
517
+ showTitle();
518
+ console.log(HELP);
519
+ return;
520
+ }
413
521
  const options = parseArgs(argv);
414
522
 
415
- console.log(`\n ${indigo(bold('Nevela'))} ${dim(`v${VERSION}`)}\n`);
523
+ showTitle();
416
524
 
417
525
  // A package manager may hand over an older installer than the newest: pnpm skips versions
418
526
  // published in the last few hours, and both pnpm and npm cache. Fetch the newest and let
@@ -430,19 +538,17 @@ async function main() {
430
538
  }
431
539
 
432
540
  let name = options.name;
433
- if (!name) {
434
- // The only question this ever asks, and only when the name was left off.
435
- if (options.yes || !process.stdin.isTTY) fail('Give the app a name: pnpm create nevela my-app');
436
- const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
437
- name = (await prompt.question(' What is the app called? ')).trim();
438
- prompt.close();
439
- }
440
- if (!/^[a-z0-9][a-z0-9-_]*$/.test(name)) {
441
- fail(`"${name}" can't be used as a name. Use lowercase letters, numbers and dashes, for example my-app.`);
541
+ if (name === undefined) {
542
+ // Nobody to ask: say what to type instead.
543
+ if (options.yes || !process.stdin.isTTY) fail(`Give the app a name: ${typedNevela ? 'nevela new my-app' : 'pnpm create nevela my-app'}`);
544
+ name = await askName();
545
+ console.log('');
546
+ } else {
547
+ const problem = nameProblem(name);
548
+ if (problem) fail(problem);
442
549
  }
443
550
 
444
551
  const root = path.resolve(process.cwd(), name);
445
- if (fs.existsSync(root) && fs.readdirSync(root).length > 0) fail(`${root} already exists and isn't empty.`);
446
552
 
447
553
  checkRequirements();
448
554
  const pm = detectPackageManager(options.pm);
@@ -583,7 +689,7 @@ async function main() {
583
689
  }
584
690
  console.log(`\n Add your first resource: ${dim(`${nevela} resource Product --fields="name:string, price:money"`)}`);
585
691
  console.log(` Check the app: ${dim(`${nevela} status`)} Upgrade it later: ${dim(`${nevela} upgrade`)} Everything: ${dim(nevela)}`);
586
- if (nevela !== 'php nevela') {
692
+ if (nevela !== 'php nevela' && nevela !== 'nevela') {
587
693
  console.log(`\n ${dim(`In this shell "php" isn't a command (your PHP is php.bat), so use ${nevela}. In PowerShell, php nevela works too.`)}`);
588
694
  }
589
695
  console.log(` Docs: ${DOCS}/start/quickstart/\n`);
package/net.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // Reading a URL, without fetch().
2
+ //
3
+ // On Windows, a process that exits just after a fetch() has finished trips an assertion
4
+ // inside Node ("UV_HANDLE_CLOSING") and prints a crash where the error message should be.
5
+ // The installer asks npm for the latest version first thing, so every mistake it reports
6
+ // straight afterwards ended that way: no app name, a name it can't use, a folder that
7
+ // already exists. A plain https request on a connection that closes with the answer doesn't.
8
+
9
+ import https from 'node:https';
10
+
11
+ /**
12
+ * GET `url`. Resolves to { ok, status, body } with the body as a Buffer, or to null when
13
+ * the server couldn't be reached within `milliseconds`. Never rejects.
14
+ *
15
+ * The time allowed is for the whole exchange, redirects included, and not only for a
16
+ * silence on the line.
17
+ */
18
+ export function get(url, milliseconds, redirects = 3, deadline = Date.now() + milliseconds) {
19
+ return new Promise((resolve) => {
20
+ let timer = null;
21
+ const settle = (value) => {
22
+ clearTimeout(timer);
23
+ resolve(value);
24
+ };
25
+ try {
26
+ const request = https.get(url, { agent: false, headers: { connection: 'close', 'user-agent': 'create-nevela' } }, (response) => {
27
+ const status = response.statusCode ?? 0;
28
+ if (status >= 300 && status < 400 && response.headers.location && redirects > 0) {
29
+ response.resume();
30
+ settle(get(new URL(response.headers.location, url).href, milliseconds, redirects - 1, deadline));
31
+ return;
32
+ }
33
+ const chunks = [];
34
+ response.on('data', (chunk) => chunks.push(chunk));
35
+ response.on('end', () => settle({ ok: status >= 200 && status < 300, status, body: Buffer.concat(chunks) }));
36
+ response.on('error', () => settle(null));
37
+ });
38
+ request.on('error', () => settle(null));
39
+ timer = setTimeout(() => request.destroy(new Error('timed out')), Math.max(0, deadline - Date.now()));
40
+ } catch {
41
+ settle(null);
42
+ }
43
+ });
44
+ }
45
+
46
+ /** GET `url` and read it as JSON. Null when it couldn't be reached, or isn't JSON, or isn't a 2xx. */
47
+ export async function getJson(url, milliseconds) {
48
+ const response = await get(url, milliseconds);
49
+ if (!response?.ok) return null;
50
+ try {
51
+ return JSON.parse(response.body.toString('utf8'));
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
package/nevela.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // The `nevela` command.
3
+ //
4
+ // The same program as create-nevela. It has a file of its own so the program can tell
5
+ // which of the two was typed: `nevela` with nothing after it says what it can do, where
6
+ // `pnpm create nevela` with nothing after it starts a new app.
7
+
8
+ await import('./index.mjs');
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "create-nevela",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "Create a new Nevela app: a Laravel API and a Next.js dashboard from one resource description.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "create-nevela": "index.mjs",
8
- "nevela": "index.mjs"
8
+ "nevela": "nevela.mjs"
9
9
  },
10
10
  "files": [
11
11
  "index.mjs",
12
+ "nevela.mjs",
13
+ "banner.mjs",
14
+ "net.mjs",
12
15
  "template.mjs",
13
16
  "packagist.mjs",
14
17
  "selfupdate.mjs",
package/packagist.mjs CHANGED
@@ -1,8 +1,12 @@
1
1
  // Deciding where a new app gets nevela/laravel from.
2
2
 
3
+ import { getJson } from './net.mjs';
4
+
5
+ const RELEASES = 'https://repo.packagist.org/p2/nevela/laravel.json';
6
+
3
7
  /** Whether `candidate` is a stable release Composer's `^major.minor` would accept. */
4
8
  export function satisfiesCaret(candidate, [major, minor]) {
5
- const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(candidate);
9
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(candidate));
6
10
  if (!match) return false;
7
11
  const [theirMajor, theirMinor] = match.slice(1).map(Number);
8
12
  // Below 1.0 a caret holds the minor version too: ^0.1 means 0.1.x only.
@@ -23,29 +27,18 @@ export function isNewer(a, b) {
23
27
  * listed isn't enough: with no tagged release yet, `composer require` would fail.
24
28
  */
25
29
  export async function onPackagist(wanted) {
26
- try {
27
- const response = await fetch('https://repo.packagist.org/p2/nevela/laravel.json', { signal: AbortSignal.timeout(8000) });
28
- if (!response.ok) return false;
29
- const releases = (await response.json()).packages?.['nevela/laravel'] ?? [];
30
- return releases.some((release) => satisfiesCaret(release.version, wanted));
31
- } catch {
32
- return false;
33
- }
30
+ const releases = (await getJson(RELEASES, 8000))?.packages?.['nevela/laravel'];
31
+ return Array.isArray(releases) && releases.some((release) => satisfiesCaret(release?.version, wanted));
34
32
  }
35
33
 
36
34
  /** The newest stable nevela/laravel on Packagist, as "x.y.z", or null when it can't be reached. */
37
35
  export async function latestRelease() {
38
- try {
39
- const response = await fetch('https://repo.packagist.org/p2/nevela/laravel.json', { signal: AbortSignal.timeout(8000) });
40
- if (!response.ok) return null;
41
- const releases = (await response.json()).packages?.['nevela/laravel'] ?? [];
42
- let latest = null;
43
- for (const release of releases) {
44
- const version = /^v?(\d+\.\d+\.\d+)$/.exec(release.version)?.[1];
45
- if (version && (latest === null || isNewer(version, latest))) latest = version;
46
- }
47
- return latest;
48
- } catch {
49
- return null;
36
+ const releases = (await getJson(RELEASES, 8000))?.packages?.['nevela/laravel'];
37
+ if (!Array.isArray(releases)) return null;
38
+ let latest = null;
39
+ for (const release of releases) {
40
+ const version = /^v?(\d+\.\d+\.\d+)$/.exec(String(release?.version))?.[1];
41
+ if (version && (latest === null || isNewer(version, latest))) latest = version;
50
42
  }
43
+ return latest;
51
44
  }
package/selfupdate.mjs CHANGED
@@ -10,19 +10,15 @@ import fs from 'node:fs';
10
10
  import os from 'node:os';
11
11
  import path from 'node:path';
12
12
  import zlib from 'node:zlib';
13
+ import { get, getJson } from './net.mjs';
13
14
  import { isNewer } from './packagist.mjs';
14
15
 
15
16
  const REGISTRY = 'https://registry.npmjs.org/create-nevela';
16
17
 
17
18
  /** The newest create-nevela on npm, or null when npm couldn't be asked. Never throws. */
18
19
  export async function latestVersion() {
19
- try {
20
- const response = await fetch(`${REGISTRY}/latest`, { signal: AbortSignal.timeout(4000) });
21
- const latest = (await response.json()).version;
22
- return typeof latest === 'string' && /^\d+\.\d+\.\d+$/.test(latest) ? latest : null;
23
- } catch {
24
- return null;
25
- }
20
+ const latest = (await getJson(`${REGISTRY}/latest`, 4000))?.version;
21
+ return typeof latest === 'string' && /^\d+\.\d+\.\d+$/.test(latest) ? latest : null;
26
22
  }
27
23
 
28
24
  /**
@@ -84,16 +80,17 @@ export function untar(buffer, dir) {
84
80
  export async function runVersion(version, args) {
85
81
  const dir = path.join(os.tmpdir(), `create-nevela-${version}-${process.pid}`);
86
82
  try {
87
- const response = await fetch(`${REGISTRY}/-/create-nevela-${version}.tgz`, { signal: AbortSignal.timeout(30000) });
88
- if (!response.ok) return null;
89
- untar(zlib.gunzipSync(Buffer.from(await response.arrayBuffer())), dir);
83
+ const response = await get(`${REGISTRY}/-/create-nevela-${version}.tgz`, 30000);
84
+ if (!response?.ok) return null;
85
+ untar(zlib.gunzipSync(response.body), dir);
90
86
  const entry = path.join(dir, 'package', 'index.mjs');
91
87
  if (!fs.existsSync(entry)) return null;
92
88
 
93
89
  const result = spawnSync(process.execPath, [entry, ...args], {
94
90
  stdio: 'inherit',
95
- // The newer one must not go looking for a newer one in turn.
96
- env: { ...process.env, NEVELA_NO_SELF_UPDATE: '1' },
91
+ // The newer one must not go looking for a newer one in turn, and the name has
92
+ // already been printed large once.
93
+ env: { ...process.env, NEVELA_NO_SELF_UPDATE: '1', NEVELA_HANDED_OVER: '1' },
97
94
  });
98
95
  return result.status ?? 1;
99
96
  } catch {
@@ -18,7 +18,7 @@ use Nevela\Laravel\Support\Naming;
18
18
  final class Nevela
19
19
  {
20
20
  /** Written by `pnpm release`; the same number as the repository's git tag. */
21
- public const VERSION = '0.4.1';
21
+ public const VERSION = '0.4.2';
22
22
 
23
23
  /** @var array<string, Descriptor> */
24
24
  private static array $descriptors = [];
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nevela-web",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {
package/tool.mjs CHANGED
@@ -54,5 +54,50 @@ export function globalInstall(dir, exists = fs.existsSync) {
54
54
  return { manager: 'npm', command: INSTALL.npm };
55
55
  }
56
56
 
57
+ /**
58
+ * Every folder on the PATH that holds a nevela command, in the order the shell looks.
59
+ *
60
+ * More than one means it was installed more than once, say with npm and with pnpm. The
61
+ * shell runs the first and never mentions the rest, so updating one of the others changes
62
+ * nothing you can see: `npm install -g create-nevela@latest` succeeds and `nevela` is
63
+ * still the old one.
64
+ *
65
+ * @param {Record<string, string | undefined>} env
66
+ * @param {object} [system] Replaceable in tests
67
+ */
68
+ export function copiesOnPath(env = process.env, { exists = fs.existsSync, real = fs.realpathSync, windows = process.platform === 'win32' } = {}) {
69
+ const names = windows ? ['nevela.cmd', 'nevela.exe', 'nevela.ps1', 'nevela'] : ['nevela'];
70
+ const separator = windows ? '\\' : '/';
71
+ const found = [];
72
+ const seen = new Set();
73
+ for (const entry of String(env.PATH ?? env.Path ?? '').split(windows ? ';' : ':')) {
74
+ const dir = entry.trim().replace(/^"|"$/g, '').replace(/[\\/]+$/, '');
75
+ if (!dir) continue;
76
+ const file = names.map((name) => `${dir}${separator}${name}`).find((candidate) => exists(candidate));
77
+ if (!file) continue;
78
+ // The same folder listed twice, or two names for one folder (/bin and /usr/bin), is one copy.
79
+ let target = file;
80
+ try {
81
+ target = real(file);
82
+ } catch {
83
+ // Left as it is.
84
+ }
85
+ const key = windows ? target.toLowerCase() : target;
86
+ if (seen.has(key)) continue;
87
+ seen.add(key);
88
+ found.push(dir);
89
+ }
90
+ return found;
91
+ }
92
+
93
+ /** What removes the copy whose command is in `dir`, judged by the folder. */
94
+ export function removeCommand(dir) {
95
+ const where = dir.replace(/\\/g, '/').toLowerCase();
96
+ if (/\/pnpm(\/|$)/.test(where)) return 'pnpm remove -g create-nevela';
97
+ if (/\/\.bun\//.test(where)) return 'bun remove -g create-nevela';
98
+ if (/\/yarn\/|\/\.yarn\//.test(where)) return 'yarn global remove create-nevela';
99
+ return 'npm uninstall -g create-nevela';
100
+ }
101
+
57
102
  /** What to type to get the `nevela` command, for someone who doesn't have it yet. */
58
103
  export const INSTALL_COMMAND = INSTALL.npm.join(' ').replace('@latest', '');