Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | 7x 652x 169x 37x 31x 31x 31x 31x 30x 748x 158x 172x 368x 229x 1x 228x 80x 18x 43x 60x 19x 7x 1x 124x 38x 38x 38x 181x 170x 170x 170x 1x 169x 169x 168x 105x 105x 163x 31x 28x 28x 28x 28x 28x 28x 28x 28x 138x 28x 3x 1x 27x 27x 27x 27x 27x 58x 4x 27x 3x 24x 24x 25x | import { Subject } from 'rxjs';
import type {
SmartCubeCommand,
SmartCubeEvent,
SmartCubeTransportConnection,
} from '../../bindings/smartCubeTransport.js';
import { JSONL_REPLAY_FORMAT, JSONL_REPLAY_VERSION } from '../jsonlFormat.js';
type JsonlEntry = { type: string; data: unknown };
type ReplayOptions = {
/** Invoked in recorded order immediately before a mock event is delivered. */
beforeEvent?: (event: SmartCubeEvent, index: number) => void;
};
export { JSONL_REPLAY_FORMAT, JSONL_REPLAY_VERSION };
type JsonlReplayHeader = {
format: typeof JSONL_REPLAY_FORMAT;
version: typeof JSONL_REPLAY_VERSION;
};
/** Transport identity reconstructed from a replay capture. */
export type JsonlMockIdentity = {
deviceName: string;
deviceMAC: string;
protocol: { id: string; name: string };
};
/** One structurally valid record from a replayable JSONL export. */
export type ValidatedJsonlEntry = Omit<JsonlEntry, 'data'> & {
recordedAt: string;
data: Record<string, unknown>;
};
/** Parsed capture data shared by JSONL replay consumers. */
export type JsonlReplay = {
entries: readonly ValidatedJsonlEntry[];
header: JsonlReplayHeader | null;
identity: JsonlMockIdentity;
events: readonly SmartCubeEvent[];
};
function fail(lineNumber: number, message: string): never {
throw new Error(`Invalid JSONL replay input at line ${lineNumber}: ${message}`);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function isJsonlEntry(value: unknown): value is ValidatedJsonlEntry {
return (
isRecord(value) &&
typeof value.recordedAt === 'string' &&
typeof value.type === 'string' &&
isRecord(value.data)
);
}
function readHeader(entry: ValidatedJsonlEntry, lineNumber: number): JsonlReplayHeader | null {
if (entry.type !== 'trace_header' && entry.type !== 'log_started') return null;
const { format, version } = entry.data;
Iif (format === undefined && version === undefined) return null;
Iif (format !== JSONL_REPLAY_FORMAT) fail(lineNumber, `unsupported format ${String(format)}`);
if (version !== JSONL_REPLAY_VERSION) fail(lineNumber, `unsupported version ${String(version)}`);
return { format, version };
}
function isNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isNullableNumber(value: unknown): value is number | null {
return value === null || isNumber(value);
}
function isVector(value: unknown, keys: readonly string[]): boolean {
return isRecord(value) && keys.every((key) => isNumber(value[key]));
}
function optional(value: unknown, predicate: (value: unknown) => boolean): boolean {
return value === undefined || predicate(value);
}
function isNumberArray(value: unknown): boolean {
return Array.isArray(value) && value.every(isNumber);
}
function isCubieState(value: unknown): boolean {
return (
isRecord(value) &&
isNumberArray(value.CP) &&
isNumberArray(value.CO) &&
isNumberArray(value.EP) &&
isNumberArray(value.EO)
);
}
function isGoCubeType(value: unknown): boolean {
return isRecord(value) && isNumber(value.code) && typeof value.name === 'string';
}
function isGoCubeOfflineStats(value: unknown): boolean {
return (
isRecord(value) &&
isNumber(value.moves) &&
isNumber(value.timeSeconds) &&
isNumber(value.solves)
);
}
function smartCubeEventError(value: unknown): string | undefined {
if (!isRecord(value) || typeof value.type !== 'string' || !isNumber(value.timestamp)) {
return 'cube_event data requires string type and numeric timestamp';
}
switch (value.type) {
case 'MOVE':
return typeof value.move === 'string' &&
isNumber(value.face) &&
isNumber(value.direction) &&
isNullableNumber(value.localTimestamp) &&
isNullableNumber(value.cubeTimestamp) &&
optional(value.serial, isNumber) &&
optional(value.goCubeCenterOrientation, isNumber)
? undefined
: 'invalid MOVE event';
case 'FACELETS':
return typeof value.facelets === 'string' &&
optional(value.serial, isNumber) &&
optional(value.state, isCubieState)
? undefined
: 'invalid FACELETS event';
case 'GYRO':
return isVector(value.quaternion, ['x', 'y', 'z', 'w']) &&
optional(value.velocity, (velocity) => isVector(velocity, ['x', 'y', 'z']))
? undefined
: 'invalid GYRO event';
case 'BATTERY':
return isNumber(value.batteryLevel) ? undefined : 'invalid BATTERY event';
case 'HARDWARE':
return optional(value.hardwareName, (field) => typeof field === 'string') &&
optional(value.softwareVersion, (field) => typeof field === 'string') &&
optional(value.hardwareVersion, (field) => typeof field === 'string') &&
optional(value.productDate, (field) => typeof field === 'string') &&
optional(value.gyroSupported, (field) => typeof field === 'boolean') &&
optional(value.goCubeType, isGoCubeType) &&
optional(value.goCubeOfflineStats, isGoCubeOfflineStats)
? undefined
: 'invalid HARDWARE event';
case 'DISCONNECT':
return undefined;
default:
return `unsupported cube event type ${value.type}`;
}
}
/** Narrow an unknown JSONL payload to a supported smart-cube event. */
export function isSmartCubeEvent(value: unknown): value is SmartCubeEvent {
return smartCubeEventError(value) === undefined;
}
/**
* Validate an app JSONL export before replaying it. Logs without a header are
* accepted as legacy exports; `log_started` remains accepted for older files.
*/
export function validateJsonlReplay(contents: string): {
entries: readonly ValidatedJsonlEntry[];
header: JsonlReplayHeader | null;
} {
const entries: ValidatedJsonlEntry[] = [];
let header: JsonlReplayHeader | null = null;
for (const [index, line] of contents.split('\n').entries()) {
if (line.trim() === '') continue;
const lineNumber = index + 1;
let value: unknown;
try {
value = JSON.parse(line);
} catch {
fail(lineNumber, 'invalid JSON');
}
Iif (!isJsonlEntry(value)) fail(lineNumber, 'expected { recordedAt, type, data } record');
if (entries.length === 0) header = readHeader(value, lineNumber);
if (value.type === 'cube_event') {
const error = smartCubeEventError(value.data);
if (error) fail(lineNumber, error);
}
entries.push(value);
}
return { entries, header };
}
function identityFromEntries(entries: readonly ValidatedJsonlEntry[]): JsonlMockIdentity {
const header = entries[0];
const session = header && isRecord(header.data.session) ? header.data.session : undefined;
const protocol = session && isRecord(session.protocol) ? session.protocol : undefined;
const protocolId =
typeof session?.protocol === 'string'
? session.protocol
: typeof protocol?.id === 'string'
? protocol.id
: 'jsonl-mock';
const protocolName =
typeof protocol?.name === 'string'
? protocol.name
: protocolId === 'jsonl-mock'
? 'JSONL mock'
: protocolId;
return {
deviceName:
typeof session?.device === 'string'
? session.device
: typeof session?.deviceName === 'string'
? session.deviceName
: 'JSONL mock cube',
deviceMAC: typeof session?.deviceMAC === 'string' ? session.deviceMAC : '',
protocol: { id: protocolId, name: protocolName },
};
}
/** Parse once, then share validated identity and raw events across rebuilds. */
export function createJsonlReplay(contents: string): JsonlReplay {
const { entries, header } = validateJsonlReplay(contents);
const events = entries.flatMap((entry) =>
entry.type === 'cube_event' && isSmartCubeEvent(entry.data) ? [entry.data] : [],
);
return { entries, header, identity: identityFromEntries(entries), events };
}
/** Parse only validated raw cube events; derived UI records are ignored. */
export function parseJsonlCubeEvents(contents: string): SmartCubeEvent[] {
return [...createJsonlReplay(contents).events];
}
/**
* Reads capture identity from the replay header. Older, headerless exports
* deliberately retain the generic mock identity so they remain replayable.
*/
export function readJsonlMockIdentity(contents: string): JsonlMockIdentity {
return createJsonlReplay(contents).identity;
}
/** In-memory connection for replaying redacted JSONL exports through a session. */
export function createJsonlMockConnection(source: string | JsonlReplay) {
const replay = typeof source === 'string' ? createJsonlReplay(source) : source;
const { events, identity } = replay;
const events$ = new Subject<SmartCubeEvent>();
const sentCommands: SmartCubeCommand[] = [];
const connection: SmartCubeTransportConnection = {
deviceName: identity.deviceName,
deviceMAC: identity.deviceMAC,
protocol: identity.protocol,
capabilities: { gyroscope: true, battery: true, facelets: true, hardware: true, reset: true },
events$,
sendCommand: async (command) => {
sentCommands.push(command);
},
disconnect: async () => {
events$.complete();
},
};
return {
connection,
identity,
events,
sentCommands,
replay(options: ReplayOptions = {}): void {
events.forEach((event, index) => {
options.beforeEvent?.(event, index);
events$.next(event);
});
},
emit(event: SmartCubeEvent): void {
events$.next(event);
},
};
}
|