jspm 2.0.0-beta.7 → 3.0.0

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.
Files changed (100) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +26 -32
  3. package/dist/cli.js +1391 -0
  4. package/jspm.js +10 -0
  5. package/package.json +32 -60
  6. package/CHANGELOG.md +0 -25
  7. package/bin/jspm +0 -46
  8. package/lib/api.d.ts +0 -10
  9. package/lib/api.js +0 -71
  10. package/lib/api.js.map +0 -1
  11. package/lib/build/index.d.ts +0 -24
  12. package/lib/build/index.js +0 -163
  13. package/lib/build/index.js.map +0 -1
  14. package/lib/cli.d.ts +0 -1
  15. package/lib/cli.js +0 -701
  16. package/lib/cli.js.map +0 -1
  17. package/lib/compile/cjs-convert.d.ts +0 -7
  18. package/lib/compile/cjs-convert.js +0 -375
  19. package/lib/compile/cjs-convert.js.map +0 -1
  20. package/lib/compile/dew-resolve.d.ts +0 -9
  21. package/lib/compile/dew-resolve.js +0 -117
  22. package/lib/compile/dew-resolve.js.map +0 -1
  23. package/lib/compile/dew-worker.d.ts +0 -1
  24. package/lib/compile/dew-worker.js +0 -302
  25. package/lib/compile/dew-worker.js.map +0 -1
  26. package/lib/config/config-file.d.ts +0 -67
  27. package/lib/config/config-file.js +0 -591
  28. package/lib/config/config-file.js.map +0 -1
  29. package/lib/config/global-config-file.d.ts +0 -8
  30. package/lib/config/global-config-file.js +0 -89
  31. package/lib/config/global-config-file.js.map +0 -1
  32. package/lib/config/index.d.ts +0 -15
  33. package/lib/config/index.js +0 -59
  34. package/lib/config/index.js.map +0 -1
  35. package/lib/config/jspm-file.d.ts +0 -8
  36. package/lib/config/jspm-file.js +0 -84
  37. package/lib/config/jspm-file.js.map +0 -1
  38. package/lib/config/package-json-file.d.ts +0 -49
  39. package/lib/config/package-json-file.js +0 -332
  40. package/lib/config/package-json-file.js.map +0 -1
  41. package/lib/exec/index.d.ts +0 -12
  42. package/lib/exec/index.js +0 -117
  43. package/lib/exec/index.js.map +0 -1
  44. package/lib/install/bin.d.ts +0 -2
  45. package/lib/install/bin.js +0 -85
  46. package/lib/install/bin.js.map +0 -1
  47. package/lib/install/binary-build.d.ts +0 -2
  48. package/lib/install/binary-build.js +0 -89
  49. package/lib/install/binary-build.js.map +0 -1
  50. package/lib/install/fetch.d.ts +0 -53
  51. package/lib/install/fetch.js +0 -270
  52. package/lib/install/fetch.js.map +0 -1
  53. package/lib/install/index.d.ts +0 -66
  54. package/lib/install/index.js +0 -1164
  55. package/lib/install/index.js.map +0 -1
  56. package/lib/install/package.d.ts +0 -142
  57. package/lib/install/package.js +0 -625
  58. package/lib/install/package.js.map +0 -1
  59. package/lib/install/publish.d.ts +0 -14
  60. package/lib/install/publish.js +0 -186
  61. package/lib/install/publish.js.map +0 -1
  62. package/lib/install/registry-manager.d.ts +0 -134
  63. package/lib/install/registry-manager.js +0 -521
  64. package/lib/install/registry-manager.js.map +0 -1
  65. package/lib/install/source.d.ts +0 -10
  66. package/lib/install/source.js +0 -378
  67. package/lib/install/source.js.map +0 -1
  68. package/lib/map/common.d.ts +0 -12
  69. package/lib/map/common.js +0 -182
  70. package/lib/map/common.js.map +0 -1
  71. package/lib/map/esm-lexer.d.ts +0 -17
  72. package/lib/map/esm-lexer.js +0 -506
  73. package/lib/map/esm-lexer.js.map +0 -1
  74. package/lib/map/index.d.ts +0 -15
  75. package/lib/map/index.js +0 -336
  76. package/lib/map/index.js.map +0 -1
  77. package/lib/map/utils.d.ts +0 -10
  78. package/lib/map/utils.js +0 -169
  79. package/lib/map/utils.js.map +0 -1
  80. package/lib/overrides.d.ts +0 -3
  81. package/lib/overrides.js +0 -29
  82. package/lib/overrides.js.map +0 -1
  83. package/lib/project.d.ts +0 -71
  84. package/lib/project.js +0 -434
  85. package/lib/project.js.map +0 -1
  86. package/lib/utils/cache.d.ts +0 -11
  87. package/lib/utils/cache.js +0 -121
  88. package/lib/utils/cache.js.map +0 -1
  89. package/lib/utils/common.d.ts +0 -55
  90. package/lib/utils/common.js +0 -267
  91. package/lib/utils/common.js.map +0 -1
  92. package/lib/utils/opts.d.ts +0 -6
  93. package/lib/utils/opts.js +0 -200
  94. package/lib/utils/opts.js.map +0 -1
  95. package/lib/utils/run-cmd.d.ts +0 -4
  96. package/lib/utils/run-cmd.js +0 -39
  97. package/lib/utils/run-cmd.js.map +0 -1
  98. package/lib/utils/ui.d.ts +0 -38
  99. package/lib/utils/ui.js +0 -496
  100. package/lib/utils/ui.js.map +0 -1
package/dist/cli.js ADDED
@@ -0,0 +1,1391 @@
1
+ // src/cli.ts
2
+ import c8 from "picocolors";
3
+
4
+ // node_modules/cac/dist/index.mjs
5
+ import { EventEmitter } from "events";
6
+ function toArr(any) {
7
+ return any == null ? [] : Array.isArray(any) ? any : [any];
8
+ }
9
+ function toVal(out, key, val, opts) {
10
+ var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
11
+ out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
12
+ }
13
+ function mri2(args, opts) {
14
+ args = args || [];
15
+ opts = opts || {};
16
+ var k, arr, arg, name, val, out = { _: [] };
17
+ var i = 0, j = 0, idx = 0, len = args.length;
18
+ const alibi = opts.alias !== void 0;
19
+ const strict = opts.unknown !== void 0;
20
+ const defaults = opts.default !== void 0;
21
+ opts.alias = opts.alias || {};
22
+ opts.string = toArr(opts.string);
23
+ opts.boolean = toArr(opts.boolean);
24
+ if (alibi) {
25
+ for (k in opts.alias) {
26
+ arr = opts.alias[k] = toArr(opts.alias[k]);
27
+ for (i = 0; i < arr.length; i++) {
28
+ (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
29
+ }
30
+ }
31
+ }
32
+ for (i = opts.boolean.length; i-- > 0; ) {
33
+ arr = opts.alias[opts.boolean[i]] || [];
34
+ for (j = arr.length; j-- > 0; )
35
+ opts.boolean.push(arr[j]);
36
+ }
37
+ for (i = opts.string.length; i-- > 0; ) {
38
+ arr = opts.alias[opts.string[i]] || [];
39
+ for (j = arr.length; j-- > 0; )
40
+ opts.string.push(arr[j]);
41
+ }
42
+ if (defaults) {
43
+ for (k in opts.default) {
44
+ name = typeof opts.default[k];
45
+ arr = opts.alias[k] = opts.alias[k] || [];
46
+ if (opts[name] !== void 0) {
47
+ opts[name].push(k);
48
+ for (i = 0; i < arr.length; i++) {
49
+ opts[name].push(arr[i]);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ const keys = strict ? Object.keys(opts.alias) : [];
55
+ for (i = 0; i < len; i++) {
56
+ arg = args[i];
57
+ if (arg === "--") {
58
+ out._ = out._.concat(args.slice(++i));
59
+ break;
60
+ }
61
+ for (j = 0; j < arg.length; j++) {
62
+ if (arg.charCodeAt(j) !== 45)
63
+ break;
64
+ }
65
+ if (j === 0) {
66
+ out._.push(arg);
67
+ } else if (arg.substring(j, j + 3) === "no-") {
68
+ name = arg.substring(j + 3);
69
+ if (strict && !~keys.indexOf(name)) {
70
+ return opts.unknown(arg);
71
+ }
72
+ out[name] = false;
73
+ } else {
74
+ for (idx = j + 1; idx < arg.length; idx++) {
75
+ if (arg.charCodeAt(idx) === 61)
76
+ break;
77
+ }
78
+ name = arg.substring(j, idx);
79
+ val = arg.substring(++idx) || (i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i]);
80
+ arr = j === 2 ? [name] : name;
81
+ for (idx = 0; idx < arr.length; idx++) {
82
+ name = arr[idx];
83
+ if (strict && !~keys.indexOf(name))
84
+ return opts.unknown("-".repeat(j) + name);
85
+ toVal(out, name, idx + 1 < arr.length || val, opts);
86
+ }
87
+ }
88
+ }
89
+ if (defaults) {
90
+ for (k in opts.default) {
91
+ if (out[k] === void 0) {
92
+ out[k] = opts.default[k];
93
+ }
94
+ }
95
+ }
96
+ if (alibi) {
97
+ for (k in out) {
98
+ arr = opts.alias[k] || [];
99
+ while (arr.length > 0) {
100
+ out[arr.shift()] = out[k];
101
+ }
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+ var removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
107
+ var findAllBrackets = (v) => {
108
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
109
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
110
+ const res = [];
111
+ const parse = (match) => {
112
+ let variadic = false;
113
+ let value = match[1];
114
+ if (value.startsWith("...")) {
115
+ value = value.slice(3);
116
+ variadic = true;
117
+ }
118
+ return {
119
+ required: match[0].startsWith("<"),
120
+ value,
121
+ variadic
122
+ };
123
+ };
124
+ let angledMatch;
125
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
126
+ res.push(parse(angledMatch));
127
+ }
128
+ let squareMatch;
129
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
130
+ res.push(parse(squareMatch));
131
+ }
132
+ return res;
133
+ };
134
+ var getMriOptions = (options) => {
135
+ const result = { alias: {}, boolean: [] };
136
+ for (const [index, option] of options.entries()) {
137
+ if (option.names.length > 1) {
138
+ result.alias[option.names[0]] = option.names.slice(1);
139
+ }
140
+ if (option.isBoolean) {
141
+ if (option.negated) {
142
+ const hasStringTypeOption = options.some((o, i) => {
143
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
144
+ });
145
+ if (!hasStringTypeOption) {
146
+ result.boolean.push(option.names[0]);
147
+ }
148
+ } else {
149
+ result.boolean.push(option.names[0]);
150
+ }
151
+ }
152
+ }
153
+ return result;
154
+ };
155
+ var findLongest = (arr) => {
156
+ return arr.sort((a, b) => {
157
+ return a.length > b.length ? -1 : 1;
158
+ })[0];
159
+ };
160
+ var padRight = (str, length) => {
161
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
162
+ };
163
+ var camelcase = (input) => {
164
+ return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
165
+ return p1 + p2.toUpperCase();
166
+ });
167
+ };
168
+ var setDotProp = (obj, keys, val) => {
169
+ let i = 0;
170
+ let length = keys.length;
171
+ let t = obj;
172
+ let x;
173
+ for (; i < length; ++i) {
174
+ x = t[keys[i]];
175
+ t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
176
+ }
177
+ };
178
+ var setByType = (obj, transforms) => {
179
+ for (const key of Object.keys(transforms)) {
180
+ const transform = transforms[key];
181
+ if (transform.shouldTransform) {
182
+ obj[key] = Array.prototype.concat.call([], obj[key]);
183
+ if (typeof transform.transformFunction === "function") {
184
+ obj[key] = obj[key].map(transform.transformFunction);
185
+ }
186
+ }
187
+ }
188
+ };
189
+ var getFileName = (input) => {
190
+ const m = /([^\\\/]+)$/.exec(input);
191
+ return m ? m[1] : "";
192
+ };
193
+ var camelcaseOptionName = (name) => {
194
+ return name.split(".").map((v, i) => {
195
+ return i === 0 ? camelcase(v) : v;
196
+ }).join(".");
197
+ };
198
+ var CACError = class extends Error {
199
+ constructor(message) {
200
+ super(message);
201
+ this.name = this.constructor.name;
202
+ if (typeof Error.captureStackTrace === "function") {
203
+ Error.captureStackTrace(this, this.constructor);
204
+ } else {
205
+ this.stack = new Error(message).stack;
206
+ }
207
+ }
208
+ };
209
+ var Option = class {
210
+ constructor(rawName, description, config) {
211
+ this.rawName = rawName;
212
+ this.description = description;
213
+ this.config = Object.assign({}, config);
214
+ rawName = rawName.replace(/\.\*/g, "");
215
+ this.negated = false;
216
+ this.names = removeBrackets(rawName).split(",").map((v) => {
217
+ let name = v.trim().replace(/^-{1,2}/, "");
218
+ if (name.startsWith("no-")) {
219
+ this.negated = true;
220
+ name = name.replace(/^no-/, "");
221
+ }
222
+ return camelcaseOptionName(name);
223
+ }).sort((a, b) => a.length > b.length ? 1 : -1);
224
+ this.name = this.names[this.names.length - 1];
225
+ if (this.negated && this.config.default == null) {
226
+ this.config.default = true;
227
+ }
228
+ if (rawName.includes("<")) {
229
+ this.required = true;
230
+ } else if (rawName.includes("[")) {
231
+ this.required = false;
232
+ } else {
233
+ this.isBoolean = true;
234
+ }
235
+ }
236
+ };
237
+ var processArgs = process.argv;
238
+ var platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
239
+ var Command = class {
240
+ constructor(rawName, description, config = {}, cli2) {
241
+ this.rawName = rawName;
242
+ this.description = description;
243
+ this.config = config;
244
+ this.cli = cli2;
245
+ this.options = [];
246
+ this.aliasNames = [];
247
+ this.name = removeBrackets(rawName);
248
+ this.args = findAllBrackets(rawName);
249
+ this.examples = [];
250
+ }
251
+ usage(text) {
252
+ this.usageText = text;
253
+ return this;
254
+ }
255
+ allowUnknownOptions() {
256
+ this.config.allowUnknownOptions = true;
257
+ return this;
258
+ }
259
+ ignoreOptionDefaultValue() {
260
+ this.config.ignoreOptionDefaultValue = true;
261
+ return this;
262
+ }
263
+ version(version2, customFlags = "-v, --version") {
264
+ this.versionNumber = version2;
265
+ this.option(customFlags, "Display version number");
266
+ return this;
267
+ }
268
+ example(example) {
269
+ this.examples.push(example);
270
+ return this;
271
+ }
272
+ option(rawName, description, config) {
273
+ const option = new Option(rawName, description, config);
274
+ this.options.push(option);
275
+ return this;
276
+ }
277
+ alias(name) {
278
+ this.aliasNames.push(name);
279
+ return this;
280
+ }
281
+ action(callback) {
282
+ this.commandAction = callback;
283
+ return this;
284
+ }
285
+ isMatched(name) {
286
+ return this.name === name || this.aliasNames.includes(name);
287
+ }
288
+ get isDefaultCommand() {
289
+ return this.name === "" || this.aliasNames.includes("!");
290
+ }
291
+ get isGlobalCommand() {
292
+ return this instanceof GlobalCommand;
293
+ }
294
+ hasOption(name) {
295
+ name = name.split(".")[0];
296
+ return this.options.find((option) => {
297
+ return option.names.includes(name);
298
+ });
299
+ }
300
+ outputHelp() {
301
+ const { name, commands } = this.cli;
302
+ const {
303
+ versionNumber,
304
+ options: globalOptions,
305
+ helpCallback
306
+ } = this.cli.globalCommand;
307
+ let sections = [
308
+ {
309
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
310
+ }
311
+ ];
312
+ sections.push({
313
+ title: "Usage",
314
+ body: ` $ ${name} ${this.usageText || this.rawName}`
315
+ });
316
+ const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
317
+ if (showCommands) {
318
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
319
+ sections.push({
320
+ title: "Commands",
321
+ body: commands.map((command) => {
322
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
323
+ }).join("\n")
324
+ });
325
+ sections.push({
326
+ title: `For more info, run any command with the \`--help\` flag`,
327
+ body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
328
+ });
329
+ }
330
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
331
+ if (!this.isGlobalCommand && !this.isDefaultCommand) {
332
+ options = options.filter((option) => option.name !== "version");
333
+ }
334
+ if (options.length > 0) {
335
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
336
+ sections.push({
337
+ title: "Options",
338
+ body: options.map((option) => {
339
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
340
+ }).join("\n")
341
+ });
342
+ }
343
+ if (this.examples.length > 0) {
344
+ sections.push({
345
+ title: "Examples",
346
+ body: this.examples.map((example) => {
347
+ if (typeof example === "function") {
348
+ return example(name);
349
+ }
350
+ return example;
351
+ }).join("\n")
352
+ });
353
+ }
354
+ if (helpCallback) {
355
+ sections = helpCallback(sections) || sections;
356
+ }
357
+ console.log(sections.map((section) => {
358
+ return section.title ? `${section.title}:
359
+ ${section.body}` : section.body;
360
+ }).join("\n\n"));
361
+ }
362
+ outputVersion() {
363
+ const { name } = this.cli;
364
+ const { versionNumber } = this.cli.globalCommand;
365
+ if (versionNumber) {
366
+ console.log(`${name}/${versionNumber} ${platformInfo}`);
367
+ }
368
+ }
369
+ checkRequiredArgs() {
370
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
371
+ if (this.cli.args.length < minimalArgsCount) {
372
+ throw new CACError(`missing required args for command \`${this.rawName}\``);
373
+ }
374
+ }
375
+ checkUnknownOptions() {
376
+ const { options, globalCommand } = this.cli;
377
+ if (!this.config.allowUnknownOptions) {
378
+ for (const name of Object.keys(options)) {
379
+ if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
380
+ throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
381
+ }
382
+ }
383
+ }
384
+ }
385
+ checkOptionValue() {
386
+ const { options: parsedOptions, globalCommand } = this.cli;
387
+ const options = [...globalCommand.options, ...this.options];
388
+ for (const option of options) {
389
+ const value = parsedOptions[option.name.split(".")[0]];
390
+ if (option.required) {
391
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
392
+ if (value === true || value === false && !hasNegated) {
393
+ throw new CACError(`option \`${option.rawName}\` value is missing`);
394
+ }
395
+ }
396
+ }
397
+ }
398
+ };
399
+ var GlobalCommand = class extends Command {
400
+ constructor(cli2) {
401
+ super("@@global@@", "", {}, cli2);
402
+ }
403
+ };
404
+ var __assign = Object.assign;
405
+ var CAC = class extends EventEmitter {
406
+ constructor(name = "") {
407
+ super();
408
+ this.name = name;
409
+ this.commands = [];
410
+ this.rawArgs = [];
411
+ this.args = [];
412
+ this.options = {};
413
+ this.globalCommand = new GlobalCommand(this);
414
+ this.globalCommand.usage("<command> [options]");
415
+ }
416
+ usage(text) {
417
+ this.globalCommand.usage(text);
418
+ return this;
419
+ }
420
+ command(rawName, description, config) {
421
+ const command = new Command(rawName, description || "", config, this);
422
+ command.globalCommand = this.globalCommand;
423
+ this.commands.push(command);
424
+ return command;
425
+ }
426
+ option(rawName, description, config) {
427
+ this.globalCommand.option(rawName, description, config);
428
+ return this;
429
+ }
430
+ help(callback) {
431
+ this.globalCommand.option("-h, --help", "Display this message");
432
+ this.globalCommand.helpCallback = callback;
433
+ this.showHelpOnExit = true;
434
+ return this;
435
+ }
436
+ version(version2, customFlags = "-v, --version") {
437
+ this.globalCommand.version(version2, customFlags);
438
+ this.showVersionOnExit = true;
439
+ return this;
440
+ }
441
+ example(example) {
442
+ this.globalCommand.example(example);
443
+ return this;
444
+ }
445
+ outputHelp() {
446
+ if (this.matchedCommand) {
447
+ this.matchedCommand.outputHelp();
448
+ } else {
449
+ this.globalCommand.outputHelp();
450
+ }
451
+ }
452
+ outputVersion() {
453
+ this.globalCommand.outputVersion();
454
+ }
455
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
456
+ this.args = args;
457
+ this.options = options;
458
+ if (matchedCommand) {
459
+ this.matchedCommand = matchedCommand;
460
+ }
461
+ if (matchedCommandName) {
462
+ this.matchedCommandName = matchedCommandName;
463
+ }
464
+ return this;
465
+ }
466
+ unsetMatchedCommand() {
467
+ this.matchedCommand = void 0;
468
+ this.matchedCommandName = void 0;
469
+ }
470
+ parse(argv = processArgs, {
471
+ run = true
472
+ } = {}) {
473
+ this.rawArgs = argv;
474
+ if (!this.name) {
475
+ this.name = argv[1] ? getFileName(argv[1]) : "cli";
476
+ }
477
+ let shouldParse = true;
478
+ for (const command of this.commands) {
479
+ const parsed = this.mri(argv.slice(2), command);
480
+ const commandName = parsed.args[0];
481
+ if (command.isMatched(commandName)) {
482
+ shouldParse = false;
483
+ const parsedInfo = __assign(__assign({}, parsed), {
484
+ args: parsed.args.slice(1)
485
+ });
486
+ this.setParsedInfo(parsedInfo, command, commandName);
487
+ this.emit(`command:${commandName}`, command);
488
+ }
489
+ }
490
+ if (shouldParse) {
491
+ for (const command of this.commands) {
492
+ if (command.name === "") {
493
+ shouldParse = false;
494
+ const parsed = this.mri(argv.slice(2), command);
495
+ this.setParsedInfo(parsed, command);
496
+ this.emit(`command:!`, command);
497
+ }
498
+ }
499
+ }
500
+ if (shouldParse) {
501
+ const parsed = this.mri(argv.slice(2));
502
+ this.setParsedInfo(parsed);
503
+ }
504
+ if (this.options.help && this.showHelpOnExit) {
505
+ this.outputHelp();
506
+ run = false;
507
+ this.unsetMatchedCommand();
508
+ }
509
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
510
+ this.outputVersion();
511
+ run = false;
512
+ this.unsetMatchedCommand();
513
+ }
514
+ const parsedArgv = { args: this.args, options: this.options };
515
+ if (run) {
516
+ this.runMatchedCommand();
517
+ }
518
+ if (!this.matchedCommand && this.args[0]) {
519
+ this.emit("command:*");
520
+ }
521
+ return parsedArgv;
522
+ }
523
+ mri(argv, command) {
524
+ const cliOptions = [
525
+ ...this.globalCommand.options,
526
+ ...command ? command.options : []
527
+ ];
528
+ const mriOptions = getMriOptions(cliOptions);
529
+ let argsAfterDoubleDashes = [];
530
+ const doubleDashesIndex = argv.indexOf("--");
531
+ if (doubleDashesIndex > -1) {
532
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
533
+ argv = argv.slice(0, doubleDashesIndex);
534
+ }
535
+ let parsed = mri2(argv, mriOptions);
536
+ parsed = Object.keys(parsed).reduce((res, name) => {
537
+ return __assign(__assign({}, res), {
538
+ [camelcaseOptionName(name)]: parsed[name]
539
+ });
540
+ }, { _: [] });
541
+ const args = parsed._;
542
+ const options = {
543
+ "--": argsAfterDoubleDashes
544
+ };
545
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
546
+ let transforms = /* @__PURE__ */ Object.create(null);
547
+ for (const cliOption of cliOptions) {
548
+ if (!ignoreDefault && cliOption.config.default !== void 0) {
549
+ for (const name of cliOption.names) {
550
+ options[name] = cliOption.config.default;
551
+ }
552
+ }
553
+ if (Array.isArray(cliOption.config.type)) {
554
+ if (transforms[cliOption.name] === void 0) {
555
+ transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
556
+ transforms[cliOption.name]["shouldTransform"] = true;
557
+ transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
558
+ }
559
+ }
560
+ }
561
+ for (const key of Object.keys(parsed)) {
562
+ if (key !== "_") {
563
+ const keys = key.split(".");
564
+ setDotProp(options, keys, parsed[key]);
565
+ setByType(options, transforms);
566
+ }
567
+ }
568
+ return {
569
+ args,
570
+ options
571
+ };
572
+ }
573
+ runMatchedCommand() {
574
+ const { args, options, matchedCommand: command } = this;
575
+ if (!command || !command.commandAction)
576
+ return;
577
+ command.checkUnknownOptions();
578
+ command.checkOptionValue();
579
+ command.checkRequiredArgs();
580
+ const actionArgs = [];
581
+ command.args.forEach((arg, index) => {
582
+ if (arg.variadic) {
583
+ actionArgs.push(args.slice(index));
584
+ } else {
585
+ actionArgs.push(args[index]);
586
+ }
587
+ });
588
+ actionArgs.push(options);
589
+ return command.commandAction.apply(this, actionArgs);
590
+ }
591
+ };
592
+ var cac = (name = "") => new CAC(name);
593
+ var dist_default = cac;
594
+
595
+ // package.json
596
+ var version = "3.0.0";
597
+
598
+ // src/clearCache.ts
599
+ import c from "picocolors";
600
+ import { clearCache as _clearCache } from "@jspm/generator";
601
+ async function clearCache(flags) {
602
+ _clearCache();
603
+ !flags.silent && console.warn(`${c.green("Ok:")} Cache cleared successfully`);
604
+ }
605
+
606
+ // src/install.ts
607
+ import c4 from "picocolors";
608
+
609
+ // src/logger.ts
610
+ import fs from "fs/promises";
611
+ import os from "os";
612
+ import c2 from "picocolors";
613
+ var logEnabled = !!process.env.JSPM_CLI_LOG;
614
+ var _log;
615
+ var _logStream;
616
+ if (logEnabled) {
617
+ ({ log: _log, logStream: _logStream } = createLogger());
618
+ try {
619
+ let logPath;
620
+ if (process.env.JSPM_CLI_LOG === "1" || process.env.JSPM_CLI_LOG?.toLowerCase() === "true") {
621
+ logPath = `${os.tmpdir()}/jspm-${new Date().toISOString().slice(0, 19)}.log`;
622
+ } else {
623
+ logPath = process.env.JSPM_CLI_LOG;
624
+ }
625
+ const logWriter = async (msg) => await fs.writeFile(logPath, msg, {
626
+ encoding: "utf-8",
627
+ flag: "a+",
628
+ mode: 438
629
+ });
630
+ (async () => {
631
+ console.log(c2.red(`Creating debug logger at ${logPath}`));
632
+ await logWriter("");
633
+ for await (const { type, message } of _logStream()) {
634
+ const time = new Date().toISOString().slice(11, 23);
635
+ const prefix = c2.bold(`${time} ${type}:`);
636
+ await logWriter(`${prefix} ${message}
637
+ `);
638
+ }
639
+ })();
640
+ } catch (e) {
641
+ console.log(c2.red(`Failed to create debug logger: ${e.message}`));
642
+ }
643
+ }
644
+ function log(type, message) {
645
+ _log && _log(type, message);
646
+ }
647
+ function withType(type) {
648
+ return (message) => log(type, message);
649
+ }
650
+ function createLogger() {
651
+ let resolveQueue;
652
+ let queuePromise = new Promise((resolve) => resolveQueue = resolve);
653
+ let queue = [];
654
+ const logStream = async function* () {
655
+ while (true) {
656
+ while (queue.length)
657
+ yield queue.shift();
658
+ await queuePromise;
659
+ }
660
+ };
661
+ function log2(type, message) {
662
+ if (queue.length) {
663
+ queue.push({ type, message });
664
+ } else {
665
+ queue = [{ type, message }];
666
+ const _resolveQueue = resolveQueue;
667
+ queuePromise = new Promise((resolve) => resolveQueue = resolve);
668
+ _resolveQueue();
669
+ }
670
+ }
671
+ return { log: log2, logStream };
672
+ }
673
+
674
+ // src/utils.ts
675
+ import fs2 from "fs/promises";
676
+ import path from "path";
677
+ import { pathToFileURL } from "url";
678
+ import { Generator, analyzeHtml } from "@jspm/generator";
679
+ import ora from "ora";
680
+ import c3 from "picocolors";
681
+ var defaultInputPath = "./importmap.json";
682
+ var defaultHtmlTemplate = `<!DOCTYPE html>
683
+ <html>
684
+ <head>
685
+ <meta charset="utf-8">
686
+ <title>JSPM example</title>
687
+ <script type="importmap"></script>
688
+ </head>
689
+ <body>
690
+ </body>
691
+ </html>`;
692
+ var availableProviders = [
693
+ "jspm.io",
694
+ "nodemodules",
695
+ "deno",
696
+ "jsdelivr",
697
+ "skypack",
698
+ "unpkg",
699
+ "esm.sh",
700
+ "jspm.io#system"
701
+ ];
702
+ var JspmError = class extends Error {
703
+ jspmError = true;
704
+ };
705
+ function wrapCommand(fn) {
706
+ return async (...args) => {
707
+ try {
708
+ await fn(...args);
709
+ } catch (e) {
710
+ stopSpinner();
711
+ process.exitCode = 1;
712
+ if (e instanceof JspmError || e?.jspmError) {
713
+ console.error(`${c3.red("Error:")} ${e.message}
714
+ `);
715
+ return;
716
+ }
717
+ throw e;
718
+ }
719
+ };
720
+ }
721
+ async function writeOutput(generator, pins, env, flags, silent = false) {
722
+ if (flags.stdout)
723
+ return writeStdoutOutput(generator, pins, silent);
724
+ const mapFile = getOutputPath(flags);
725
+ if (mapFile.endsWith(".html"))
726
+ return writeHtmlOutput(mapFile, generator, pins, env, flags, silent);
727
+ return writeJsonOutput(mapFile, generator, pins, env, flags, silent);
728
+ }
729
+ async function writeStdoutOutput(generator, pins, silent = false) {
730
+ let map = pins?.length ? (await generator.extractMap(pins))?.map : generator.getMap();
731
+ map = { ...map };
732
+ !silent && console.log(JSON.stringify(map, null, 2));
733
+ return map;
734
+ }
735
+ async function writeHtmlOutput(mapFile, generator, pins, env, flags, silent = false) {
736
+ if (!await canWrite(mapFile))
737
+ throw new JspmError(
738
+ `JSPM does not have permission to write to ${mapFile}.`
739
+ );
740
+ const mapFileRel = path.relative(process.cwd(), mapFile);
741
+ if (!await exists(mapFile)) {
742
+ !silent && console.warn(
743
+ `${c3.cyan(
744
+ "Note:"
745
+ )} HTML file ${mapFileRel} does not exist, creating one.`
746
+ );
747
+ await fs2.writeFile(mapFile, defaultHtmlTemplate, "utf-8");
748
+ }
749
+ let html;
750
+ try {
751
+ html = await fs2.readFile(mapFile, "utf-8");
752
+ } catch (e) {
753
+ throw new JspmError(
754
+ `Failed to read HTML file ${c3.cyan(mapFile)} for injection.`
755
+ );
756
+ }
757
+ const outputHtml = await generator.htmlInject(html, {
758
+ pins: pins ?? true,
759
+ htmlUrl: generator.mapUrl,
760
+ // URL of the output map
761
+ rootUrl: generator.rootUrl,
762
+ preload: flags.preload,
763
+ integrity: flags.integrity,
764
+ whitespace: !flags.compact,
765
+ comment: false
766
+ });
767
+ await fs2.writeFile(mapFile, outputHtml);
768
+ !silent && console.warn(`${c3.green("Ok:")} Updated ${c3.cyan(mapFileRel)}`);
769
+ }
770
+ async function writeJsonOutput(mapFile, generator, pins, env, flags, silent = false) {
771
+ const log2 = withType("utils/writeJsonOutput");
772
+ let map;
773
+ if (pins?.length) {
774
+ log2(`Extracting map for top-level pins: ${pins?.join(", ")}`);
775
+ map = (await generator.extractMap(pins))?.map;
776
+ } else {
777
+ log2(`Extracting full map`);
778
+ map = generator.getMap();
779
+ }
780
+ map = { env, ...map };
781
+ log2(`${JSON.stringify(map, null, 2)}`);
782
+ if (!await canWrite(mapFile))
783
+ throw new JspmError(
784
+ `JSPM does not have permission to write to ${mapFile}.`
785
+ );
786
+ try {
787
+ const existing = JSON.parse(await fs2.readFile(mapFile, "utf8"));
788
+ map = Object.assign({}, existing, map);
789
+ } catch {
790
+ }
791
+ await fs2.writeFile(
792
+ mapFile,
793
+ flags.compact ? JSON.stringify(map) : JSON.stringify(map, null, 2)
794
+ );
795
+ const mapFileRel = path.relative(process.cwd(), mapFile);
796
+ !silent && console.warn(`${c3.green("Ok:")} Updated ${c3.cyan(mapFileRel)}`);
797
+ return map;
798
+ }
799
+ async function getGenerator(flags, setEnv = true) {
800
+ const log2 = withType("utils/getGenerator");
801
+ const mapUrl = getOutputMapUrl(flags);
802
+ const rootUrl = getRootUrl(flags);
803
+ const baseUrl = new URL(path.dirname(mapUrl.href));
804
+ log2(
805
+ `Creating generator with mapUrl ${mapUrl}, baseUrl ${baseUrl}, rootUrl ${rootUrl}`
806
+ );
807
+ return new Generator({
808
+ mapUrl,
809
+ baseUrl,
810
+ rootUrl,
811
+ inputMap: await getInputMap(flags),
812
+ env: setEnv ? await getEnv(flags) : void 0,
813
+ defaultProvider: getProvider(flags),
814
+ resolutions: getResolutions(flags),
815
+ cache: getCacheMode(flags),
816
+ freeze: flags.freeze,
817
+ commonJS: true
818
+ // TODO: only for --local flag
819
+ });
820
+ }
821
+ async function getInput(flags) {
822
+ const mapFile = getInputPath(flags);
823
+ if (!await exists(mapFile))
824
+ return void 0;
825
+ if (!await canRead(mapFile)) {
826
+ if (mapFile === defaultInputPath)
827
+ return void 0;
828
+ else
829
+ throw new JspmError(`JSPM does not have permission to read ${mapFile}.`);
830
+ }
831
+ return fs2.readFile(mapFile, "utf-8");
832
+ }
833
+ async function getInputMap(flags) {
834
+ let inputMap;
835
+ const input = await getInput(flags);
836
+ const mapUrl = getOutputMapUrl(flags);
837
+ if (input) {
838
+ try {
839
+ inputMap = JSON.parse(input);
840
+ } catch {
841
+ try {
842
+ const analysis = analyzeHtml(input, mapUrl);
843
+ inputMap = analysis.map;
844
+ } catch {
845
+ throw new JspmError(
846
+ `Input map "${getInputPath(
847
+ flags
848
+ )}" is neither a valid JSON or a HTML file containing an inline import map.`
849
+ );
850
+ }
851
+ }
852
+ }
853
+ return inputMap || {};
854
+ }
855
+ function getInputPath(flags) {
856
+ return path.resolve(process.cwd(), flags.map || defaultInputPath);
857
+ }
858
+ function getOutputPath(flags) {
859
+ return path.resolve(
860
+ process.cwd(),
861
+ flags.output || flags.map || defaultInputPath
862
+ );
863
+ }
864
+ function getOutputMapUrl(flags) {
865
+ return pathToFileURL(getOutputPath(flags));
866
+ }
867
+ function getRootUrl(flags) {
868
+ if (!flags.root)
869
+ return void 0;
870
+ return pathToFileURL(path.resolve(process.cwd(), flags.root));
871
+ }
872
+ var excludeDefinitions = {
873
+ production: ["development"],
874
+ development: ["production"],
875
+ node: ["browser", "deno"],
876
+ deno: ["node", "browser"],
877
+ browser: ["node", "deno"]
878
+ };
879
+ function removeEnvs(env, removeEnvs2) {
880
+ for (const removeEnv of removeEnvs2) {
881
+ if (env.includes(removeEnv))
882
+ env.splice(env.indexOf(removeEnv), 1);
883
+ }
884
+ return env.sort();
885
+ }
886
+ function addEnvs(env, newEnvs) {
887
+ let excludeEnvs = [];
888
+ for (const newEnv of newEnvs) {
889
+ if (!env.includes(newEnv))
890
+ env.push(newEnv);
891
+ const excludes = excludeDefinitions[newEnv];
892
+ if (excludes)
893
+ excludeEnvs = excludeEnvs.concat(excludes);
894
+ }
895
+ for (const exclude of excludeEnvs) {
896
+ if (env.includes(exclude) && !newEnvs.includes(exclude))
897
+ env.splice(env.indexOf(exclude), 1);
898
+ }
899
+ return env.sort();
900
+ }
901
+ async function getEnv(flags) {
902
+ const inputMap = await getInputMap(flags);
903
+ const envFlags = Array.isArray(flags.env) ? flags.env : (flags.env || "").split(",").map((e) => e.trim()).filter(Boolean);
904
+ let env = inputMap.env || ["development", "browser", "module"];
905
+ env = removeEnvs(
906
+ env,
907
+ envFlags.filter((env2) => env2.startsWith("no-")).map((env2) => env2.slice(3))
908
+ );
909
+ env = addEnvs(
910
+ env,
911
+ envFlags.filter((env2) => !env2.startsWith("no-"))
912
+ );
913
+ return removeNonStaticEnvKeys(env);
914
+ }
915
+ function getProvider(flags) {
916
+ if (flags.provider && !availableProviders.includes(flags.provider))
917
+ throw new JspmError(
918
+ `Invalid provider "${flags.provider}". Available providers are: "${availableProviders.join('", "')}".`
919
+ );
920
+ return flags.provider;
921
+ }
922
+ function removeNonStaticEnvKeys(env) {
923
+ return env.filter(
924
+ (e) => e !== "import" && e !== "require" && e !== "default"
925
+ );
926
+ }
927
+ function getResolutions(flags) {
928
+ if (!flags.resolution)
929
+ return;
930
+ const resolutions = Array.isArray(flags.resolution) ? flags.resolution : flags.resolution.split(",").map((r) => r.trim());
931
+ return Object.fromEntries(
932
+ resolutions.map((resolution) => {
933
+ if (!resolution.includes("=")) {
934
+ throw new JspmError(
935
+ `Resolutions must be mappings from package names to package versions or specifiers, such as ${c3.bold(
936
+ "--resolution pkg=1.2.3"
937
+ )} or ${c3.bold("--resolution pkg=npm:other@1.2.3")}`
938
+ );
939
+ }
940
+ return resolution.split("=");
941
+ })
942
+ );
943
+ }
944
+ var validCacheModes = ["online", "offline", "no-cache"];
945
+ function getCacheMode(flags) {
946
+ if (!flags.cache)
947
+ return true;
948
+ if (!validCacheModes.includes(flags.cache))
949
+ throw new JspmError(
950
+ `Invalid cache mode "${flags.cache}". Available modes are: "${validCacheModes.join('", "')}".
951
+ ${c3.bold(
952
+ "online"
953
+ )} Use a locally cached module if available and fresh.
954
+ ${c3.bold(
955
+ "offline"
956
+ )} Use a locally cached module if available, even if stale.
957
+ ${c3.bold(
958
+ "no-cache"
959
+ )} Never use the local cache.`
960
+ );
961
+ if (flags.cache === "offline")
962
+ return "offline";
963
+ if (flags.cache === "online")
964
+ return true;
965
+ return false;
966
+ }
967
+ var spinner = ora({ spinner: "dots" });
968
+ function startSpinner(text) {
969
+ spinner.start(text);
970
+ }
971
+ function stopSpinner() {
972
+ spinner.stop();
973
+ }
974
+ async function exists(file) {
975
+ try {
976
+ await fs2.access(file);
977
+ return true;
978
+ } catch (e) {
979
+ return false;
980
+ }
981
+ }
982
+ async function canRead(file) {
983
+ try {
984
+ await fs2.access(file, (fs2.constants || fs2).R_OK);
985
+ return true;
986
+ } catch (e) {
987
+ return false;
988
+ }
989
+ }
990
+ async function canWrite(file) {
991
+ try {
992
+ if (!await exists(file))
993
+ return true;
994
+ await fs2.access(file, (fs2.constants || fs2).W_OK);
995
+ return true;
996
+ } catch (e) {
997
+ return false;
998
+ }
999
+ }
1000
+ function isUrlLikeNotPackage(spec) {
1001
+ if (spec.endsWith("/"))
1002
+ return false;
1003
+ if (spec.startsWith("./") || spec.startsWith("../") || spec.startsWith("/"))
1004
+ return true;
1005
+ try {
1006
+ new URL(spec);
1007
+ return spec[spec.indexOf(":") + 1] === "/";
1008
+ } catch {
1009
+ return false;
1010
+ }
1011
+ }
1012
+
1013
+ // src/install.ts
1014
+ async function install(packages, flags) {
1015
+ const log2 = withType("install/install");
1016
+ log2(`Installing packages: ${packages.join(", ")}`);
1017
+ log2(`Flags: ${JSON.stringify(flags)}`);
1018
+ const isInstallable = (p) => !isUrlLikeNotPackage(p.target);
1019
+ const parsedPackages = packages.map((p) => {
1020
+ if (!p.includes("="))
1021
+ return { target: p };
1022
+ const [alias, target] = p.split("=");
1023
+ return { alias, target };
1024
+ });
1025
+ const resolvedPackages = parsedPackages.filter(isInstallable);
1026
+ const urlLikePackages = parsedPackages.filter((p) => !isInstallable(p));
1027
+ const env = await getEnv(flags);
1028
+ const input = await getInput(flags);
1029
+ const generator = await getGenerator(flags);
1030
+ let pins = [];
1031
+ if (input) {
1032
+ pins = await generator.addMappings(input);
1033
+ }
1034
+ if (urlLikePackages?.length) {
1035
+ const imports = {};
1036
+ for (const { alias, target } of urlLikePackages) {
1037
+ if (!alias)
1038
+ throw new JspmError(`URL-like target "${target}" must be given an alias to install under, such as "name=${target}".`);
1039
+ imports[alias] = target;
1040
+ }
1041
+ pins.push(...await generator.addMappings(JSON.stringify({ imports })));
1042
+ }
1043
+ log2(`Input map parsed: ${input}`);
1044
+ if (resolvedPackages.length) {
1045
+ !flags.silent && startSpinner(
1046
+ `Installing ${c4.bold(
1047
+ resolvedPackages.map((p) => p.alias || p.target).join(", ")
1048
+ )}. (${env.join(", ")})`
1049
+ );
1050
+ await generator.install(resolvedPackages);
1051
+ stopSpinner();
1052
+ } else if (pins.length) {
1053
+ !flags.silent && startSpinner(`Reinstalling all top-level imports.`);
1054
+ await generator.install();
1055
+ stopSpinner();
1056
+ } else {
1057
+ !flags.silent && console.warn(
1058
+ `${c4.red(
1059
+ "Warning:"
1060
+ )} Nothing to install, outputting an empty import map. Either provide a list of package to install, or a non-empty input file.`
1061
+ );
1062
+ }
1063
+ return await writeOutput(generator, null, env, flags, flags.silent);
1064
+ }
1065
+
1066
+ // src/link.ts
1067
+ import * as fs3 from "node:fs/promises";
1068
+ import { pathToFileURL as pathToFileURL2 } from "url";
1069
+ import c5 from "picocolors";
1070
+ async function link(modules, flags) {
1071
+ const log2 = withType("link/link");
1072
+ log2(`Linking modules: ${modules.join(", ")}`);
1073
+ log2(`Flags: ${JSON.stringify(flags)}`);
1074
+ const env = await getEnv(flags);
1075
+ const inputMapPath = getInputPath(flags);
1076
+ const outputMapPath = getOutputPath(flags);
1077
+ const generator = await getGenerator(flags);
1078
+ const inlinePins = [];
1079
+ const resolvedModules = (await Promise.all(
1080
+ modules.map((spec) => resolveModule(spec, inlinePins, generator))
1081
+ )).filter((m) => !!m);
1082
+ const input = await getInput(flags);
1083
+ const pins = inlinePins.concat(resolvedModules.map((p) => p.target));
1084
+ let allPins = pins;
1085
+ if (input) {
1086
+ allPins = pins.concat(await generator.addMappings(input));
1087
+ }
1088
+ log2(`Input map parsed: ${input}`);
1089
+ log2(`Trace installing: ${allPins.concat(pins).join(", ")}`);
1090
+ if (allPins.length) {
1091
+ if (modules.length === 0) {
1092
+ !flags.silent && startSpinner(`Linking input.`);
1093
+ } else {
1094
+ !flags.silent && startSpinner(
1095
+ `Linking ${c5.bold(
1096
+ resolvedModules.map((p) => p.alias || p.target).join(", ")
1097
+ )}. (${env.join(", ")})`
1098
+ );
1099
+ }
1100
+ await generator.link(allPins.concat(pins));
1101
+ stopSpinner();
1102
+ } else {
1103
+ !flags.silent && console.warn(
1104
+ `${c5.red(
1105
+ "Warning:"
1106
+ )} Found nothing to link, will default to relinking input map. Provide a list of modules or HTML files with inline modules to change this behaviour.`
1107
+ );
1108
+ }
1109
+ if (inputMapPath !== outputMapPath && modules.length !== 0) {
1110
+ return await writeOutput(generator, pins, env, flags, flags.silent);
1111
+ } else {
1112
+ return await writeOutput(generator, null, env, flags, flags.silent);
1113
+ }
1114
+ }
1115
+ async function resolveModule(p, inlinePins, generator) {
1116
+ const log2 = withType("link/resolveModule");
1117
+ let res;
1118
+ if (p.includes("=")) {
1119
+ const [alias, target] = p.split("=");
1120
+ res = { alias, target };
1121
+ } else {
1122
+ res = { target: p };
1123
+ }
1124
+ if (res.target.startsWith("%")) {
1125
+ log2(`Resolving target '${res.target}' as '${res.target.slice(1)}'`);
1126
+ res.target = res.target.slice(1);
1127
+ } else {
1128
+ try {
1129
+ await fs3.access(res.target);
1130
+ const targetPath = res.target.startsWith(".") || res.target.startsWith("/") ? res.target : `./${res.target}`;
1131
+ log2(`Resolving target '${res.target}' as '${targetPath}'`);
1132
+ res.target = targetPath;
1133
+ return handleLocalFile(res, inlinePins, generator);
1134
+ } catch (e) {
1135
+ }
1136
+ }
1137
+ return res;
1138
+ }
1139
+ async function handleLocalFile(resolvedModule, inlinePins, generator) {
1140
+ const source = await fs3.readFile(resolvedModule.target, { encoding: "utf8" });
1141
+ const { default: babel } = await import("@babel/core");
1142
+ try {
1143
+ babel.parse(source);
1144
+ return resolvedModule;
1145
+ } catch (e) {
1146
+ }
1147
+ const targetUrl = pathToFileURL2(resolvedModule.target);
1148
+ let pins;
1149
+ try {
1150
+ pins = await generator.linkHtml(source, targetUrl);
1151
+ } catch (e) {
1152
+ if (e?.jspmError) {
1153
+ e.message += `, linking HTML file "${resolvedModule.target}"`;
1154
+ }
1155
+ throw e;
1156
+ }
1157
+ if (!pins || pins.length === 0) {
1158
+ throw new Error("No inline HTML modules found to link.");
1159
+ }
1160
+ inlinePins.push(...pins);
1161
+ }
1162
+
1163
+ // src/uninstall.ts
1164
+ import c6 from "picocolors";
1165
+ async function uninstall(packages, flags) {
1166
+ const log2 = withType("install/install");
1167
+ log2(`Uninstalling packages: ${packages.join(", ")}`);
1168
+ log2(`Flags: ${JSON.stringify(flags)}`);
1169
+ if (packages.length === 0) {
1170
+ !flags.silent && console.warn(
1171
+ `${c6.red(
1172
+ "Warning:"
1173
+ )} Nothing to uninstall. Please provide a list of packages.`
1174
+ );
1175
+ return;
1176
+ }
1177
+ const env = await getEnv(flags);
1178
+ const input = await getInput(flags);
1179
+ const generator = await getGenerator(flags);
1180
+ if (typeof input !== "undefined")
1181
+ await generator.addMappings(input);
1182
+ log2(`Input map parsed: ${input}`);
1183
+ !flags.silent && startSpinner(
1184
+ `Uninstalling ${c6.bold(packages.join(", "))}. (${env.join(", ")})`
1185
+ );
1186
+ await generator.uninstall(packages);
1187
+ stopSpinner();
1188
+ return await writeOutput(generator, null, env, flags, flags.silent);
1189
+ }
1190
+
1191
+ // src/update.ts
1192
+ import c7 from "picocolors";
1193
+ async function update(packages, flags) {
1194
+ const log2 = withType("update/update");
1195
+ log2(`Updating packages: ${packages.join(", ")}`);
1196
+ log2(`Flags: ${JSON.stringify(flags)}`);
1197
+ const env = await getEnv(flags);
1198
+ const generator = await getGenerator(flags);
1199
+ let inputPins = [];
1200
+ const input = await getInput(flags);
1201
+ if (typeof input !== "undefined") {
1202
+ inputPins = await generator.addMappings(input);
1203
+ }
1204
+ log2(`Input map parsed: ${input}`);
1205
+ if (packages.length === 0 && inputPins.length === 0) {
1206
+ !flags.silent && console.warn(
1207
+ `${c7.red(
1208
+ "Warning:"
1209
+ )} Nothing to update. Please provide a list of packages or a non-empty input file.`
1210
+ );
1211
+ return;
1212
+ } else {
1213
+ !flags.silent && startSpinner(
1214
+ `Updating ${c7.bold(
1215
+ packages.length ? packages.join(", ") : "everything"
1216
+ )}. (${env.join(", ")})`
1217
+ );
1218
+ await generator.update(packages.length ? packages : void 0);
1219
+ stopSpinner();
1220
+ }
1221
+ return await writeOutput(generator, null, env, flags, flags.silent);
1222
+ }
1223
+
1224
+ // src/cli.ts
1225
+ var cli = dist_default(c8.yellow("jspm"));
1226
+ var mapOpt = [
1227
+ "-m, --map <file>",
1228
+ "File containing initial import map",
1229
+ { default: "importmap.json" }
1230
+ ];
1231
+ var envOpt = [
1232
+ "-e, --env <environments>",
1233
+ "Comma-separated environment condition overrides",
1234
+ {}
1235
+ ];
1236
+ var resolutionOpt = [
1237
+ "-r, --resolution <resolutions>",
1238
+ "Comma-separated dependency resolution overrides",
1239
+ {}
1240
+ ];
1241
+ var providerOpt = [
1242
+ "-p, --provider <provider>",
1243
+ "Default module provider",
1244
+ {}
1245
+ ];
1246
+ var stdoutOpt = [
1247
+ "--stdout",
1248
+ "Output the import map to stdout",
1249
+ { default: false }
1250
+ ];
1251
+ var compactOpt = [
1252
+ "--compact",
1253
+ "Output a compact import map",
1254
+ { default: false }
1255
+ ];
1256
+ var outputOpt = [
1257
+ "-o, --output <file>",
1258
+ "File to inject the final import map into (default: --map / importmap.json)",
1259
+ {}
1260
+ ];
1261
+ var preloadOpt = [
1262
+ "--preload",
1263
+ "Add module preloads to HTML output",
1264
+ { default: false }
1265
+ ];
1266
+ var integrityOpt = [
1267
+ "--integrity",
1268
+ "Add module preloads with integrity attributes to HTML output",
1269
+ { default: false }
1270
+ ];
1271
+ var cacheOpt = [
1272
+ "--cache <mode>",
1273
+ "Cache mode for fetches (online, offline, no-cache)",
1274
+ { default: "online" }
1275
+ ];
1276
+ var rootOpt = [
1277
+ "--root <url>",
1278
+ "URL to treat as server root, i.e. rebase import maps against",
1279
+ {}
1280
+ ];
1281
+ var freezeOpt = [
1282
+ "--freeze",
1283
+ "Freeze input map dependencies, i.e. do not modify them",
1284
+ { default: false }
1285
+ ];
1286
+ var silentOpt = ["--silent", "Silence all output", { default: false }];
1287
+ cli.option(...silentOpt).version(version).help(defaultHelpCb);
1288
+ cli.command("[...args]").allowUnknownOptions().usage("[command] [options]").action(
1289
+ wrapCommand((args) => {
1290
+ if (!args.length)
1291
+ return cli.outputHelp();
1292
+ throw new JspmError(
1293
+ `Unknown command: ${args[0]}
1294
+ Run "jspm" without any arguments to see the help file.`
1295
+ );
1296
+ })
1297
+ );
1298
+ cli.command("link [...modules]", "link modules").alias("trace").option(...mapOpt).option(...outputOpt).option(...envOpt).option(...resolutionOpt).option(...providerOpt).option(...cacheOpt).option(...rootOpt).option(...integrityOpt).option(...preloadOpt).option(...compactOpt).option(...freezeOpt).option(...stdoutOpt).example(
1299
+ (name) => `Link a remote package in importmap.json
1300
+ $ ${name} link chalk@5.2.0
1301
+ `
1302
+ ).example(
1303
+ (name) => `Link a local module
1304
+ $ ${name} link ./src/cli.js
1305
+ `
1306
+ ).example(
1307
+ (name) => `Link an HTML file and update its import map including preload and integrity tags
1308
+ $ ${name} link --map index.html --integrity --preload
1309
+ `
1310
+ ).usage(
1311
+ `link [flags] [...modules]
1312
+
1313
+ Traces and installs all dependencies necessary to execute the given modules into an import map, including both static and dynamic module imports. The given modules can be:
1314
+ 1. Paths to local JavaScript modules, such as "./src/my-module.mjs".
1315
+ 2. Paths to local HTML files, such as "index.html", in which case all module scripts in the file are linked.
1316
+ 3. Valid package specifiers, such as \`react\` or \`chalk@5.2.0\`, in which case the package's main export is linked.
1317
+ 4. Valid package specifiers with subpaths, such as \`sver@1.1.1/convert-range\`, in which case the subpath is resolved against the package's exports and the resulting module is linked.
1318
+
1319
+ In some cases there may be ambiguity. For instance, you may want to link the NPM package "app.js", but your working directory contains a local file called "app.js" as well. In these cases local files are preferred by default, and external packages must be prefixed with the "%" character (i.e. "%app.js").
1320
+
1321
+ If no modules are given, all "imports" in the initial map are relinked.`
1322
+ ).action(wrapCommand(link));
1323
+ cli.command("install [...packages]", "install packages").alias("i").option(...mapOpt).option(...outputOpt).option(...envOpt).option(...resolutionOpt).option(...providerOpt).option(...cacheOpt).option(...rootOpt).option(...integrityOpt).option(...preloadOpt).option(...compactOpt).option(...freezeOpt).option(...stdoutOpt).example(
1324
+ (name) => `Install a package
1325
+ $ ${name} install lit
1326
+ `
1327
+ ).example(
1328
+ (name) => `Install a versioned package and subpath
1329
+ $ ${name} install npm:lit@2.2.0/decorators.js
1330
+ `
1331
+ ).example(
1332
+ (name) => `Install a versioned package
1333
+ $ ${name} install npm:react@18.2.0
1334
+ `
1335
+ ).example(
1336
+ (name) => `Install a Denoland package and use the Deno provider
1337
+ $ ${name} install -p deno denoload:oak
1338
+ `
1339
+ ).example(
1340
+ (name) => `Install "alias" as an alias of the resolution react
1341
+ $ ${name} install alias=react
1342
+ `
1343
+ ).usage(
1344
+ `link [flags] [...packages]
1345
+
1346
+ Installs packages into an import map, along with all of the dependencies that are necessary to import them.By default, the latest versions of the packages that are compatible with the local "package.json" are installed, unless an explicit version is specified. The given packages must be valid package specifiers, such as \`npm:react@18.0.0\` or \`denoland:oak\`. If a package specifier with no registry is given, such as \`lit\`, the registry is assumed to be NPM. Packages can be installed under an alias by using specifiers such as \`myname=npm:lit@2.1.0\`. An optional subpath can be provided, such as \`npm:lit@2.2.0/decorators.js\`, in which case only the dependencies for that subpath are installed.
1347
+
1348
+ If no packages are provided, all "imports" in the initial map are reinstalled.`
1349
+ ).action(wrapCommand(install));
1350
+ cli.command("uninstall [...packages]", "remove packages").option(...mapOpt).option(...outputOpt).option(...envOpt).option(...resolutionOpt).option(...providerOpt).option(...cacheOpt).option(...rootOpt).option(...integrityOpt).option(...preloadOpt).option(...compactOpt).option(...freezeOpt).option(...stdoutOpt).example(
1351
+ (name) => `
1352
+ $ ${name} uninstall lit lodash
1353
+
1354
+ Uninstall "lit" and "lodash" from importmap.json.
1355
+ `
1356
+ ).usage(
1357
+ `uninstall [flags] [...packages]
1358
+
1359
+ Uninstalls packages from an import map. The given packages must be valid package specifiers, such as \`npm:react@18.0.0\`, \`denoland:oak\` or \`lit\`, and must be present in the initial import map.`
1360
+ ).action(wrapCommand(uninstall));
1361
+ cli.command("update [...packages]", "update packages").alias("upgrade").option(...mapOpt).option(...outputOpt).option(...envOpt).option(...resolutionOpt).option(...providerOpt).option(...cacheOpt).option(...rootOpt).option(...integrityOpt).option(...preloadOpt).option(...compactOpt).option(...freezeOpt).option(...stdoutOpt).example(
1362
+ (name) => `
1363
+ $ ${name} update react-dom
1364
+
1365
+ Update the react-dom package.
1366
+ `
1367
+ ).usage(
1368
+ `update [flags] [...packages]
1369
+
1370
+ Updates packages in an import map to the latest versions that are compatible with the local \`package.json\`. The given packages must be valid package specifiers, such as \`npm:react@18.0.0\`, \`denoland:oak\` or \`lit\`, and must be present in the initial import map.`
1371
+ ).action(wrapCommand(update));
1372
+ cli.command("clear-cache", "clear the local package cache").usage(
1373
+ `clear-cache
1374
+
1375
+ Clears the global module fetch cache, for situations where the contents of a dependency may have changed without a version bump. This can happen during local development, for instance.`
1376
+ ).alias("cc").action(wrapCommand(clearCache));
1377
+ function defaultHelpCb(helpSections) {
1378
+ for (const section of Object.values(helpSections)) {
1379
+ if (section.title === "Commands") {
1380
+ section.body = section.body.split("\n").slice(1).join("\n");
1381
+ }
1382
+ }
1383
+ for (const section of Object.values(helpSections)) {
1384
+ if (section.title)
1385
+ section.title = c8.bold(section.title);
1386
+ }
1387
+ return helpSections;
1388
+ }
1389
+ export {
1390
+ cli
1391
+ };