All files / shared schema.ts

100% Statements 27/27
100% Branches 12/12
100% Functions 12/12
100% Lines 23/23

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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401                              26x       32x 31x 31x                       132x 132x   11x 32x 2x                   26x       8x               30x                                             26x                                         26x                                       4x               2x                                                                                                                                                                                                                                                                                     169x 101x           26x                                               26x   164x           26x   4x                                                                                                                                                                                
import { z } from "zod";
import type { PinMode } from "./types/arduino.types";
import { INPUT_LIMITS, isSafeHeaderName } from "./input-limits";
import { normalizeSourcePath } from "./source-project";
import type { SourceLocation } from "./source-project";
 
// The read-only default sketch served by GET /api/sketches
export interface Sketch {
  id: string;
  name: string;
  content: string;
  createdAt: Date;
  updatedAt: Date;
}
 
const compilerHeaderSchema = z
  .object({
    name: z.string().refine(
      (name) => {
        if (name.length > INPUT_LIMITS.compile.maxHeaderNameChars) return false;
        const normalized = normalizeSourcePath(name);
        return normalized?.split("/").every(isSafeHeaderName) === true;
      },
      "Header name must be a safe relative POSIX path",
    ),
    content: z.string().max(INPUT_LIMITS.compile.maxHeaderContentChars),
  })
  .strict();
 
function rejectEntryHeaderCollision(
  data: { entryFile?: string; headers?: Array<{ name: string }> },
  ctx: z.RefinementCtx,
): void {
  const entryPath = normalizeSourcePath(data.entryFile ?? "sketch.ino");
  if (!entryPath || !data.headers) return;
 
  data.headers.forEach((header, index) => {
    if (normalizeSourcePath(header.name) === entryPath) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["headers", index, "name"],
        message: "Header path must not collide with the entry file",
      });
    }
  });
}
 
/** Runtime contract for the public REST compiler endpoint. */
export const compileRequestSchema = z
  .object({
    code: z.string().min(1).max(INPUT_LIMITS.compile.maxCodeChars),
    entryFile: z.string().refine(
      (entryFile) => normalizeSourcePath(entryFile) !== undefined,
      "Entry file must be a safe relative POSIX path",
    ).optional(),
    headers: z
      .array(compilerHeaderSchema)
      .max(INPUT_LIMITS.compile.maxHeaders)
      .refine(
        (headers) =>
          new Set(headers.map((header) => header.name.toLowerCase())).size ===
          headers.length,
        "Header names must be unique",
      )
      .optional(),
    fqbn: z.string().min(1).max(INPUT_LIMITS.compile.maxFqbnChars).optional(),
    libraries: z
      .array(z.string().min(1).max(INPUT_LIMITS.compile.maxLibraryNameChars))
      .max(INPUT_LIMITS.compile.maxLibraries)
      .optional(),
  })
  .strict()
  .superRefine(rejectEntryHeaderCollision);
 
/**
 * Canonical WebSocket message type identifiers.
 *
 * Use this constant instead of inline string literals when constructing
 * messages. The literal type narrowing (via `as const`) keeps the
 * discriminated union in `wsMessageSchema` fully type-safe.
 *
 * Example:  sendMessageToClient(ws, { type: WSMessageType.SERIAL_OUTPUT, data })
 */
export const WSMessageType = {
  SERIAL_OUTPUT: "serial_output",
  SERIAL_INPUT: "serial_input",
  START_SIMULATION: "start_simulation",
  PAUSE_SIMULATION: "pause_simulation",
  RESUME_SIMULATION: "resume_simulation",
  STOP_SIMULATION: "stop_simulation",
  CODE_CHANGED: "code_changed",
  COMPILATION_ERROR: "compilation_error",
  COMPILATION_STATUS: "compilation_status",
  SIMULATION_STATUS: "simulation_status",
  HANDSHAKE: "handshake",
  PIN_STATE: "pin_state",
  PIN_STATE_BATCH: "pin_state_batch",
  SET_PIN_VALUE: "set_pin_value",
  IO_REGISTRY: "io_registry",
  SIM_TELEMETRY: "sim_telemetry",
  OPERATION_ERROR: "operation_error",
} as const;
 
// WebSocket message types
export const wsMessageSchema = z.discriminatedUnion("type", [
  z.object({
    type: z.literal("serial_output"),
    data: z.string(),
    isComplete: z.boolean().optional(),
  }),
  z.object({
    type: z.literal("serial_input"),
    data: z.string().max(INPUT_LIMITS.webSocket.maxSerialInputChars),
  }).strict(),
  z.object({
    type: z.literal("start_simulation"),
    timeout: z
      .number()
      .int()
      .min(INPUT_LIMITS.simulation.minTimeoutSeconds)
      .max(INPUT_LIMITS.simulation.maxTimeoutSeconds)
      .optional(),
    code: z.string().max(INPUT_LIMITS.compile.maxCodeChars).optional(),
    entryFile: z.string().refine(
      (entryFile) => normalizeSourcePath(entryFile) !== undefined,
      "Entry file must be a safe relative POSIX path",
    ).optional(),
    headers: z
      .array(compilerHeaderSchema)
      .max(INPUT_LIMITS.compile.maxHeaders)
      .refine(
        (headers) =>
          new Set(headers.map((header) => header.name.toLowerCase())).size ===
          headers.length,
        "Header names must be unique",
      )
      .optional(),
  }).strict(),
  z.object({
    type: z.literal("pause_simulation"),
  }).strict(),
  z.object({
    type: z.literal("resume_simulation"),
  }).strict(),
  z.object({
    type: z.literal("stop_simulation"),
  }).strict(),
  z.object({
    type: z.literal("code_changed"),
  }).strict(),
  z.object({
    type: z.literal("compilation_error"),
    data: z.string(),
  }),
  z.object({
    type: z.literal("compilation_status"),
    arduinoCliStatus: z
      .enum(["idle", "compiling", "success", "error"])
      .optional(),
    workerIndex: z.number().int().min(0).optional(),
    workerTotal: z.number().int().min(1).optional(),
    message: z.string().optional(),
  }),
  z.object({
    type: z.literal("simulation_status"),
    status: z.enum(["running", "stopped", "paused", "queued"]),
  }),
  z.object({
    type: z.literal("handshake"),
    testRunId: z.string(),
    protocolVersion: z.string().optional(),
  }),
  z.object({
    type: z.literal("pin_state"),
    pin: z.number(),
    stateType: z.enum(["mode", "value", "pwm"]),
    value: z.number(),
  }),
  z.object({
    type: z.literal("pin_state_batch"),
    states: z.array(
      z.object({
        pin: z.number(),
        stateType: z.enum(["mode", "value", "pwm"]),
        value: z.number(),
      })
    ),
    timestamp: z.number(),
  }),
  z.object({
    type: z.literal("set_pin_value"),
    pin: z
      .number()
      .int()
      .min(INPUT_LIMITS.simulation.minPin)
      .max(INPUT_LIMITS.simulation.maxPin),
    value: z
      .number()
      .int()
      .min(0)
      .max(INPUT_LIMITS.simulation.maxPinValue),
  }).strict(),
  z.object({
    type: z.literal("io_registry"),
    registry: z.array(
      z.object({
        pin: z.string(),
        defined: z.boolean(),
        pinMode: z.number().optional(),
        definedAt: z
          .object({
            line: z.number(),
            loopContext: z
              .object({
                variable: z.string(),
                operator: z.string(),
                limit: z.number(),
                startLine: z.number(),
                endLine: z.number(),
              })
              .optional(),
          })
          .optional(),
        usedAt: z
          .array(
            z.object({
              line: z.number(),
              operation: z.string(),
              loopContext: z
                .object({
                  variable: z.string(),
                  operator: z.string(),
                  limit: z.number(),
                  startLine: z.number(),
                  endLine: z.number(),
                })
                .optional(),
            }),
          )
          .optional(),
      }),
    ),
    baudrate: z.number().optional(),
    reason: z.string().optional(),
  }),
  z.object({
    type: z.literal("sim_telemetry"),
    metrics: z.object({
      timestamp: z.number(),
      intendedPinChangesPerSecond: z.number(),
      actualPinChangesPerSecond: z.number(),
      droppedPinChangesPerSecond: z.number(),
      batchesPerSecond: z.number(),
      avgStatesPerBatch: z.number(),
      serialOutputPerSecond: z.number(),
      serialBytesPerSecond: z.number(),
      serialBytesTotal: z.number(),
      serialIntendedBytesPerSecond: z.number(),
      serialDroppedBytesPerSecond: z.number(),
    }),
  }),
  z.object({
    type: z.literal("operation_error"),
    operation: z.enum(["compile", "start_simulation"]),
    // Keep operation-error codes open so newer server versions can be
    // forwarded by clients without requiring a schema release first.
    code: z.string().min(1),
    message: z.string(),
    retryAfter: z.number().int().positive().optional(),
  }).strict(),
]).superRefine((data, ctx) => {
  if (data.type === "start_simulation") {
    rejectEntryHeaderCollision(data, ctx);
  }
});
 
export type WSMessage = z.infer<typeof wsMessageSchema>;
 
const CLIENT_TO_SERVER_MESSAGE_TYPES = [
  WSMessageType.SERIAL_INPUT,
  WSMessageType.START_SIMULATION,
  WSMessageType.PAUSE_SIMULATION,
  WSMessageType.RESUME_SIMULATION,
  WSMessageType.STOP_SIMULATION,
  WSMessageType.CODE_CHANGED,
  WSMessageType.SET_PIN_VALUE,
] as const;
 
type ClientToServerMessageType = (typeof CLIENT_TO_SERVER_MESSAGE_TYPES)[number];
 
/** Messages the browser is allowed to send to the simulation server. */
export type ClientToServerWSMessage = Extract<
  WSMessage,
  { type: ClientToServerMessageType }
>;
 
/** Messages emitted by the simulation server and consumed by the browser. */
export type ServerToClientWSMessage = Exclude<
  WSMessage,
  ClientToServerWSMessage
>;
 
export const clientToServerWSMessageSchema = wsMessageSchema.refine(
  (message): message is ClientToServerWSMessage =>
    CLIENT_TO_SERVER_MESSAGE_TYPES.includes(
      message.type as ClientToServerMessageType,
    ),
  { message: "Message type is not allowed from client to server" },
);
 
export const serverToClientWSMessageSchema = wsMessageSchema.refine(
  (message): message is ServerToClientWSMessage =>
    !CLIENT_TO_SERVER_MESSAGE_TYPES.includes(
      message.type as ClientToServerMessageType,
    ),
  { message: "Message type is not allowed from server to client" },
);
 
// Parser Message Types
export type ParserMessage = {
  id: string;
  type: "warning" | "error" | "info";
  category:
    | "serial"
    | "hardware"
    | "structure"
    | "performance"
    | "library"
    | "pins"
    | "reserved-name";
  severity: 1 | 2 | 3;
  /** Source file for project-aware parser diagnostics. */
  file?: string;
  line?: number;
  column?: number;
  message: string;
  suggestion?: string;
};
 
// I/O Pin Record for Registry Display
export interface IOPinRecord {
  pin: string;
  defined: boolean;
  // ── Numeric pin id (0-13 digital, 14-19 = A0-A5). Optional for compat. ──
  pinId?: number;
  // ── Per-operation line arrays (for extended / eye-on view) ───────────────
  pinModeLines?: Array<number | "runtime">;
  pinModeModes?: Array<PinMode>;
  digitalReadLines?: Array<number | "runtime">;
  digitalWriteLines?: Array<number | "runtime">;
  analogReadLines?: Array<number | "runtime">;
  analogWriteLines?: Array<number | "runtime">;
  /** Project-aware static locations, retained alongside legacy line arrays. */
  pinModeLocations?: SourceLocation[];
  digitalReadLocations?: SourceLocation[];
  digitalWriteLocations?: SourceLocation[];
  analogReadLocations?: SourceLocation[];
  analogWriteLocations?: SourceLocation[];
  // ── Conflict / warning flags (TC 9: write-on-input, TC 11: multi-mode) ───
  conflict?: boolean;
  conflictMessage?: string;
  // ── Legacy fields (kept for runtime path + backward compat) ─────────────
  /**
   * Legacy runtime field. Prefer pinModeLines and pinModeModes for static data.
   */
  pinMode?: number; // 0=INPUT, 1=OUTPUT, 2=INPUT_PULLUP
  /**
   * Legacy runtime field. Prefer pinModeLines for static data.
   */
  definedAt?: {
    line: number;
    loopContext?: {
      variable: string;
      operator: string;
      limit: number;
      startLine: number;
      endLine: number;
    };
  };
  /**
   * Legacy runtime and compatibility field for operation usage data.
   */
  usedAt?: Array<{
    line: number;
    operation: string;
    loopContext?: {
      variable: string;
      operator: string;
      limit: number;
      startLine: number;
      endLine: number;
    };
  }>;
}
 
// Output line for serial monitor/plotter and compilation output
export interface OutputLine {
  text: string;
  complete: boolean;
}