index.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.jack = exports.Jack = exports.isConfigOption = exports.isConfigType = void 0;
  7. const node_util_1 = require("node:util");
  8. const parse_args_js_1 = require("./parse-args.js");
  9. // it's a tiny API, just cast it inline, it's fine
  10. //@ts-ignore
  11. const cliui_1 = __importDefault(require("@isaacs/cliui"));
  12. const node_path_1 = require("node:path");
  13. const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80);
  14. // indentation spaces from heading level
  15. const indent = (n) => (n - 1) * 2;
  16. const toEnvKey = (pref, key) => {
  17. return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')]
  18. .join(' ')
  19. .trim()
  20. .toUpperCase()
  21. .replace(/ /g, '_');
  22. };
  23. const toEnvVal = (value, delim = '\n') => {
  24. const str = typeof value === 'string' ? value
  25. : typeof value === 'boolean' ?
  26. value ? '1'
  27. : '0'
  28. : typeof value === 'number' ? String(value)
  29. : Array.isArray(value) ?
  30. value.map((v) => toEnvVal(v)).join(delim)
  31. : /* c8 ignore start */ undefined;
  32. if (typeof str !== 'string') {
  33. throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`);
  34. }
  35. /* c8 ignore stop */
  36. return str;
  37. };
  38. const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ?
  39. env ? env.split(delim).map(v => fromEnvVal(v, type, false))
  40. : []
  41. : type === 'string' ? env
  42. : type === 'boolean' ? env === '1'
  43. : +env.trim());
  44. const isConfigType = (t) => typeof t === 'string' &&
  45. (t === 'string' || t === 'number' || t === 'boolean');
  46. exports.isConfigType = isConfigType;
  47. const undefOrType = (v, t) => v === undefined || typeof v === t;
  48. const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t));
  49. const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v);
  50. // print the value type, for error message reporting
  51. const valueType = (v) => typeof v === 'string' ? 'string'
  52. : typeof v === 'boolean' ? 'boolean'
  53. : typeof v === 'number' ? 'number'
  54. : Array.isArray(v) ?
  55. joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]'
  56. : `${v.type}${v.multiple ? '[]' : ''}`;
  57. const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ?
  58. types[0]
  59. : `(${types.join('|')})`;
  60. const isValidValue = (v, type, multi) => {
  61. if (multi) {
  62. if (!Array.isArray(v))
  63. return false;
  64. return !v.some((v) => !isValidValue(v, type, false));
  65. }
  66. if (Array.isArray(v))
  67. return false;
  68. return typeof v === type;
  69. };
  70. const isConfigOption = (o, type, multi) => !!o &&
  71. typeof o === 'object' &&
  72. (0, exports.isConfigType)(o.type) &&
  73. o.type === type &&
  74. undefOrType(o.short, 'string') &&
  75. undefOrType(o.description, 'string') &&
  76. undefOrType(o.hint, 'string') &&
  77. undefOrType(o.validate, 'function') &&
  78. (o.type === 'boolean' ?
  79. o.validOptions === undefined
  80. : undefOrTypeArray(o.validOptions, o.type)) &&
  81. (o.default === undefined || isValidValue(o.default, type, multi)) &&
  82. !!o.multiple === multi;
  83. exports.isConfigOption = isConfigOption;
  84. function num(o = {}) {
  85. const { default: def, validate: val, validOptions, ...rest } = o;
  86. if (def !== undefined && !isValidValue(def, 'number', false)) {
  87. throw new TypeError('invalid default value', {
  88. cause: {
  89. found: def,
  90. wanted: 'number',
  91. },
  92. });
  93. }
  94. if (!undefOrTypeArray(validOptions, 'number')) {
  95. throw new TypeError('invalid validOptions', {
  96. cause: {
  97. found: validOptions,
  98. wanted: 'number[]',
  99. },
  100. });
  101. }
  102. const validate = val ?
  103. val
  104. : undefined;
  105. return {
  106. ...rest,
  107. default: def,
  108. validate,
  109. validOptions,
  110. type: 'number',
  111. multiple: false,
  112. };
  113. }
  114. function numList(o = {}) {
  115. const { default: def, validate: val, validOptions, ...rest } = o;
  116. if (def !== undefined && !isValidValue(def, 'number', true)) {
  117. throw new TypeError('invalid default value', {
  118. cause: {
  119. found: def,
  120. wanted: 'number[]',
  121. },
  122. });
  123. }
  124. if (!undefOrTypeArray(validOptions, 'number')) {
  125. throw new TypeError('invalid validOptions', {
  126. cause: {
  127. found: validOptions,
  128. wanted: 'number[]',
  129. },
  130. });
  131. }
  132. const validate = val ?
  133. val
  134. : undefined;
  135. return {
  136. ...rest,
  137. default: def,
  138. validate,
  139. validOptions,
  140. type: 'number',
  141. multiple: true,
  142. };
  143. }
  144. function opt(o = {}) {
  145. const { default: def, validate: val, validOptions, ...rest } = o;
  146. if (def !== undefined && !isValidValue(def, 'string', false)) {
  147. throw new TypeError('invalid default value', {
  148. cause: {
  149. found: def,
  150. wanted: 'string',
  151. },
  152. });
  153. }
  154. if (!undefOrTypeArray(validOptions, 'string')) {
  155. throw new TypeError('invalid validOptions', {
  156. cause: {
  157. found: validOptions,
  158. wanted: 'string[]',
  159. },
  160. });
  161. }
  162. const validate = val ?
  163. val
  164. : undefined;
  165. return {
  166. ...rest,
  167. default: def,
  168. validate,
  169. validOptions,
  170. type: 'string',
  171. multiple: false,
  172. };
  173. }
  174. function optList(o = {}) {
  175. const { default: def, validate: val, validOptions, ...rest } = o;
  176. if (def !== undefined && !isValidValue(def, 'string', true)) {
  177. throw new TypeError('invalid default value', {
  178. cause: {
  179. found: def,
  180. wanted: 'string[]',
  181. },
  182. });
  183. }
  184. if (!undefOrTypeArray(validOptions, 'string')) {
  185. throw new TypeError('invalid validOptions', {
  186. cause: {
  187. found: validOptions,
  188. wanted: 'string[]',
  189. },
  190. });
  191. }
  192. const validate = val ?
  193. val
  194. : undefined;
  195. return {
  196. ...rest,
  197. default: def,
  198. validate,
  199. validOptions,
  200. type: 'string',
  201. multiple: true,
  202. };
  203. }
  204. function flag(o = {}) {
  205. const { hint, default: def, validate: val, ...rest } = o;
  206. delete rest.validOptions;
  207. if (def !== undefined && !isValidValue(def, 'boolean', false)) {
  208. throw new TypeError('invalid default value');
  209. }
  210. const validate = val ?
  211. val
  212. : undefined;
  213. if (hint !== undefined) {
  214. throw new TypeError('cannot provide hint for flag');
  215. }
  216. return {
  217. ...rest,
  218. default: def,
  219. validate,
  220. type: 'boolean',
  221. multiple: false,
  222. };
  223. }
  224. function flagList(o = {}) {
  225. const { hint, default: def, validate: val, ...rest } = o;
  226. delete rest.validOptions;
  227. if (def !== undefined && !isValidValue(def, 'boolean', true)) {
  228. throw new TypeError('invalid default value');
  229. }
  230. const validate = val ?
  231. val
  232. : undefined;
  233. if (hint !== undefined) {
  234. throw new TypeError('cannot provide hint for flag list');
  235. }
  236. return {
  237. ...rest,
  238. default: def,
  239. validate,
  240. type: 'boolean',
  241. multiple: true,
  242. };
  243. }
  244. const toParseArgsOptionsConfig = (options) => {
  245. const c = {};
  246. for (const longOption in options) {
  247. const config = options[longOption];
  248. /* c8 ignore start */
  249. if (!config) {
  250. throw new Error('config must be an object: ' + longOption);
  251. }
  252. /* c8 ignore start */
  253. if ((0, exports.isConfigOption)(config, 'number', true)) {
  254. c[longOption] = {
  255. type: 'string',
  256. multiple: true,
  257. default: config.default?.map(c => String(c)),
  258. };
  259. }
  260. else if ((0, exports.isConfigOption)(config, 'number', false)) {
  261. c[longOption] = {
  262. type: 'string',
  263. multiple: false,
  264. default: config.default === undefined ?
  265. undefined
  266. : String(config.default),
  267. };
  268. }
  269. else {
  270. const conf = config;
  271. c[longOption] = {
  272. type: conf.type,
  273. multiple: !!conf.multiple,
  274. default: conf.default,
  275. };
  276. }
  277. const clo = c[longOption];
  278. if (typeof config.short === 'string') {
  279. clo.short = config.short;
  280. }
  281. if (config.type === 'boolean' &&
  282. !longOption.startsWith('no-') &&
  283. !options[`no-${longOption}`]) {
  284. c[`no-${longOption}`] = {
  285. type: 'boolean',
  286. multiple: config.multiple,
  287. };
  288. }
  289. }
  290. return c;
  291. };
  292. const isHeading = (r) => r.type === 'heading';
  293. const isDescription = (r) => r.type === 'description';
  294. /**
  295. * Class returned by the {@link jack} function and all configuration
  296. * definition methods. This is what gets chained together.
  297. */
  298. class Jack {
  299. #configSet;
  300. #shorts;
  301. #options;
  302. #fields = [];
  303. #env;
  304. #envPrefix;
  305. #allowPositionals;
  306. #usage;
  307. #usageMarkdown;
  308. constructor(options = {}) {
  309. this.#options = options;
  310. this.#allowPositionals = options.allowPositionals !== false;
  311. this.#env =
  312. this.#options.env === undefined ? process.env : this.#options.env;
  313. this.#envPrefix = options.envPrefix;
  314. // We need to fib a little, because it's always the same object, but it
  315. // starts out as having an empty config set. Then each method that adds
  316. // fields returns `this as Jack<C & { ...newConfigs }>`
  317. this.#configSet = Object.create(null);
  318. this.#shorts = Object.create(null);
  319. }
  320. /**
  321. * Set the default value (which will still be overridden by env or cli)
  322. * as if from a parsed config file. The optional `source` param, if
  323. * provided, will be included in error messages if a value is invalid or
  324. * unknown.
  325. */
  326. setConfigValues(values, source = '') {
  327. try {
  328. this.validate(values);
  329. }
  330. catch (er) {
  331. const e = er;
  332. if (source && e && typeof e === 'object') {
  333. if (e.cause && typeof e.cause === 'object') {
  334. Object.assign(e.cause, { path: source });
  335. }
  336. else {
  337. e.cause = { path: source };
  338. }
  339. }
  340. throw e;
  341. }
  342. for (const [field, value] of Object.entries(values)) {
  343. const my = this.#configSet[field];
  344. // already validated, just for TS's benefit
  345. /* c8 ignore start */
  346. if (!my) {
  347. throw new Error('unexpected field in config set: ' + field, {
  348. cause: { found: field },
  349. });
  350. }
  351. /* c8 ignore stop */
  352. my.default = value;
  353. }
  354. return this;
  355. }
  356. /**
  357. * Parse a string of arguments, and return the resulting
  358. * `{ values, positionals }` object.
  359. *
  360. * If an {@link JackOptions#envPrefix} is set, then it will read default
  361. * values from the environment, and write the resulting values back
  362. * to the environment as well.
  363. *
  364. * Environment values always take precedence over any other value, except
  365. * an explicit CLI setting.
  366. */
  367. parse(args = process.argv) {
  368. this.loadEnvDefaults();
  369. const p = this.parseRaw(args);
  370. this.applyDefaults(p);
  371. this.writeEnv(p);
  372. return p;
  373. }
  374. loadEnvDefaults() {
  375. if (this.#envPrefix) {
  376. for (const [field, my] of Object.entries(this.#configSet)) {
  377. const ek = toEnvKey(this.#envPrefix, field);
  378. const env = this.#env[ek];
  379. if (env !== undefined) {
  380. my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim);
  381. }
  382. }
  383. }
  384. }
  385. applyDefaults(p) {
  386. for (const [field, c] of Object.entries(this.#configSet)) {
  387. if (c.default !== undefined && !(field in p.values)) {
  388. //@ts-ignore
  389. p.values[field] = c.default;
  390. }
  391. }
  392. }
  393. /**
  394. * Only parse the command line arguments passed in.
  395. * Does not strip off the `node script.js` bits, so it must be just the
  396. * arguments you wish to have parsed.
  397. * Does not read from or write to the environment, or set defaults.
  398. */
  399. parseRaw(args) {
  400. if (args === process.argv) {
  401. args = args.slice(process._eval !== undefined ? 1 : 2);
  402. }
  403. const options = toParseArgsOptionsConfig(this.#configSet);
  404. const result = (0, parse_args_js_1.parseArgs)({
  405. args,
  406. options,
  407. // always strict, but using our own logic
  408. strict: false,
  409. allowPositionals: this.#allowPositionals,
  410. tokens: true,
  411. });
  412. const p = {
  413. values: {},
  414. positionals: [],
  415. };
  416. for (const token of result.tokens) {
  417. if (token.kind === 'positional') {
  418. p.positionals.push(token.value);
  419. if (this.#options.stopAtPositional ||
  420. this.#options.stopAtPositionalTest?.(token.value)) {
  421. p.positionals.push(...args.slice(token.index + 1));
  422. break;
  423. }
  424. }
  425. else if (token.kind === 'option') {
  426. let value = undefined;
  427. if (token.name.startsWith('no-')) {
  428. const my = this.#configSet[token.name];
  429. const pname = token.name.substring('no-'.length);
  430. const pos = this.#configSet[pname];
  431. if (pos &&
  432. pos.type === 'boolean' &&
  433. (!my ||
  434. (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) {
  435. value = false;
  436. token.name = pname;
  437. }
  438. }
  439. const my = this.#configSet[token.name];
  440. if (!my) {
  441. throw new Error(`Unknown option '${token.rawName}'. ` +
  442. `To specify a positional argument starting with a '-', ` +
  443. `place it at the end of the command after '--', as in ` +
  444. `'-- ${token.rawName}'`, {
  445. cause: {
  446. found: token.rawName + (token.value ? `=${token.value}` : ''),
  447. },
  448. });
  449. }
  450. if (value === undefined) {
  451. if (token.value === undefined) {
  452. if (my.type !== 'boolean') {
  453. throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, {
  454. cause: {
  455. name: token.rawName,
  456. wanted: valueType(my),
  457. },
  458. });
  459. }
  460. value = true;
  461. }
  462. else {
  463. if (my.type === 'boolean') {
  464. throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } });
  465. }
  466. if (my.type === 'string') {
  467. value = token.value;
  468. }
  469. else {
  470. value = +token.value;
  471. if (value !== value) {
  472. throw new Error(`Invalid value '${token.value}' provided for ` +
  473. `'${token.rawName}' option, expected number`, {
  474. cause: {
  475. name: token.rawName,
  476. found: token.value,
  477. wanted: 'number',
  478. },
  479. });
  480. }
  481. }
  482. }
  483. }
  484. if (my.multiple) {
  485. const pv = p.values;
  486. const tn = pv[token.name] ?? [];
  487. pv[token.name] = tn;
  488. tn.push(value);
  489. }
  490. else {
  491. const pv = p.values;
  492. pv[token.name] = value;
  493. }
  494. }
  495. }
  496. for (const [field, value] of Object.entries(p.values)) {
  497. const valid = this.#configSet[field]?.validate;
  498. const validOptions = this.#configSet[field]?.validOptions;
  499. let cause;
  500. if (validOptions && !isValidOption(value, validOptions)) {
  501. cause = { name: field, found: value, validOptions: validOptions };
  502. }
  503. if (valid && !valid(value)) {
  504. cause = cause || { name: field, found: value };
  505. }
  506. if (cause) {
  507. throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause });
  508. }
  509. }
  510. return p;
  511. }
  512. /**
  513. * do not set fields as 'no-foo' if 'foo' exists and both are bools
  514. * just set foo.
  515. */
  516. #noNoFields(f, val, s = f) {
  517. if (!f.startsWith('no-') || typeof val !== 'boolean')
  518. return;
  519. const yes = f.substring('no-'.length);
  520. // recurse so we get the core config key we care about.
  521. this.#noNoFields(yes, val, s);
  522. if (this.#configSet[yes]?.type === 'boolean') {
  523. throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } });
  524. }
  525. }
  526. /**
  527. * Validate that any arbitrary object is a valid configuration `values`
  528. * object. Useful when loading config files or other sources.
  529. */
  530. validate(o) {
  531. if (!o || typeof o !== 'object') {
  532. throw new Error('Invalid config: not an object', {
  533. cause: { found: o },
  534. });
  535. }
  536. const opts = o;
  537. for (const field in o) {
  538. const value = opts[field];
  539. /* c8 ignore next - for TS */
  540. if (value === undefined)
  541. continue;
  542. this.#noNoFields(field, value);
  543. const config = this.#configSet[field];
  544. if (!config) {
  545. throw new Error(`Unknown config option: ${field}`, {
  546. cause: { found: field },
  547. });
  548. }
  549. if (!isValidValue(value, config.type, !!config.multiple)) {
  550. throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, {
  551. cause: {
  552. name: field,
  553. found: value,
  554. wanted: valueType(config),
  555. },
  556. });
  557. }
  558. let cause;
  559. if (config.validOptions &&
  560. !isValidOption(value, config.validOptions)) {
  561. cause = {
  562. name: field,
  563. found: value,
  564. validOptions: config.validOptions,
  565. };
  566. }
  567. if (config.validate && !config.validate(value)) {
  568. cause = cause || { name: field, found: value };
  569. }
  570. if (cause) {
  571. throw new Error(`Invalid config value for ${field}: ${value}`, {
  572. cause,
  573. });
  574. }
  575. }
  576. }
  577. writeEnv(p) {
  578. if (!this.#env || !this.#envPrefix)
  579. return;
  580. for (const [field, value] of Object.entries(p.values)) {
  581. const my = this.#configSet[field];
  582. this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim);
  583. }
  584. }
  585. /**
  586. * Add a heading to the usage output banner
  587. */
  588. heading(text, level, { pre = false } = {}) {
  589. if (level === undefined) {
  590. level = this.#fields.some(r => isHeading(r)) ? 2 : 1;
  591. }
  592. this.#fields.push({ type: 'heading', text, level, pre });
  593. return this;
  594. }
  595. /**
  596. * Add a long-form description to the usage output at this position.
  597. */
  598. description(text, { pre } = {}) {
  599. this.#fields.push({ type: 'description', text, pre });
  600. return this;
  601. }
  602. /**
  603. * Add one or more number fields.
  604. */
  605. num(fields) {
  606. return this.#addFields(fields, num);
  607. }
  608. /**
  609. * Add one or more multiple number fields.
  610. */
  611. numList(fields) {
  612. return this.#addFields(fields, numList);
  613. }
  614. /**
  615. * Add one or more string option fields.
  616. */
  617. opt(fields) {
  618. return this.#addFields(fields, opt);
  619. }
  620. /**
  621. * Add one or more multiple string option fields.
  622. */
  623. optList(fields) {
  624. return this.#addFields(fields, optList);
  625. }
  626. /**
  627. * Add one or more flag fields.
  628. */
  629. flag(fields) {
  630. return this.#addFields(fields, flag);
  631. }
  632. /**
  633. * Add one or more multiple flag fields.
  634. */
  635. flagList(fields) {
  636. return this.#addFields(fields, flagList);
  637. }
  638. /**
  639. * Generic field definition method. Similar to flag/flagList/number/etc,
  640. * but you must specify the `type` (and optionally `multiple` and `delim`)
  641. * fields on each one, or Jack won't know how to define them.
  642. */
  643. addFields(fields) {
  644. const next = this;
  645. for (const [name, field] of Object.entries(fields)) {
  646. this.#validateName(name, field);
  647. next.#fields.push({
  648. type: 'config',
  649. name,
  650. value: field,
  651. });
  652. }
  653. Object.assign(next.#configSet, fields);
  654. return next;
  655. }
  656. #addFields(fields, fn) {
  657. const next = this;
  658. Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => {
  659. this.#validateName(name, field);
  660. const option = fn(field);
  661. next.#fields.push({
  662. type: 'config',
  663. name,
  664. value: option,
  665. });
  666. return [name, option];
  667. })));
  668. return next;
  669. }
  670. #validateName(name, field) {
  671. if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) {
  672. throw new TypeError(`Invalid option name: ${name}, ` +
  673. `must be '-' delimited ASCII alphanumeric`);
  674. }
  675. if (this.#configSet[name]) {
  676. throw new TypeError(`Cannot redefine option ${field}`);
  677. }
  678. if (this.#shorts[name]) {
  679. throw new TypeError(`Cannot redefine option ${name}, already ` +
  680. `in use for ${this.#shorts[name]}`);
  681. }
  682. if (field.short) {
  683. if (!/^[a-zA-Z0-9]$/.test(field.short)) {
  684. throw new TypeError(`Invalid ${name} short option: ${field.short}, ` +
  685. 'must be 1 ASCII alphanumeric character');
  686. }
  687. if (this.#shorts[field.short]) {
  688. throw new TypeError(`Invalid ${name} short option: ${field.short}, ` +
  689. `already in use for ${this.#shorts[field.short]}`);
  690. }
  691. this.#shorts[field.short] = name;
  692. this.#shorts[name] = name;
  693. }
  694. }
  695. /**
  696. * Return the usage banner for the given configuration
  697. */
  698. usage() {
  699. if (this.#usage)
  700. return this.#usage;
  701. let headingLevel = 1;
  702. const ui = (0, cliui_1.default)({ width });
  703. const first = this.#fields[0];
  704. let start = first?.type === 'heading' ? 1 : 0;
  705. if (first?.type === 'heading') {
  706. ui.div({
  707. padding: [0, 0, 0, 0],
  708. text: normalize(first.text),
  709. });
  710. }
  711. ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' });
  712. if (this.#options.usage) {
  713. ui.div({
  714. text: this.#options.usage,
  715. padding: [0, 0, 0, 2],
  716. });
  717. }
  718. else {
  719. const cmd = (0, node_path_1.basename)(String(process.argv[1]));
  720. const shortFlags = [];
  721. const shorts = [];
  722. const flags = [];
  723. const opts = [];
  724. for (const [field, config] of Object.entries(this.#configSet)) {
  725. if (config.short) {
  726. if (config.type === 'boolean')
  727. shortFlags.push(config.short);
  728. else
  729. shorts.push([config.short, config.hint || field]);
  730. }
  731. else {
  732. if (config.type === 'boolean')
  733. flags.push(field);
  734. else
  735. opts.push([field, config.hint || field]);
  736. }
  737. }
  738. const sf = shortFlags.length ? ' -' + shortFlags.join('') : '';
  739. const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join('');
  740. const lf = flags.map(k => ` --${k}`).join('');
  741. const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join('');
  742. const usage = `${cmd}${sf}${so}${lf}${lo}`.trim();
  743. ui.div({
  744. text: usage,
  745. padding: [0, 0, 0, 2],
  746. });
  747. }
  748. ui.div({ padding: [0, 0, 0, 0], text: '' });
  749. const maybeDesc = this.#fields[start];
  750. if (maybeDesc && isDescription(maybeDesc)) {
  751. const print = normalize(maybeDesc.text, maybeDesc.pre);
  752. start++;
  753. ui.div({ padding: [0, 0, 0, 0], text: print });
  754. ui.div({ padding: [0, 0, 0, 0], text: '' });
  755. }
  756. const { rows, maxWidth } = this.#usageRows(start);
  757. // every heading/description after the first gets indented by 2
  758. // extra spaces.
  759. for (const row of rows) {
  760. if (row.left) {
  761. // If the row is too long, don't wrap it
  762. // Bump the right-hand side down a line to make room
  763. const configIndent = indent(Math.max(headingLevel, 2));
  764. if (row.left.length > maxWidth - 3) {
  765. ui.div({ text: row.left, padding: [0, 0, 0, configIndent] });
  766. ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] });
  767. }
  768. else {
  769. ui.div({
  770. text: row.left,
  771. padding: [0, 1, 0, configIndent],
  772. width: maxWidth,
  773. }, { padding: [0, 0, 0, 0], text: row.text });
  774. }
  775. if (row.skipLine) {
  776. ui.div({ padding: [0, 0, 0, 0], text: '' });
  777. }
  778. }
  779. else {
  780. if (isHeading(row)) {
  781. const { level } = row;
  782. headingLevel = level;
  783. // only h1 and h2 have bottom padding
  784. // h3-h6 do not
  785. const b = level <= 2 ? 1 : 0;
  786. ui.div({ ...row, padding: [0, 0, b, indent(level)] });
  787. }
  788. else {
  789. ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] });
  790. }
  791. }
  792. }
  793. return (this.#usage = ui.toString());
  794. }
  795. /**
  796. * Return the usage banner markdown for the given configuration
  797. */
  798. usageMarkdown() {
  799. if (this.#usageMarkdown)
  800. return this.#usageMarkdown;
  801. const out = [];
  802. let headingLevel = 1;
  803. const first = this.#fields[0];
  804. let start = first?.type === 'heading' ? 1 : 0;
  805. if (first?.type === 'heading') {
  806. out.push(`# ${normalizeOneLine(first.text)}`);
  807. }
  808. out.push('Usage:');
  809. if (this.#options.usage) {
  810. out.push(normalizeMarkdown(this.#options.usage, true));
  811. }
  812. else {
  813. const cmd = (0, node_path_1.basename)(String(process.argv[1]));
  814. const shortFlags = [];
  815. const shorts = [];
  816. const flags = [];
  817. const opts = [];
  818. for (const [field, config] of Object.entries(this.#configSet)) {
  819. if (config.short) {
  820. if (config.type === 'boolean')
  821. shortFlags.push(config.short);
  822. else
  823. shorts.push([config.short, config.hint || field]);
  824. }
  825. else {
  826. if (config.type === 'boolean')
  827. flags.push(field);
  828. else
  829. opts.push([field, config.hint || field]);
  830. }
  831. }
  832. const sf = shortFlags.length ? ' -' + shortFlags.join('') : '';
  833. const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join('');
  834. const lf = flags.map(k => ` --${k}`).join('');
  835. const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join('');
  836. const usage = `${cmd}${sf}${so}${lf}${lo}`.trim();
  837. out.push(normalizeMarkdown(usage, true));
  838. }
  839. const maybeDesc = this.#fields[start];
  840. if (maybeDesc && isDescription(maybeDesc)) {
  841. out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre));
  842. start++;
  843. }
  844. const { rows } = this.#usageRows(start);
  845. // heading level in markdown is number of # ahead of text
  846. for (const row of rows) {
  847. if (row.left) {
  848. out.push('#'.repeat(headingLevel + 1) +
  849. ' ' +
  850. normalizeOneLine(row.left, true));
  851. if (row.text)
  852. out.push(normalizeMarkdown(row.text));
  853. }
  854. else if (isHeading(row)) {
  855. const { level } = row;
  856. headingLevel = level;
  857. out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`);
  858. }
  859. else {
  860. out.push(normalizeMarkdown(row.text, !!row.pre));
  861. }
  862. }
  863. return (this.#usageMarkdown = out.join('\n\n') + '\n');
  864. }
  865. #usageRows(start) {
  866. // turn each config type into a row, and figure out the width of the
  867. // left hand indentation for the option descriptions.
  868. let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3)));
  869. let maxWidth = 8;
  870. let prev = undefined;
  871. const rows = [];
  872. for (const field of this.#fields.slice(start)) {
  873. if (field.type !== 'config') {
  874. if (prev?.type === 'config')
  875. prev.skipLine = true;
  876. prev = undefined;
  877. field.text = normalize(field.text, !!field.pre);
  878. rows.push(field);
  879. continue;
  880. }
  881. const { value } = field;
  882. const desc = value.description || '';
  883. const mult = value.multiple ? 'Can be set multiple times' : '';
  884. const opts = value.validOptions?.length ?
  885. `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}`
  886. : '';
  887. const dmDelim = desc.includes('\n') ? '\n\n' : '\n';
  888. const extra = [opts, mult].join(dmDelim).trim();
  889. const text = (normalize(desc) + dmDelim + extra).trim();
  890. const hint = value.hint ||
  891. (value.type === 'number' ? 'n'
  892. : value.type === 'string' ? field.name
  893. : undefined);
  894. const short = !value.short ? ''
  895. : value.type === 'boolean' ? `-${value.short} `
  896. : `-${value.short}<${hint}> `;
  897. const left = value.type === 'boolean' ?
  898. `${short}--${field.name}`
  899. : `${short}--${field.name}=<${hint}>`;
  900. const row = { text, left, type: 'config' };
  901. if (text.length > width - maxMax) {
  902. row.skipLine = true;
  903. }
  904. if (prev && left.length > maxMax)
  905. prev.skipLine = true;
  906. prev = row;
  907. const len = left.length + 4;
  908. if (len > maxWidth && len < maxMax) {
  909. maxWidth = len;
  910. }
  911. rows.push(row);
  912. }
  913. return { rows, maxWidth };
  914. }
  915. /**
  916. * Return the configuration options as a plain object
  917. */
  918. toJSON() {
  919. return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [
  920. field,
  921. {
  922. type: def.type,
  923. ...(def.multiple ? { multiple: true } : {}),
  924. ...(def.delim ? { delim: def.delim } : {}),
  925. ...(def.short ? { short: def.short } : {}),
  926. ...(def.description ?
  927. { description: normalize(def.description) }
  928. : {}),
  929. ...(def.validate ? { validate: def.validate } : {}),
  930. ...(def.validOptions ? { validOptions: def.validOptions } : {}),
  931. ...(def.default !== undefined ? { default: def.default } : {}),
  932. ...(def.hint ? { hint: def.hint } : {}),
  933. },
  934. ]));
  935. }
  936. /**
  937. * Custom printer for `util.inspect`
  938. */
  939. [node_util_1.inspect.custom](_, options) {
  940. return `Jack ${(0, node_util_1.inspect)(this.toJSON(), options)}`;
  941. }
  942. }
  943. exports.Jack = Jack;
  944. // Unwrap and un-indent, so we can wrap description
  945. // strings however makes them look nice in the code.
  946. const normalize = (s, pre = false) => {
  947. if (pre)
  948. // prepend a ZWSP to each line so cliui doesn't strip it.
  949. return s
  950. .split('\n')
  951. .map(l => `\u200b${l}`)
  952. .join('\n');
  953. return s
  954. .split(/^\s*```\s*$/gm)
  955. .map((s, i) => {
  956. if (i % 2 === 1) {
  957. if (!s.trim()) {
  958. return `\`\`\`\n\`\`\`\n`;
  959. }
  960. // outdent the ``` blocks, but preserve whitespace otherwise.
  961. const split = s.split('\n');
  962. // throw out the \n at the start and end
  963. split.pop();
  964. split.shift();
  965. const si = split.reduce((shortest, l) => {
  966. /* c8 ignore next */
  967. const ind = l.match(/^\s*/)?.[0] ?? '';
  968. if (ind.length)
  969. return Math.min(ind.length, shortest);
  970. else
  971. return shortest;
  972. }, Infinity);
  973. /* c8 ignore next */
  974. const i = isFinite(si) ? si : 0;
  975. return ('\n```\n' +
  976. split.map(s => `\u200b${s.substring(i)}`).join('\n') +
  977. '\n```\n');
  978. }
  979. return (s
  980. // remove single line breaks, except for lists
  981. .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`)
  982. // normalize mid-line whitespace
  983. .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2')
  984. // two line breaks are enough
  985. .replace(/\n{3,}/g, '\n\n')
  986. // remove any spaces at the start of a line
  987. .replace(/\n[ \t]+/g, '\n')
  988. .trim());
  989. })
  990. .join('\n');
  991. };
  992. // normalize for markdown printing, remove leading spaces on lines
  993. const normalizeMarkdown = (s, pre = false) => {
  994. const n = normalize(s, pre).replace(/\\/g, '\\\\');
  995. return pre ?
  996. `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\``
  997. : n.replace(/\n +/g, '\n').trim();
  998. };
  999. const normalizeOneLine = (s, pre = false) => {
  1000. const n = normalize(s, pre)
  1001. .replace(/[\s\u200b]+/g, ' ')
  1002. .trim();
  1003. return pre ? `\`${n}\`` : n;
  1004. };
  1005. /**
  1006. * Main entry point. Create and return a {@link Jack} object.
  1007. */
  1008. const jack = (options = {}) => new Jack(options);
  1009. exports.jack = jack;
  1010. //# sourceMappingURL=index.js.map