Files
weiguang-jewelry-ledger/新账系统/e2e/fake-clock.cjs
T
黄健铭andClaude Opus 5.5 28c64814f0 格式化:Prettier统一代码风格(仅格式,无逻辑变化)
仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:58:53 -08:00

121 lines
4.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// 验证工具专用:用 node --require 预加载,只影响本进程。
// 固定 Date 与 crypto 随机源,使 today()、时间戳、ID、盐与会话令牌在两次相同运行中完全一致。
// 环境变量:
// FAKE_CLOCK_START 起始时刻(ISO,默认 2026-11-20T02:00:00.000Z,即上海 10:00)
// FAKE_CLOCK_TICK_MS 每次读取时钟后前进的毫秒数(默认 0:时钟只在控制端设置时变化)
// FAKE_RANDOM_SEED 随机种子(默认 golden-seed)
// FAKE_CLOCK_IPC=1 通过 process.send 通道接受 {type:'fake-clock',op,ms,id} 控制消息
const crypto = require('node:crypto');
const RealDate = Date;
let current = RealDate.parse(process.env.FAKE_CLOCK_START || '2026-11-20T02:00:00.000Z');
if (!Number.isFinite(current)) throw new Error('FAKE_CLOCK_START 无效');
let tick = Number(process.env.FAKE_CLOCK_TICK_MS || 0);
function read() {
const value = current;
current += tick;
return value;
}
function FakeDate(...args) {
if (!new.target) return new RealDate(read()).toString();
return Reflect.construct(RealDate, args.length ? args : [read()], new.target);
}
Object.setPrototypeOf(FakeDate, RealDate);
FakeDate.prototype = RealDate.prototype;
FakeDate.now = () => read();
FakeDate.parse = RealDate.parse;
FakeDate.UTC = RealDate.UTC;
Object.defineProperty(RealDate.prototype, 'constructor', { value: FakeDate, writable: true, configurable: true });
globalThis.Date = FakeDate;
// 计数器式 SHA-256 流,按调用顺序输出确定字节。
const seed = process.env.FAKE_RANDOM_SEED || 'golden-seed';
let counter = 0,
pool = Buffer.alloc(0);
function bytes(n) {
while (pool.length < n) {
const block = crypto
.createHash('sha256')
.update(seed + ':' + counter++)
.digest();
pool = Buffer.concat([pool, block]);
}
const out = Buffer.from(pool.subarray(0, n));
pool = pool.subarray(n);
return out;
}
function randomBytes(size, callback) {
const out = bytes(size);
if (typeof callback === 'function') {
process.nextTick(callback, null, out);
return;
}
return out;
}
function randomUUID() {
const b = bytes(16);
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
const h = b.toString('hex');
return h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20);
}
function getRandomValues(array) {
const b = bytes(array.byteLength);
new Uint8Array(array.buffer, array.byteOffset, array.byteLength).set(b);
return array;
}
function randomFillSync(buffer, offset = 0, size) {
const view = new Uint8Array(buffer.buffer || buffer, buffer.byteOffset || 0, buffer.byteLength);
const end = size === undefined ? view.length : offset + size;
view.set(bytes(end - offset), offset);
return buffer;
}
for (const [name, fn] of Object.entries({ randomBytes, randomUUID, getRandomValues, randomFillSync })) {
try {
Object.defineProperty(crypto, name, { value: fn, writable: true, configurable: true, enumerable: true });
} catch {
try {
crypto[name] = fn;
} catch {}
}
}
if (crypto.randomUUID !== randomUUID || crypto.randomBytes !== randomBytes) throw new Error('无法固定 crypto 随机源');
try {
Object.defineProperty(globalThis.crypto, 'randomUUID', { value: randomUUID, configurable: true, writable: true });
Object.defineProperty(globalThis.crypto, 'getRandomValues', {
value: getRandomValues,
configurable: true,
writable: true,
});
} catch {}
Math.random = () => bytes(6).readUIntBE(0, 6) / 2 ** 48;
const control = {
now: () => current,
set(ms) {
if (!Number.isFinite(ms)) throw new Error('无效时刻');
current = ms;
},
advance(ms) {
current += ms;
},
setTick(ms) {
tick = ms;
},
RealDate,
};
globalThis.__fakeClock = control;
if (process.env.FAKE_CLOCK_IPC === '1' && typeof process.send === 'function') {
process.on('message', message => {
if (!message || message.type !== 'fake-clock') return;
try {
if (message.op === 'set') control.set(message.ms);
else if (message.op === 'advance') control.advance(message.ms);
else if (message.op === 'tick') control.setTick(message.ms);
process.send({ type: 'fake-clock-ack', id: message.id, now: current });
} catch (error) {
process.send({ type: 'fake-clock-ack', id: message.id, error: error.message });
}
});
}