index.js 34 KB

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