impl/typescript.ts
989 bytes · the TypeScript implementation · view raw
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { addDays } from "./dates_add_days.ts"; ← from dates.add-days ^1.0.0 · built alongside by fune
import { type TrialPeriod } from "./subscriptions_trial_end_types.ts";
/**
* The last free day and the first charge date of a trial of `trialDays` days
* starting on `startDate`. The start day counts as day one, so the last free
* day is start + trialDays - 1 and the charge is the day after it.
*/
export function trialEnd(startDate: string, trialDays: number): TrialPeriod {
if (!Number.isInteger(trialDays)) {
throw new TypeError(`trial days must be an integer, received ${trialDays}`);
}
if (trialDays < 0) {
throw new RangeError(`trial days must not be negative, received ${trialDays}`);
}
// addDays validates the start date even when there is no trial, so a
// malformed date never slips through as the "first charge date".
const firstChargeDate = addDays(startDate, trialDays);
const lastTrialDay = trialDays === 0 ? null : addDays(startDate, trialDays - 1);
return { lastTrialDay, firstChargeDate };
}