Restore strict --expire units in the shared duration tokenizer

The shared tokenizer accepts `ms` for the simulation windows, and without a
per-caller unit set that grammar leaked into --expire: `--expire 500ms` was
a usage error before the parsers were unified and became silently rounded to
a 1h / 1s link after.

tokenizeDuration now takes an allowed-unit set; the expire flags pass
EXPIRE_UNITS (d/h/m/s) while parseDurationMs keeps the full set. Adds a
regression test asserting sub-second input stays exit 2 on both flags.
This commit is contained in:
gitea committed 2026-10-11 19:51:29 +08:00
1 parent 8c3d98fd98
commit 19c8dd3146
3 files changed
+34 -4

No files matched your search

+22 -1
View File
@@ -42,6 +42,15 @@ const UNIT_ALIASES: Record<string, DurationUnit> = {
const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i;
export interface TokenizeDurationOptions {
/**
* Units this caller accepts. Restricting the set keeps a shared tokenizer
* from quietly widening a flag's grammar: sub-second input was a usage error
* for `--expire` before the parsers were unified, and must stay one.
*/
units?: readonly DurationUnit[];
}
/**
* Parse a duration literal. Returns `undefined` when the input cannot be read
* at all — callers decide whether that is a usage error or a default.
@@ -49,7 +58,10 @@ const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i;
* A unitless number keeps whatever magnitude it had; pair it with
* {@link expireSeconds} or an explicit `unitless` argument to resolve it.
*/
export function tokenizeDuration(value: string | number): DurationToken | undefined {
export function tokenizeDuration(
value: string | number,
options: TokenizeDurationOptions = {}
): DurationToken | undefined {
if (typeof value === "number") {
return Number.isFinite(value) ? { value, unit: undefined } : undefined;
}
@@ -71,9 +83,18 @@ export function tokenizeDuration(value: string | number): DurationToken | undefi
if (!unit) {
return undefined;
}
if (options.units && !options.units.includes(unit)) {
return undefined;
}
return { value: parseFloat(match[1]), unit };
}
/**
* Units the `--expire` flags accept. Sub-second precision is meaningless for
* an assistance link and was rejected before the parsers were shared.
*/
export const EXPIRE_UNITS: readonly DurationUnit[] = ["d", "h", "m", "s"];
/** Convert a token to seconds, resolving a unitless value as `unitless`. */
export function durationSeconds(token: DurationToken, unitless: DurationUnit): number {
switch (token.unit ?? unitless) {