index.js 35 KB

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