index.js 34 KB

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