v1.0 with SW PWA enabled

This commit is contained in:
Blomios
2026-01-01 17:40:53 +01:00
parent 1c0e22aac1
commit 3c8bebb2ad
29775 changed files with 2197201 additions and 119080 deletions

View File

@ -1,55 +1,10 @@
import { inspect } from 'node:util';
import { parseArgs } from './parse-args.js';
import { inspect, parseArgs, } from 'node:util';
// it's a tiny API, just cast it inline, it's fine
//@ts-ignore
import cliui from '@isaacs/cliui';
import { basename } from 'node:path';
const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80);
// indentation spaces from heading level
const indent = (n) => (n - 1) * 2;
const toEnvKey = (pref, key) => {
return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')]
.join(' ')
.trim()
.toUpperCase()
.replace(/ /g, '_');
};
const toEnvVal = (value, delim = '\n') => {
const str = typeof value === 'string' ? value
: typeof value === 'boolean' ?
value ? '1'
: '0'
: typeof value === 'number' ? String(value)
: Array.isArray(value) ?
value.map((v) => toEnvVal(v)).join(delim)
: /* c8 ignore start */ undefined;
if (typeof str !== 'string') {
throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`);
}
/* c8 ignore stop */
return str;
};
const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ?
env ? env.split(delim).map(v => fromEnvVal(v, type, false))
: []
: type === 'string' ? env
: type === 'boolean' ? env === '1'
: +env.trim());
export const isConfigType = (t) => typeof t === 'string' &&
(t === 'string' || t === 'number' || t === 'boolean');
const undefOrType = (v, t) => v === undefined || typeof v === t;
const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t));
const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v);
// print the value type, for error message reporting
const valueType = (v) => typeof v === 'string' ? 'string'
: typeof v === 'boolean' ? 'boolean'
: typeof v === 'number' ? 'number'
: Array.isArray(v) ?
joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]'
: `${v.type}${v.multiple ? '[]' : ''}`;
const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ?
types[0]
: `(${types.join('|')})`;
const isValidValue = (v, type, multi) => {
if (multi) {
if (!Array.isArray(v))
@ -60,10 +15,22 @@ const isValidValue = (v, type, multi) => {
return false;
return typeof v === type;
};
export const isConfigOption = (o, type, multi) => !!o &&
const isValidOption = (v, vo) => !!vo &&
(Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v));
/**
* Determine whether an unknown object is a {@link ConfigOption} based only
* on its `type` and `multiple` property
*/
export const isConfigOptionOfType = (o, type, multi) => !!o &&
typeof o === 'object' &&
isConfigType(o.type) &&
o.type === type &&
!!o.multiple === multi;
/**
* Determine whether an unknown object is a {@link ConfigOption} based on
* it having all valid properties
*/
export const isConfigOption = (o, type, multi) => isConfigOptionOfType(o, type, multi) &&
undefOrType(o.short, 'string') &&
undefOrType(o.description, 'string') &&
undefOrType(o.hint, 'string') &&
@ -71,218 +38,176 @@ export const isConfigOption = (o, type, multi) => !!o &&
(o.type === 'boolean' ?
o.validOptions === undefined
: undefOrTypeArray(o.validOptions, o.type)) &&
(o.default === undefined || isValidValue(o.default, type, multi)) &&
!!o.multiple === multi;
function num(o = {}) {
const { default: def, validate: val, validOptions, ...rest } = o;
if (def !== undefined && !isValidValue(def, 'number', false)) {
throw new TypeError('invalid default value', {
cause: {
found: def,
wanted: 'number',
},
});
}
if (!undefOrTypeArray(validOptions, 'number')) {
throw new TypeError('invalid validOptions', {
cause: {
found: validOptions,
wanted: 'number[]',
},
});
}
const validate = val ?
val
: undefined;
return {
...rest,
default: def,
validate,
validOptions,
type: 'number',
multiple: false,
};
}
function numList(o = {}) {
const { default: def, validate: val, validOptions, ...rest } = o;
if (def !== undefined && !isValidValue(def, 'number', true)) {
throw new TypeError('invalid default value', {
cause: {
found: def,
wanted: 'number[]',
},
});
}
if (!undefOrTypeArray(validOptions, 'number')) {
throw new TypeError('invalid validOptions', {
cause: {
found: validOptions,
wanted: 'number[]',
},
});
}
const validate = val ?
val
: undefined;
return {
...rest,
default: def,
validate,
validOptions,
type: 'number',
multiple: true,
};
}
function opt(o = {}) {
const { default: def, validate: val, validOptions, ...rest } = o;
if (def !== undefined && !isValidValue(def, 'string', false)) {
throw new TypeError('invalid default value', {
cause: {
found: def,
wanted: 'string',
},
});
}
if (!undefOrTypeArray(validOptions, 'string')) {
throw new TypeError('invalid validOptions', {
cause: {
found: validOptions,
wanted: 'string[]',
},
});
}
const validate = val ?
val
: undefined;
return {
...rest,
default: def,
validate,
validOptions,
type: 'string',
multiple: false,
};
}
function optList(o = {}) {
const { default: def, validate: val, validOptions, ...rest } = o;
if (def !== undefined && !isValidValue(def, 'string', true)) {
throw new TypeError('invalid default value', {
cause: {
found: def,
wanted: 'string[]',
},
});
}
if (!undefOrTypeArray(validOptions, 'string')) {
throw new TypeError('invalid validOptions', {
cause: {
found: validOptions,
wanted: 'string[]',
},
});
}
const validate = val ?
val
: undefined;
return {
...rest,
default: def,
validate,
validOptions,
type: 'string',
multiple: true,
};
}
function flag(o = {}) {
const { hint, default: def, validate: val, ...rest } = o;
delete rest.validOptions;
if (def !== undefined && !isValidValue(def, 'boolean', false)) {
throw new TypeError('invalid default value');
}
const validate = val ?
val
: undefined;
if (hint !== undefined) {
throw new TypeError('cannot provide hint for flag');
}
return {
...rest,
default: def,
validate,
type: 'boolean',
multiple: false,
};
}
function flagList(o = {}) {
const { hint, default: def, validate: val, ...rest } = o;
delete rest.validOptions;
if (def !== undefined && !isValidValue(def, 'boolean', true)) {
throw new TypeError('invalid default value');
}
const validate = val ?
val
: undefined;
if (hint !== undefined) {
throw new TypeError('cannot provide hint for flag list');
}
return {
...rest,
default: def,
validate,
type: 'boolean',
multiple: true,
};
}
const toParseArgsOptionsConfig = (options) => {
const c = {};
for (const longOption in options) {
const config = options[longOption];
/* c8 ignore start */
if (!config) {
throw new Error('config must be an object: ' + longOption);
}
/* c8 ignore start */
if (isConfigOption(config, 'number', true)) {
c[longOption] = {
type: 'string',
multiple: true,
default: config.default?.map(c => String(c)),
};
}
else if (isConfigOption(config, 'number', false)) {
c[longOption] = {
type: 'string',
multiple: false,
default: config.default === undefined ?
undefined
: String(config.default),
};
}
else {
const conf = config;
c[longOption] = {
type: conf.type,
multiple: !!conf.multiple,
default: conf.default,
};
}
const clo = c[longOption];
if (typeof config.short === 'string') {
clo.short = config.short;
}
if (config.type === 'boolean' &&
!longOption.startsWith('no-') &&
!options[`no-${longOption}`]) {
c[`no-${longOption}`] = {
type: 'boolean',
multiple: config.multiple,
};
}
}
return c;
};
(o.default === undefined || isValidValue(o.default, type, multi));
const isHeading = (r) => r.type === 'heading';
const isDescription = (r) => r.type === 'description';
const width = Math.min(process?.stdout?.columns ?? 80, 80);
// indentation spaces from heading level
const indent = (n) => (n - 1) * 2;
const toEnvKey = (pref, key) => [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')]
.join(' ')
.trim()
.toUpperCase()
.replace(/ /g, '_');
const toEnvVal = (value, delim = '\n') => {
const str = typeof value === 'string' ? value
: typeof value === 'boolean' ?
value ? '1'
: '0'
: typeof value === 'number' ? String(value)
: Array.isArray(value) ?
value.map((v) => toEnvVal(v)).join(delim)
: /* c8 ignore start */ undefined;
if (typeof str !== 'string') {
throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`, { cause: { code: 'JACKSPEAK' } });
}
/* c8 ignore stop */
return str;
};
const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ?
env ? env.split(delim).map(v => fromEnvVal(v, type, false))
: []
: type === 'string' ? env
: type === 'boolean' ? env === '1'
: +env.trim());
const undefOrType = (v, t) => v === undefined || typeof v === t;
const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t));
// print the value type, for error message reporting
const valueType = (v) => typeof v === 'string' ? 'string'
: typeof v === 'boolean' ? 'boolean'
: typeof v === 'number' ? 'number'
: Array.isArray(v) ?
`${joinTypes([...new Set(v.map(v => valueType(v)))])}[]`
: `${v.type}${v.multiple ? '[]' : ''}`;
const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ?
types[0]
: `(${types.join('|')})`;
const validateFieldMeta = (field, fieldMeta) => {
if (fieldMeta) {
if (field.type !== undefined && field.type !== fieldMeta.type) {
throw new TypeError(`invalid type`, {
cause: {
found: field.type,
wanted: [fieldMeta.type, undefined],
},
});
}
if (field.multiple !== undefined &&
!!field.multiple !== fieldMeta.multiple) {
throw new TypeError(`invalid multiple`, {
cause: {
found: field.multiple,
wanted: [fieldMeta.multiple, undefined],
},
});
}
return fieldMeta;
}
if (!isConfigType(field.type)) {
throw new TypeError(`invalid type`, {
cause: {
found: field.type,
wanted: ['string', 'number', 'boolean'],
},
});
}
return {
type: field.type,
multiple: !!field.multiple,
};
};
const validateField = (o, type, multiple) => {
const validateValidOptions = (def, validOptions) => {
if (!undefOrTypeArray(validOptions, type)) {
throw new TypeError('invalid validOptions', {
cause: {
found: validOptions,
wanted: valueType({ type, multiple: true }),
},
});
}
if (def !== undefined && validOptions !== undefined) {
const valid = Array.isArray(def) ?
def.every(v => validOptions.includes(v))
: validOptions.includes(def);
if (!valid) {
throw new TypeError('invalid default value not in validOptions', {
cause: {
found: def,
wanted: validOptions,
},
});
}
}
};
if (o.default !== undefined &&
!isValidValue(o.default, type, multiple)) {
throw new TypeError('invalid default value', {
cause: {
found: o.default,
wanted: valueType({ type, multiple }),
},
});
}
if (isConfigOptionOfType(o, 'number', false) ||
isConfigOptionOfType(o, 'number', true)) {
validateValidOptions(o.default, o.validOptions);
}
else if (isConfigOptionOfType(o, 'string', false) ||
isConfigOptionOfType(o, 'string', true)) {
validateValidOptions(o.default, o.validOptions);
}
else if (isConfigOptionOfType(o, 'boolean', false) ||
isConfigOptionOfType(o, 'boolean', true)) {
if (o.hint !== undefined) {
throw new TypeError('cannot provide hint for flag');
}
if (o.validOptions !== undefined) {
throw new TypeError('cannot provide validOptions for flag');
}
}
return o;
};
const toParseArgsOptionsConfig = (options) => {
return Object.entries(options).reduce((acc, [longOption, o]) => {
const p = {
type: 'string',
multiple: !!o.multiple,
...(typeof o.short === 'string' ? { short: o.short } : undefined),
};
const setNoBool = () => {
if (!longOption.startsWith('no-') && !options[`no-${longOption}`]) {
acc[`no-${longOption}`] = {
type: 'boolean',
multiple: !!o.multiple,
};
}
};
const setDefault = (def, fn) => {
if (def !== undefined) {
p.default = fn(def);
}
};
if (isConfigOption(o, 'number', false)) {
setDefault(o.default, String);
}
else if (isConfigOption(o, 'number', true)) {
setDefault(o.default, d => d.map(v => String(v)));
}
else if (isConfigOption(o, 'string', false) ||
isConfigOption(o, 'string', true)) {
setDefault(o.default, v => v);
}
else if (isConfigOption(o, 'boolean', false) ||
isConfigOption(o, 'boolean', true)) {
p.type = 'boolean';
setDefault(o.default, v => v);
setNoBool();
}
acc[longOption] = p;
return acc;
}, {});
};
/**
* Class returned by the {@link jack} function and all configuration
* definition methods. This is what gets chained together.
@ -309,6 +234,30 @@ export class Jack {
this.#configSet = Object.create(null);
this.#shorts = Object.create(null);
}
/**
* Resulting definitions, suitable to be passed to Node's `util.parseArgs`,
* but also including `description` and `short` fields, if set.
*/
get definitions() {
return this.#configSet;
}
/** map of `{ <short>: <long> }` strings for each short name defined */
get shorts() {
return this.#shorts;
}
/**
* options passed to the {@link Jack} constructor
*/
get jackOptions() {
return this.#options;
}
/**
* the data used to generate {@link Jack#usage} and
* {@link Jack#usageMarkdown} content.
*/
get usageFields() {
return this.#fields;
}
/**
* Set the default value (which will still be overridden by env or cli)
* as if from a parsed config file. The optional `source` param, if
@ -320,16 +269,13 @@ export class Jack {
this.validate(values);
}
catch (er) {
const e = er;
if (source && e && typeof e === 'object') {
if (e.cause && typeof e.cause === 'object') {
Object.assign(e.cause, { path: source });
}
else {
e.cause = { path: source };
}
if (source && er instanceof Error) {
/* c8 ignore next */
const cause = typeof er.cause === 'object' ? er.cause : {};
er.cause = { ...cause, path: source };
Error.captureStackTrace(er, this.setConfigValues);
}
throw e;
throw er;
}
for (const [field, value] of Object.entries(values)) {
const my = this.#configSet[field];
@ -337,7 +283,10 @@ export class Jack {
/* c8 ignore start */
if (!my) {
throw new Error('unexpected field in config set: ' + field, {
cause: { found: field },
cause: {
code: 'JACKSPEAK',
found: field,
},
});
}
/* c8 ignore stop */
@ -392,10 +341,9 @@ export class Jack {
if (args === process.argv) {
args = args.slice(process._eval !== undefined ? 1 : 2);
}
const options = toParseArgsOptionsConfig(this.#configSet);
const result = parseArgs({
args,
options,
options: toParseArgsOptionsConfig(this.#configSet),
// always strict, but using our own logic
strict: false,
allowPositionals: this.#allowPositionals,
@ -435,6 +383,7 @@ export class Jack {
`place it at the end of the command after '--', as in ` +
`'-- ${token.rawName}'`, {
cause: {
code: 'JACKSPEAK',
found: token.rawName + (token.value ? `=${token.value}` : ''),
},
});
@ -444,6 +393,7 @@ export class Jack {
if (my.type !== 'boolean') {
throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, {
cause: {
code: 'JACKSPEAK',
name: token.rawName,
wanted: valueType(my),
},
@ -453,7 +403,7 @@ export class Jack {
}
else {
if (my.type === 'boolean') {
throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } });
throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { code: 'JACKSPEAK', found: token } });
}
if (my.type === 'string') {
value = token.value;
@ -464,6 +414,7 @@ export class Jack {
throw new Error(`Invalid value '${token.value}' provided for ` +
`'${token.rawName}' option, expected number`, {
cause: {
code: 'JACKSPEAK',
name: token.rawName,
found: token.value,
wanted: 'number',
@ -488,15 +439,12 @@ export class Jack {
for (const [field, value] of Object.entries(p.values)) {
const valid = this.#configSet[field]?.validate;
const validOptions = this.#configSet[field]?.validOptions;
let cause;
if (validOptions && !isValidOption(value, validOptions)) {
cause = { name: field, found: value, validOptions: validOptions };
}
if (valid && !valid(value)) {
cause = cause || { name: field, found: value };
}
const cause = validOptions && !isValidOption(value, validOptions) ?
{ name: field, found: value, validOptions }
: valid && !valid(value) ? { name: field, found: value }
: undefined;
if (cause) {
throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause });
throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause: { ...cause, code: 'JACKSPEAK' } });
}
}
return p;
@ -512,7 +460,7 @@ export class Jack {
// recurse so we get the core config key we care about.
this.#noNoFields(yes, val, s);
if (this.#configSet[yes]?.type === 'boolean') {
throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } });
throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { code: 'JACKSPEAK', found: s, wanted: yes } });
}
}
/**
@ -522,7 +470,7 @@ export class Jack {
validate(o) {
if (!o || typeof o !== 'object') {
throw new Error('Invalid config: not an object', {
cause: { found: o },
cause: { code: 'JACKSPEAK', found: o },
});
}
const opts = o;
@ -535,33 +483,27 @@ export class Jack {
const config = this.#configSet[field];
if (!config) {
throw new Error(`Unknown config option: ${field}`, {
cause: { found: field },
cause: { code: 'JACKSPEAK', found: field },
});
}
if (!isValidValue(value, config.type, !!config.multiple)) {
throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, {
cause: {
code: 'JACKSPEAK',
name: field,
found: value,
wanted: valueType(config),
},
});
}
let cause;
if (config.validOptions &&
!isValidOption(value, config.validOptions)) {
cause = {
name: field,
found: value,
validOptions: config.validOptions,
};
}
if (config.validate && !config.validate(value)) {
cause = cause || { name: field, found: value };
}
const cause = config.validOptions && !isValidOption(value, config.validOptions) ?
{ name: field, found: value, validOptions: config.validOptions }
: config.validate && !config.validate(value) ?
{ name: field, found: value }
: undefined;
if (cause) {
throw new Error(`Invalid config value for ${field}: ${value}`, {
cause,
cause: { ...cause, code: 'JACKSPEAK' },
});
}
}
@ -595,37 +537,37 @@ export class Jack {
* Add one or more number fields.
*/
num(fields) {
return this.#addFields(fields, num);
return this.#addFieldsWith(fields, 'number', false);
}
/**
* Add one or more multiple number fields.
*/
numList(fields) {
return this.#addFields(fields, numList);
return this.#addFieldsWith(fields, 'number', true);
}
/**
* Add one or more string option fields.
*/
opt(fields) {
return this.#addFields(fields, opt);
return this.#addFieldsWith(fields, 'string', false);
}
/**
* Add one or more multiple string option fields.
*/
optList(fields) {
return this.#addFields(fields, optList);
return this.#addFieldsWith(fields, 'string', true);
}
/**
* Add one or more flag fields.
*/
flag(fields) {
return this.#addFields(fields, flag);
return this.#addFieldsWith(fields, 'boolean', false);
}
/**
* Add one or more multiple flag fields.
*/
flagList(fields) {
return this.#addFields(fields, flagList);
return this.#addFieldsWith(fields, 'boolean', true);
}
/**
* Generic field definition method. Similar to flag/flagList/number/etc,
@ -633,29 +575,22 @@ export class Jack {
* fields on each one, or Jack won't know how to define them.
*/
addFields(fields) {
const next = this;
for (const [name, field] of Object.entries(fields)) {
this.#validateName(name, field);
next.#fields.push({
type: 'config',
name,
value: field,
});
}
Object.assign(next.#configSet, fields);
return next;
return this.#addFields(this, fields);
}
#addFields(fields, fn) {
const next = this;
#addFieldsWith(fields, type, multiple) {
return this.#addFields(this, fields, {
type,
multiple,
});
}
#addFields(next, fields, opt) {
Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => {
this.#validateName(name, field);
const option = fn(field);
next.#fields.push({
type: 'config',
name,
value: option,
});
return [name, option];
const { type, multiple } = validateFieldMeta(field, opt);
const value = { ...field, type, multiple };
validateField(value, type, multiple);
next.#fields.push({ type: 'config', name, value });
return [name, value];
})));
return next;
}
@ -691,6 +626,7 @@ export class Jack {
if (this.#usage)
return this.#usage;
let headingLevel = 1;
//@ts-ignore
const ui = cliui({ width });
const first = this.#fields[0];
let start = first?.type === 'heading' ? 1 : 0;
@ -932,6 +868,10 @@ export class Jack {
return `Jack ${inspect(this.toJSON(), options)}`;
}
}
/**
* Main entry point. Create and return a {@link Jack} object.
*/
export const jack = (options = {}) => new Jack(options);
// Unwrap and un-indent, so we can wrap description
// strings however makes them look nice in the code.
const normalize = (s, pre = false) => {
@ -993,8 +933,4 @@ const normalizeOneLine = (s, pre = false) => {
.trim();
return pre ? `\`${n}\`` : n;
};
/**
* Main entry point. Create and return a {@link Jack} object.
*/
export const jack = (options = {}) => new Jack(options);
//# sourceMappingURL=index.js.map