@pipelex/create-method-app 0.71.0 → 0.71.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
@@ -5,36 +5,37 @@ Start an app that runs an [MTHDS](https://mthds.ai) method through the [Pipelex]
5
5
  ```bash
6
6
  export PIPELEX_API_KEY=… # from app.pipelex.com
7
7
  npm create @pipelex/method-app@latest my-app -- --method ./receipt_review.mthds
8
- make -C my-app serve
8
+ cd my-app
9
+ npm run serve
9
10
  ```
10
11
 
11
- The first command writes the [`webapp-js`](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps/webapp-js) template of the [method-app family](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps), the `method-apps/` directory of `Pipelex/pipelex-sdk`, into `my-app/`, commits it as it came, and runs the copy's own `make create`, which scaffolds the method, names the project after it and runs `make all`. The second starts the dev server in the background, proves that the page answers, and prints its URL; `make stop` stops it. `make dev` runs the same server in the foreground instead.
12
+ The first command writes the [`webapp-js`](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps/webapp-js) template of the [method-app family](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps), the `method-apps/` directory of `Pipelex/pipelex-sdk`, into `my-app/`, commits it as it came, and runs the copy's own `npm run create`, after the `npm install` it needs, which scaffolds the method, names the project after it and runs `npm run all`. The second starts the dev server in the background, proves that the page answers, and prints its URL; `npm run serve -- stop` stops it. `npm run dev` runs the same server in the foreground instead. None of it needs `make` or a POSIX shell, so the same commands run on macOS, Linux and Windows, in PowerShell and `cmd` as in any POSIX shell.
12
13
 
13
14
  `--method` takes a `.mthds` file or a directory of them, a method id from your organization's catalog (`mt_…`, or `mt_…@<version>` and `mt_…@draft` to pin a version or run the draft), or a published package address (`github.com/Pipelex/methods/text_stats@v0.2.0`). A path is read from where you typed the command.
14
15
 
15
16
  ## What it needs
16
17
 
17
- - **Node.js** at or above the template's floor (22.13 for `webapp-js`), `make`, and `git` unless you pass `--no-git`.
18
- - **`PIPELEX_API_KEY`** in the environment, since a fresh copy has no `.env.local` for `make create` to read it from. `make create` runs with it and never copies it into the project: the project's `.env.local` gets an empty `PIPELEX_API_KEY` line, where you put your own key before `make dev`. The initializer only checks that it is set, and never prints it.
18
+ - **Node.js** at or above the template's floor (22.13 for `webapp-js`) with its npm, and `git` unless you pass `--no-git`. The initializer runs npm itself, the one that ran it under `npm create`, or, on Windows, the one the Node installer puts beside `node.exe`; `make` is not needed.
19
+ - **`PIPELEX_API_KEY`** in the environment, since a fresh copy has no `.env.local` for `npm run create` to read it from. `npm run create` runs with it and never copies it into the project: the project's `.env.local` gets an empty `PIPELEX_API_KEY` line, where you put your own key before `npm run dev`. The initializer only checks that it is set, and never prints it.
19
20
  - **A directory that is missing, empty, or holds only `.git`.** Anything else, `.DS_Store` included, is refused, and nothing is written.
20
21
 
21
22
  The package has no dependency. It carries the template inside it, packed from the family's repository at the commit it was published from, so `@X.Y.Z` writes exactly the X.Y.Z template and nothing is fetched from GitHub.
22
23
 
23
24
  ## Options
24
25
 
25
- | Option | What it does |
26
- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
- | `--method <m>` | The method the app runs. Required unless `--no-create`. |
28
- | `--name`, `--title`, `--description` | The project's package name, title and description, which `make create` otherwise derives from the method. |
29
- | `--pipe`, `--method-name`, `--label` | The pipe to run, the method's directory name and its tab label, when the method does not settle them. |
30
- | `--author-name`, `--author-email`, `--repo-url`, `--license`, `--license-holder`, `--license-year` | What the project says about who made it. Nothing is invented. |
31
- | `--dry-run` | `make create` plans and prints the identity without changing a file. The copy and its commit stand, and the verdict names the real `make create` to run. |
32
- | `--no-create` | Write the template and commit it, then stop. The verdict names the `make create` to run, after writing `.env.local` yourself, for instance. |
33
- | `--no-git` | Make no repository and no commit. |
34
- | `--quiet` | Write `make create`'s output to a log and print its path, so the summary stays in view. |
35
- | `--template <name>` | The template to write. `webapp-js` is the default and the only one. |
26
+ | Option | What it does |
27
+ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
28
+ | `--method <m>` | The method the app runs. Required unless `--no-create`. |
29
+ | `--name`, `--title`, `--description` | The project's package name, title and description, which `npm run create` otherwise derives from the method. |
30
+ | `--pipe`, `--method-name`, `--label` | The pipe to run, the method's directory name and its tab label, when the method does not settle them. |
31
+ | `--author-name`, `--author-email`, `--repo-url`, `--license`, `--license-holder`, `--license-year` | What the project says about who made it. Nothing is invented. |
32
+ | `--dry-run` | `npm run create` plans and prints the identity without changing a file. The copy and its commit stand, and the verdict names the real `npm run create` to run. |
33
+ | `--no-create` | Write the template and commit it, then stop. The verdict names the `npm install` and `npm run create` to run, after writing `.env.local` yourself, for instance. |
34
+ | `--no-git` | Make no repository and no commit. |
35
+ | `--quiet` | Write the output of `npm install` and `npm run create` to a log and print its path, so the summary stays in view. |
36
+ | `--template <name>` | The template to write. `webapp-js` is the default and the only one. |
36
37
 
37
- Each create option is named after the `make create` variable it sets (`--author-email` is `AUTHOR_EMAIL`), and reaches `make create` as one argument, so no value needs quoting beyond what your shell needs. A blank value is not passed on. Nothing is ever asked: a missing value is a refusal naming the option.
38
+ Each create option is named after the variable of the family's create contract it sets (`--author-email` is `AUTHOR_EMAIL`), which is also the flag of the template's own `npm run create`, and reaches it as one argument, `--method` as the first, so no value needs quoting beyond what your shell needs. A blank value is not passed on. Nothing is ever asked: a missing value is a refusal naming the option.
38
39
 
39
40
  ## Git
40
41
 
@@ -54,27 +55,27 @@ A path the enclosing repository ignores, such as a `tmp/` its `.gitignore` lists
54
55
 
55
56
  A commit needs a git identity, and a missing one is refused before anything is written. When git shows none outside a repository, the initializer asks again inside a throwaway repository at the destination, which it removes before going on, so an identity given only by an `includeIf "gitdir:…"` section is found. At a path another repository ignores, it always asks inside that throwaway repository, since an identity set in the enclosing repository's own configuration does not reach the new one.
56
57
 
57
- The pristine commit reads `Start from Pipelex/pipelex-sdk/method-apps/webapp-js <version> (<sha>)`, so `make create`'s changes are a diff you can read before committing them. `make create` itself commits nothing.
58
+ The pristine commit reads `Start from Pipelex/pipelex-sdk/method-apps/webapp-js <version> (<sha>)`, so `npm run create`'s changes are a diff you can read before committing them. `npm run create` itself commits nothing.
58
59
 
59
60
  ## What it prints
60
61
 
61
62
  A run ends with one verdict line, the last line it prints on standard output, whose first word is stable:
62
63
 
63
- | Verdict | Meaning |
64
- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
65
- | `created <dir>; next: cd <dir> && make serve` | The copy, the git outcome, and a green `make create` |
66
- | `copied <dir>; next: …` | With `--no-create` or `--dry-run`: the copy and the git outcome, and the `make create` to run next |
67
- | `refused: not-empty` | The destination holds something other than a lone `.git`; nothing was written |
68
- | `refused: unusable-destination` | The destination cannot be read: a file stands where a directory of its path should be, or a directory on it cannot be read; nothing was written |
69
- | `refused: repository-has-history`, `refused: repository-has-staged-files`, `refused: inside-template-checkout` | The git reading above; nothing was written |
70
- | `refused: no-method`, `no-key`, `missing-tool`, `node-too-old`, `no-git-identity`, `unknown-option`, `unknown-template`, `other-ecosystem`, `usage` | The preflight; nothing was written, and the line names the fix |
71
- | `failed: write` | The copy failed or was interrupted, and everything the initializer had created was removed; nothing else was touched |
72
- | `failed: commit` | Git refused the pristine commit, for instance through a global hook; the copy stands, and the line says how to commit it and what to run next |
73
- | `failed: create` | `make create` did not succeed; the copy and its commit stand, and `make create`'s own message says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot |
74
-
75
- Before the verdict come the warnings `make create` printed, each once, and the git outcome. The exit code is 0 for `created` and `copied` and 1 otherwise, but the verdict is the line to read.
76
-
77
- Everything the initializer prints goes to standard output, `make create`'s output included when `--quiet` is not given. Under `npm create`, a run that exits 1 is followed by npm's own `npm error` lines on standard error, so read the verdict from standard output rather than from the last line of everything printed. `npm create --loglevel=silent @pipelex/method-app@latest …` removes npm's lines and leaves the initializer's alone.
64
+ | Verdict | Meaning |
65
+ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
66
+ | ``created <dir>; next: `cd <dir>`, then `npm run serve` `` | The copy, the git outcome, and a green `npm run create` |
67
+ | `copied <dir>; next: …` | With `--no-create` or `--dry-run`: the copy and the git outcome, and the `npm run create` to run next, after `npm install` when it has not run |
68
+ | `refused: not-empty` | The destination holds something other than a lone `.git`; nothing was written |
69
+ | `refused: unusable-destination` | The destination cannot be read: a file stands where a directory of its path should be, or a directory on it cannot be read; nothing was written |
70
+ | `refused: repository-has-history`, `refused: repository-has-staged-files`, `refused: inside-template-checkout` | The git reading above; nothing was written |
71
+ | `refused: no-method`, `no-key`, `missing-tool`, `node-too-old`, `no-git-identity`, `unknown-option`, `unknown-template`, `other-ecosystem`, `usage` | The preflight; nothing was written, and the line names the fix |
72
+ | `failed: write` | The copy failed or was interrupted, and everything the initializer had created was removed; nothing else was touched |
73
+ | `failed: commit` | Git refused the pristine commit, for instance through a global hook; the copy stands, and the line says how to commit it and what to run next |
74
+ | `failed: create` | `npm install` or `npm run create` did not succeed; the copy and its commit stand. After a failed install, the line names both commands to run once npm's message is dealt with; after a failed `npm run create`, its own message says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot |
75
+
76
+ Before the verdict come the warnings `npm run create` printed, each once, and the git outcome. A `next:` names its commands one after the other, each between backquotes, to run in turn: no separator reads the same in every shell, since Windows PowerShell 5.1 has no `&&` and `cmd` no `;`. Each word is quoted for the system the initializer ran on: in single quotes for a POSIX shell, and on Windows in double quotes, which PowerShell and `cmd` both read, or in PowerShell's single quotes for a word holding a `$` or a backquote. The exit code is 0 for `created` and `copied` and 1 otherwise, but the verdict is the line to read.
77
+
78
+ Everything the initializer prints goes to standard output, npm's output included when `--quiet` is not given. Under `npm create`, a run that exits 1 is followed by npm's own `npm error` lines on standard error, so read the verdict from standard output rather than from the last line of everything printed. `npm create --loglevel=silent @pipelex/method-app@latest …` removes npm's lines and leaves the initializer's alone.
78
79
 
79
80
  A Python template, such as `cli-python`, is refused with `refused: other-ecosystem`. No initializer serves the Python templates yet, so the line points at the template's README, which shows how to copy it out of a release of `Pipelex/pipelex-sdk` and run its `make create`.
80
81
 
package/lib/git.mjs CHANGED
@@ -280,7 +280,7 @@ export function commitPristine({ dest, init, paths, message, env }) {
280
280
 
281
281
  /**
282
282
  * The commands a person runs to make the pristine commit by hand, once the
283
- * copy stands, joined with `&&` for a shell. `quote` quotes one word.
283
+ * copy stands, in order. `quote` quotes one word.
284
284
  */
285
285
  export function pristineByHand({ dest, init, message, quote }) {
286
286
  const at = `git -C ${quote(dest)}`;
@@ -288,5 +288,5 @@ export function pristineByHand({ dest, init, message, quote }) {
288
288
  ...(init ? [`${at} init -q`, `${at} symbolic-ref HEAD refs/heads/main`] : []),
289
289
  `${at} add --force -A`,
290
290
  `${at} commit -m ${quote(message)}`,
291
- ].join(" && ");
291
+ ];
292
292
  }
package/lib/main.mjs CHANGED
@@ -1,27 +1,29 @@
1
1
  /**
2
2
  * `create-method-app`: write a template of the family into a directory, make
3
3
  * the pristine commit where nothing of the user's is at stake, and run the
4
- * copy's own `make create`.
4
+ * copy's own gesture: `npm install`, then `npm run create`. Nothing it runs
5
+ * needs `make` or a POSIX shell, so it runs on Windows as elsewhere.
5
6
  *
6
7
  * The order is the safety story:
7
8
  *
8
9
  * 1. **A preflight that leaves nothing behind.** The arguments and the
9
- * template; Node at or above the template's `engines` floor; `make`, and
10
- * `git` unless `--no-git`; `--method` and `PIPELEX_API_KEY` unless
11
- * `--no-create`, the key tested for presence and never printed; the
12
- * destination rule; git's reading of the destination, and an identity when
13
- * a commit will be made. It writes nothing but a missing destination inside
14
- * another repository's work tree, made so that git reads it as the
15
- * directory it will be, and the throwaway repository in which a new
16
- * repository's identity is read when none shows outside one, or always
17
- * under a path another repository ignores, and removes each before going
18
- * on. Each failure is a `refused:` verdict naming the fix.
10
+ * template; Node at or above the template's `engines` floor; npm unless
11
+ * `--no-create`, and `git` unless `--no-git`; `--method` and
12
+ * `PIPELEX_API_KEY` unless `--no-create`, the key tested for presence and
13
+ * never printed; the destination rule; git's reading of the destination,
14
+ * and an identity when a commit will be made. It writes nothing but a
15
+ * missing destination inside another repository's work tree, made so that
16
+ * git reads it as the directory it will be, and the throwaway repository
17
+ * in which a new repository's identity is read when none shows outside
18
+ * one, or always under a path another repository ignores, and removes
19
+ * each before going on. Each failure is a `refused:` verdict naming the fix.
19
20
  * 2. **The write**, exclusive, removing what it created when it cannot finish.
20
21
  * 3. **Git**: a new repository on `main` outside any work tree or where the
21
22
  * enclosing repository ignores the destination, then the pristine commit;
22
23
  * the commit alone at the root of a repository with no commit yet; nothing
23
24
  * inside another repository's work tree, or with `--no-git`.
24
- * 4. **`make create`**, unless `--no-create`, streamed or logged.
25
+ * 4. **`npm install`, then `npm run create`**, unless `--no-create`, streamed
26
+ * or logged.
25
27
  * 5. **The report**: the gesture's warnings, the git outcome, and the verdict
26
28
  * line, last.
27
29
  *
@@ -45,10 +47,18 @@ import {
45
47
  readGit,
46
48
  templateOrigin,
47
49
  } from "./git.mjs";
48
- import { extractWarnings, makeArgs, runMake } from "./make.mjs";
50
+ import {
51
+ createWords,
52
+ extractWarnings,
53
+ npmInvocation,
54
+ npmProblem,
55
+ onPath,
56
+ runCreate,
57
+ stampInstall,
58
+ } from "./npm.mjs";
49
59
  import { decodePack, PackError } from "./pack.mjs";
50
60
  import { loadTable, PACKAGE_ROOT } from "./templates.mjs";
51
- import { EXIT_OK, shellQuote, Verdict } from "./verdict.mjs";
61
+ import { EXIT_OK, inTurn, shellQuote, Verdict } from "./verdict.mjs";
52
62
  import { DestinationChanged, Interrupted, writeTree } from "./write.mjs";
53
63
 
54
64
  export const PACKS_DIR = path.join(PACKAGE_ROOT, "templates");
@@ -58,21 +68,6 @@ export function ownVersion() {
58
68
  return JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf8")).version;
59
69
  }
60
70
 
61
- /** Whether an executable named `tool` is on the `PATH` `env` carries. */
62
- export function onPath(tool, env) {
63
- for (const dir of (env.PATH ?? "").split(path.delimiter)) {
64
- if (dir === "") continue;
65
- const candidate = path.join(dir, tool);
66
- try {
67
- fs.accessSync(candidate, fs.constants.X_OK);
68
- if (fs.statSync(candidate).isFile()) return true;
69
- } catch {
70
- // not here
71
- }
72
- }
73
- return false;
74
- }
75
-
76
71
  /** Compare two `X.Y.Z` versions. */
77
72
  export function compareVersions(a, b) {
78
73
  const pa = a.split(".").map(Number);
@@ -121,9 +116,11 @@ function nodeFloor(pack) {
121
116
 
122
117
  /** Everything a run reads from outside, so a test can substitute each. */
123
118
  export function resolveDeps(deps = {}) {
119
+ const env = deps.env ?? process.env;
124
120
  return {
125
121
  cwd: deps.cwd ?? process.cwd(),
126
- env: deps.env ?? process.env,
122
+ env,
123
+ npm: deps.npm ?? npmInvocation(env),
127
124
  out: deps.out ?? process.stdout,
128
125
  packDir: deps.packDir ?? PACKS_DIR,
129
126
  nodeVersion: deps.nodeVersion ?? process.versions.node,
@@ -160,7 +157,7 @@ function chooseTemplate(args, table) {
160
157
  if (!takes.has(variable)) {
161
158
  throw Verdict.refused(
162
159
  "unknown-option",
163
- `${flag} is not an option of ${template}'s make create`,
160
+ `${flag} is not an option of ${template}'s npm run create`,
164
161
  );
165
162
  }
166
163
  }
@@ -248,13 +245,23 @@ function planGit(args, dest, found, env) {
248
245
  return plan;
249
246
  }
250
247
 
251
- /** The make create line to run next, without --dry-run, quoted for a shell. */
252
- function nextCreate(table, template, values) {
248
+ /**
249
+ * The commands to run next, without --dry-run, quoted for this system's shell
250
+ * and in order: `cd` into the copy, then `npm run create`, after the
251
+ * `npm install` it needs unless `installed`.
252
+ */
253
+ function nextCreate(dest, table, template, values, { installed = false } = {}) {
253
254
  const forwarded = { ...values };
254
255
  delete forwarded.DRY_RUN;
255
- const words = makeArgs(table.variablesOf(template), forwarded, table.switches).map(shellQuote);
256
- if (values[table.required] === undefined) words.splice(1, 0, `${table.required}=<method>`);
257
- return `make ${words.join(" ")}`;
256
+ const words = createWords(
257
+ table.variablesOf(template),
258
+ forwarded,
259
+ table.switches,
260
+ table.required,
261
+ ).map((word) => shellQuote(word));
262
+ if (values[table.required] === undefined) words.unshift("<method>");
263
+ const create = `npm run create -- ${words.join(" ")}`;
264
+ return inTurn([`cd ${shellQuote(dest)}`, ...(installed ? [] : ["npm install"]), create]);
258
265
  }
259
266
 
260
267
  async function create(argv, d, say, state) {
@@ -277,13 +284,15 @@ async function create(argv, d, say, state) {
277
284
  `${template} needs Node ${floor} or later, and this is Node ${d.nodeVersion}: switch to a newer Node, then run this again`,
278
285
  );
279
286
  }
280
- const missing = ["make", ...(args.noGit ? [] : ["git"])].filter((tool) => !onPath(tool, d.env));
281
- if (missing.length > 0) {
282
- throw Verdict.refused(
283
- "missing-tool",
284
- `${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not on the PATH: install ${missing.length > 1 ? "them" : "it"}${missing.includes("git") ? ", or pass --no-git to make no repository" : ""}`,
285
- );
287
+ const missing = [];
288
+ if (!args.noCreate) {
289
+ const npmMissing = npmProblem(d.npm, d.env);
290
+ if (npmMissing !== null) missing.push(npmMissing);
291
+ }
292
+ if (!args.noGit && !onPath("git", d.env)) {
293
+ missing.push("git is not on the PATH: install it, or pass --no-git to make no repository");
286
294
  }
295
+ if (missing.length > 0) throw Verdict.refused("missing-tool", missing.join("; "));
287
296
  if (!args.noCreate && args.values[table.required] === undefined) {
288
297
  throw Verdict.refused(
289
298
  "no-method",
@@ -293,7 +302,7 @@ async function create(argv, d, say, state) {
293
302
  if (!args.noCreate && !d.env.PIPELEX_API_KEY?.trim()) {
294
303
  throw Verdict.refused(
295
304
  "no-key",
296
- "PIPELEX_API_KEY is not set: export it in this shell for make create, which never copies it into the project, or pass --no-create and write .env.local yourself before running make create",
305
+ "PIPELEX_API_KEY is not set: export it in this shell for npm run create, which never copies it into the project, or pass --no-create and write .env.local yourself before running npm run create",
297
306
  );
298
307
  }
299
308
 
@@ -374,39 +383,38 @@ async function create(argv, d, say, state) {
374
383
  for (const line of error.message.split("\n")) say(line);
375
384
  throw Verdict.failed(
376
385
  "commit",
377
- `git refused the pristine commit (above). The copy stands in ${dest}: commit it with ${pristineByHand({ dest, init: git.init, message, quote: shellQuote })}, then run cd ${shellQuote(dest)} && ${nextCreate(table, template, values)}`,
386
+ `git refused the pristine commit (above). The copy stands in ${dest}: commit it with ${inTurn(pristineByHand({ dest, init: git.init, message, quote: shellQuote }))}, then run ${nextCreate(dest, table, template, values)}`,
378
387
  );
379
388
  }
380
389
  }
381
390
 
382
- const where = shellQuote(dest);
383
391
  if (args.noCreate) {
384
392
  say(gitLine);
385
- return { line: `copied ${dest}; next: cd ${where} && ${nextCreate(table, template, values)}` };
393
+ return { line: `copied ${dest}; next: ${nextCreate(dest, table, template, values)}` };
386
394
  }
387
395
 
388
- // ── make create ──
396
+ // ── npm install, then npm run create ──
389
397
  state.phase = "create";
390
398
  const stands = git.commit ? "The copy and its commit stand" : "The copy stands";
391
399
  if (d.signal?.aborted) {
392
400
  say(gitLine);
393
401
  throw Verdict.failed(
394
402
  "create",
395
- `${d.signal.reason ?? "a signal"} interrupted the run before make create started. ${stands} in ${dest}; run cd ${where} && ${nextCreate(table, template, values)}`,
403
+ `${d.signal.reason ?? "a signal"} interrupted the run before npm install started. ${stands} in ${dest}; run ${nextCreate(dest, table, template, values)}`,
396
404
  );
397
405
  }
398
406
  let logFile;
399
407
  if (args.quiet) {
400
- logFile = path.join(
401
- fs.mkdtempSync(path.join(d.tmpDir, "create-method-app-")),
402
- "make-create.log",
408
+ logFile = path.join(fs.mkdtempSync(path.join(d.tmpDir, "create-method-app-")), "create.log");
409
+ say(
410
+ `create-method-app: running npm install and npm run create in ${dest}; their output goes to ${logFile}`,
403
411
  );
404
- say(`create-method-app: running make create in ${dest}; its output goes to ${logFile}`);
405
412
  } else {
406
- say(`create-method-app: running make create in ${dest}\n`);
413
+ say(`create-method-app: running npm install and npm run create in ${dest}\n`);
407
414
  }
408
- const argvMake = makeArgs(table.variablesOf(template), values, table.switches);
409
- const result = await runMake(argvMake, {
415
+ const words = createWords(table.variablesOf(template), values, table.switches, table.required);
416
+ const result = await runCreate(words, {
417
+ npm: d.npm,
410
418
  cwd: dest,
411
419
  env: d.env,
412
420
  out: d.out,
@@ -416,30 +424,54 @@ async function create(argv, d, say, state) {
416
424
 
417
425
  const warnings = extractWarnings(result.output);
418
426
  say("");
419
- say(warnings.length > 0 ? "warnings from make create:" : "warnings from make create: none");
427
+ say(warnings.length > 0 ? "warnings from npm run create:" : "warnings from npm run create: none");
420
428
  for (const warning of warnings) say(` ${warning}`);
421
429
  say(gitLine);
430
+ if (result.error?.stuck) {
431
+ throw Verdict.failed(
432
+ "create",
433
+ `${d.signal?.reason ?? "a signal"} interrupted npm ${result.step}, and ${result.error.message}: stop it yourself. ${stands} in ${dest}.`,
434
+ );
435
+ }
422
436
  if (result.error !== null) {
423
437
  throw Verdict.failed(
424
438
  "create",
425
- `make could not be run: ${result.error.message}. ${stands} in ${dest}.`,
439
+ `npm could not be run: ${result.error.message}. ${stands} in ${dest}.`,
426
440
  );
427
441
  }
442
+ const interrupted = d.signal?.aborted ? (d.signal.reason ?? "a signal") : null;
428
443
  if (result.status !== 0) {
429
- const how =
430
- result.status === null ? `was stopped by ${result.signal}` : `exited ${result.status}`;
444
+ // Elsewhere a stopped step ends by a signal; on Windows, which has none,
445
+ // it ends with a status, and the interruption is what stopped it.
446
+ let how = `exited ${result.status}`;
447
+ if (result.status === null) how = `was stopped by ${result.signal}`;
448
+ else if (interrupted !== null) how = `was stopped by ${interrupted}`;
431
449
  const said = args.quiet ? `the end of its log, ${logFile},` : "its own message above";
450
+ if (result.step === "install") {
451
+ throw Verdict.failed(
452
+ "create",
453
+ `npm install ${how}, so npm run create did not start. ${stands} in ${dest}, and ${said} says why; once that is fixed, run ${nextCreate(dest, table, template, values)}`,
454
+ );
455
+ }
456
+ throw Verdict.failed(
457
+ "create",
458
+ `npm run create ${how}. ${stands} in ${dest}, and ${said} says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot.`,
459
+ );
460
+ }
461
+ if (result.step === "install") {
462
+ // The install succeeded, and an interruption came before the gesture.
432
463
  throw Verdict.failed(
433
464
  "create",
434
- `make create ${how}. ${stands} in ${dest}, and ${said} says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot.`,
465
+ `${interrupted ?? "a signal"} interrupted the run before npm run create started. ${stands} in ${dest}, its dependencies installed; run ${nextCreate(dest, table, template, values, { installed: true })}`,
435
466
  );
436
467
  }
437
468
  if (values.DRY_RUN) {
438
469
  return {
439
- line: `copied ${dest} (make create --dry-run changed nothing); next: cd ${where} && ${nextCreate(table, template, values)}`,
470
+ line: `copied ${dest} (npm run create --dry-run changed nothing); next: ${nextCreate(dest, table, template, values, { installed: true })}`,
440
471
  };
441
472
  }
442
- return { line: `created ${dest}; next: cd ${where} && make serve` };
473
+ stampInstall(dest);
474
+ return { line: `created ${dest}; next: ${inTurn([`cd ${shellQuote(dest)}`, "npm run serve"])}` };
443
475
  }
444
476
 
445
477
  /**
package/lib/npm.mjs ADDED
@@ -0,0 +1,286 @@
1
+ /**
2
+ * The copy's own gesture, run with npm: `npm install`, since a fresh copy has
3
+ * no `node_modules` and the gesture's script needs its dependencies, then
4
+ * `npm run create -- <method> [--flag value …]`. Both run with an argument
5
+ * vector and no shell of the initializer's, so no value ever needs quoting
6
+ * here: each reaches npm as one argument, and npm hands it to the script.
7
+ * Nothing here needs `make`, so the same run works on Windows, where npm is a
8
+ * `.cmd` file that Node will not spawn without a shell: there npm is run as
9
+ * its own script, `npm-cli.js`, with this Node, as the template's
10
+ * `scripts/lib/npm.mts` does.
11
+ *
12
+ * The output of both steps is streamed, or, with `--quiet`, written to one log
13
+ * alone. Either way it is read for the gesture's warnings, which open with
14
+ * `! ` (the gesture's own) or `warning: ` (the bootstrap's), and are printed
15
+ * again at the end because `npm run all` fills the tail. The gesture runs its
16
+ * bootstrap twice, a dry run then the write, so each warning is kept once.
17
+ */
18
+
19
+ import { spawn } from "node:child_process";
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import process from "node:process";
23
+
24
+ import { gitEnv } from "./git.mjs";
25
+ import { flagOf } from "./templates.mjs";
26
+
27
+ /** npm's own script, which npm names in `npm_execpath` for whatever it runs. */
28
+ const NPM_SCRIPT = "npm-cli.js";
29
+
30
+ /**
31
+ * How to run npm: a command and the arguments that come before npm's own.
32
+ * Under `npm create`, npm names its own script in `npm_execpath`, and it is run
33
+ * with this Node, so the gesture runs under the npm that ran the initializer.
34
+ * Another package manager names its own script there, which is not npm's and
35
+ * is passed over. Elsewhere it is `npm` on the `PATH`, except on Windows, where
36
+ * `npm` is `npm.cmd`: there npm's script is the one the Node installer puts
37
+ * beside `node.exe`.
38
+ */
39
+ export function npmInvocation(env, platform = process.platform, execPath = process.execPath) {
40
+ const named = env.npm_execpath;
41
+ const pathOf = platform === "win32" ? path.win32 : path.posix;
42
+ if (named !== undefined && pathOf.basename(named) === NPM_SCRIPT) {
43
+ return { command: execPath, args: [named] };
44
+ }
45
+ if (platform !== "win32") return { command: "npm", args: [] };
46
+ return {
47
+ command: execPath,
48
+ args: [path.win32.join(path.win32.dirname(execPath), "node_modules", "npm", "bin", NPM_SCRIPT)],
49
+ };
50
+ }
51
+
52
+ /** The value of `name` in `env`, whose names Windows reads without regard to case. */
53
+ export function envValue(env, name, platform = process.platform) {
54
+ if (platform !== "win32") return env[name];
55
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
56
+ return key === undefined ? undefined : env[key];
57
+ }
58
+
59
+ /**
60
+ * Whether an executable named `tool` is on the `PATH` `env` carries. On
61
+ * Windows a command is a file named `tool` plus one of the extensions
62
+ * `PATHEXT` lists, such as `git.exe`.
63
+ */
64
+ export function onPath(tool, env, platform = process.platform) {
65
+ const pathOf = platform === "win32" ? path.win32 : path.posix;
66
+ const names =
67
+ platform === "win32"
68
+ ? (envValue(env, "PATHEXT", platform) ?? ".COM;.EXE;.BAT;.CMD")
69
+ .split(";")
70
+ .filter((ext) => ext !== "")
71
+ .map((ext) => `${tool}${ext}`)
72
+ : [tool];
73
+ for (const dir of (envValue(env, "PATH", platform) ?? "").split(pathOf.delimiter)) {
74
+ if (dir === "") continue;
75
+ for (const name of names) {
76
+ const candidate = pathOf.join(dir, name);
77
+ try {
78
+ fs.accessSync(candidate, fs.constants.X_OK);
79
+ if (fs.statSync(candidate).isFile()) return true;
80
+ } catch {
81
+ // not here
82
+ }
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * Why npm cannot be run as `invocation` says, or null: `npm` not on the
90
+ * `PATH`, or npm's script missing where it is named.
91
+ */
92
+ export function npmProblem(invocation, env, platform = process.platform) {
93
+ if (invocation.args.length === 0) {
94
+ return onPath(invocation.command, env, platform)
95
+ ? null
96
+ : "npm is not on the PATH: install Node.js with its npm, or pass --no-create to write the template alone";
97
+ }
98
+ const script = invocation.args[0];
99
+ return fs.existsSync(script)
100
+ ? null
101
+ : `npm is not where ${script} names it: reinstall Node.js with its npm, or pass --no-create to write the template alone`;
102
+ }
103
+
104
+ /**
105
+ * The words `npm run create` takes after `--`: the method, then each value
106
+ * given, in the contract's order, as its flag and the value as typed, and a
107
+ * switch given as its flag alone. A template's `make create` forwards each
108
+ * variable the same way, which the family's create contract holds it to.
109
+ */
110
+ export function createWords(order, values, switches, required) {
111
+ const words = values[required] === undefined ? [] : [values[required]];
112
+ for (const variable of order) {
113
+ if (variable === required) continue;
114
+ if (switches.has(variable)) {
115
+ if (values[variable]) words.push(flagOf(variable));
116
+ } else if (values[variable] !== undefined) {
117
+ words.push(flagOf(variable), values[variable]);
118
+ }
119
+ }
120
+ return words;
121
+ }
122
+
123
+ /**
124
+ * The stamp of the copy's last install, which its Makefile's install guard
125
+ * reads: `make install` leaves it, and `make create` leaves it after its
126
+ * install and again after the gesture, whose lock re-sync rewrites
127
+ * `package-lock.json` and changes nothing `node_modules` holds. Left the same
128
+ * way here, a project made by the initializer does not reinstall on its first
129
+ * `make` check what is already installed.
130
+ */
131
+ export const INSTALL_STAMP = path.join("node_modules", ".lock-installed");
132
+
133
+ /**
134
+ * Leave the stamp of an install in `dir`, now, when it holds `node_modules`.
135
+ * The stamp only spares a reinstall, so a stamp that cannot be written is let
136
+ * go: the guard then reads npm's own record of the install instead.
137
+ */
138
+ export function stampInstall(dir) {
139
+ if (!fs.existsSync(path.join(dir, "node_modules"))) return;
140
+ const stamp = path.join(dir, INSTALL_STAMP);
141
+ try {
142
+ fs.closeSync(fs.openSync(stamp, "a"));
143
+ const now = new Date();
144
+ fs.utimesSync(stamp, now, now);
145
+ } catch {
146
+ // best effort, as above
147
+ }
148
+ }
149
+
150
+ /** The warnings in a run's output, each once, in the order they first appeared. */
151
+ export function extractWarnings(output) {
152
+ const seen = new Set();
153
+ for (const line of output.split(/\r?\n/)) {
154
+ if ((line.startsWith("! ") || line.startsWith("warning: ")) && !seen.has(line)) seen.add(line);
155
+ }
156
+ return [...seen];
157
+ }
158
+
159
+ /** How long a step has to end once it is stopped, before the run stops waiting for it. */
160
+ export const STOP_GRACE_MS = 10_000;
161
+
162
+ /**
163
+ * Stop a child and everything it started. Elsewhere npm passes the signal on
164
+ * to the script it runs; on Windows there is no signal to pass, so the whole
165
+ * tree is ended with `taskkill`, which Windows ships. A `taskkill` that cannot
166
+ * run, or that ends with a failure, as when it is denied access, falls back
167
+ * to ending npm alone, which is all Node can do there.
168
+ */
169
+ function stop(child, platform, taskkill) {
170
+ if (platform !== "win32") {
171
+ child.kill("SIGTERM");
172
+ return;
173
+ }
174
+ if (child.pid === undefined) return;
175
+ const killer = spawn(taskkill, ["/pid", String(child.pid), "/T", "/F"], {
176
+ stdio: "ignore",
177
+ windowsHide: true,
178
+ });
179
+ let fellBack = false;
180
+ const fallBack = () => {
181
+ if (fellBack) return;
182
+ fellBack = true;
183
+ child.kill();
184
+ };
185
+ killer.on("error", fallBack);
186
+ killer.on("close", (code) => {
187
+ if (code !== 0) fallBack();
188
+ });
189
+ }
190
+
191
+ /** Run one npm command, sending its output to `take`. Resolves `{ status, signal, error }`. */
192
+ function runOne(invocation, args, { cwd, env, take, signal, platform, taskkill, graceMs }) {
193
+ return new Promise((resolve) => {
194
+ const child = spawn(invocation.command, [...invocation.args, ...args], {
195
+ cwd,
196
+ env,
197
+ stdio: ["ignore", "pipe", "pipe"],
198
+ windowsHide: true,
199
+ });
200
+ child.stdout.on("data", take);
201
+ child.stderr.on("data", take);
202
+ let failed = null;
203
+ let settled = false;
204
+ let bound;
205
+ // Stopped, the step gets a bounded time to end: a run whose step would
206
+ // not stop ends anyway, saying the step may still run, rather than wait
207
+ // for it as long as it takes.
208
+ const onAbort = () => {
209
+ stop(child, platform, taskkill);
210
+ bound = setTimeout(() => {
211
+ failed = new Error(
212
+ `npm (pid ${child.pid}) did not stop within ${Math.round(graceMs / 1000)}s of the interruption, and may still be running`,
213
+ );
214
+ failed.stuck = true;
215
+ // Let go of it, so the run can end while it runs on.
216
+ child.stdout.destroy();
217
+ child.stderr.destroy();
218
+ child.unref();
219
+ finish(null, null);
220
+ }, graceMs);
221
+ bound.unref?.();
222
+ };
223
+ signal?.addEventListener("abort", onAbort, { once: true });
224
+ const finish = (status, killedBy) => {
225
+ if (settled) return;
226
+ settled = true;
227
+ clearTimeout(bound);
228
+ signal?.removeEventListener("abort", onAbort);
229
+ resolve({ status, signal: killedBy, error: failed });
230
+ };
231
+ child.on("error", (error) => {
232
+ failed = error;
233
+ // A process that never started emits no close of its own.
234
+ if (child.pid === undefined) finish(null, null);
235
+ });
236
+ child.on("close", finish);
237
+ });
238
+ }
239
+
240
+ /**
241
+ * Run `npm install`, then, if it succeeded and nothing interrupted the run,
242
+ * `npm run create -- <words>`, in `cwd`. Resolves
243
+ * `{ step, status, signal, output, error }`, `step` being the one that ended
244
+ * the run, `install` or `create`; never rejects. `out` receives the stream
245
+ * unless `logFile` is given. An abort of `signal` stops the step running.
246
+ */
247
+ export async function runCreate(
248
+ words,
249
+ {
250
+ npm,
251
+ cwd,
252
+ env,
253
+ out,
254
+ logFile,
255
+ signal,
256
+ platform = process.platform,
257
+ taskkill = "taskkill",
258
+ graceMs = STOP_GRACE_MS,
259
+ },
260
+ ) {
261
+ const log = logFile ? fs.openSync(logFile, "w", 0o600) : null;
262
+ const chunks = [];
263
+ const take = (chunk) => {
264
+ chunks.push(chunk);
265
+ if (log !== null) fs.writeSync(log, chunk);
266
+ else out.write(chunk);
267
+ };
268
+ // Without the variables that point git elsewhere, which the initializer
269
+ // drops for its own git calls too: the copy's install wires its hooks with
270
+ // `git config`, which would otherwise write into the repository a caller's
271
+ // `GIT_DIR` names rather than the copy's.
272
+ const options = { cwd, env: gitEnv(env), take, signal, platform, taskkill, graceMs };
273
+ let step = "install";
274
+ let result;
275
+ try {
276
+ result = await runOne(npm, ["install"], options);
277
+ if (result.error === null && result.status === 0) stampInstall(cwd);
278
+ if (result.error === null && result.status === 0 && !signal?.aborted) {
279
+ step = "create";
280
+ result = await runOne(npm, ["run", "create", "--", ...words], options);
281
+ }
282
+ } finally {
283
+ if (log !== null) fs.closeSync(log);
284
+ }
285
+ return { step, ...result, output: Buffer.concat(chunks).toString("utf8") };
286
+ }
package/lib/verdict.mjs CHANGED
@@ -6,13 +6,14 @@
6
6
  * `npm error` lines on standard error after a run that exits 1. The exit code
7
7
  * is presentation: 0 for `created` and `copied`, 1 otherwise.
8
8
  *
9
- * created <dir> the copy, the git outcome, and a green make create
9
+ * created <dir> the copy, the git outcome, and a green npm run create
10
10
  * copied <dir> --no-create or --dry-run: the copy and the git outcome only
11
11
  * refused: <why> the preflight stopped, and nothing was written
12
12
  * failed: write the copy failed or was interrupted, and what it created was removed
13
13
  * failed: commit git refused the pristine commit; the copy stands
14
- * failed: create make create did not succeed; the copy and the commit stand, and its
15
- * own message says what to run next
14
+ * failed: create npm install or npm run create did not succeed; the copy and the
15
+ * commit stand, and npm's or the gesture's own message says what to
16
+ * run next
16
17
  */
17
18
 
18
19
  export const EXIT_OK = 0;
@@ -42,7 +43,33 @@ export class Verdict extends Error {
42
43
  }
43
44
  }
44
45
 
45
- /** Quote a word for a line a person may paste into a shell. */
46
- export function shellQuote(word) {
47
- return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
46
+ import process from "node:process";
47
+
48
+ /**
49
+ * Quote a word for a line a person may paste into this system's shell. A POSIX
50
+ * shell takes single quotes. Windows has two shells and no quoting they share
51
+ * entirely: double quotes are quotes in both PowerShell and `cmd`, where single
52
+ * quotes are not quotes to `cmd`, so a word is double-quoted there, unless it
53
+ * holds a `$` or a backquote, which PowerShell would expand inside double
54
+ * quotes, and then it is single-quoted as PowerShell reads it. A word left bare
55
+ * on Windows holds nothing either shell reads specially: no `@`, which
56
+ * PowerShell splats, no `,`, which it makes a list, and no `%`, though `cmd`
57
+ * expands a `%NAME%` even between quotes.
58
+ */
59
+ export function shellQuote(word, platform = process.platform) {
60
+ if (platform !== "win32") {
61
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
62
+ }
63
+ if (/^[\w+=:./\\-]+$/.test(word)) return word;
64
+ if (/[$`]/.test(word)) return `'${word.replaceAll("'", "''")}'`;
65
+ return `"${word.replaceAll('"', '""')}"`;
66
+ }
67
+
68
+ /**
69
+ * Commands a person runs one after the other, each in backquotes, as npm names
70
+ * a command: no separator between two commands reads the same in every shell,
71
+ * since Windows PowerShell 5.1 has no `&&` and `cmd` no `;`.
72
+ */
73
+ export function inTurn(commands) {
74
+ return commands.map((command) => `\`${command}\``).join(", then ");
48
75
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pipelex/create-method-app",
3
- "version": "0.71.0",
3
+ "version": "0.71.1",
4
4
  "description": "Start a Pipelex method app: npm create @pipelex/method-app@latest my-app -- --method <bundle | mt_… | address>",
5
5
  "keywords": [
6
6
  "pipelex",
Binary file
package/lib/make.mjs DELETED
@@ -1,105 +0,0 @@
1
- /**
2
- * The copy's `make create`, run with an argument vector and no shell, so no
3
- * value ever needs quoting: each variable reaches make as one `NAME=value`
4
- * word, which the template's Makefile reads with `$(value …)` and hands to its
5
- * gesture exactly as typed.
6
- *
7
- * The output is streamed, or, with `--quiet`, written to a log alone. Either
8
- * way it is read for the gesture's warnings, which open with `! ` (the
9
- * gesture's own) or `warning: ` (the bootstrap's), and are printed again at the
10
- * end because `make all` fills the tail. The gesture runs its bootstrap twice,
11
- * a dry run then the write, so each warning is kept once.
12
- */
13
-
14
- import { spawn } from "node:child_process";
15
- import fs from "node:fs";
16
-
17
- import { gitEnv } from "./git.mjs";
18
-
19
- /**
20
- * Variables through which an enclosing make would reach this one as if they
21
- * had been typed on its command line. The Makefile trusts only command-line
22
- * values, so none may arrive any other way.
23
- */
24
- const MAKE_CHANNELS = ["MAKEFLAGS", "MFLAGS", "MAKELEVEL", "MAKEOVERRIDES"];
25
-
26
- /**
27
- * The environment `make create` runs in: without the make channels, and
28
- * without the variables that point git elsewhere, which the initializer drops
29
- * for its own git calls too. The copy's install wires its hooks with
30
- * `git config`, which would otherwise write into the repository a caller's
31
- * `GIT_DIR` names rather than the copy's.
32
- */
33
- export function makeEnv(env) {
34
- const clean = gitEnv(env);
35
- for (const name of MAKE_CHANNELS) delete clean[name];
36
- return clean;
37
- }
38
-
39
- /** `make create`'s arguments: `create`, then `NAME=value` for each value given, in the contract's order. */
40
- export function makeArgs(order, values, switches) {
41
- const args = ["create"];
42
- for (const variable of order) {
43
- if (switches.has(variable)) {
44
- if (values[variable]) args.push(`${variable}=1`);
45
- } else if (values[variable] !== undefined) {
46
- args.push(`${variable}=${values[variable]}`);
47
- }
48
- }
49
- return args;
50
- }
51
-
52
- /** The warnings in a run's output, each once, in the order they first appeared. */
53
- export function extractWarnings(output) {
54
- const seen = new Set();
55
- for (const line of output.split(/\r?\n/)) {
56
- if ((line.startsWith("! ") || line.startsWith("warning: ")) && !seen.has(line)) seen.add(line);
57
- }
58
- return [...seen];
59
- }
60
-
61
- /**
62
- * Run `make` in `cwd`. Resolves `{ status, signal, output, error }`; never
63
- * rejects. `out` receives the stream unless `logFile` is given. An abort of
64
- * `signal` passes SIGTERM on to make.
65
- */
66
- export function runMake(args, { cwd, env, out, logFile, signal }) {
67
- return new Promise((resolve) => {
68
- const log = logFile ? fs.openSync(logFile, "w", 0o600) : null;
69
- const chunks = [];
70
- const child = spawn("make", args, {
71
- cwd,
72
- env: makeEnv(env),
73
- stdio: ["ignore", "pipe", "pipe"],
74
- });
75
- const take = (chunk) => {
76
- chunks.push(chunk);
77
- if (log !== null) fs.writeSync(log, chunk);
78
- else out.write(chunk);
79
- };
80
- child.stdout.on("data", take);
81
- child.stderr.on("data", take);
82
- const onAbort = () => child.kill("SIGTERM");
83
- signal?.addEventListener("abort", onAbort, { once: true });
84
- let failed = null;
85
- let settled = false;
86
- const finish = (status, killedBy) => {
87
- if (settled) return;
88
- settled = true;
89
- signal?.removeEventListener("abort", onAbort);
90
- if (log !== null) fs.closeSync(log);
91
- resolve({
92
- status,
93
- signal: killedBy,
94
- output: Buffer.concat(chunks).toString("utf8"),
95
- error: failed,
96
- });
97
- };
98
- child.on("error", (error) => {
99
- failed = error;
100
- // A make that never started emits no close of its own.
101
- if (child.pid === undefined) finish(null, null);
102
- });
103
- child.on("close", finish);
104
- });
105
- }