"use strict"; // Source-level pin for the once-task NaN-timestamp guard in bot.js // (adpanel:scheduler-nan-timestamp). // // `new Date(...).getTime()` yields NaN for malformed input and NaN compares // false against every inequality — so the pre-existing future check passed // it, and JSON.stringify shipped NaN as null, which the create route's // contract treated as an ABSENT timestamp, i.e. run-now ("once" task fired // immediately). The fix adds an explicit Number.isFinite gate BEFORE the // future check. // // bot.js is one IIFE with structure-pin precedent (the bot-*.test.js files // read the source and assert on well-anchored windows) — never require() it. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const ROOT = path.join(__dirname, ".."); const BOT_JS = path.join(ROOT, "public", "js", "bot.js"); const botSrc = fs.readFileSync(BOT_JS, "utf8"); // The once branch of createSchedulerTask — the anchor is unique in the file. const branchStart = botSrc.indexOf("if (schedulerCurrentScheduleType === 'once') {"); assert.notStrictEqual(branchStart, -1, "once branch not found in createSchedulerTask"); const branchEnd = botSrc.indexOf("} else {", branchStart); assert.notStrictEqual(branchEnd, -1, "no recurring else after the once branch"); const onceBranch = botSrc.slice(branchStart, branchEnd); const createSource = botSrc.match(/^ async function createSchedulerTask\(\) \{[\s\S]+?^ \}/m)?.[0]; assert.ok(createSource); test("the once branch rejects a non-finite scheduledTimestamp before serializing the request", () => { assert.ok( onceBranch.includes("adpanel:scheduler-nan-timestamp"), "the guard must carry the adpanel:scheduler-nan-timestamp constraint comment" ); const guardAt = onceBranch.indexOf("if (!Number.isFinite(scheduledTimestamp)) {"); assert.notStrictEqual(guardAt, -1, "the Number.isFinite guard is missing from the once branch"); assert.ok( onceBranch.includes("alert('Please enter a valid date and time')"), "the guard must alert in the existing alert+return style" ); const guardReturnAt = onceBranch.indexOf("return;", guardAt); assert.notStrictEqual(guardReturnAt, -1, "the guard must return early"); assert.ok(createSource.indexOf(onceBranch) + guardReturnAt < createSource.indexOf("const body = JSON.stringify({")); }); test("only an unchanged pending one-time submission can retry after its scheduled time", async () => { const runAt = new Date("2030-05-10T12:00").getTime(); let clock = runAt - 60_000; class FixtureDate extends Date { static now() { return clock; } } const taskName = { value: "Fixture task" }; const requests = []; const messages = []; let keysIssued = 0; const localDateInputValue = vm.runInNewContext(`(${botSrc.match(/^ function localDateInputValue\([\s\S]+?^ \}/m)[0]})`, { Date: FixtureDate }); const create = vm.runInNewContext(`(${createSource})`, { Date: FixtureDate, schedulerCreateInFlight: false, pendingSchedulerCreate: null, schedulerTaskName: taskName, schedulerActionType: { value: "server_start" }, schedulerCurrentScheduleType: "once", schedulerDate: { value: "2030-05-10" }, schedulerTime: { value: "12:00" }, schedulerModal: null, schedulerCreateBtn: null, hasPerm: () => true, localDateInputValue, bot: "fixture", alert: message => messages.push(message), createCommandRequestId: () => `fixture-key-${++keysIssued}`, fetchWithServerActionToken: async (_url, request) => { requests.push(request); if (requests.length === 1) throw new Error("Response unavailable"); return { ok: true }; }, schedulerModalIsActive: () => true, switchSchedulerTab() {}, resetSchedulerForm() {}, }); await create(); assert.strictEqual(JSON.parse(requests[0].body).scheduledTimestamp, runAt); clock = runAt + 1; taskName.value = "Changed task"; await create(); assert.strictEqual(messages.at(-1), "Scheduled time must be in the future"); assert.strictEqual(requests.length, 1); taskName.value = "Fixture task"; await create(); assert.strictEqual(requests.length, 2); assert.strictEqual(requests[1].body, requests[0].body); assert.strictEqual(requests[1].headers["Idempotency-Key"], requests[0].headers["Idempotency-Key"]); assert.strictEqual(keysIssued, 1); await create(); assert.strictEqual(requests.length, 2, "a successful retry clears the pending request"); }); test("opening Scheduler defaults a blank date and leaves the selected draft date intact", () => { const source = botSrc.match(/^ function openSchedulerModal\(\) \{[\s\S]+?^ \}/m)?.[0]; assert.ok(source); const schedulerDate = { value: "" }; const open = vm.runInNewContext(`(${source})`, { schedulerModal: {}, schedulerDate, hasPerm: () => true, showModalElement() {}, afterModalPaint() {}, localDateInputValue: () => "2030-05-01", document: { querySelector: () => null }, applySchedulerActionPermGating: () => false, }); open(); assert.strictEqual(schedulerDate.value, "2030-05-01"); schedulerDate.value = "2030-05-10"; open(); assert.strictEqual(schedulerDate.value, "2030-05-10"); }); test("one-time Scheduler input rejects a spring-forward gap instead of shifting the time", (t) => { const previousTimezone = process.env.TZ; process.env.TZ = "America/New_York"; t.after(() => { if (previousTimezone === undefined) delete process.env.TZ; else process.env.TZ = previousTimezone; }); const localDate = botSrc.match(/^ function localDateInputValue\([\s\S]+?^ \}/m)?.[0]; assert.ok(localDate); class FixtureDate extends Date { static now() { return new Date("2030-03-01T00:00:00Z").getTime(); } } const messages = []; const parseOnce = vm.runInNewContext(`(${localDate})`, { Date: FixtureDate }); const calculate = vm.runInNewContext(`(time => { const schedulerDate = { value: '2030-03-10' }, schedulerTime = { value: time }; const schedulerCurrentScheduleType = 'once'; let scheduleType, scheduledTimestamp; ${onceBranch}} return scheduledTimestamp; })`, { Date: FixtureDate, localDateInputValue: parseOnce, alert: message => messages.push(message) }); assert.strictEqual(calculate("02:30"), undefined); assert.match(messages[0], /does not exist/); assert.strictEqual(calculate("03:30"), Date.parse("2030-03-10T03:30:00-04:00")); });