dsh-plugin-toolkit 0.20.12 → 0.20.14

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/lib/compat.mjs CHANGED
@@ -123,24 +123,29 @@ function comparator(op, version) {
123
123
  function lowerBounds(partial, inclusive) {
124
124
  const version = filled(partial);
125
125
  if (inclusive === true) return [comparator('>=', version)];
126
- if (partial.patch === null) {
127
- return [comparator('>=', full(version.major, version.minor + 1, 0))];
128
- }
126
+ // The missing component decides the next boundary: `>1` starts at 2.0.0,
127
+ // while `>1.2` starts at 1.3.0. Check the major-only case first, or the
128
+ // filled-in minor would turn `>1` into `>=1.1.0` and accept 1.2.3 — a
129
+ // version npm rejects.
129
130
  if (partial.minor === null) {
130
131
  return [comparator('>=', full(version.major + 1, 0, 0))];
131
132
  }
133
+ if (partial.patch === null) {
134
+ return [comparator('>=', full(version.major, version.minor + 1, 0))];
135
+ }
132
136
  return [comparator('>', version)];
133
137
  }
134
138
 
135
139
  function upperBounds(partial, inclusive) {
136
140
  const version = filled(partial);
137
141
  if (inclusive === true) {
138
- if (partial.patch === null) return [comparator('<', full(version.major, version.minor + 1, 0))];
142
+ // `<=1` includes all of 1.x, so its exclusive ceiling is 2.0.0, not 1.1.0.
139
143
  if (partial.minor === null) return [comparator('<', full(version.major + 1, 0, 0))];
144
+ if (partial.patch === null) return [comparator('<', full(version.major, version.minor + 1, 0))];
140
145
  return [comparator('<=', version)];
141
146
  }
142
- if (partial.patch === null) return [comparator('<', full(version.major, version.minor, 0))];
143
147
  if (partial.minor === null) return [comparator('<', full(version.major, 0, 0))];
148
+ if (partial.patch === null) return [comparator('<', full(version.major, version.minor, 0))];
144
149
  return [comparator('<', version)];
145
150
  }
146
151
 
@@ -175,7 +180,9 @@ function plainBounds(partial) {
175
180
  }
176
181
 
177
182
  function expandToken(token) {
178
- const match = /^(\^|~|>=|<=|>|<|=)?(.*)$/u.exec(token);
183
+ // `~>` is npm's older spelling of `~`; package.json files in the wild still
184
+ // use it, and npm accepts both, so the answer here has to as well.
185
+ const match = /^(~>|\^|~|>=|<=|>|<|=)?(.*)$/u.exec(token);
179
186
  if (match === null) return null;
180
187
  const operator = match[1] ?? '=';
181
188
  const body = match[2].trim();
@@ -186,7 +193,7 @@ function expandToken(token) {
186
193
  if (partial.major === null) return null;
187
194
  return caretBounds(partial);
188
195
  }
189
- if (operator === '~') {
196
+ if (operator === '~' || operator === '~>') {
190
197
  if (partial.major === null) return null;
191
198
  return tildeBounds(partial);
192
199
  }
package/lib/dev.mjs CHANGED
@@ -13,16 +13,18 @@ import path from 'node:path';
13
13
  import { spawnSync } from 'node:child_process';
14
14
 
15
15
  import { exportTarget } from './doctor.mjs';
16
+ import { expandHome, resolvePath } from './paths.mjs';
16
17
 
17
18
  const IGNORED = new Set(['node_modules', '.git', 'docs', 'test', 'tests', 'coverage', 'fixtures']);
18
19
 
19
20
  export function resolveEntry(dir, manifest) {
21
+ const root = resolvePath(dir);
20
22
  const declared = manifest?.dsh?.client?.entry;
21
23
  const exported = manifest?.exports;
22
24
  const subpath = typeof exported === 'string' ? undefined : exportTarget(exported?.['./client']);
23
25
  const candidates = [declared, subpath, 'client.js', 'lib/client.js', 'dist/client.js'].filter((value) => typeof value === 'string');
24
26
  for (const candidate of candidates) {
25
- const absolute = path.resolve(dir, candidate);
27
+ const absolute = path.resolve(root, candidate);
26
28
  if (fs.existsSync(absolute)) return absolute;
27
29
  }
28
30
  return null;
@@ -30,8 +32,8 @@ export function resolveEntry(dir, manifest) {
30
32
 
31
33
  /** Where the installed copy lives, so the host's watcher sees the change. */
32
34
  export function resolveDest(name, { dest, home = path.join(os.homedir(), '.dsh') } = {}) {
33
- if (typeof dest === 'string' && dest.length > 0) return path.resolve(dest);
34
- const profiles = path.join(home, 'profiles');
35
+ if (typeof dest === 'string' && dest.length > 0) return resolvePath(dest);
36
+ const profiles = path.join(resolvePath(home), 'profiles');
35
37
  if (fs.existsSync(profiles) === false) return null;
36
38
  for (const profile of fs.readdirSync(profiles)) {
37
39
  const candidate = path.join(profiles, profile, 'node_modules', name);
@@ -167,8 +169,9 @@ export async function readGraph({ host, timeoutMs = 3000, fetchImpl = fetch }) {
167
169
  }
168
170
 
169
171
  export function watchPlugin({ dir, onChange, debounceMs = 200, io = console }) {
172
+ const root = resolvePath(dir);
170
173
  const timers = new Map();
171
- const watcher = fs.watch(dir, { recursive: true }, (event, file) => {
174
+ const watcher = fs.watch(root, { recursive: true }, (event, file) => {
172
175
  if (typeof file !== 'string') return;
173
176
  const parts = file.split(path.sep);
174
177
  if (parts.some((part) => IGNORED.has(part)) === true) return;
@@ -179,7 +182,7 @@ export function watchPlugin({ dir, onChange, debounceMs = 200, io = console }) {
179
182
  onChange(file);
180
183
  }, debounceMs));
181
184
  });
182
- io.log(`watching ${dir}`);
185
+ io.log(`watching ${root}`);
183
186
  return () => {
184
187
  for (const timer of timers.values()) clearTimeout(timer);
185
188
  watcher.close();
@@ -201,13 +204,14 @@ export async function dev(options) {
201
204
  sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
202
205
  } = options;
203
206
 
204
- const manifestPath = path.join(dir, 'package.json');
207
+ const root = resolvePath(dir);
208
+ const manifestPath = path.join(root, 'package.json');
205
209
  if (fs.existsSync(manifestPath) === false) {
206
- io.error(`dsh-plugin dev: ${dir} has no package.json`);
210
+ io.error(`dsh-plugin dev: ${root} has no package.json`);
207
211
  return 1;
208
212
  }
209
213
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
210
- const source = entryOption === undefined ? resolveEntry(dir, manifest) : path.resolve(dir, entryOption);
214
+ const source = entryOption === undefined ? resolveEntry(root, manifest) : path.resolve(root, expandHome(entryOption));
211
215
  if (source === null) {
212
216
  io.error('dsh-plugin dev: no client entry found (dsh.client.entry, client.js, lib/client.js)');
213
217
  return 1;
@@ -217,13 +221,13 @@ export async function dev(options) {
217
221
  io.error(`dsh-plugin dev: ${manifest.name} is not installed in any profile; pass --dest`);
218
222
  return 1;
219
223
  }
220
- const relative = path.relative(dir, source);
224
+ const relative = path.relative(root, source);
221
225
  const target = path.join(destDir, relative);
222
226
  io.log(`${manifest.name}: ${source} -> ${target}`);
223
227
 
224
228
  const sync = async (reason) => {
225
229
  if (buildCommand !== undefined) {
226
- const built = build({ command: buildCommand, cwd: dir, io });
230
+ const built = build({ command: buildCommand, cwd: root, io });
227
231
  if (built.ok === false) {
228
232
  io.error(`build failed (exit ${built.status}); nothing copied`);
229
233
  return { ok: false };
@@ -269,7 +273,7 @@ export async function dev(options) {
269
273
  stopping = true;
270
274
  };
271
275
  process.once('SIGINT', stop);
272
- const close = watchPlugin({ dir, debounceMs, io, onChange: (file) => { void sync(file); } });
276
+ const close = watchPlugin({ dir: root, debounceMs, io, onChange: (file) => { void sync(file); } });
273
277
  await sync('initial');
274
278
  while (stopping === false) await sleep(200);
275
279
  close();
package/lib/doctor.mjs CHANGED
@@ -10,11 +10,37 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
 
12
12
  import { hostCompatibility, parsePartialVersion, parseRange } from './compat.mjs';
13
+ import { resolvePath } from './paths.mjs';
13
14
 
14
15
  export { hostCompatibility } from './compat.mjs';
15
16
 
16
17
  const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
17
18
 
19
+ /**
20
+ * npm publishes and installs by `name`; a missing, empty or malformed one fails
21
+ * at the publish/pack boundary, after every other check has already passed.
22
+ *
23
+ * The shape is npm's "valid for a new package" rule without a dependency:
24
+ * lower-case URL-safe segments, no leading dot/hyphen/underscore, at most 214
25
+ * characters, and not one of the two names npm reserves. `init` uses the same
26
+ * predicate, so a scaffold's name and the preflight that blesses it cannot
27
+ * drift apart.
28
+ */
29
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
30
+ const MAX_NAME_LENGTH = 214;
31
+ const RESERVED_NAMES = new Set(['node_modules', 'favicon.ico']);
32
+
33
+ export function isValidPackageName(name) {
34
+ return (
35
+ typeof name === 'string' &&
36
+ name.length > 0 &&
37
+ name.length <= MAX_NAME_LENGTH &&
38
+ name === name.trim() &&
39
+ NPM_NAME.test(name) &&
40
+ RESERVED_NAMES.has(name.toLowerCase()) === false
41
+ );
42
+ }
43
+
18
44
  /**
19
45
  * A complete bare version is a comparator set, but it is not a range the market
20
46
  * index can repeat: it pins one version. The parser accepts it, so reject that
@@ -30,9 +56,12 @@ function isRangeExpression(value) {
30
56
  }
31
57
 
32
58
  export function readManifest(dir) {
33
- const manifestPath = path.join(dir, 'package.json');
59
+ // `doctor '~/my-panel'` arrives with a literal tilde from cmd/PowerShell.
60
+ // Resolve it here too, because this is also a public entry point.
61
+ const target = resolvePath(dir);
62
+ const manifestPath = path.join(target, 'package.json');
34
63
  if (fs.existsSync(manifestPath) === false) {
35
- throw new Error(`no package.json in ${dir}`);
64
+ throw new Error(`no package.json in ${target}`);
36
65
  }
37
66
  // Notepad and some VS Code configurations save UTF-8 with a BOM. JSON.parse
38
67
  // rejects it with a bare `Unexpected token`, so strip it and name the file
@@ -59,6 +88,29 @@ export function hostRange(manifest) {
59
88
  return typeof dsh === 'string' && dsh.trim() !== '' ? dsh.trim() : null;
60
89
  }
61
90
 
91
+ /**
92
+ * `doctor` reads this before anything that needs a package name: `verify` packs
93
+ * and installs the tarball under it, and the loader imports the bare name. An
94
+ * empty string and a deleted field both mean "npm cannot publish this", so they
95
+ * get the same actionable answer rather than being treated as present.
96
+ */
97
+ export function checkName(manifest) {
98
+ const name = manifest?.name;
99
+ if (name === undefined || name === null) {
100
+ return 'package.json has no "name", so npm cannot publish or install the package';
101
+ }
102
+ if (typeof name !== 'string') {
103
+ return 'package.json "name" is not a string, so npm cannot publish or install the package';
104
+ }
105
+ if (name.trim() === '') {
106
+ return 'package.json has an empty "name", so npm cannot publish or install the package';
107
+ }
108
+ if (isValidPackageName(name) === false) {
109
+ return `package.json "name" ${JSON.stringify(name)} is not a valid npm package name; use lower-case letters, digits, dots, hyphens or underscores, for example my-plugin or @me/my-plugin`;
110
+ }
111
+ return null;
112
+ }
113
+
62
114
  export function checkVersion(manifest) {
63
115
  const value = version(manifest);
64
116
  if (value === null) return 'package.json has no version';
@@ -98,14 +150,18 @@ export function checkHostCompatibility(manifest, hostVersion) {
98
150
  return hostCompatibility(range, hostVersion);
99
151
  }
100
152
 
101
- export function checkReadme(dir) {
102
- const readmePath = path.join(dir, 'README.md');
103
- if (fs.existsSync(readmePath) === false) return 'README.md is missing';
104
- const text = fs.readFileSync(readmePath, 'utf8');
153
+ /**
154
+ * The README questions that do not depend on where the text came from: is there
155
+ * a Requirements section, and does it name the range the manifest declares.
156
+ *
157
+ * Factored out because `doctor --remote` reads the same README over the GitHub
158
+ * API; a second copy would drift and the two commands would disagree about the
159
+ * same repository.
160
+ */
161
+ export function checkReadmeText(text, manifest) {
105
162
  if (/^#{1,3}\s*Requirements/im.test(text) === false) {
106
163
  return 'README.md has no Requirements section, so users cannot tell which host it needs';
107
164
  }
108
- const { manifest } = readManifest(dir);
109
165
  const range = hostRange(manifest);
110
166
  // ">= 0.2.0" and ">=0.2.0" are the same range; authors write both.
111
167
  const squeeze = (value) => value.replace(/\s+/g, '');
@@ -115,6 +171,12 @@ export function checkReadme(dir) {
115
171
  return null;
116
172
  }
117
173
 
174
+ export function checkReadme(dir) {
175
+ const readmePath = path.join(dir, 'README.md');
176
+ if (fs.existsSync(readmePath) === false) return 'README.md is missing';
177
+ return checkReadmeText(fs.readFileSync(readmePath, 'utf8'), readManifest(dir).manifest);
178
+ }
179
+
118
180
  export function checkPatchFile(dir, manifest) {
119
181
  const bundle = manifest.dsh?.bundle;
120
182
  if (bundle === undefined || typeof bundle.patch !== 'string') return null;
@@ -431,33 +493,168 @@ export function checkRootExport(dir, manifest) {
431
493
  return null;
432
494
  }
433
495
 
496
+ /**
497
+ * Replace comments and the contents of string, template and regex literals
498
+ * with spaces, keeping newlines. The export check is a source question, not an
499
+ * execution: `doctor` must never import the plugin it is checking, and an
500
+ * `apply` written in prose or a message is not an export. This is deliberately
501
+ * a small lexer rather than a module evaluator or a new dependency.
502
+ */
503
+ function codeOnly(source) {
504
+ let out = '';
505
+ let i = 0;
506
+ const n = source.length;
507
+ const blank = (text) => text.replace(/[^\r\n]/gu, ' ');
508
+
509
+ /** True when a `/` here starts a regex literal rather than a division. */
510
+ const regexMayStart = () => {
511
+ const trimmed = out.trimEnd();
512
+ if (trimmed === '') return true;
513
+ const last = trimmed.at(-1);
514
+ if ('([{,;:=!?&|+-*%^~<>'.includes(last)) return true;
515
+ const word = /([A-Za-z_$][\w$]*)$/u.exec(trimmed)?.[1];
516
+ return (
517
+ word !== undefined &&
518
+ ['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'yield', 'await', 'case', 'throw', 'else', 'do'].includes(word)
519
+ );
520
+ };
521
+
522
+ while (i < n) {
523
+ const ch = source[i];
524
+ const next = source[i + 1];
525
+
526
+ // A shebang is a comment line, even though it does not use `//`.
527
+ if (i === 0 && ch === '#' && next === '!') {
528
+ let end = source.indexOf('\n', i);
529
+ if (end === -1) end = n;
530
+ out += blank(source.slice(i, end));
531
+ i = end;
532
+ continue;
533
+ }
534
+
535
+ if (ch === '/' && next === '/') {
536
+ let end = i + 2;
537
+ while (end < n && source[end] !== '\n' && source[end] !== '\r') end++;
538
+ out += blank(source.slice(i, end));
539
+ i = end;
540
+ continue;
541
+ }
542
+
543
+ if (ch === '/' && next === '*') {
544
+ const close = source.indexOf('*/', i + 2);
545
+ const end = close === -1 ? n : close + 2;
546
+ out += blank(source.slice(i, end));
547
+ i = end;
548
+ continue;
549
+ }
550
+
551
+ if (ch === '"' || ch === "'" || ch === '`') {
552
+ const start = i;
553
+ i++;
554
+ while (i < n) {
555
+ if (source[i] === '\\') {
556
+ i += 2;
557
+ continue;
558
+ }
559
+ if (source[i] === ch) {
560
+ i++;
561
+ break;
562
+ }
563
+ i++;
564
+ }
565
+ // Keep the delimiters so adjacent code does not become one token; the
566
+ // literal's contents are not code and cannot export anything.
567
+ out += ch + blank(source.slice(start + 1, source[i - 1] === ch ? i - 1 : i)) + (source[i - 1] === ch ? ch : '');
568
+ continue;
569
+ }
570
+
571
+ if (ch === '/' && regexMayStart()) {
572
+ const start = i;
573
+ let inClass = false;
574
+ i++;
575
+ while (i < n) {
576
+ if (source[i] === '\\') {
577
+ i += 2;
578
+ continue;
579
+ }
580
+ if (source[i] === '\n' || source[i] === '\r') break;
581
+ if (source[i] === '[') inClass = true;
582
+ else if (source[i] === ']') inClass = false;
583
+ else if (source[i] === '/' && inClass === false) {
584
+ i++;
585
+ while (i < n && /[a-z]/iu.test(source[i])) i++;
586
+ break;
587
+ }
588
+ i++;
589
+ }
590
+ out += blank(source.slice(start, i));
591
+ continue;
592
+ }
593
+
594
+ out += ch;
595
+ i++;
596
+ }
597
+ return out;
598
+ }
599
+
600
+ /** The exported name of each specifier in `export { ... }`, comments removed. */
601
+ function exportedNames(code) {
602
+ const names = [];
603
+ for (const match of code.matchAll(/\bexport\s*\{([^}]*)\}/gu)) {
604
+ for (const part of match[1].split(',')) {
605
+ const specifier = /^\s*(?:([\w$]+)\s+as\s+)?([\w$]+)\s*$/u.exec(part);
606
+ if (specifier === null) continue;
607
+ // The second name is the exported one: `helper as apply` exports apply.
608
+ names.push(specifier[2]);
609
+ }
610
+ }
611
+ return names;
612
+ }
613
+
614
+ /** True when a CommonJS module assigns an `apply` function to its exports. */
615
+ function commonJsExportsApply(code) {
616
+ if (/\b(?:module\s*\.\s*)?exports\s*\.\s*apply\s*=/u.test(code)) return true;
617
+ for (const match of code.matchAll(/\bmodule\s*\.\s*exports\s*=\s*\{([^}]*)\}/gu)) {
618
+ if (/(?:^|,)\s*(?:async\s+)?apply\s*(?::|\(|,|$)/mu.test(match[1])) return true;
619
+ }
620
+ return false;
621
+ }
622
+
434
623
  /**
435
624
  * True when the module source exports `apply` in any of the forms a plugin
436
625
  * actually uses. Factored out because `doctor --remote` asks the same question
437
626
  * about a file it read over the API, and two copies would drift.
627
+ *
628
+ * Comments, strings and regex literals are removed first, so a comment saying
629
+ * "TODO: export function apply() {}" is not mistaken for the export it tells
630
+ * the author to write.
438
631
  */
439
632
  export function exportsApply(source) {
440
633
  if (typeof source !== 'string') return false;
441
- return /export\s+(?:async\s+)?function\s+apply\b|export\s+(?:const|let|var)\s+apply\b|export\s*\{[^}]*\bapply\b|\bapply\s*[:=]\s*(?:async\s*)?(?:function|\()/.test(
442
- source,
443
- );
634
+ const code = codeOnly(source);
635
+ if (/\bexport\s+(?:async\s+)?function\s*\*?\s*apply\b/u.test(code)) return true;
636
+ if (/\bexport\s+(?:const|let|var)\s+apply\b/u.test(code)) return true;
637
+ if (exportedNames(code).includes('apply')) return true;
638
+ return commonJsExportsApply(code);
444
639
  }
445
640
 
446
641
  /** Runs every check and returns `{ failures, notes }`. */
447
642
  export function doctor(dir, { installed = false } = {}) {
448
- const { manifest } = readManifest(dir);
643
+ const target = resolvePath(dir);
644
+ const { manifest } = readManifest(target);
449
645
  const checks = [
646
+ ['name', checkName(manifest)],
450
647
  ['version', checkVersion(manifest)],
451
648
  ['engines.dsh', checkHostRange(manifest)],
452
- ['readme', checkReadme(dir)],
649
+ ['readme', checkReadme(target)],
453
650
  ['dsh field', checkDshField(manifest)],
454
- ['patch file', checkPatchFile(dir, manifest)],
455
- ['client entry', checkClientEntry(dir, manifest)],
456
- ['client declaration', checkClientDeclaration(dir, manifest)],
651
+ ['patch file', checkPatchFile(target, manifest)],
652
+ ['client entry', checkClientEntry(target, manifest)],
653
+ ['client declaration', checkClientDeclaration(target, manifest)],
457
654
  // After install the tarball is already unpacked, so `files` cannot be used to
458
655
  // decide what shipped: npm always ships package.json and the README.
459
656
  ['files list', installed === true ? null : checkFilesList(manifest)],
460
- ['root export', checkRootExport(dir, manifest)],
657
+ ['root export', checkRootExport(target, manifest)],
461
658
  ];
462
659
  const failures = checks.filter(([, result]) => result !== null && typeof result === 'string');
463
660
  return {
package/lib/fix.mjs CHANGED
@@ -17,6 +17,7 @@ import path from 'node:path';
17
17
 
18
18
  import { hostRangePlan, satisfiesRange } from './compat.mjs';
19
19
  import { checkHostRange, doctor, hostRange } from './doctor.mjs';
20
+ import { resolvePath } from './paths.mjs';
20
21
 
21
22
  /** The oldest host the toolkit itself supports, and the range `init` writes. */
22
23
  export const DEFAULT_ENGINES = '>=0.2.0';
@@ -82,6 +83,52 @@ function failure(check, message) {
82
83
  return { ok: false, failures: [{ check, message }] };
83
84
  }
84
85
 
86
+ /**
87
+ * Decide what the `engines.dsh` edit should be for one manifest.
88
+ *
89
+ * The local fixer and the remote planner share this decision so the range a
90
+ * `fix --remote` plan prints is exactly the range `--write` applies in a
91
+ * checkout. `manifest` is the object after the edit when there is one;
92
+ * `noop` means the current range already clears `doctor` and `force` does not
93
+ * ask for a replacement.
94
+ */
95
+ export function planEnginesEdit(manifest, { range, host, force = false } = {}) {
96
+ const requested = resolveEnginesRange({ range, host });
97
+ if (requested.error !== undefined) {
98
+ return failure('host', requested.error);
99
+ }
100
+ const { proposed } = requested;
101
+ if (isHostRange(proposed) === false) {
102
+ return failure('engines.dsh', `"${proposed}" is not a semver range, so it would not clear the doctor check`);
103
+ }
104
+
105
+ const current = hostRange(manifest);
106
+ const correct = current !== null && checkHostRange(manifest) === null;
107
+ const same = normalize(current) === normalize(proposed);
108
+ const forced = force === true || requested.force === true;
109
+ const noop = correct === true && (forced !== true || same === true);
110
+ const engines =
111
+ manifest.engines !== null && typeof manifest.engines === 'object' && Array.isArray(manifest.engines) === false
112
+ ? manifest.engines
113
+ : {};
114
+ const next = noop === true ? null : { ...manifest, engines: { ...engines, dsh: proposed } };
115
+
116
+ return {
117
+ ok: true,
118
+ proposed,
119
+ current,
120
+ correct,
121
+ same,
122
+ forced,
123
+ noop,
124
+ manifest: next,
125
+ reason: noop === true ? 'already-correct' : current === null ? 'missing' : correct === true ? 'different' : 'not-a-range',
126
+ host: requested.host,
127
+ nextMajor: requested.nextMajor,
128
+ why: requested.why,
129
+ };
130
+ }
131
+
85
132
  /** Keep the indentation and the final newline the manifest already had. */
86
133
  function formatting(raw) {
87
134
  const indent = /^[\t ]+"/m.exec(raw);
@@ -210,7 +257,7 @@ export function unifiedDiff(before, after, { file = 'package.json', context = 3
210
257
  * result.
211
258
  */
212
259
  export function fixEngines({ dir = '.', range, host, write = false, force = false } = {}) {
213
- const target = path.resolve(dir);
260
+ const target = resolvePath(dir);
214
261
  const manifestPath = path.join(target, 'package.json');
215
262
  if (fs.existsSync(manifestPath) === false) {
216
263
  return failure('manifest', `no package.json in ${target}`);
@@ -228,20 +275,11 @@ export function fixEngines({ dir = '.', range, host, write = false, force = fals
228
275
  return failure('manifest', `${manifestPath} does not hold a JSON object`);
229
276
  }
230
277
 
231
- const requested = resolveEnginesRange({ range, host });
232
- if (requested.error !== undefined) {
233
- return failure('host', requested.error);
234
- }
235
- const { proposed } = requested;
236
- if (isHostRange(proposed) === false) {
237
- return failure('engines.dsh', `"${proposed}" is not a semver range, so it would not clear the doctor check`);
238
- }
278
+ const planned = planEnginesEdit(manifest, { range, host, force });
279
+ if (planned.ok !== true) return planned;
239
280
 
240
- const current = hostRange(manifest);
241
- const correct = current !== null && checkHostRange(manifest) === null;
242
- const same = normalize(current) === normalize(proposed);
243
- const forced = force === true || requested.force === true;
244
- if (correct === true && (forced !== true || same === true)) {
281
+ const { proposed, current } = planned;
282
+ if (planned.noop === true) {
245
283
  return {
246
284
  ok: true,
247
285
  dir: target,
@@ -252,18 +290,13 @@ export function fixEngines({ dir = '.', range, host, write = false, force = fals
252
290
  changed: false,
253
291
  written: false,
254
292
  reason: 'already-correct',
255
- host: requested.host,
256
- nextMajor: requested.nextMajor,
257
- why: requested.why,
293
+ host: planned.host,
294
+ nextMajor: planned.nextMajor,
295
+ why: planned.why,
258
296
  };
259
297
  }
260
298
 
261
- const engines =
262
- manifest.engines !== null && typeof manifest.engines === 'object' && Array.isArray(manifest.engines) === false
263
- ? manifest.engines
264
- : {};
265
- const next = { ...manifest, engines: { ...engines, dsh: proposed } };
266
- const content = renderManifest(next, raw);
299
+ const content = renderManifest(planned.manifest, raw);
267
300
 
268
301
  let written = false;
269
302
  if (write === true) {
@@ -280,10 +313,10 @@ export function fixEngines({ dir = '.', range, host, write = false, force = fals
280
313
  range: proposed,
281
314
  changed: true,
282
315
  written,
283
- reason: current === null ? 'missing' : correct === true ? 'different' : 'not-a-range',
284
- host: requested.host,
285
- nextMajor: requested.nextMajor,
286
- why: requested.why,
316
+ reason: planned.reason,
317
+ host: planned.host,
318
+ nextMajor: planned.nextMajor,
319
+ why: planned.why,
287
320
  };
288
321
  }
289
322
 
@@ -292,6 +325,11 @@ function manualRepair(failure, dir, manifest) {
292
325
  const packageFile = path.join(dir, 'package.json');
293
326
  const at = (file) => ({ file, path: path.relative(dir, file) || path.basename(file) });
294
327
  switch (failure.check) {
328
+ case 'name':
329
+ return {
330
+ ...at(packageFile),
331
+ manual: 'set "name" to the npm package name, for example my-plugin or @me/my-plugin',
332
+ };
295
333
  case 'version':
296
334
  return {
297
335
  ...at(packageFile),
@@ -369,7 +407,7 @@ function setField(target, field, value) {
369
407
  * be worse than saying so. A plan is pure: it never writes.
370
408
  */
371
409
  export function repairPlan({ dir = '.', range, host } = {}) {
372
- const target = path.resolve(dir);
410
+ const target = resolvePath(dir);
373
411
  const manifestPath = path.join(target, 'package.json');
374
412
  const requested = resolveEnginesRange({ range, host });
375
413
  if (requested.error !== undefined) {
package/lib/github.mjs CHANGED
@@ -10,6 +10,7 @@ import fs from 'node:fs';
10
10
  import os from 'node:os';
11
11
  import path from 'node:path';
12
12
  import { run } from './exec.mjs';
13
+ import { expandHome } from './paths.mjs';
13
14
 
14
15
  const UA = 'dsh-plugin-toolkit';
15
16
 
@@ -21,9 +22,9 @@ const UA = 'dsh-plugin-toolkit';
21
22
  export function parseTarget(input) {
22
23
  const raw = typeof input === 'string' ? input.trim() : '';
23
24
  if (raw === '') return { kind: 'empty' };
24
- // `~/kit` is how a person writes a home folder; `fs.existsSync` would call it
25
- // a search and send the name to github.com.
26
- const expanded = raw === '~' || raw.startsWith('~/') === true ? path.join(os.homedir(), raw.slice(1)) : raw;
25
+ // `~/kit` (and the Windows `~\kit`) is how a person writes a home folder;
26
+ // `fs.existsSync` would call it a search and send the name to github.com.
27
+ const expanded = expandHome(raw);
27
28
  if (fs.existsSync(expanded) === true) return { kind: 'local', dir: path.resolve(expanded) };
28
29
 
29
30
  const url = raw.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s#?]+)(?:\/.*)?$/i);
@@ -7,9 +7,10 @@
7
7
  import fs from 'node:fs';
8
8
 
9
9
  import { checkHostRange } from './doctor.mjs';
10
+ import { resolvePath } from './paths.mjs';
10
11
 
11
12
  export function readIndex(file) {
12
- return JSON.parse(fs.readFileSync(file, 'utf8'));
13
+ return JSON.parse(fs.readFileSync(resolvePath(file), 'utf8'));
13
14
  }
14
15
 
15
16
  export function findPlugin(index, name) {
@@ -81,5 +82,5 @@ export function auditVersions(index, name) {
81
82
  }
82
83
 
83
84
  export function writeIndex(file, index) {
84
- fs.writeFileSync(file, `${JSON.stringify(index, null, 2)}\n`);
85
+ fs.writeFileSync(resolvePath(file), `${JSON.stringify(index, null, 2)}\n`);
85
86
  }
package/lib/init.mjs CHANGED
@@ -8,16 +8,18 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
 
11
+ import { isValidPackageName } from './doctor.mjs';
12
+ import { resolvePath } from './paths.mjs';
13
+
11
14
  // The scaffold pins the toolkit it was generated by, not a number typed once:
12
15
  // a scaffold that installs two minor versions behind is the first thing a new
13
16
  // author sees and the last thing anyone updates.
14
17
  const VERSION = JSON.parse(
15
18
  fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
16
19
  ).version;
17
- const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
18
20
 
19
21
  export function checkName(name) {
20
- if (typeof name !== 'string' || NPM_NAME.test(name) === false) {
22
+ if (isValidPackageName(name) === false) {
21
23
  return 'name must be a valid npm package name, e.g. my-plugin or @me/my-plugin';
22
24
  }
23
25
  return null;
@@ -192,7 +194,10 @@ export function init({ dir, name, title, force = false }) {
192
194
  const problem = checkName(name);
193
195
  if (problem !== null) return { ok: false, failures: [{ check: 'name', message: problem }] };
194
196
 
195
- const target = path.resolve(dir);
197
+ // `init '~/my-panel'` reaches this function with the tilde intact on
198
+ // cmd/PowerShell. Expand it here as well as in the CLI so a direct caller
199
+ // cannot create a directory literally named `~` either.
200
+ const target = resolvePath(dir);
196
201
  if (fs.existsSync(target) === true) {
197
202
  const entries = fs.readdirSync(target).filter((entry) => entry !== '.git');
198
203
  if (entries.length > 0 && force !== true) {