diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 4adca31..71df4cf 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -16,7 +16,7 @@ body: attributes: label: ALPR Community version description: Find this under Settings → Release. Include the source revision there when reporting an installation or update problem. - placeholder: v0.1.58 + placeholder: v0.1.59 validations: required: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fceaac..3b568a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,6 +111,11 @@ jobs: yarn install --frozen-lockfile --ignore-scripts --network-timeout 100000 node scripts/install-openvino-runtime.mjs + - name: Verify Axis camera ingestion against isolated PostgreSQL + env: + ALPR_AXIS_TEST_SERVER_URL: postgresql://postgres:fixture-test-password@127.0.0.1:5432/postgres + run: yarn test:camera-inputs:postgres + - name: Exercise load, no-op, guarded clear, and refusal paths shell: bash run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index bb6dbd7..100e17b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 0.1.59 — 2026-11-01 + +- Add configurable AXIS License Plate Verifier inputs through HTTP push, MQTT, or both under Settings > Integrations > Camera Inputs. Existing Blue Iris cameras continue automatically. +- Store validated events durably before acknowledgement, correlate passages, deduplicate transports, apply later OCR/image/direction corrections, and preserve original observations and human review. +- Configure camera identity, broker/topic, optional ROI, image storage, movement direction labels, and immediate or finalized processing; include connection tests and recent-event diagnostics. +- Keep recording independent from recognition. Axis events do not create Blue Iris recording links or automatically enable vehicle identification from scene images. +- Update User Guide 3.27 and installation/update examples. Physical Axis hardware was unavailable; firmware-specific compatibility still needs camera testing. +- Fix the PostgreSQL integration-test connection password for authenticated CI servers. +- Update vulnerable Next.js, Nodemailer and transitive dependencies; remove unused legacy image and UI-generator dependencies. + ## 0.1.58 — 2026-10-21 - Resize Recognition Feed and Plate Database columns using draggable header dividers or the keyboard, with separate saved widths per browser and a reset option. diff --git a/README.md b/README.md index 22f5fc0..305963f 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,10 @@ checksums local or SSH image storage, and starts an outbound-isolated target for browser review. It stores no passwords in state and never stops, switches, or deletes the retained source. +## Camera inputs + +Settings > Integrations > Camera Inputs supports Blue Iris and AXIS License Plate Verifier HTTP/MQTT sources. Existing Blue Iris feeds continue automatically. See [camera input setup](docs/CAMERA_INPUTS.md). + ## Blue Iris ingestion Send ALPR JSON to `/api/plate-reads`. Authenticate with either of these HTTP diff --git a/app/api/camera-inputs/[id]/events/route.js b/app/api/camera-inputs/[id]/events/route.js new file mode 100644 index 0000000..324d030 --- /dev/null +++ b/app/api/camera-inputs/[id]/events/route.js @@ -0,0 +1,35 @@ +import { getPool } from "@/lib/db"; +import { publicInput } from "@/lib/camera-inputs/config.mjs"; +import { CameraInputRepository } from "@/lib/camera-inputs/repository.mjs"; +import { denyUnlessRoutePermission } from "@/lib/route-permission.mjs"; + +export async function GET(_request, { params }) { + const denied = await denyUnlessRoutePermission("system.manage_settings"); + if (denied) return denied; + const { id } = await params; + try { + const pool = await getPool(); + const result = await pool.query( + `SELECT events.id,events.status,events.received_at,events.transport, + events.payload - 'image' - 'sceneImage' AS event, + CASE WHEN passages.last_event_id=events.id THEN reads.thumbnail_path END AS thumbnail_path, + CASE WHEN passages.last_event_id=events.id THEN reads.image_path END AS image_path, + CASE WHEN passages.last_event_id=events.id THEN passages.scene_image_path END AS scene_image_path, + CASE WHEN passages.last_event_id=events.id THEN passages.scene_thumbnail_path END AS scene_thumbnail_path + FROM public.camera_input_events events LEFT JOIN public.plate_reads reads ON reads.id=events.read_id + LEFT JOIN public.camera_input_passages passages ON passages.id=events.passage_id + WHERE events.input_id=$1 ORDER BY events.id DESC LIMIT 5`, + [id], + ); + const input = publicInput(await new CameraInputRepository(pool).get(id)); + return Response.json( + { events: result.rows, input }, + { headers: { "Cache-Control": "no-store" } }, + ); + } catch { + return Response.json( + { error: "Unable to load recent events" }, + { status: 503 }, + ); + } +} diff --git a/app/api/camera-inputs/[id]/test/route.js b/app/api/camera-inputs/[id]/test/route.js new file mode 100644 index 0000000..5d7760c --- /dev/null +++ b/app/api/camera-inputs/[id]/test/route.js @@ -0,0 +1,29 @@ +import mqtt from "mqtt"; +import { getPool } from "@/lib/db"; +import { denyUnlessRoutePermission } from "@/lib/route-permission.mjs"; +import { CameraInputRepository } from "@/lib/camera-inputs/repository.mjs"; +import { testMqttConnection } from "@/lib/camera-inputs/connection-test.mjs"; + +export async function POST(_request, { params }) { + const denied = await denyUnlessRoutePermission("system.manage_settings"); + if (denied) return denied; + const { id } = await params; + try { + const input = ( + await new CameraInputRepository(await getPool()).mqttInputs() + ).find((row) => row.id === id); + if (!input?.broker_enabled) + return Response.json( + { error: "Select an enabled MQTT input and broker first" }, + { status: 400 }, + ); + return Response.json(await testMqttConnection(input, mqtt.connect), { + headers: { "Cache-Control": "no-store" }, + }); + } catch { + return Response.json( + { error: "Connection test unavailable" }, + { status: 503 }, + ); + } +} diff --git a/app/api/camera-inputs/axis/[id]/route.js b/app/api/camera-inputs/axis/[id]/route.js new file mode 100644 index 0000000..f0ed5e8 --- /dev/null +++ b/app/api/camera-inputs/axis/[id]/route.js @@ -0,0 +1,21 @@ +import { getPool } from "@/lib/db"; +import { CameraInputRepository } from "@/lib/camera-inputs/repository.mjs"; +import { wakeCameraInputs } from "@/lib/camera-inputs/runtime.mjs"; +import { createAxisReceiver } from "@/lib/camera-inputs/http.mjs"; + +export const runtime = "nodejs"; +export async function POST(request, { params }) { + const { id } = await params; + try { + const receiver = createAxisReceiver({ + repository: new CameraInputRepository(await getPool()), + wake: wakeCameraInputs, + }); + return await receiver(request, id); + } catch { + return Response.json( + { error: "Event receiver unavailable; retry later" }, + { status: 503 }, + ); + } +} diff --git a/app/api/camera-inputs/route.js b/app/api/camera-inputs/route.js new file mode 100644 index 0000000..acc4f3a --- /dev/null +++ b/app/api/camera-inputs/route.js @@ -0,0 +1,61 @@ +import { getPool } from "@/lib/db"; +import { denyUnlessRoutePermission } from "@/lib/route-permission.mjs"; +import { CameraInputRepository } from "@/lib/camera-inputs/repository.mjs"; +import { InputError, readAxisRequest } from "@/lib/camera-inputs/axis.mjs"; + +export async function GET() { + const denied = await denyUnlessRoutePermission("system.manage_settings"); + if (denied) return denied; + try { + const pool = await getPool(); + const [inputs, brokers] = await Promise.all([ + new CameraInputRepository(pool).list(), + pool.query( + "SELECT id,name,broker,port,enabled FROM public.mqttbrokers ORDER BY name", + ), + ]); + return Response.json( + { inputs, brokers: brokers.rows }, + { headers: { "Cache-Control": "no-store" } }, + ); + } catch { + return Response.json( + { error: "Unable to load camera inputs" }, + { status: 503 }, + ); + } +} +export async function POST(request) { + const denied = await denyUnlessRoutePermission("system.manage_settings"); + if (denied) return denied; + try { + const data = await readAxisRequest(request, 64 * 1024); + if (!data || Array.isArray(data) || typeof data !== "object") + throw new InputError("Expected camera settings"); + const repository = new CameraInputRepository(await getPool()); + const result = await repository.save(data, data.id || null); + return Response.json(result, { headers: { "Cache-Control": "no-store" } }); + } catch (error) { + const status = + error instanceof InputError + ? error.status + : error?.code === "23505" + ? 409 + : error?.code === "23503" || error?.code === "22P02" + ? 400 + : 503; + return Response.json( + { + error: + error instanceof InputError + ? error.message + : status === 409 + ? "That camera name or device is already configured" + : status === 400 + ? "Invalid camera or broker selection" + : "Unable to save camera settings", + }, + { status }, + ); + } +} diff --git a/app/api/plate-reads/route.js b/app/api/plate-reads/route.js index 2a1e4dc..f470637 100644 --- a/app/api/plate-reads/route.js +++ b/app/api/plate-reads/route.js @@ -1,848 +1,9 @@ -import { - checkPlateForNotification, - getPool, - isPlateIgnored, -} from "@/lib/db"; -import { sendPushoverNotification } from "@/lib/notifications"; -import { - processAcceptedPlateReadEffects, -} from "@/lib/accepted-plate-read-effects.mjs"; -import { NotificationAcceptedReadService } from "@/lib/notification-accepted-read-service.mjs"; -import { NotificationRuntimeRepository } from "@/lib/notification-runtime-repository.mjs"; -import { reconcileLateDuplicateRead } from "@/lib/late-duplicate-reconciliation.mjs"; -import { createPlateReadEventIdentity } from "@/lib/plate-read-event-identity.mjs"; -import { parseBlueIrisAlertPointer } from "@/lib/blue-iris-alert-pointer.mjs"; -import { - applyBlueIrisDirectionEligibility, - blueIrisTriggerDirectionColumns, - persistBlueIrisPrimaryDirectionForRead, - resolveBlueIrisTriggerDirectionForRead, -} from "@/lib/blue-iris-trigger-direction.mjs"; -import { assessDirectionImageEligibility } from "@/lib/direction-image-eligibility.mjs"; -import { wakeBlueIrisVehicleFrameWorker } from "@/lib/blue-iris-vehicle-frame-runtime.mjs"; -import { - recordAliasApplicationWithClient, - resolvePlateAliasWithClient, -} from "@/lib/plate-review-repository.mjs"; -import { MqttAcceptedReadService } from "@/lib/mqtt/accepted-read-service.mjs"; -import { MqttRepository } from "@/lib/mqtt/repository.mjs"; -import { getConfig } from "@/lib/settings"; -import fileStorage from "@/lib/fileStorage"; -import { createIntegrationIngressRecorder } from "@/lib/integration-ingress.mjs"; -import { - appendReadPipelineEvents, - buildAcceptedReadPipelineEvents, - buildLateDuplicateReconciliationEvent, - buildLegacyPushoverPipelineEvent, -} from "@/lib/read-pipeline-timeline.mjs"; import { createIntegrationRouteHandler } from "@/lib/request-auth.mjs"; -import { overviewReadQueueState } from "@/lib/vehicle-overview-association.mjs"; -import { createComponentLogger } from "@/logging/logger"; -import { publishPlateReadChanges } from "@/lib/sse"; - -const plateIngressLogger = createComponentLogger("plate-read-ingress"); -const plateIngressRecorder = createIntegrationIngressRecorder({ - query: async (text, values) => { - const pool = await getPool(); - return pool.query(text, values); - }, - logger: plateIngressLogger, -}); - -async function recordReadPipelineEvents(buildEvents, context = {}) { - try { - const events = typeof buildEvents === "function" ? buildEvents() : buildEvents; - const pool = await getPool(); - await appendReadPipelineEvents( - (text, values) => pool.query(text, values), - events, - ); - } catch (error) { - plateIngressLogger.warn("read_pipeline_timeline_append_failed", { - readId: context.readId ?? null, - requestId: context.requestId ?? null, - errorCode: error?.code || "READ_PIPELINE_TIMELINE_APPEND_FAILED", - }); - } -} - -// Revised to use a blacklist of all other possible AI labels if using the memo -const EXCLUDED_LABELS = [ - "person", - "bicycle", - "car", - "motorcycle", - "bus", - "truck", - "bird", - "cat", - "dog", - "horse", - "sheep", - "cow", - "bear", - "deer", - "rabbit", - "raccoon", - "fox", - "skunk", - "squirrel", - "pig", - "vehicle", - "boat", - "bottle", - "chair", - "cup", - "table", - "airplane", - "train", - "traffic light", - "fire hydrant", - "stop sign", - "parking meter", - "bench", - "elephant", - "zebra", - "giraffe", - "backpack", - "umbrella", - "handbag", - "tie", - "suitcase", - "frisbee", - "skis", - "snowboard", - "sports ball", - "kite", - "baseball bat", - "baseball glove", - "skateboard", - "surfboard", - "tennis racket", - "wine glass", - "fork", - "knife", - "spoon", - "bowl", - "banana", - "apple", - "sandwich", - "orange", - "broccoli", - "carrot", - "hot dog", - "pizza", - "donut", - "cake", - "couch", - "potted plant", - "bed", - "dining table", - "toilet", - "tv", - "laptop", - "mouse", - "remote", - "keyboard", - "cell phone", - "microwave", - "oven", - "toaster", - "sink", - "refrigerator", - "book", - "clock", - "vase", - "scissors", - "teddy bear", - "hair drier", - "toothbrush", - "plate", - "dayplate", - "nightplate", - "people", - "motorbike", -].map((label) => label.toLowerCase()); - -function extractPlatesFromMemo(memo) { - if (!memo) { - return []; - } - - // Split up all the detected objects/plates in memo - const detections = memo.split(",").map((d) => d.trim()); - - // Process each item in the memo - const plates = detections - .map((detection) => { - // Split by colon to separate label from confidence - const [label] = detection.split(":"); - - if (!label) { - return null; - } - - // Convert to lowercase for comparison - const normalizedLabel = label.trim().toLowerCase(); - - // ignore other AI objects and only return plates - if (EXCLUDED_LABELS.includes(normalizedLabel)) { - return null; - } - - // The older dayplate and nightplate models return the plate in brackets - let plateNumber = label.trim(); - if (plateNumber.includes("[") && plateNumber.includes("]")) { - plateNumber = plateNumber.replace(/\[|\]/g, ""); - } - - // Return cleaned plate number in uppercase - return plateNumber.toUpperCase(); - }) - .filter((plate) => plate !== null); - - return [...new Set(plates)]; // Remove duplicates -} - -async function processPlateRead(data, _request, context = {}) { - let dbClient = null; - let transactionOpen = false; - const transactionImages = []; - - try { - // Preserve whether Blue Iris supplied a timestamp. The database still gets - // a valid server timestamp when it is missing, while the MQTT payload can - // label that case as a server-receipt fallback. - const timestamp = data.timestamp || new Date().toISOString(); - const camera = data.camera || null; - let plates = []; - - // Handle AI dump format if present - if (data.ai_dump) { - try { - const aiDumpArray = Array.isArray(data.ai_dump) - ? data.ai_dump - : [data.ai_dump]; - - // Find the ALPR response in the ai_dump array - const aiData = aiDumpArray.find((item) => item?.api === "alpr"); - - if (aiData?.found?.predictions) { - // Get all plate annotations for this batch - const allPlateAnnotations = aiData.found.predictions - .filter((pred) => pred.valid_ocr_annotation) - .map((pred) => pred.plate_annotation) - .filter(Boolean) - .join("&"); - - // Process each prediction - plates = aiData.found.predictions.map((prediction) => ({ - plate_number: prediction.plate?.toUpperCase(), - confidence: prediction.confidence.toFixed(2), - crop_coordinates: [ - prediction.x_min, - prediction.y_min, - prediction.x_max, - prediction.y_max, - ], - ...(prediction.valid_ocr_annotation && { - ocr_annotation: { - ocr_annotation: prediction.ocr_annotation, - }, - plate_annotation: allPlateAnnotations, - }), - })); - } - } catch { - context.setOutcome?.({ - outcome: "invalid_plate_payload", - errorCode: "INVALID_PLATE_PAYLOAD", - }); - plateIngressLogger.warn("plate_read_payload_invalid", { - requestId: context.requestId, - cameraName: camera, - errorCode: "INVALID_PLATE_PAYLOAD", - }); - return Response.json( - { error: "Invalid plate-read payload" }, - { status: 400 } - ); - } - } - // Backwards compatibility for older formats - else if (data.memo) { - //extract plates from memo - plates = extractPlatesFromMemo(data.memo).map((plate) => ({ - plate_number: plate, - })); - } else if (data.plate_number) { - plates = [ - { - plate_number: data.plate_number.toUpperCase(), - }, - ]; - } - - if (plates.length === 0) { - context.setOutcome?.({ - outcome: "no_valid_plates", - errorCode: "NO_VALID_PLATES", - }); - return Response.json( - { error: "No valid plates found in request" }, - { status: 400 } - ); - } - - let directionImageEligibility; - try { - directionImageEligibility = await assessDirectionImageEligibility(data.Image); - } catch { - directionImageEligibility = { - eligible: false, - evaluated: false, - monochrome: false, - monochromeRatio: null, - reason: "direction_image_assessment_failed", - }; - plateIngressLogger.warn("direction_image_assessment_failed", { - requestId: context.requestId, - cameraName: camera, - errorCode: "DIRECTION_IMAGE_ASSESSMENT_FAILED", - }); - } - - // Get database connection - const pool = await getPool(); - dbClient = await pool.connect(); - await dbClient.query("BEGIN"); - transactionOpen = true; - - const config = await getConfig(); - const mqttRepository = new MqttRepository({ - pool, - executor: dbClient, - }); - const mqttService = new MqttAcceptedReadService({ - repository: mqttRepository, - logger: plateIngressLogger, - matchingSettings: config.plateMatching, - }); - const notificationService = new NotificationAcceptedReadService({ - repository: new NotificationRuntimeRepository({ executor: dbClient }), - mqttRepository, - logger: plateIngressLogger, - matchingSettings: config.plateMatching, - }); - const resolvedBlueIrisTriggerDirection = await resolveBlueIrisTriggerDirectionForRead({ - query: (text, values) => dbClient.query(text, values), - camera, - value: data.trigger_type ?? data.triggerType ?? data.TYPE, - }); - const blueIrisTriggerDirection = applyBlueIrisDirectionEligibility( - resolvedBlueIrisTriggerDirection, - directionImageEligibility - ); - const blueIrisTriggerColumns = blueIrisTriggerDirectionColumns(blueIrisTriggerDirection); - const overviewVehicleView = overviewReadQueueState({ - eligibility: directionImageEligibility, - directionStatus: blueIrisTriggerColumns.bi_trigger_direction_status, - directionLabel: blueIrisTriggerColumns.bi_trigger_direction_label, - }); - - const processedPlates = []; - const duplicatePlates = []; - const duplicateTargetReadIds = []; - const ignoredPlates = []; - const pendingEffects = []; - const duplicateReconciliations = []; - let overviewWorkQueued = false; - const blueIrisAlert = parseBlueIrisAlertPointer({ - clip: data.ALERT_CLIP, - path: data.ALERT_PATH, - camera, - }); - - for (const plateData of plates) { - const observedPlate = plateData.plate_number; - const alias = await resolvePlateAliasWithClient(dbClient, { - observedPlate, - cameraName: camera, - }); - const effectivePlate = alias?.target_plate || observedPlate; - const effectivePlateData = { - ...plateData, - observed_plate: observedPlate, - plate_number: effectivePlate, - }; - - // Ignore decisions use the effective identity so a reviewed alias inherits - // the known plate's behavior without altering the immutable observation. - const isIgnored = await isPlateIgnored(effectivePlate); - if (isIgnored) { - ignoredPlates.push(observedPlate); - continue; - } - - let imagePaths = { imagePath: null, thumbnailPath: null }; - if (data.Image) { - try { - imagePaths = await fileStorage.saveImage( - data.Image, - plateData.plate_number - ); - } catch { - plateIngressLogger.error("plate_image_storage_failed", { - requestId: context.requestId, - cameraName: camera, - errorCode: "PLATE_IMAGE_STORAGE_FAILED", - }); - } - } - - // Track files as soon as they are created. Any failure between image - // storage and COMMIT must remove them along with the rolled-back row. - if (imagePaths.imagePath || imagePaths.thumbnailPath) { - transactionImages.push(imagePaths); - } - - const biPath = blueIrisAlert.playbackPath; - - const eventIdentity = createPlateReadEventIdentity({ - plateNumber: observedPlate, - timestamp, - cameraName: camera, - }); - - const result = await dbClient.query( - `WITH new_plate AS ( - INSERT INTO plates (plate_number) - VALUES ($1) - ON CONFLICT (plate_number) DO NOTHING - ), - new_read AS ( - INSERT INTO plate_reads ( - plate_number, - observed_plate, - applied_alias_id, - review_status, - review_revision, - validated, - image_data, - image_path, - thumbnail_path, - timestamp, - camera_name, - bi_path, - bi_alert_clip, - bi_alert_path, - bi_alert_offset_ms, - bi_trigger_type, - bi_trigger_direction_status, - bi_trigger_direction_label, - bi_trigger_direction_profile_version, - bi_trigger_direction_algorithm, - bi_trigger_direction_error_code, - confidence, - crop_coordinates, - ocr_annotation, - plate_annotation, - event_identity, - vehicle_image_status, - vehicle_image_queue_kind, - vehicle_image_attempt_count, - vehicle_image_retryable, - vehicle_image_error_code, - vehicle_image_updated_at - ) - SELECT $1, $2::varchar, $3, - CASE WHEN $3::bigint IS NULL THEN 'unreviewed' ELSE 'alias_resolved' END, - CASE WHEN $3::bigint IS NULL THEN 0 ELSE 1 END, - ($3::bigint IS NOT NULL), - $4, $5, $6, $7, $8::varchar, $9, $10, $11, $12, - $18, $19, $20, $21, $22, $23, - $13, $14, $15, $16, $17, - $24, $25, 0, $26, $27, CURRENT_TIMESTAMP - WHERE NOT EXISTS ( - SELECT 1 FROM plate_reads - WHERE observed_plate = $2::varchar AND timestamp = $7 - AND camera_name IS NOT DISTINCT FROM $8::varchar - ) - ON CONFLICT DO NOTHING - RETURNING id - ), - traffic_camera_observation AS ( - INSERT INTO public.camera_observations ( - source_key, camera_key, observation_kind, - observation_timestamp, received_at, direction_label, - blue_iris_timeline_path, plate_read_id, raw_payload, - idempotency_key - ) - SELECT 'plate-ingress', COALESCE(NULLIF(BTRIM($8::text), ''), 'unconfigured-camera'), - 'lpr', $7, CURRENT_TIMESTAMP, $20, - $11, new_read.id, - jsonb_build_object('eventIdentity', $17::text), - repeat(md5('plate-read:' || new_read.id::text), 2) - FROM new_read - ON CONFLICT (idempotency_key) DO NOTHING - RETURNING id - ) - SELECT id, NULL::bigint AS duplicate_target_read_id - FROM new_read - UNION ALL - SELECT NULL::bigint AS id, existing.id AS duplicate_target_read_id - FROM plate_reads existing - WHERE existing.observed_plate = $2::varchar - AND existing.timestamp = $7 - AND existing.camera_name IS NOT DISTINCT FROM $8::varchar - AND NOT EXISTS (SELECT 1 FROM new_read) - ORDER BY duplicate_target_read_id DESC NULLS LAST - LIMIT 1`, - [ - effectivePlate, - observedPlate, - alias?.id || null, - null, - imagePaths.imagePath, - imagePaths.thumbnailPath, - timestamp, - camera, - biPath, - blueIrisAlert.alertClip, - blueIrisAlert.alertPath, - blueIrisAlert.offsetMs, - effectivePlateData.confidence || null, - effectivePlateData.crop_coordinates || null, - effectivePlateData.ocr_annotation || null, - effectivePlateData.plate_annotation || null, - eventIdentity, - blueIrisTriggerColumns.bi_trigger_type, - blueIrisTriggerColumns.bi_trigger_direction_status, - blueIrisTriggerColumns.bi_trigger_direction_label, - blueIrisTriggerColumns.bi_trigger_direction_profile_version, - blueIrisTriggerColumns.bi_trigger_direction_algorithm, - blueIrisTriggerColumns.bi_trigger_direction_error_code, - overviewVehicleView.status, - overviewVehicleView.queueKind, - overviewVehicleView.retryable, - overviewVehicleView.errorCode, - ] - ); - - const resultRow = result.rows?.[0] || {}; - if (!resultRow.id) { - duplicatePlates.push(observedPlate); - const duplicateTargetReadId = Number.parseInt( - String(resultRow.duplicate_target_read_id ?? ""), - 10, - ); - if (Number.isSafeInteger(duplicateTargetReadId) - && duplicateTargetReadId > 0 - && !duplicateTargetReadIds.includes(duplicateTargetReadId)) { - duplicateTargetReadIds.push(duplicateTargetReadId); - } - - let reconciliation = null; - let directionNotificationResult = null; - if (Number.isSafeInteger(duplicateTargetReadId) && duplicateTargetReadId > 0) { - reconciliation = await reconcileLateDuplicateRead( - (text, values) => dbClient.query(text, values), - { - readId: duplicateTargetReadId, - imagePath: imagePaths.imagePath, - thumbnailPath: imagePaths.thumbnailPath, - alert: { - bi_path: biPath, - bi_alert_clip: blueIrisAlert.alertClip, - bi_alert_path: blueIrisAlert.alertPath, - bi_alert_offset_ms: blueIrisAlert.offsetMs, - }, - recognition: { - confidence: effectivePlateData.confidence ?? null, - crop_coordinates: effectivePlateData.crop_coordinates ?? null, - ocr_annotation: effectivePlateData.ocr_annotation ?? null, - plate_annotation: effectivePlateData.plate_annotation ?? null, - }, - direction: blueIrisTriggerColumns, - vehicleOverview: overviewVehicleView, - }, - ); - - if (reconciliation.directionAttached) { - const primaryDirection = await persistBlueIrisPrimaryDirectionForRead({ - query: (text, values) => dbClient.query(text, values), - readId: duplicateTargetReadId, - camera, - evidence: blueIrisTriggerDirection, - }); - if (primaryDirection) { - directionNotificationResult = await notificationService.processVehicleDirection( - { - ...reconciliation.read, - id: duplicateTargetReadId, - persisted_timestamp: reconciliation.read.timestamp, - }, - primaryDirection, - ); - if ( - directionNotificationResult.status === "error" - || directionNotificationResult.status === "partial" - ) { - throw new Error( - `Blue Iris direction notification outbox handoff failed for reconciled read ${duplicateTargetReadId}` - ); - } - } - } - - if (reconciliation.changed) { - duplicateReconciliations.push({ - reconciliation, - directionNotificationResult, - }); - if (reconciliation.overviewQueued) overviewWorkQueued = true; - } - } - - if (!reconciliation?.imageAttached) { - await fileStorage - .deleteImage(imagePaths.imagePath, imagePaths.thumbnailPath) - .catch(() => plateIngressLogger.warn("duplicate_plate_image_cleanup_failed", { - requestId: context.requestId, - cameraName: camera, - errorCode: "DUPLICATE_IMAGE_CLEANUP_FAILED", - })); - const trackedImageIndex = transactionImages.indexOf(imagePaths); - if (trackedImageIndex >= 0) { - transactionImages.splice(trackedImageIndex, 1); - } - } - } else { - const readId = resultRow.id; - const primaryDirection = await persistBlueIrisPrimaryDirectionForRead({ - query: (text, values) => dbClient.query(text, values), - readId, - camera, - evidence: blueIrisTriggerDirection, - }); - await recordAliasApplicationWithClient(dbClient, { - readId, - eventIdentity, - alias, - observedPlate, - }); - processedPlates.push({ - plate: effectivePlate, - observedPlate, - id: readId, - aliasApplied: Boolean(alias), - }); - if (overviewVehicleView.queueKind === "overview") overviewWorkQueued = true; - - const acceptedRead = { - ...effectivePlateData, - id: readId, - plate_number: effectivePlate, - camera_name: camera, - timestamp: data.timestamp || null, - persisted_timestamp: timestamp, - image_path: imagePaths.imagePath, - thumbnail_path: imagePaths.thumbnailPath, - bi_path: biPath, - bi_alert_clip: blueIrisAlert.alertClip, - bi_alert_path: blueIrisAlert.alertPath, - bi_alert_offset_ms: blueIrisAlert.offsetMs, - ...blueIrisTriggerColumns, - }; - - const mqttResult = await mqttService.processAcceptedRead(acceptedRead); - if (mqttResult.status === "error" || mqttResult.status === "partial") { - throw new Error( - `MQTT outbox handoff failed for accepted read ${readId}` - ); - } - const unifiedResult = await notificationService.processAcceptedRead(acceptedRead); - if (unifiedResult.status === "error" || unifiedResult.status === "partial") { - throw new Error( - `Unified notification outbox handoff failed for accepted read ${readId}` - ); - } - let directionResult = null; - if (primaryDirection) { - directionResult = await notificationService.processVehicleDirection( - acceptedRead, - primaryDirection - ); - if (directionResult.status === "error" || directionResult.status === "partial") { - throw new Error( - `Blue Iris direction notification outbox handoff failed for accepted read ${readId}` - ); - } - } - - pendingEffects.push({ - read: acceptedRead, - imageData: data.Image, - mqttResult, - unifiedResult, - directionResult, - aliasApplied: Boolean(alias), - imageStored: Boolean(imagePaths.imagePath), - thumbnailStored: Boolean(imagePaths.thumbnailPath), - alertPointerPresent: Boolean( - blueIrisAlert.alertClip || blueIrisAlert.alertPath || blueIrisAlert.playbackPath - ), - direction: blueIrisTriggerColumns, - vehicleOverview: overviewVehicleView, - }); - } - } - - await dbClient.query("COMMIT"); - transactionOpen = false; - publishPlateReadChanges( - [ - ...processedPlates.map(({ id }) => id), - ...duplicateTargetReadIds, - ], - processedPlates.length > 0 ? "ingested" : "duplicate_reconciled" - ); - for (const effect of pendingEffects) { - await recordReadPipelineEvents( - () => buildAcceptedReadPipelineEvents({ - readId: effect.read.id, - requestId: context.requestId, - ingressReceiptId: context.ingressReceiptId, - aliasApplied: effect.aliasApplied, - imageStored: effect.imageStored, - thumbnailStored: effect.thumbnailStored, - alertPointerPresent: effect.alertPointerPresent, - direction: effect.direction, - mqttResult: effect.mqttResult, - notificationResult: effect.unifiedResult, - directionNotificationResult: effect.directionResult, - vehicleOverview: effect.vehicleOverview, - }), - { readId: effect.read.id, requestId: context.requestId }, - ); - } - for (const effect of duplicateReconciliations) { - await recordReadPipelineEvents( - () => [buildLateDuplicateReconciliationEvent({ - readId: effect.reconciliation.readId, - requestId: context.requestId, - ingressReceiptId: context.ingressReceiptId, - reconciliation: effect.reconciliation, - directionNotificationResult: effect.directionNotificationResult, - })], - { readId: effect.reconciliation.readId, requestId: context.requestId }, - ); - } - if (overviewWorkQueued) wakeBlueIrisVehicleFrameWorker(); - - // Unified MQTT and Pushover handoffs committed with each read. The legacy - // Pushover path remains post-commit until every migrated rule is cut over. - for (const effect of pendingEffects) { - try { - const legacyResult = await processAcceptedPlateReadEffects({ - read: effect.read, - imageData: effect.imageData, - shouldSendPushover: checkPlateForNotification, - sendPushover: sendPushoverNotification, - processMqtt: async () => effect.mqttResult, - logger: plateIngressLogger, - }); - await recordReadPipelineEvents( - () => [buildLegacyPushoverPipelineEvent({ - readId: effect.read.id, - requestId: context.requestId, - ingressReceiptId: context.ingressReceiptId, - result: legacyResult, - })], - { readId: effect.read.id, requestId: context.requestId }, - ); - } catch { - plateIngressLogger.error("accepted_plate_notification_processing_failed", { - requestId: context.requestId, - processedCount: processedPlates.length, - errorCode: "ACCEPTED_READ_EFFECT_FAILED", - }); - } - } - - const responseStatus = processedPlates.length > 0 ? 201 : 409; - const outcome = processedPlates.length > 0 - ? "accepted" - : duplicatePlates.length > 0 - ? "duplicate" - : ignoredPlates.length > 0 - ? "ignored" - : "no_changes"; - const outcomeDetails = { - outcome, - processedReadIds: processedPlates.map(({ id }) => id), - processedCount: processedPlates.length, - duplicateCount: duplicatePlates.length, - duplicateTargetReadIds, - duplicateReconciledCount: duplicateReconciliations.length, - duplicateReconciledReadIds: duplicateReconciliations.map( - ({ reconciliation }) => reconciliation.readId, - ), - ignoredCount: ignoredPlates.length, - overviewWorkQueued, - }; - context.setOutcome?.(outcomeDetails); - plateIngressLogger.info("plate_read_ingress_completed", { - requestId: context.requestId, - cameraName: camera, - httpStatus: responseStatus, - triggerType: blueIrisTriggerColumns.bi_trigger_type, - directionStatus: blueIrisTriggerColumns.bi_trigger_direction_status, - directionLabel: blueIrisTriggerColumns.bi_trigger_direction_label, - directionErrorCode: blueIrisTriggerColumns.bi_trigger_direction_error_code, - directionProfileVersion: blueIrisTriggerColumns.bi_trigger_direction_profile_version, - directionAlgorithm: blueIrisTriggerColumns.bi_trigger_direction_algorithm, - ...outcomeDetails, - }); - - return Response.json( - { - processed: processedPlates, - duplicates: duplicatePlates, - ignored: ignoredPlates, - message: `Processed ${processedPlates.length} plates, ${duplicatePlates.length} duplicates, ${ignoredPlates.length} ignored`, - }, - { status: responseStatus } - ); - } catch (error) { - const shouldDeleteTransactionImages = transactionOpen; - - if (dbClient && transactionOpen) { - try { - await dbClient.query("ROLLBACK"); - } catch { - plateIngressLogger.error("plate_read_transaction_rollback_failed", { - requestId: context.requestId, - errorCode: "PLATE_READ_ROLLBACK_FAILED", - }); - } - } - - if (shouldDeleteTransactionImages) { - await Promise.allSettled( - transactionImages.map(({ imagePath, thumbnailPath }) => - fileStorage.deleteImage(imagePath, thumbnailPath) - ) - ); - } - - throw error; - } finally { - if (dbClient) { - dbClient.release(); - } - } -} +import { + processPlateRead, + plateIngressLogger, + plateIngressRecorder, +} from "@/lib/plate-read-ingestion"; export const POST = createIntegrationRouteHandler(processPlateRead, { integration: "blue_iris", diff --git a/app/settings/integrations/camera-inputs/page.jsx b/app/settings/integrations/camera-inputs/page.jsx new file mode 100644 index 0000000..86a63f7 --- /dev/null +++ b/app/settings/integrations/camera-inputs/page.jsx @@ -0,0 +1,8 @@ +import { CameraInputs } from "@/components/settings/CameraInputs"; +import { requirePagePermission } from "@/lib/page-permission.mjs"; + +export const dynamic = "force-dynamic"; +export default async function CameraInputsPage() { + await requirePagePermission("system.manage_settings"); + return ; +} diff --git a/components/settings/CameraInputs.jsx b/components/settings/CameraInputs.jsx new file mode 100644 index 0000000..e59b22a --- /dev/null +++ b/components/settings/CameraInputs.jsx @@ -0,0 +1,743 @@ +"use client"; + +import Link from "next/link"; +import Image from "next/image"; +import { useCallback, useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; + +const blank = { + camera_name: "", + source: "", + transport: "http", + enabled: true, + device_id: "", + broker_id: "", + topic_filter: "", + qos: 1, + processing_mode: "immediate", + store_images: true, + direction_in: "In", + direction_out: "Out", + roi_filter: "", +}; +const selectClass = + "h-10 w-full rounded-md border border-input bg-background px-3 text-sm"; +async function api(url, data) { + const response = await fetch( + url, + data === undefined + ? { cache: "no-store" } + : { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(data), + }, + ); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || "Request failed"); + return result; +} +function Field({ label, children }) { + return ( + + ); +} +function date(value) { + return value ? new Date(value).toLocaleString() : "No events yet"; +} + +export function CameraInputs() { + const [inputs, setInputs] = useState([]); + const [brokers, setBrokers] = useState([]); + const [draft, setDraft] = useState(null); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(""); + const [credential, setCredential] = useState(null); + const [events, setEvents] = useState([]); + const [listening, setListening] = useState(null); + const [brokerDraft, setBrokerDraft] = useState(null); + const [origin, setOrigin] = useState(""); + const [loaded, setLoaded] = useState(false); + const load = useCallback(async () => { + const result = await api("/api/camera-inputs"); + setInputs(result.inputs); + setBrokers(result.brokers); + setLoaded(true); + }, []); + useEffect(() => { + setOrigin(window.location.origin); + void load().catch((error) => setMessage(error.message)); + }, [load]); + useEffect(() => { + if (!listening) return; + let active = true; + const refresh = async () => { + try { + const result = await api(`/api/camera-inputs/${listening.id}/events`); + if (active) { + setEvents(result.events); + if (result.input) + setInputs((current) => + current.map((input) => + input.id === result.input.id + ? { ...input, ...result.input } + : input, + ), + ); + } + } catch (error) { + if (active) setMessage(error.message); + } + }; + void refresh(); + const timer = setInterval(() => { + void refresh(); + }, 2000); + const deadline = setTimeout(() => { + if (active) { + setListening(null); + setMessage("Listening finished. Recent events are shown below."); + } + }, 60000); + return () => { + active = false; + clearInterval(timer); + clearTimeout(deadline); + }; + }, [listening, load]); + const change = (key, value) => + setDraft((current) => ({ ...current, [key]: value })); + const edit = (input) => { + setDraft({ ...blank, ...input }); + setCredential(null); + setMessage(""); + setBrokerDraft(null); + }; + const endpoint = draft?.id + ? `${origin}/api/camera-inputs/axis/${draft.id}` + : "Save this camera to generate its destination URL."; + async function save(event) { + event.preventDefault(); + setBusy(true); + setMessage(""); + try { + const result = await api("/api/camera-inputs", draft); + setDraft({ ...blank, ...result.input }); + if (result.credential) + setCredential({ id: result.input.id, secret: result.credential }); + await load(); + setMessage("Camera input saved. Existing history is preserved."); + } catch (error) { + setMessage(error.message); + } finally { + setBusy(false); + } + } + async function addBroker() { + setBusy(true); + try { + const result = await api("/api/mqtt/brokers", brokerDraft); + await load(); + change("broker_id", result.data.id); + setBrokerDraft(null); + } catch (error) { + setMessage(error.message); + } finally { + setBusy(false); + } + } + async function test(input) { + setBusy(true); + setMessage(""); + try { + const result = await api(`/api/camera-inputs/${input.id}/test`, {}); + setMessage(result.ok ? result.message : result.error); + } catch (error) { + setMessage(error.message); + } finally { + setBusy(false); + } + } + return ( +
+ + +
+
+ Camera inputs + + Choose where each camera supplies its plate recognition. + Existing Blue Iris cameras work automatically. + +
+ +
+
+ +
+ + + + + + + + + + + + + {inputs.map((input) => ( + + + + + + + + + ))} + +
CameraRecognition sourceDeliveryStatusLast eventActions
{input.camera_name} + {input.source === "axis" + ? "Axis License Plate Verifier" + : "Blue Iris"} + {input.transport} + {input.enabled + ? input.legacy + ? "Existing input" + : input.connection_status + : "Disabled"} + {input.last_error ? ( +

+ {input.last_error} +

+ ) : null} +
{date(input.last_received_at)} +
+ + {input.id && input.source === "axis" ? ( + <> + + {input.transport !== "http" ? ( + + ) : null} + + ) : null} +
+
+
+ {loaded && !inputs.length ? ( +

+ Connect your first camera using Add camera input. Existing Blue + Iris feeds also appear automatically after their first read. +

+ ) : null} +
+
+ {message ? ( +

+ {message} +

+ ) : null} + {draft ? ( + + + + {draft.id || draft.legacy + ? "Configure camera input" + : "Add camera input"} + + + Recognition comes from the selected source. Blue Iris recording + and playback can be configured separately. + + + +
+ + + change("camera_name", event.target.value) + } + /> + +
+ + Where does plate recognition come from? + +
+ {[ + [ + "blue_iris", + "Blue Iris", + "Receive recognition results and alert images from Blue Iris.", + ], + [ + "axis", + "Axis License Plate Verifier", + "Receive recognition results directly from the camera.", + ], + ].map(([value, title, description]) => ( + + ))} +
+
+ {draft.source === "blue_iris" ? ( +
+

+ Send Blue Iris alert JSON to{" "} + {origin}/api/plate-reads with your existing + integration API key. +

+

+ Use this camera name in the alert’s camera field. Existing + alert actions require no changes. +

+ + Blue Iris connection settings + + · + + Integration API key + +
+ ) : null} + {draft.source === "axis" ? ( + <> + {draft.legacy ? ( +

+ Saving Axis as the source will stop accepting Blue Iris + recognition for this camera name. Existing records and + Blue Iris recording remain available. +

+ ) : null} + + + change("device_id", event.target.value) + } + placeholder="Enter this camera’s device identity" + /> + + + + + {draft.transport !== "mqtt" ? ( +
+

+ Axis → Integration → Push events +

+

+ Choose HTTP POST, send New, Update and Lost events, + include images, and enable the camera’s Event buffer. +

+ + event.target.select()} + /> + +

+ Use an ALPR address reachable from the camera. The + address above comes from this browser; replace its host + if you use a different camera-facing address. +

+ {draft.id ? ( + <> +

+ HTTP Basic username:{" "} + {draft.id} +

+

+ Use the generated source credential as the password. + Header authentication also accepts this credential + as x-api-key or Bearer. +

+ + + ) : null} +

+ Use HTTPS when the camera and ALPR network supports it. +

+
+ ) : null} + {draft.transport !== "http" ? ( +
+ + + + + + + change("topic_filter", event.target.value) + } + placeholder="Copy the camera’s ALPV.AllPlates publication topic" + /> + + + + +

+ Also set the camera’s AllPlates publication to QoS 1, + with Retain set to None. ALPR uses its own persistent + client ID and imports only events matching this camera’s + identity. +

+
+ ) : null} + {brokerDraft ? ( +
+

New MQTT broker

+ {[ + ["name", "Broker name"], + ["broker", "Hostname or IP"], + ["port", "Port"], + ["username", "Username"], + ["password", "Password"], + ].map(([key, label]) => ( + + + setBrokerDraft((current) => ({ + ...current, + [key]: event.target.value, + })) + } + /> + + ))} + + +
+ ) : null} + + + change("roi_filter", event.target.value) + } + placeholder="Leave blank to accept every area of interest" + /> + + + + +

+ Immediate alerts use the first recognition. Later + corrections update the read without sending the same passage + alert again. Finalized mode waits for the best available + result. +

+
+ + + change("direction_in", event.target.value) + } + /> + + + + change("direction_out", event.target.value) + } + /> + +
+ + + ) : null} + +
+ + +
+
+
+
+ ) : null} + {credential ? ( + + + Source credential + + Copy this credential now. It is shown only when generated. + Replacing it requires updating the camera. + + + + event.target.select()} + autoComplete="off" + /> +

+ HTTP Basic username:{" "} + {credential.id} +

+
+
+ ) : null} + {events.length ? ( + + + Recent Axis events + + Camera-supplied observations are retained for seven days. Images + use application storage. Thumbnails show the latest observation + for each passage. + + + + {events.map((entry) => ( +
+ {entry.thumbnail_path ? ( + {`Plate + ) : null} + {entry.scene_thumbnail_path ? ( + Camera-supplied scene + ) : null} +
+

+ {entry.event.plate} · {entry.event.state} +

+

+ {entry.event.direction} · {entry.transport.toUpperCase()} ·{" "} + {entry.status} +

+

{date(entry.event.timestamp)}

+

+ {entry.event.metadata?.region}{" "} + {entry.event.metadata?.country} +

+
+
+ ))} +
+
+ ) : null} +

+ Recognition source and recording source are separate. Axis recognition + can be used alongside Blue Iris recording and playback.{" "} + + Configure Blue Iris + +

+
+ ); +} diff --git a/components/settings/IntegrationsLayoutShell.jsx b/components/settings/IntegrationsLayoutShell.jsx index bde15e3..08c2783 100644 --- a/components/settings/IntegrationsLayoutShell.jsx +++ b/components/settings/IntegrationsLayoutShell.jsx @@ -5,6 +5,7 @@ import { usePathname } from "next/navigation"; import { SettingsShell } from "@/components/settings/SettingsShell"; const pageDetails = { + "/settings/integrations/camera-inputs": { id: "cameraInputs", title: "Camera Inputs", description: "Configure Blue Iris and Axis plate recognition sources, HTTP push, and incoming MQTT events." }, "/settings/integrations/mqtt": { id: "mqtt", title: "MQTT", diff --git a/components/settings/SettingsShell.jsx b/components/settings/SettingsShell.jsx index 2a2617e..cfcd972 100644 --- a/components/settings/SettingsShell.jsx +++ b/components/settings/SettingsShell.jsx @@ -50,6 +50,7 @@ const navigationSections = [ { title: "Integrations", items: [ + { title: "Camera Inputs", id: "cameraInputs", href: "/settings/integrations/camera-inputs", icon: ScanSearch, permission: "system.manage_settings" }, { title: "MQTT", id: "mqtt", href: "/settings/integrations/mqtt", icon: Antenna, permission: "mqtt.manage" }, { title: "Pushover", id: "pushover", href: "/settings/integrations/pushover", icon: Bell, permission: "system.manage_settings" }, { title: "Email", id: "email", href: "/settings/integrations/email", icon: Mail, permission: "system.manage_settings" }, diff --git a/docs/CAMERA_INPUTS.md b/docs/CAMERA_INPUTS.md new file mode 100644 index 0000000..fceb827 --- /dev/null +++ b/docs/CAMERA_INPUTS.md @@ -0,0 +1,61 @@ +# Camera inputs + +Open **Settings > Integrations > Camera Inputs**. Select a recognition source for each camera: **Blue Iris** or **AXIS License Plate Verifier**. Different cameras can use different sources. Existing Blue Iris cameras appear automatically after a read; their alert actions, API key, camera names and history continue to work without enrollment. + +Recognition and recording are independent. An Axis camera may supply recognition directly while Blue Iris continues recording it. This integration does not manufacture Blue Iris alert/clip pointers for Axis events; playback pointers require an actual Blue Iris alert association. The existing Blue Iris recording setup remains available independently. + +## Blue Iris + +Use the exact camera name sent in the Blue Iris alert JSON. Send the existing alert body to `/api/plate-reads`, authenticated with the existing integration API key in `x-api-key` or `Authorization: Bearer`. Existing unregistered camera names continue to be accepted automatically. + +Explicitly switching a camera name to Axis makes Axis its recognition source. Blue Iris recognition arriving for that configured camera name is then acknowledged without importing another read. Disabling an explicitly configured input stops its imports. History is preserved, and the recording configuration is not changed. + +## Axis HTTP push + +1. Add an input, choose Axis, enter a camera name (maximum 30 characters), and enter the camera's serial number or MAC address. Device identity must match the event; IP addresses are not identities. +2. Select HTTP push and save. Copy the destination URL and the generated source credential. A credential is displayed only when generated. It is stored as a hash, scoped to this input, and cannot authenticate to application administration. +3. In Axis License Plate Verifier, open **Integration > Push events** and select HTTP POST. Use the generated destination path with an ALPR hostname/IP and port reachable from the camera. A browser reverse-proxy address may need a different camera-facing host. Prefer HTTPS. +4. Configure HTTP Basic authentication: username is the source UUID displayed by ALPR; password is the generated source credential. ALPR also accepts that credential through `x-api-key` or `Authorization: Bearer`. These are incoming push credentials, not camera administrator credentials. URL query credentials are rejected. +5. Enable New, Update and Lost events. Include images and enable the camera **Event buffer**. ALPR accepts `application/json` with base64 images or `multipart/form-data` containing an event JSON part and image files. Where available, **Send two images** supplies a scene/vehicle image alongside a plate crop. +6. Use **Listen for event**, then Axis's Test button or a real passage. Camera Test events go through the real import path and may trigger configured notifications. Avoid test plate values on a production installation. + +HTTP 200 means the event is durably stored for processing, including an idempotent duplicate; temporary storage failure receives 503 so the camera can retry. Buffer capacity and behavior depend on the installed ALPV version. Sending a second image does not automatically enable vehicle identification processing for that image. + +## Axis MQTT + +1. Keep the camera connected to an external MQTT broker. ALPR is a client, not an MQTT broker. +2. Enable the camera's **ALPV.AllPlates** publication. Copy its exact incoming topic, including device prefix and any namespace components. No separate image or payload topic is required when the JSON contains `message.data.lpImage`. +3. In Camera Inputs, select MQTT and select an existing broker or add one. Configure host/IP, port, credentials and TLS. TLS verifies the broker certificate using the host trust store. +4. Enter the topic or MQTT filter. `+` and a final `#` are supported. A dedicated broker account needs subscription/read access to that filter. The payload's camera identity must still match the configured serial/MAC. +5. Use QoS 1 for both the camera publication and ALPR subscription; keep retained publication disabled. ALPR deliberately ignores retained messages. The stable, automatically generated subscriber client ID is separate from outgoing notifications and camera/Home Assistant clients. The connection uses a persistent session. +6. Configure broker persistence and queue/message-size limits for the image-bearing payloads. A persistent broker can queue QoS 1 events during an ALPR outage. It does not recover events the camera never delivered to it, and broker limits can still cause loss. +7. Save, use **Test MQTT** to verify connection and topic permission, and **Listen for event** to inspect actual received events. Changes normally take effect within ten seconds. No ALPR API key or camera administrator password is needed for MQTT ingestion. + +The subscriber saves a validated event to PostgreSQL before acknowledging QoS 1 delivery. Temporary database failures leave the publish unacknowledged and reconnect the client. Processing retries persist across application restarts. Invalid events are acknowledged and reported as input diagnostics so a malformed message cannot prevent later valid events. + +## Passage processing + +- **Immediate:** accept the first received New/Update/Lost event promptly, then apply later plate/image/direction corrections to the same passage. `observed_plate` remains the first immutable observation. Plate-read notifications use the first recognition and do not repeat when OCR changes. +- **Finalized:** retain events until Lost; if Lost is missing, finalize after 30 seconds without another received observation. This favors corrected recognition over latency. +- Correlation uses configured camera identity, Axis runtime `carID`, event state and a bounded capture-time window. An explicit newer New event starts a new occurrence when a runtime carID is reused. Delayed older events do not overwrite newer results. +- HTTP and MQTT payloads normalize to the same event identity, excluding transport-specific packet counters. **HTTP and MQTT (advanced)** can be used together for one configured input without duplicating the same event. +- Zero or absent plate confidence does not automatically discard a read. Vehicle confidence is not substituted for plate confidence. `Accepted`/`Denied` is an access-control decision, not an OCR validity flag. +- Camera in/out direction labels are configurable. Movement direction is kept separate from front/rear vehicle view. Later direction observations use the existing durable direction-notification pipeline. +- Human-reviewed plate corrections take precedence over automatic OCR changes. Original observations and subsequent camera metadata remain separate. +- An optional raw Axis ROI ID limits imports to one area of interest. Blank accepts every ROI; the raw event ID may differ from the camera UI's displayed AOI number. +- Receipt metadata is retained for seven days. Embedded image data is removed after import, including earlier buffered observations in finalized mode. Saved plate and scene images use application storage. Recent events display thumbnails only beside the latest observation for a passage, so an earlier plate value is not paired with a later corrected image. Pending finalization retains the required image-bearing receipt. + +## Compatibility and validation + +The integration targets documented ALPV AllPlates MQTT events and ALPV HTTP JSON/multipart push formats. Firmware/app versions can vary. No Axis hardware was available during implementation; transport emulation and automated tests do not replace camera-specific compatibility verification. + +Run unit and regression checks with `yarn test`, `yarn lint`, and `yarn typecheck`. The wire-level MQTT test uses a local TCP broker fixture. The PostgreSQL verification creates and drops its own uniquely named database on an explicitly supplied isolated local server: + +```text +ALPR_AXIS_TEST_SERVER_URL=postgresql://postgres@127.0.0.1:PORT/postgres +node --experimental-loader ./scripts/camera-inputs-test-loader.mjs scripts/test-camera-inputs-postgres.mjs +``` + +Do not point that verification at an application database. It exercises the actual shared ingestion service, migrations, images, source compatibility, deduplication, corrections, and rollback/retry behavior. + +Sources: [Axis License Plate Verifier manual](https://help.axis.com/en-us/axis-license-plate-verifier), [ALPV event API](https://developer.axis.com/vapix/applications/license-plate-verifier-api/), [MQTT Event Bridge](https://developer.axis.com/vapix/network-video/mqtt-event-bridge/), [Axis OS MQTT behavior](https://help.axis.com/en-us/axis-os-knowledge-base). diff --git a/docs/COMMUNITY_PRODUCT_ROADMAP.md b/docs/COMMUNITY_PRODUCT_ROADMAP.md index 6f4142e..58bf9b6 100644 --- a/docs/COMMUNITY_PRODUCT_ROADMAP.md +++ b/docs/COMMUNITY_PRODUCT_ROADMAP.md @@ -1,6 +1,17 @@ # Community product roadmap -Last reviewed: October 21, 2026 +Last reviewed: November 1, 2026 + +## Axis camera recognition + +Community v0.1.59 adds per-camera recognition sources under Settings > +Integrations > Camera Inputs. Existing Blue Iris cameras continue automatically. +AXIS License Plate Verifier can send HTTP push, MQTT, or both, with configurable +camera identity, broker/topic, images, ROI, direction labels and passage timing. +Durable receipts support retry, transport deduplication and later corrections +while preserving original observations and human review. Recognition remains +independent of recording. Real Axis camera/firmware validation remains outstanding; +see [Camera inputs](CAMERA_INPUTS.md) for supported formats and setup. ## Adjustable table columns @@ -90,6 +101,8 @@ inherited Git history. Every release gate requires: - API-key-authenticated plate ingestion, including Blue Iris JSON and image macros; +- AXIS License Plate Verifier HTTP/MQTT input with scoped credentials, durable + event receipts, configurable source selection and connection diagnostics; - an event-driven Recognition Feed, searchable database, dashboard, tags, known and monitored plates, audited corrections, recurring OCR aliases, and bounded CSV/JSON exports; diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 2f0012b..36e361d 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -64,7 +64,7 @@ Clone the canonical repository and detach at the exact stable release tag: ```bash git clone https://github.com/prsmith777/ALPR-Database-Community.git cd ALPR-Database-Community -git checkout --detach v0.1.58 +git checkout --detach v0.1.59 ./alpr-community install ``` diff --git a/docs/UPDATES.md b/docs/UPDATES.md index 3d77ab0..452d60e 100644 --- a/docs/UPDATES.md +++ b/docs/UPDATES.md @@ -47,7 +47,7 @@ shown on the GitHub Releases page, rather than deploying moving `main`: ```bash git clone https://github.com/prsmith777/ALPR-Database-Community.git cd ALPR-Database-Community -git checkout --detach v0.1.58 +git checkout --detach v0.1.59 ./alpr-community install ``` @@ -88,7 +88,7 @@ alpr_native_update() ( set -Eeuo pipefail download_dir="$(mktemp -d /tmp/alpr-maintenance-download.XXXXXX)" trap 'rm -rf -- "$download_dir"' EXIT - asset_base="https://github.com/prsmith777/ALPR-Database-Community/releases/download/v0.1.58" + asset_base="https://github.com/prsmith777/ALPR-Database-Community/releases/download/v0.1.59" curl -fLsS --retry 3 "$asset_base/community-maintenance.sh" -o "$download_dir/community-maintenance.sh" curl -fLsS --retry 3 "$asset_base/community-maintenance.sh.sha256" -o "$download_dir/community-maintenance.sh.sha256" (cd "$download_dir" && sha256sum --check --strict community-maintenance.sh.sha256) @@ -99,7 +99,7 @@ unset -f alpr_native_update ``` The launcher verifies the canonical repository and exact released tag, loads the -fixed tools outside your checkout, and asks for **INSTALL v0.1.58**. It uses the +fixed tools outside your checkout, and asks for **INSTALL v0.1.59**. It uses the same guarded backup/install workflow and does not reset or reinstall your system. It temporarily stops only this installation's matching per-user systemd update agent, then restarts it with the installed code. Keep the terminal open and do diff --git a/instrumentation.node.js b/instrumentation.node.js index 29d2b94..18715eb 100644 --- a/instrumentation.node.js +++ b/instrumentation.node.js @@ -17,6 +17,7 @@ export async function registerMqttNodeInstrumentation({ export async function registerNodeInstrumentation({ logger = console, startMqtt = (options) => registerMqttNodeInstrumentation(options), + loadCameraInputStartup = () => import("./lib/camera-inputs/startup.mjs"), loadVehicleFrameStartup = () => import("./lib/blue-iris-vehicle-frame-startup.mjs"), loadNotificationStartup = () => import("./lib/notification-operations-startup.mjs"), loadMaintenanceStartup = () => import("./lib/maintenance-startup.mjs"), @@ -31,7 +32,8 @@ export async function registerNodeInstrumentation({ if (typeof startMqtt !== "function" || typeof loadVehicleFrameStartup !== "function" || typeof loadNotificationStartup !== "function" || typeof loadMaintenanceStartup !== "function" || typeof loadStorageMonitorStartup !== "function" || typeof loadVehicleAssetCatalogStartup !== "function" || typeof loadVehicleEventShadowStartup !== "function" || typeof loadVehicleImageCropStartup !== "function" || typeof loadVehicleAssetEmbeddingStartup !== "function" || typeof loadVehicleAssetAttributeStartup !== "function" || typeof loadVehicleReidV2LiveStartup !== "function") { throw new Error("Node instrumentation loaders must be functions"); } - const [mqttResult, vehicleFrameResult, notificationResult, maintenanceResult, storageMonitorResult, vehicleAssetCatalogResult, vehicleEventShadowResult, vehicleImageCropResult, vehicleAssetEmbeddingResult, vehicleAssetAttributeResult, vehicleReidV2LiveResult] = await Promise.allSettled([ + const [cameraInputResult, mqttResult, vehicleFrameResult, notificationResult, maintenanceResult, storageMonitorResult, vehicleAssetCatalogResult, vehicleEventShadowResult, vehicleImageCropResult, vehicleAssetEmbeddingResult, vehicleAssetAttributeResult, vehicleReidV2LiveResult] = await Promise.allSettled([ + (async () => (await loadCameraInputStartup()).startCameraInputsWithRetry({ logger }))(), startMqtt({ logger }), (async () => { const startup = await loadVehicleFrameStartup(); @@ -116,6 +118,7 @@ export async function registerNodeInstrumentation({ logger?.error?.(`${name} instrumentation startup failed`, { error }); return { status: "error", error }; }; + const cameraInputs = normalizeResult(cameraInputResult, "Camera inputs"); const mqtt = normalizeResult(mqttResult, "MQTT"); const vehicleFrames = normalizeResult(vehicleFrameResult, "Blue Iris vehicle frames"); const notificationOperations = normalizeResult(notificationResult, "Notification operations"); @@ -128,9 +131,10 @@ export async function registerNodeInstrumentation({ const vehicleAssetAttributes = normalizeResult(vehicleAssetAttributeResult, "Canonical crop attributes"); const vehicleReid = normalizeResult(vehicleReidV2LiveResult, "Authoritative ReID"); return { - status: mqtt.status === "started" && vehicleFrames.status === "started" && notificationOperations.status === "started" && maintenance.status === "started" && storageMonitor.status === "started" && vehicleAssetCatalog.status === "started" && vehicleEventShadow.status === "started" && vehicleImageCrops.status === "started" && vehicleAssetEmbeddings.status === "started" && vehicleAssetAttributes.status === "started" && vehicleReid.status === "started" + status: cameraInputs.status === "started" && mqtt.status === "started" && vehicleFrames.status === "started" && notificationOperations.status === "started" && maintenance.status === "started" && storageMonitor.status === "started" && vehicleAssetCatalog.status === "started" && vehicleEventShadow.status === "started" && vehicleImageCrops.status === "started" && vehicleAssetEmbeddings.status === "started" && vehicleAssetAttributes.status === "started" && vehicleReid.status === "started" ? "started" : "partial", + cameraInputs, mqtt, vehicleFrames, notificationOperations, diff --git a/lib/camera-inputs/axis.mjs b/lib/camera-inputs/axis.mjs new file mode 100644 index 0000000..edcf470 --- /dev/null +++ b/lib/camera-inputs/axis.mjs @@ -0,0 +1,282 @@ +import { createHash } from "node:crypto"; + +export const AXIS_MAX_BODY_BYTES = 32 * 1024 * 1024; +export class InputError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} +export function text(value, limit = 255) { + if (value != null && !["string", "number", "boolean"].includes(typeof value)) + throw new InputError("Invalid text field"); + const result = String(value ?? "").trim(); + if (result.length > limit || /[\u0000-\u001f]/.test(result)) + throw new InputError("Invalid text field"); + return result; +} +export function deviceKey(value) { + const key = text(value, 64).replace(/[:-]/g, "").toUpperCase(); + if (!/^[A-Z0-9]{4,64}$/.test(key)) + throw new InputError("Enter the camera serial number or MAC address"); + return key; +} +function image(value) { + if (value == null || value === "") return null; + if (typeof value !== "string") throw new InputError("Invalid image encoding"); + const encoded = value + .replace(/^data:image\/(?:jpeg|jpg|png);base64,/i, "") + .replace(/\s/g, ""); + if ( + encoded.length > AXIS_MAX_BODY_BYTES || + !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded) || + encoded.length % 4 !== 0 + ) { + throw new InputError("Invalid image encoding"); + } + const bytes = Buffer.from(encoded, "base64"); + if ( + !(bytes[0] === 0xff && bytes[1] === 0xd8) && + !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) + ) { + throw new InputError("Only JPEG and PNG event images are supported"); + } + return encoded; +} +export function normalizeAxisEvent(payload, input) { + if (!payload || Array.isArray(payload) || typeof payload !== "object") + throw new InputError("Expected an Axis event object"); + const mqtt = Boolean(payload.message?.data); + if (mqtt && !/(?:^|\/)ALPV\.AllPlates$/.test(text(payload.topic, 512))) + throw new InputError("Expected an ALPV.AllPlates event"); + const data = mqtt ? payload.message.data : payload; + const plate = text( + text( + mqtt + ? data.text + : (data.plateText ?? data.plateUTF8 ?? data.plateUnicode), + 10, + ).toUpperCase(), + 10, + ); + if (!plate || !/^[\p{L}\p{N} -]+$/u.test(plate)) + throw new InputError("Invalid or missing plate number"); + const camera = deviceKey( + mqtt + ? data.MACAddress + : (data.camera_info?.SerialNumber ?? data.camera_info?.MACAddress), + ); + if (camera !== input.device_id) + throw new InputError("Event camera does not match the configured camera"); + const carId = text(data.carID, 64); + if (!carId) throw new InputError("Missing Axis carID"); + const state = text(data.carState, 12).toLowerCase(); + if (!["new", "update", "lost"].includes(state)) + throw new InputError("Unsupported Axis event state"); + const capturedMs = Number(text(data.capture_timestamp, 30)); + if ( + !Number.isSafeInteger(capturedMs) || + capturedMs < 946684800000 || + capturedMs > 8640000000000000 + ) + throw new InputError( + "Invalid Axis capture timestamp (epoch milliseconds required)", + ); + const direction = text(data.carMoveDirection || "unknown", 20).toLowerCase(); + const confidenceValue = mqtt ? data.lpConfidence : data.plateConfidence; + const confidence = + confidenceValue == null || confidenceValue === "" + ? null + : Number(text(confidenceValue, 30)); + if ( + confidence !== null && + (!Number.isFinite(confidence) || confidence < 0 || confidence > 100) + ) + throw new InputError("Invalid plate confidence"); + const images = data.ImageArray ?? data.imageArray ?? []; + if (!Array.isArray(images)) throw new InputError("Invalid Axis image array"); + const attachments = images.map((item, index) => { + if (!item || typeof item !== "object" || Array.isArray(item)) + throw new InputError("Invalid Axis image entry"); + return { + type: ( + text(item.ImageType ?? item.imageType ?? "", 30) || + (index === 0 ? text(data.imageType, 30) : "") + ).toLowerCase(), + data: image(item.BinaryImage ?? item.binaryImage), + }; + }); + const plateImage = mqtt + ? image(data.lpImage) + : (attachments.find((item) => /plate|^lp$|^21$/.test(item.type))?.data ?? + (data.imageType === "plate" ? attachments[0]?.data : null)); + const sceneImage = mqtt + ? null + : (attachments.find((item) => !/plate|^lp$|^21$/.test(item.type))?.data ?? + null); + const metadata = { + country: text(mqtt ? data.country : data.plateCountry, 10), + region: text(mqtt ? data.region : data.plateRegion, 100), + regionCode: text(mqtt ? data.regionCode : data.plateRegionCode, 30), + iso3166: text(mqtt ? data["iso3166-2"] : data["plateISO3166-2"], 20), + vehicle: mqtt + ? { + type: text(data.vehicleType, 60), + color: text(data.vehicleColor, 60), + make: text(data.vehicleMake, 60), + model: text(data.vehicleModel, 60), + view: text(data.view, 20), + } + : { + type: text(data.vehicle_info?.type, 60), + color: text(data.vehicle_info?.color, 60), + make: text(data.vehicle_info?.make, 60), + model: text(data.vehicle_info?.model, 60), + view: text(data.vehicle_info?.view, 20), + }, + action: text(data.action, 30), + }; + const event = { + plate, + camera, + carId, + state, + capturedMs, + timestamp: new Date(capturedMs).toISOString(), + direction, + confidence, + roi: text(data.roiID, 30), + metadata, + }; + event.fingerprint = createHash("sha256") + .update( + JSON.stringify([ + input.id, + camera, + carId, + capturedMs, + state, + plate, + direction, + event.roi, + ]), + ) + .digest("hex"); + const primary = input.store_images ? (plateImage ?? sceneImage) : null; + const scene = input.store_images && plateImage ? sceneImage : null; + const digest = (value) => + value ? createHash("sha256").update(value).digest("hex") : null; + return { + ...event, + image: primary, + sceneImage: scene, + imageDigest: digest(primary), + sceneDigest: digest(scene), + }; +} + +export function validateTopicFilter(value) { + const filter = text(value, 512); + if (!filter || filter.includes("\u0000") || filter.startsWith("$share/")) + throw new InputError("Enter a valid MQTT topic filter"); + const levels = filter.split("/"); + if ( + levels.some( + (level, index) => + (level.includes("+") && level !== "+") || + (level.includes("#") && (level !== "#" || index !== levels.length - 1)), + ) + ) + throw new InputError("Invalid MQTT topic wildcard"); + return filter; +} +export function topicMatches(filter, topic) { + const levels = filter.split("/"); + const actual = topic.split("/"); + if (topic.startsWith("$") && !filter.startsWith("$")) return false; + for (let i = 0; i < levels.length; i++) { + if (levels[i] === "#") return true; + if ( + actual[i] === undefined || + (levels[i] !== "+" && levels[i] !== actual[i]) + ) + return false; + } + return levels.length === actual.length; +} + +export async function readAxisRequest(request, maximum = AXIS_MAX_BODY_BYTES) { + const reader = request.body?.getReader(); + if (!reader) throw new InputError("Missing event body"); + const chunks = []; + let size = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maximum) { + await reader.cancel(); + throw new InputError("Event body is too large", 413); + } + chunks.push(Buffer.from(value)); + } + } finally { + reader.releaseLock(); + } + const contentType = request.headers.get("content-type") || "application/json"; + const bytes = Buffer.concat(chunks); + try { + if (contentType.toLowerCase().startsWith("multipart/form-data")) { + const form = await new Response(bytes, { + headers: { "content-type": contentType }, + }).formData(); + let event = null; + const images = []; + for (const [name, entry] of form.entries()) { + const isJson = + name === "event" || + name === "json" || + entry?.type === "application/json" || + /\.json$/i.test(entry?.name || ""); + if (isJson) { + if (event) throw new InputError("Multiple event objects"); + event = JSON.parse( + typeof entry === "string" ? entry : await entry.text(), + ); + } else if (entry && typeof entry.arrayBuffer === "function") { + images.push({ + ImageType: /(?:plate|(?:^|[_-])lp(?:[_-]|$)|image2)/i.test( + name + " " + entry.name, + ) + ? "plate" + : "scene", + main: name === "image", + BinaryImage: Buffer.from(await entry.arrayBuffer()).toString( + "base64", + ), + }); + } + } + if (!event) + throw new InputError("Multipart request is missing its JSON event"); + return { + ...event, + ImageArray: [ + ...(event.ImageArray ?? event.imageArray ?? []), + ...images.map(({ main, ...item }) => ({ + ...item, + ImageType: + main && event.imageType === "plate" ? "plate" : item.ImageType, + })), + ], + }; + } + if (!/^application\/(?:[\w.-]+\+)?json(?:;|$)/i.test(contentType)) + throw new InputError("Use JSON or multipart/form-data", 415); + return JSON.parse(bytes.toString("utf8")); + } catch (error) { + if (error instanceof InputError) throw error; + throw new InputError("Invalid Axis event body"); + } +} diff --git a/lib/camera-inputs/config.mjs b/lib/camera-inputs/config.mjs new file mode 100644 index 0000000..333bbec --- /dev/null +++ b/lib/camera-inputs/config.mjs @@ -0,0 +1,103 @@ +import { + createHash, + randomBytes, + randomUUID, + timingSafeEqual, +} from "node:crypto"; +import { deviceKey, InputError, text, validateTopicFilter } from "./axis.mjs"; + +export function newCredential() { + return randomBytes(32).toString("hex"); +} +export function hashCredential(value) { + return createHash("sha256").update(value).digest("hex"); +} +export function verifySourceCredential(request, input) { + if ( + !input?.enabled || + input.source !== "axis" || + !["http", "both"].includes(input.transport) || + !input.credential_hash + ) + return false; + if (new URL(request.url).search) return false; + const authorization = request.headers.get("authorization") || ""; + let credential = + request.headers.get("x-api-key") || + authorization.match(/^Bearer\s+(\S+)$/i)?.[1]; + const basic = authorization.match(/^Basic\s+([A-Za-z0-9+/=]+)$/i)?.[1]; + if (!credential && basic) { + const decoded = Buffer.from(basic, "base64").toString("utf8"); + const split = decoded.indexOf(":"); + if (decoded.slice(0, split) !== input.id) return false; + credential = decoded.slice(split + 1); + } + if (!credential || credential.length > 512) return false; + const actual = Buffer.from(hashCredential(credential)); + const expected = Buffer.from(input.credential_hash); + return actual.length === expected.length && timingSafeEqual(actual, expected); +} +export function validateInput(data, previous = null) { + const source = data.source ?? previous?.source ?? "axis"; + const cameraName = text(data.camera_name ?? previous?.camera_name, 30); + if (!cameraName) + throw new InputError("Camera name is required (maximum 30 characters)"); + if (!["axis", "blue_iris"].includes(source)) + throw new InputError("Choose Blue Iris or Axis License Plate Verifier"); + const transport = + source === "blue_iris" + ? "http" + : (data.transport ?? previous?.transport ?? "http"); + if (!["http", "mqtt", "both"].includes(transport)) + throw new InputError("Choose HTTP or MQTT"); + const brokerId = + data.broker_id === "" + ? null + : (data.broker_id ?? previous?.broker_id ?? null); + if ( + ["mqtt", "both"].includes(transport) && + (!Number.isSafeInteger(Number(brokerId)) || Number(brokerId) < 1) + ) + throw new InputError("Select an MQTT broker"); + const mode = data.processing_mode ?? previous?.processing_mode ?? "immediate"; + if (!["immediate", "final"].includes(mode)) + throw new InputError("Choose immediate or finalized processing"); + const qos = Number(data.qos ?? previous?.qos ?? 1); + if (![0, 1].includes(qos)) + throw new InputError("MQTT subscription QoS must be 0 or 1"); + const boolean = (key, fallback) => { + const value = data[key] ?? previous?.[key] ?? fallback; + if (typeof value !== "boolean") + throw new InputError(`Invalid ${key} value`); + return value; + }; + return { + id: previous?.id ?? randomUUID(), + camera_name: cameraName, + source, + transport, + enabled: boolean("enabled", true), + device_id: + source === "axis" + ? deviceKey(data.device_id ?? previous?.device_id) + : null, + broker_id: ["mqtt", "both"].includes(transport) ? Number(brokerId) : null, + topic_filter: ["mqtt", "both"].includes(transport) + ? validateTopicFilter(data.topic_filter ?? previous?.topic_filter) + : null, + qos, + processing_mode: mode, + roi_filter: text(data.roi_filter ?? previous?.roi_filter, 30) || null, + store_images: boolean("store_images", true), + direction_in: text(data.direction_in ?? previous?.direction_in ?? "In", 80), + direction_out: text( + data.direction_out ?? previous?.direction_out ?? "Out", + 80, + ), + }; +} +export function publicInput(row) { + if (!row) return null; + const { credential_hash: _credentialHash, ...safe } = row; + return { ...safe, credential_configured: Boolean(row.credential_hash) }; +} diff --git a/lib/camera-inputs/connection-test.mjs b/lib/camera-inputs/connection-test.mjs new file mode 100644 index 0000000..ab85d82 --- /dev/null +++ b/lib/camera-inputs/connection-test.mjs @@ -0,0 +1,75 @@ +import { randomUUID } from "node:crypto"; +import { buildSubscriberOptions } from "./runtime.mjs"; + +export function testMqttConnection( + input, + mqttConnect, + { timeoutMs = 10000 } = {}, +) { + return new Promise((resolve) => { + let client; + let timer; + let finished = false; + const finish = (result) => { + if (finished) return; + finished = true; + clearTimeout(timer); + client?.end(true, {}, () => {}); + resolve(result); + }; + timer = setTimeout( + () => + finish({ + ok: false, + error: "Broker connection or subscription timed out", + }), + timeoutMs, + ); + try { + if (/[\s/@?#]/.test(input.broker) || input.broker.includes("://")) + throw new Error("INVALID_HOST"); + const host = input.broker.includes(":") + ? `[${input.broker.replace(/^\[|\]$/g, "")}]` + : input.broker; + client = mqttConnect( + `${input.use_tls ? "mqtts" : "mqtt"}://${host}:${input.port}`, + { + ...buildSubscriberOptions(input), + clientId: `alpr-axis-test-${randomUUID()}`, + clean: true, + reconnectPeriod: 0, + }, + ); + client.on("error", () => + finish({ + ok: false, + error: "Connection failed. Check broker, credentials and TLS.", + }), + ); + client.on("connect", () => + client.subscribe( + input.topic_filter, + { qos: input.qos }, + (error, granted) => { + finish( + !error && + granted?.length && + granted.every((item) => item.qos <= 1) + ? { + ok: true, + message: + "Broker connection and topic subscription succeeded", + } + : { ok: false, error: "Broker refused the topic subscription" }, + ); + }, + ), + ); + } catch { + finish({ + ok: false, + error: "Unable to connect to the configured broker", + }); + } + }); +} diff --git a/lib/camera-inputs/http.mjs b/lib/camera-inputs/http.mjs new file mode 100644 index 0000000..ec3b6f0 --- /dev/null +++ b/lib/camera-inputs/http.mjs @@ -0,0 +1,50 @@ +import { InputError, readAxisRequest } from "./axis.mjs"; +import { verifySourceCredential } from "./config.mjs"; + +export function createAxisReceiver({ + repository, + wake = () => {}, + logger = console, +}) { + return async (request, id) => { + try { + const input = await repository.get(id); + if (!verifySourceCredential(request, input)) + return Response.json( + { error: "Unauthorized" }, + { + status: 401, + headers: { + "WWW-Authenticate": 'Basic realm="ALPR Axis"', + "Cache-Control": "no-store", + }, + }, + ); + const payload = await readAxisRequest(request); + const result = await repository.receive(input, payload, "http"); + try { + wake(); + } catch { + /* The durable worker also polls as a fallback. */ + } + // Success acknowledges durable receipt, including idempotent redelivery. + return Response.json( + { accepted: true, duplicate: result.duplicate }, + { status: 200 }, + ); + } catch (error) { + if (error instanceof InputError) + return Response.json( + { error: error.message }, + { status: error.status }, + ); + logger.error?.("axis_http_receipt_failed", { + code: error?.code || "DATABASE_ERROR", + }); + return Response.json( + { error: "Unable to store event; retry later" }, + { status: 503 }, + ); + } + }; +} diff --git a/lib/camera-inputs/processor.mjs b/lib/camera-inputs/processor.mjs new file mode 100644 index 0000000..332fb2f --- /dev/null +++ b/lib/camera-inputs/processor.mjs @@ -0,0 +1,361 @@ +import { randomUUID } from "node:crypto"; + +export function axisDirection(input, event) { + const label = + event.direction === "in" + ? input.direction_in + : event.direction === "out" + ? input.direction_out + : null; + return label + ? { + status: "ready", + directionLabel: label, + orientation: ["front", "rear"].includes(event.metadata.vehicle.view) + ? event.metadata.vehicle.view + : "unknown", + confidence: null, + source: "axis_license_plate_verifier", + classifierVersion: "axis-lpv-direction-v1", + } + : null; +} +export async function persistAxisDirection(query, readId, camera, observation) { + if (!observation) return; + await query( + `INSERT INTO public.vehicle_direction_observations + (read_id,camera_key,embedding_model,classifier_version,profile_version,status,orientation,orientation_confidence,direction_label,sample_counts) + VALUES ($1,LOWER(BTRIM($2)),'axis-lpv','axis-lpv-direction-v1',1,'ready',$3,NULL,$4,$5::jsonb) + ON CONFLICT(read_id) DO UPDATE SET status=EXCLUDED.status,orientation=EXCLUDED.orientation, + orientation_confidence=NULL,direction_label=EXCLUDED.direction_label,sample_counts=EXCLUDED.sample_counts, + classifier_version=EXCLUDED.classifier_version,embedding_model=EXCLUDED.embedding_model,source_embedding_id=NULL,evaluated_at=CURRENT_TIMESTAMP`, + [ + readId, + camera, + observation.orientation, + observation.directionLabel, + JSON.stringify({ source: observation.source }), + ], + ); +} + +export class AxisEventProcessor { + constructor({ + pool, + ingest, + storage, + publish = () => {}, + notifyDirection = async () => {}, + logger = console, + }) { + this.pool = pool; + this.ingest = ingest; + this.storage = storage; + this.publish = publish; + this.notifyDirection = notifyDirection; + this.logger = logger; + } + async process(receipt, { finalize = false } = {}) { + const client = await this.pool.connect(); + let lockKey; + let locked = false; + let transaction = false; + let committed = false; + const files = []; + try { + let event = receipt.payload; + lockKey = `${receipt.input_id}:${event.carId}`; + locked = ( + await client.query( + "SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS locked", + [lockKey], + ) + ).rows[0].locked; + if (!locked) return false; + const input = ( + await client.query("SELECT * FROM public.camera_inputs WHERE id=$1", [ + receipt.input_id, + ]) + ).rows[0]; + if (!input?.enabled || input.source !== "axis") return false; + const current = ( + await client.query( + "SELECT * FROM public.camera_input_events WHERE id=$1", + [receipt.id], + ) + ).rows[0]; + if (!current || (current.status !== "pending" && !finalize)) return true; + receipt = current; + event = current.payload; + let passage = ( + await client.query( + `SELECT * FROM public.camera_input_passages WHERE input_id=$1 AND car_id=$2 AND source_camera=$4 + AND (id=$5::uuid OR ($5::uuid IS NULL AND first_capture <= $3::timestamptz + INTERVAL '30 seconds' AND last_capture >= $3::timestamptz - INTERVAL '30 minutes')) + ORDER BY (first_capture <= $3::timestamptz) DESC, first_capture DESC LIMIT 1`, + [input.id, event.carId, event.timestamp, event.camera, receipt.passage_id ?? null], + ) + ).rows[0]; + // The fallback query is only a candidate snapshot. Recheck under the + // passage lock, after any newer event or richer duplicate has finished. + if ( + finalize && + (!passage || passage.read_id || passage.finalized || + String(passage.last_event_id) !== String(receipt.id) || + new Date(passage.last_seen).getTime() > Date.now() - 30000) + ) + return true; + if (finalize) { + const waiting = (await client.query( + `SELECT 1 FROM public.camera_input_events WHERE input_id=$1 AND status='pending' + AND payload->>'carId'=$2 AND payload->>'camera'=$3 + AND (passage_id IS NULL OR passage_id=$4) LIMIT 1`, + [input.id, event.carId, event.camera, passage.id], + )).rows.length; + if (waiting) return true; + } + if ( + passage && + !receipt.passage_id && + event.state === "new" && + new Date(event.timestamp) > new Date(passage.last_capture) + ) + passage = null; + if (!passage) { + passage = ( + await client.query( + `INSERT INTO public.camera_input_passages(id,input_id,car_id,first_capture,last_capture,last_event_id,last_state,source_camera) + VALUES ($1,$2,$3,$4,$4,$5,$6,$7) RETURNING *`, + [ + randomUUID(), + input.id, + event.carId, + event.timestamp, + receipt.id, + event.state, + event.camera, + ], + ) + ).rows[0]; + } + const isLatest = + event.state === "lost" || + (passage.last_state !== "lost" && + new Date(event.timestamp) >= new Date(passage.last_capture)); + const direction = axisDirection(input, event); + const finish = async (query, readId, ignored = false) => { + // Receivers lock the input before the receipt; keep the same order. + await query( + "SELECT id FROM public.camera_inputs WHERE id=$1 FOR UPDATE", + [input.id], + ); + await query( + `UPDATE public.camera_input_events SET status=CASE WHEN revision=$4 THEN $2 ELSE 'pending' END,read_id=$3,passage_id=$5,processed_at=CURRENT_TIMESTAMP,leased_until=NULL, + payload=CASE WHEN revision=$4 THEN payload - 'image' - 'sceneImage' ELSE payload END WHERE id=$1`, + [ + receipt.id, + ignored ? "ignored" : "processed", + readId, + receipt.revision ?? 0, + passage.id, + ], + ); + if (readId || ignored) + await query( + `UPDATE public.camera_input_events SET read_id=$2,payload=payload - 'image' - 'sceneImage' + WHERE passage_id=$1 AND status<>'pending'`, + [passage.id, readId], + ); + await query( + `UPDATE public.camera_input_passages SET read_id=COALESCE(read_id,$2), + first_capture=LEAST(first_capture,$3::timestamptz),last_capture=GREATEST(last_capture,$3::timestamptz), + last_event_id=CASE WHEN $4 THEN $5 ELSE last_event_id END,last_state=CASE WHEN $4 THEN $6 ELSE last_state END, + direction_label=CASE WHEN $4 THEN COALESCE($7,direction_label) ELSE direction_label END, + finalized=finalized OR $8,last_seen=CURRENT_TIMESTAMP WHERE id=$1`, + [ + passage.id, + readId, + event.timestamp, + isLatest, + receipt.id, + event.state, + direction?.directionLabel ?? null, + event.state === "lost" || finalize || ignored, + ], + ); + await query( + "UPDATE public.camera_inputs SET last_imported_at=CURRENT_TIMESTAMP,last_error=NULL,connection_status='receiving' WHERE id=$1", + [input.id], + ); + }; + if ( + !passage.read_id && + input.processing_mode === "final" && + event.state !== "lost" && + !finalize + ) { + // Retain the latest pending image until LOST or the inactivity fallback. + await client.query("BEGIN"); + transaction = true; + await client.query( + "SELECT id FROM public.camera_inputs WHERE id=$1 FOR UPDATE", [input.id], + ); + await client.query( + `UPDATE public.camera_input_events SET status=CASE WHEN revision=$2 THEN 'processed' ELSE 'pending' END, + passage_id=$3,processed_at=CURRENT_TIMESTAMP,leased_until=NULL WHERE id=$1`, + [receipt.id, receipt.revision ?? 0, passage.id], + ); + await client.query( + `UPDATE public.camera_input_passages SET first_capture=LEAST(first_capture,$2::timestamptz),last_capture=GREATEST(last_capture,$2::timestamptz), + last_event_id=CASE WHEN $3 THEN $4 ELSE last_event_id END,last_state=CASE WHEN $3 THEN $5 ELSE last_state END,last_seen=CURRENT_TIMESTAMP WHERE id=$1`, + [passage.id, event.timestamp, isLatest, receipt.id, event.state], + ); + await client.query("COMMIT"); + transaction = false; + return true; + } + if (!passage.read_id) { + const thisStorage = this.storage; + const response = await this.ingest( + { + plate_number: event.plate, + camera: input.camera_name, + timestamp: new Date(passage.first_capture).toISOString(), + Image: input.store_images ? event.image : null, + }, + null, + { + axisEvent: event, + axisDirection: direction, + eventIdentity: `axis-passage:${passage.id}`, + async onAcceptedRead(query, readId, trackImage) { + if (event.sceneImage && input.store_images) { + const scene = await thisStorage.saveImage( + event.sceneImage, + event.plate, + ); + trackImage(scene); + await query( + "UPDATE public.camera_input_passages SET scene_image_path=$2,scene_thumbnail_path=$3 WHERE id=$1", + [passage.id, scene.imagePath, scene.thumbnailPath], + ); + } + await persistAxisDirection( + query, + readId, + input.camera_name, + direction, + ); + await finish(query, readId); + }, + }, + ); + if (response.status >= 500) throw new Error("AXIS_INGESTION_FAILED"); + if (![201, 409].includes(response.status)) + throw new Error("AXIS_INGESTION_REJECTED"); + const body = await response.json(); + if (!body.processed?.length) { + if (!body.ignored?.length) { + const linked = (await client.query( + "SELECT read_id FROM public.camera_input_passages WHERE id=$1", [passage.id], + )).rows[0]; + if (!linked?.read_id) throw new Error("AXIS_READ_NOT_LINKED"); + return true; + } + await client.query("BEGIN"); + transaction = true; + await finish((sql, values) => client.query(sql, values), null, true); + await client.query("COMMIT"); + transaction = false; + } + } else { + let savedImage = null; + let scene = null; + const existingImages = ( + await client.query( + "SELECT image_path FROM public.plate_reads WHERE id=$1", + [passage.read_id], + ) + ).rows[0]; + if ( + (isLatest || !existingImages?.image_path) && + event.image && + input.store_images + ) { + savedImage = await this.storage.saveImage(event.image, event.plate); + files.push(savedImage); + } + if ( + (isLatest || !passage.scene_image_path) && + event.sceneImage && + input.store_images + ) { + scene = await this.storage.saveImage(event.sceneImage, event.plate); + files.push(scene); + } + await client.query("BEGIN"); + transaction = true; + if (isLatest) { + // Human review wins over later OCR. observed_plate remains immutable. + await client.query( + `INSERT INTO public.plates(plate_number) VALUES ($1) ON CONFLICT DO NOTHING`, + [event.plate], + ); + await client.query( + `UPDATE public.plate_reads SET plate_number=CASE WHEN review_status='unreviewed' AND NOT validated THEN $2 ELSE plate_number END, + confidence=$3,image_path=COALESCE($4,image_path),thumbnail_path=COALESCE($5,thumbnail_path) + WHERE id=$1`, + [ + passage.read_id, + event.plate, + event.confidence, + savedImage?.imagePath ?? null, + savedImage?.thumbnailPath ?? null, + ], + ); + await persistAxisDirection( + (sql, values) => client.query(sql, values), + passage.read_id, + input.camera_name, + direction, + ); + if (direction) + await this.notifyDirection(client, passage.read_id, direction); + } + if (scene) + await client.query( + "UPDATE public.camera_input_passages SET scene_image_path=$2,scene_thumbnail_path=$3 WHERE id=$1", + [passage.id, scene.imagePath, scene.thumbnailPath], + ); + if (!isLatest && savedImage) + await client.query( + "UPDATE public.plate_reads SET image_path=COALESCE(image_path,$2),thumbnail_path=COALESCE(thumbnail_path,$3) WHERE id=$1", + [passage.read_id, savedImage.imagePath, savedImage.thumbnailPath], + ); + await finish( + (sql, values) => client.query(sql, values), + passage.read_id, + ); + await client.query("COMMIT"); + transaction = false; + committed = true; + this.publish([passage.read_id], "axis_updated"); + } + return true; + } catch (error) { + if (transaction) await client.query("ROLLBACK").catch(() => {}); + if (!committed) + await Promise.allSettled( + files.map((file) => + this.storage.deleteImage(file.imagePath, file.thumbnailPath), + ), + ); + throw error; + } finally { + if (locked) + await client + .query("SELECT pg_advisory_unlock(hashtextextended($1,0))", [lockKey]) + .catch(() => {}); + client.release(); + } + } +} diff --git a/lib/camera-inputs/repository.mjs b/lib/camera-inputs/repository.mjs new file mode 100644 index 0000000..42c0a5d --- /dev/null +++ b/lib/camera-inputs/repository.mjs @@ -0,0 +1,241 @@ +import { randomUUID } from "node:crypto"; +import { + hashCredential, + newCredential, + publicInput, + validateInput, +} from "./config.mjs"; +import { InputError, normalizeAxisEvent } from "./axis.mjs"; + +export class CameraInputRepository { + constructor(pool) { + this.pool = pool; + } + async get(id) { + return ( + ( + await this.pool.query( + "SELECT * FROM public.camera_inputs WHERE id = $1", + [id], + ) + ).rows[0] ?? null + ); + } + async list() { + // Existing camera names remain valid and require no enrollment or rewrite. + const configured = ( + await this.pool.query(`SELECT inputs.*, brokers.name AS broker_name, + (SELECT COUNT(*)::int FROM public.camera_input_events events WHERE events.input_id = inputs.id AND events.status = 'pending') AS pending_count + FROM public.camera_inputs inputs LEFT JOIN public.mqttbrokers brokers ON brokers.id = inputs.broker_id ORDER BY inputs.camera_name`) + ).rows.map(publicInput); + const legacy = ( + await this.pool + .query(`SELECT camera_name, MAX(timestamp) AS last_received_at FROM public.plate_reads + WHERE NULLIF(BTRIM(camera_name), '') IS NOT NULL GROUP BY camera_name`) + ).rows; + const names = new Set( + configured.map((input) => input.camera_name.trim().toLowerCase()), + ); + return [ + ...configured, + ...legacy + .filter((row) => !names.has(row.camera_name.trim().toLowerCase())) + .map((row) => ({ + ...row, + id: null, + source: "blue_iris", + transport: "http", + enabled: true, + legacy: true, + })), + ]; + } + async save(data, id = null) { + const initial = id ? await this.get(id) : null; + if (id && !initial) throw new InputError("Camera input not found", 404); + const candidate = validateInput(data, initial); + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + // Match the legacy ingestion gate, including a camera not registered yet. + await client.query( + "SELECT pg_advisory_xact_lock(hashtextextended(LOWER(BTRIM($1)),1))", + [candidate.camera_name], + ); + const previous = id + ? ( + await client.query( + "SELECT * FROM public.camera_inputs WHERE id=$1 FOR UPDATE", + [id], + ) + ).rows[0] + : null; + if (id && !previous) throw new InputError("Camera input not found", 404); + const input = id ? validateInput(data, previous) : candidate; + if (previous && input.camera_name !== previous.camera_name) + throw new InputError( + "Camera names are permanent; create another input to use a different name", + ); + if ( + previous && + (input.source !== previous.source || + input.device_id !== previous.device_id || + input.processing_mode !== previous.processing_mode) + ) { + const pending = await client.query( + "SELECT 1 FROM public.camera_input_events WHERE input_id = $1 AND status = 'pending' UNION ALL SELECT 1 FROM public.camera_input_passages WHERE input_id=$1 AND read_id IS NULL AND NOT finalized LIMIT 1", + [id], + ); + if (pending.rows.length) + throw new InputError( + "Allow pending events and passages to finish before changing camera identity or processing mode", + 409, + ); + } + const credential = + input.source === "axis" && + input.transport !== "mqtt" && + (!previous?.credential_hash || data.rotate_credential === true) + ? newCredential() + : null; + const result = await client.query( + `INSERT INTO public.camera_inputs + (id, camera_name, source, transport, enabled, device_id, broker_id, topic_filter, qos, processing_mode, store_images, direction_in, direction_out, credential_hash, roi_filter) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) + ON CONFLICT(id) DO UPDATE SET source=EXCLUDED.source, transport=EXCLUDED.transport, enabled=EXCLUDED.enabled, + device_id=EXCLUDED.device_id, broker_id=EXCLUDED.broker_id, topic_filter=EXCLUDED.topic_filter, qos=EXCLUDED.qos, + processing_mode=EXCLUDED.processing_mode, store_images=EXCLUDED.store_images, direction_in=EXCLUDED.direction_in, + direction_out=EXCLUDED.direction_out, credential_hash=EXCLUDED.credential_hash, roi_filter=EXCLUDED.roi_filter, updated_at=CURRENT_TIMESTAMP + RETURNING *`, + [ + input.id, + input.camera_name, + input.source, + input.transport, + input.enabled, + input.device_id, + input.broker_id, + input.topic_filter, + input.qos, + input.processing_mode, + input.store_images, + input.direction_in, + input.direction_out, + credential + ? hashCredential(credential) + : (previous?.credential_hash ?? null), + input.roi_filter, + ], + ); + await client.query("COMMIT"); + return { + input: publicInput(result.rows[0]), + ...(credential ? { credential } : {}), + }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } + } + async receive(input, payload, transport, { retained = false } = {}) { + if ( + !input?.enabled || + input.source !== "axis" || + ![transport, "both"].includes(input.transport) + ) + throw new InputError( + "Camera input is disabled or does not accept this transport", + 403, + ); + if (retained) + throw new InputError( + "Retained messages are not imported as new detections", + ); + const event = normalizeAxisEvent(payload, input); + if (input.roi_filter && input.roi_filter !== event.roi) + return { filtered: true, duplicate: false, eventId: null }; + if (JSON.stringify(event).length > 32 * 1024 * 1024) + throw new InputError("Event is too large", 413); + const result = await this.pool.query( + `WITH active AS ( + SELECT * FROM public.camera_inputs WHERE id=$1 AND enabled AND source='axis' + AND device_id=$5 AND transport IN ($4,'both') AND (roi_filter IS NULL OR roi_filter=$6) FOR UPDATE + ), event AS ( + INSERT INTO public.camera_input_events(input_id,fingerprint,payload,transport) + SELECT $1,$2,CASE WHEN active.store_images THEN $3::jsonb ELSE $3::jsonb - 'image' - 'sceneImage' - 'imageDigest' - 'sceneDigest' END,$4 FROM active + ON CONFLICT(input_id,fingerprint) DO UPDATE SET + payload=public.camera_input_events.payload || jsonb_strip_nulls(jsonb_build_object( + 'image',CASE WHEN public.camera_input_events.payload->>'imageDigest' IS NULL THEN EXCLUDED.payload->'image' END, + 'imageDigest',CASE WHEN public.camera_input_events.payload->>'imageDigest' IS NULL THEN EXCLUDED.payload->'imageDigest' END, + 'sceneImage',CASE WHEN public.camera_input_events.payload->>'sceneDigest' IS NULL THEN EXCLUDED.payload->'sceneImage' END, + 'sceneDigest',CASE WHEN public.camera_input_events.payload->>'sceneDigest' IS NULL THEN EXCLUDED.payload->'sceneDigest' END)), + status='pending',revision=public.camera_input_events.revision+1,next_attempt_at=CURRENT_TIMESTAMP + WHERE public.camera_input_events.status<>'ignored' AND ( + (public.camera_input_events.payload->>'imageDigest' IS NULL AND EXCLUDED.payload->>'imageDigest' IS NOT NULL) OR + (public.camera_input_events.payload->>'sceneDigest' IS NULL AND EXCLUDED.payload->>'sceneDigest' IS NOT NULL)) + RETURNING id,(xmax=0) AS inserted + ), seen AS ( + UPDATE public.camera_inputs SET last_received_at=CURRENT_TIMESTAMP,last_error=NULL,connection_status='receiving' WHERE id IN(SELECT id FROM active) + ) SELECT (SELECT id FROM event) AS id,(SELECT inserted FROM event) AS inserted,EXISTS(SELECT 1 FROM active) AS active`, + [ + input.id, + event.fingerprint, + JSON.stringify(event), + transport, + event.camera, + event.roi, + ], + ); + const row = result.rows[0]; + if (!row.active) + throw new InputError( + "Camera configuration changed; retry with the current configuration", + 403, + ); + return { duplicate: row.inserted !== true, eventId: row.id ?? null }; + } + + async status(id, status, error = null) { + await this.pool.query( + "UPDATE public.camera_inputs SET connection_status=$2, last_error=$3 WHERE id=$1", + [id, status, error], + ); + } + async mqttInputs() { + return ( + await this.pool + .query(`SELECT inputs.*, brokers.broker, brokers.port, brokers.username, brokers.password, brokers.use_tls, brokers.enabled AS broker_enabled + FROM public.camera_inputs inputs JOIN public.mqttbrokers brokers ON brokers.id = inputs.broker_id + WHERE inputs.source='axis' AND inputs.enabled AND inputs.transport IN ('mqtt','both')`) + ).rows; + } + async claim() { + return ( + ( + await this.pool.query( + `UPDATE public.camera_input_events SET leased_until=CURRENT_TIMESTAMP + INTERVAL '2 minutes', lease_token=$1 + WHERE id=(SELECT id FROM public.camera_input_events WHERE status='pending' AND next_attempt_at<=CURRENT_TIMESTAMP + AND (leased_until IS NULL OR leased_until AXIS_MAX_BODY_BYTES) + throw new InputError("MQTT event is too large", 413); + let parsed; + try { + parsed = JSON.parse(payload.toString("utf8")); + } catch { + throw new InputError("Invalid MQTT JSON"); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) + throw new InputError("Expected an Axis event object"); + const current = await this.repository.get(input.id); + const eventDevice = + parsed.message?.data?.MACAddress ?? + parsed.camera_info?.SerialNumber ?? + parsed.camera_info?.MACAddress; + // A wildcard filter may legitimately include other cameras' events. + if ( + eventDevice && + current?.device_id && + deviceKey(eventDevice) !== current.device_id + ) + return; + + const received = await this.repository.receive(current, parsed, "mqtt", { + retained: packet.retain === true, + }); + this.wake(); + return received; + } + async sync() { + const inputs = await this.repository.mqttInputs(); + const wanted = new Set(); + for (const input of inputs) { + wanted.add(input.id); + const identity = JSON.stringify([ + input.broker, + input.port, + input.username, + input.password, + input.use_tls, + input.broker_enabled, + input.topic_filter, + input.qos, + input.device_id, + ]); + let existing = this.clients.get(input.id); + if (existing && existing.identity !== identity) { + await new Promise((resolve) => existing.client.end(true, {}, resolve)); + this.clients.delete(input.id); + existing = null; + } + if (!input.broker_enabled) { + await this.repository.status( + input.id, + "disabled", + "The selected broker is disabled.", + ); + continue; + } + if (existing) continue; + // The broker host is stored separately from credentials. Do not accept a URL + // that could override transport security or inject another credential. + if (/[\s/@?#]/.test(input.broker) || input.broker.includes("://")) { + await this.repository.status( + input.id, + "error", + "Use a broker hostname or IP without a URL scheme.", + ); + continue; + } + const host = input.broker.includes(":") + ? `[${input.broker.replace(/^\[|\]$/g, "")}]` + : input.broker; + let client; + try { + client = this.mqttConnect( + `${input.use_tls ? "mqtts" : "mqtt"}://${host}:${input.port}`, + buildSubscriberOptions(input), + ); + } catch { + await this.repository.status( + input.id, + "error", + "Unable to create MQTT connection. Check broker settings.", + ); + continue; + } + this.clients.set(input.id, { client, identity }); + // MQTT.js invokes handleMessage before PUBACK for QoS 1. Persist before + // acknowledging; disconnect on transient failures so the broker can retry. + client.handleMessage = (packet, callback) => { + this.handlePacket(input, packet).then( + () => callback(), + async (error) => { + if (error instanceof InputError) { + await this.repository + .status(input.id, "receiving", error.message) + .catch(() => {}); + callback(); + return; + } + this.logger.error?.("axis_mqtt_receipt_failed", { + inputId: input.id, + code: error?.code || "DATABASE_ERROR", + }); + client.stream?.destroy(); + callback(error); + }, + ); + }; + client.on("connect", () => { + client.subscribe( + input.topic_filter, + { qos: input.qos }, + (error, granted) => { + const refused = + error || !granted?.length || granted.some((item) => item.qos > 1); + this.repository + .status( + input.id, + refused ? "error" : "subscribed", + refused + ? "Broker refused the subscription. Check topic permissions." + : null, + ) + .catch(() => {}); + }, + ); + }); + client.on("error", () => { + this.repository + .status( + input.id, + "error", + "MQTT connection failed. Check broker, credentials and TLS.", + ) + .catch(() => {}); + }); + client.on("offline", () => { + this.repository.status(input.id, "reconnecting", null).catch(() => {}); + }); + } + for (const [id, entry] of this.clients) + if (!wanted.has(id)) { + await new Promise((resolve) => entry.client.end(true, {}, resolve)); + this.clients.delete(id); + } + } + async tick() { + if (this.stopped || this.running) return; + this.running = true; + try { + if (Date.now() - this.lastSync > 10000) { + await this.sync(); + this.lastSync = Date.now(); + } + for (let count = 0; count < 10; count++) { + const event = await this.repository.claim(); + if (!event) break; + try { + await this.processor.process(event); + } catch (error) { + this.logger.error?.("axis_event_processing_failed", { + eventId: event.id, + code: error?.code || "PROCESSING_ERROR", + }); + await this.repository.fail(event); + } + } + const stale = ( + await this.pool + .query(`SELECT events.* FROM public.camera_input_passages passages + JOIN public.camera_input_events events ON events.id=passages.last_event_id + JOIN public.camera_inputs inputs ON inputs.id=passages.input_id + WHERE passages.read_id IS NULL AND NOT passages.finalized AND inputs.enabled AND inputs.processing_mode='final' + AND passages.last_seen'pending' + AND events.processed_at { + void this.tick(); + }, + this.wakeRequested ? 0 : 1000, + ); + this.wakeRequested = false; + this.timer?.unref?.(); + } + } + } + wake() { + if (!this.started || this.stopped) return; + if (this.running) { + this.wakeRequested = true; + return; + } + if (this.timer) this.cancel(this.timer); + this.timer = this.schedule(() => { + void this.tick(); + }, 0); + this.timer?.unref?.(); + } + start() { + this.started = true; + void this.tick(); + return this; + } + async stop() { + this.stopped = true; + if (this.timer) this.cancel(this.timer); + await Promise.allSettled( + [...this.clients.values()].map( + ({ client }) => new Promise((resolve) => client.end(true, {}, resolve)), + ), + ); + this.clients.clear(); + } +} + +const STATE = Symbol.for("alpr.camera-input-runtime.v1"); +export function wakeCameraInputs(stateHost = globalThis) { + stateHost[STATE]?.then((runtime) => runtime.wake()).catch(() => {}); +} +export async function startCameraInputRuntime({ + loadDependencies, + stateHost = globalThis, +} = {}) { + if (!stateHost[STATE]) { + stateHost[STATE] = (async () => { + const dependencies = loadDependencies + ? await loadDependencies() + : await loadDefaultDependencies(); + const runtime = new CameraInputRuntime(dependencies).start(); + return runtime; + })().catch((error) => { + delete stateHost[STATE]; + throw error; + }); + } + return stateHost[STATE]; +} +async function loadDefaultDependencies() { + const [ + { getPool }, + mqtt, + { processPlateRead, processCameraDirection }, + { default: storage }, + { publishPlateReadChanges }, + ] = await Promise.all([ + import("../db.js"), + import("mqtt"), + import("../plate-read-ingestion.js"), + import("../fileStorage.js"), + import("../sse.js"), + ]); + return { + pool: await getPool(), + mqttConnect: mqtt.connect ?? mqtt.default.connect, + ingest: processPlateRead, + storage, + publish: publishPlateReadChanges, + notifyDirection: processCameraDirection, + }; +} diff --git a/lib/camera-inputs/startup.mjs b/lib/camera-inputs/startup.mjs new file mode 100644 index 0000000..0515e6e --- /dev/null +++ b/lib/camera-inputs/startup.mjs @@ -0,0 +1,44 @@ +const STATE = Symbol.for("alpr.camera-input-startup.v1"); +export async function startCameraInputsWithRetry({ + stateHost = globalThis, + logger = console, + startRuntime, + schedule = setTimeout, +} = {}) { + const state = (stateHost[STATE] ||= { + starting: null, + started: false, + timer: null, + }); + if (state.started) return { status: "started", reused: true }; + if (state.starting) return state.starting; + state.starting = (async () => { + try { + const starter = + startRuntime ?? (await import("./runtime.mjs")).startCameraInputRuntime; + await starter(); + state.started = true; + return { status: "started" }; + } catch { + if (!state.timer) { + state.timer = schedule(() => { + state.timer = null; + void startCameraInputsWithRetry({ + stateHost, + logger, + startRuntime, + schedule, + }); + }, 30000); + state.timer?.unref?.(); + } + logger.error?.("Camera input startup failed; retry scheduled"); + return { status: "retry-scheduled" }; + } + })(); + try { + return await state.starting; + } finally { + state.starting = null; + } +} diff --git a/lib/help-manual.mjs b/lib/help-manual.mjs index a24c953..1d904a0 100644 --- a/lib/help-manual.mjs +++ b/lib/help-manual.mjs @@ -12,8 +12,8 @@ export const HELP_MANUAL = Object.freeze({ title: "ALPR Database Community User Guide", shortTitle: "User Guide", description: "A practical guide to using, configuring, and safely administering the portable Community application.", - manualVersion: "3.26", - updatedAt: "October 21, 2026", + manualVersion: "3.27", + updatedAt: "November 1, 2026", coverageBaseline: "Published clean-history Community release with portable configuration and no private deployment controls.", filename: "ALPR-Database-Community-User-Guide.pdf", sections: [ @@ -411,6 +411,23 @@ export const HELP_MANUAL = Object.freeze({ ], }], }, + { + id: "camera-inputs", + title: "Camera inputs: Blue Iris and Axis", + summary: "Choose each camera's plate recognition source and configure Axis HTTP push or MQTT without enrolling existing Blue Iris cameras again.", + roles: ["administrator"], + keywords: ["Axis", "ALPV", "camera inputs", "HTTP", "MQTT", "plate image", "source credential"], + settingsViews: ["/settings/integrations/camera-inputs"], + blocks: [{ type: "steps", title: "Connect a camera input", items: [ + "Open Settings > Integrations > Camera Inputs. Existing Blue Iris cameras appear automatically after a read and keep their current alert actions. Add camera input offers Blue Iris or Axis License Plate Verifier per camera.", + "For Blue Iris, use the exact camera name sent in its alert JSON and retain the API-key-protected /api/plate-reads destination. Blue Iris recording and playback settings remain separate from recognition.", + "For Axis, enter a permanent camera name and its serial number or MAC address. Choose HTTP push or MQTT. HTTP and MQTT together is an advanced option; matching events are deduplicated.", + "For HTTP push, save the input, copy its destination URL and generated source credential, then configure Axis Integration > Push events. Basic authentication uses the source ID as username and generated credential as password. Use a camera-reachable ALPR address, New/Update/Lost events, included images, and the camera Event buffer.", + "For MQTT, select or add a broker, enter its incoming AllPlates topic filter, and use QoS 1 on both the camera publication and ALPR subscription. Keep Retain set to None. ALPR uses a separate persistent client ID and checks the camera identity in every event.", + "Choose immediate processing for fast initial reads and later corrections, or finalized processing to wait for Lost with a 30-second inactivity fallback. Immediate alerts use the first recognition and are not repeated for corrections. Optional ROI ID filtering and in/out direction labels apply per camera.", + "Save and use Test MQTT to verify broker access, then Listen for event to inspect a real or camera-generated test event, plate image, time, direction, and processing state. Camera test events are real imports. Keep sample plate values out of production when testing.", + ] },{ type: "note", tone: "info", title: "Delivery and evidence", text: "HTTP success and MQTT QoS 1 acknowledgment follow durable receipt. Broker persistence is needed for ALPR disconnects; MQTT cannot recover events never delivered to the broker. Original plate observations and later corrections are retained separately, and human corrections remain authoritative. Event observations are retained for seven days; saved images use application storage. Source credentials are shown only when generated; rotating one requires updating the camera." }], + }, { id: "mqtt", title: "MQTT integration", diff --git a/lib/middleware-auth.mjs b/lib/middleware-auth.mjs index f4de6b6..4a86928 100644 --- a/lib/middleware-auth.mjs +++ b/lib/middleware-auth.mjs @@ -163,6 +163,10 @@ export function createMiddlewareHandler({ return async function handleMiddleware(request) { const pathname = request.nextUrl.pathname; + // This exact receiver authenticates its own scoped source credential before + // reading the body. All camera administration routes retain session auth. + if (/^\/api\/camera-inputs\/axis\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(pathname)) return next(); + if (isIntegrationApiPath(pathname)) { const result = await authorizeIntegrationRequest(request, { fetchImpl, diff --git a/lib/plate-read-ingestion.js b/lib/plate-read-ingestion.js new file mode 100644 index 0000000..af530d6 --- /dev/null +++ b/lib/plate-read-ingestion.js @@ -0,0 +1,933 @@ +import { checkPlateForNotification, getPool, isPlateIgnored } from "@/lib/db"; +import { sendPushoverNotification } from "@/lib/notifications"; +import { processAcceptedPlateReadEffects } from "@/lib/accepted-plate-read-effects.mjs"; +import { NotificationAcceptedReadService } from "@/lib/notification-accepted-read-service.mjs"; +import { NotificationRuntimeRepository } from "@/lib/notification-runtime-repository.mjs"; +import { reconcileLateDuplicateRead } from "@/lib/late-duplicate-reconciliation.mjs"; +import { createPlateReadEventIdentity } from "@/lib/plate-read-event-identity.mjs"; +import { parseBlueIrisAlertPointer } from "@/lib/blue-iris-alert-pointer.mjs"; +import { + applyBlueIrisDirectionEligibility, + blueIrisTriggerDirectionColumns, + persistBlueIrisPrimaryDirectionForRead, + resolveBlueIrisTriggerDirectionForRead, +} from "@/lib/blue-iris-trigger-direction.mjs"; +import { assessDirectionImageEligibility } from "@/lib/direction-image-eligibility.mjs"; +import { wakeBlueIrisVehicleFrameWorker } from "@/lib/blue-iris-vehicle-frame-runtime.mjs"; +import { + recordAliasApplicationWithClient, + resolvePlateAliasWithClient, +} from "@/lib/plate-review-repository.mjs"; +import { MqttAcceptedReadService } from "@/lib/mqtt/accepted-read-service.mjs"; +import { MqttRepository } from "@/lib/mqtt/repository.mjs"; +import { getConfig } from "@/lib/settings"; +import fileStorage from "@/lib/fileStorage"; +import { createIntegrationIngressRecorder } from "@/lib/integration-ingress.mjs"; +import { + appendReadPipelineEvents, + buildAcceptedReadPipelineEvents, + buildLateDuplicateReconciliationEvent, + buildLegacyPushoverPipelineEvent, +} from "@/lib/read-pipeline-timeline.mjs"; +import { overviewReadQueueState } from "@/lib/vehicle-overview-association.mjs"; +import { createComponentLogger } from "@/logging/logger"; +import { publishPlateReadChanges } from "@/lib/sse"; + +export const plateIngressLogger = createComponentLogger("plate-read-ingress"); +export const plateIngressRecorder = createIntegrationIngressRecorder({ + query: async (text, values) => { + const pool = await getPool(); + return pool.query(text, values); + }, + logger: plateIngressLogger, +}); + +async function recordReadPipelineEvents(buildEvents, context = {}) { + try { + const events = + typeof buildEvents === "function" ? buildEvents() : buildEvents; + const pool = await getPool(); + await appendReadPipelineEvents( + (text, values) => pool.query(text, values), + events, + ); + } catch (error) { + plateIngressLogger.warn("read_pipeline_timeline_append_failed", { + readId: context.readId ?? null, + requestId: context.requestId ?? null, + errorCode: error?.code || "READ_PIPELINE_TIMELINE_APPEND_FAILED", + }); + } +} + +// Revised to use a blacklist of all other possible AI labels if using the memo +const EXCLUDED_LABELS = [ + "person", + "bicycle", + "car", + "motorcycle", + "bus", + "truck", + "bird", + "cat", + "dog", + "horse", + "sheep", + "cow", + "bear", + "deer", + "rabbit", + "raccoon", + "fox", + "skunk", + "squirrel", + "pig", + "vehicle", + "boat", + "bottle", + "chair", + "cup", + "table", + "airplane", + "train", + "traffic light", + "fire hydrant", + "stop sign", + "parking meter", + "bench", + "elephant", + "zebra", + "giraffe", + "backpack", + "umbrella", + "handbag", + "tie", + "suitcase", + "frisbee", + "skis", + "snowboard", + "sports ball", + "kite", + "baseball bat", + "baseball glove", + "skateboard", + "surfboard", + "tennis racket", + "wine glass", + "fork", + "knife", + "spoon", + "bowl", + "banana", + "apple", + "sandwich", + "orange", + "broccoli", + "carrot", + "hot dog", + "pizza", + "donut", + "cake", + "couch", + "potted plant", + "bed", + "dining table", + "toilet", + "tv", + "laptop", + "mouse", + "remote", + "keyboard", + "cell phone", + "microwave", + "oven", + "toaster", + "sink", + "refrigerator", + "book", + "clock", + "vase", + "scissors", + "teddy bear", + "hair drier", + "toothbrush", + "plate", + "dayplate", + "nightplate", + "people", + "motorbike", +].map((label) => label.toLowerCase()); + +function extractPlatesFromMemo(memo) { + if (!memo) { + return []; + } + + // Split up all the detected objects/plates in memo + const detections = memo.split(",").map((d) => d.trim()); + + // Process each item in the memo + const plates = detections + .map((detection) => { + // Split by colon to separate label from confidence + const [label] = detection.split(":"); + + if (!label) { + return null; + } + + // Convert to lowercase for comparison + const normalizedLabel = label.trim().toLowerCase(); + + // ignore other AI objects and only return plates + if (EXCLUDED_LABELS.includes(normalizedLabel)) { + return null; + } + + // The older dayplate and nightplate models return the plate in brackets + let plateNumber = label.trim(); + if (plateNumber.includes("[") && plateNumber.includes("]")) { + plateNumber = plateNumber.replace(/\[|\]/g, ""); + } + + // Return cleaned plate number in uppercase + return plateNumber.toUpperCase(); + }) + .filter((plate) => plate !== null); + + return [...new Set(plates)]; // Remove duplicates +} + +export async function processPlateRead(data, _request, context = {}) { + let dbClient = null; + let transactionOpen = false; + const transactionImages = []; + + try { + // Preserve whether Blue Iris supplied a timestamp. The database still gets + // a valid server timestamp when it is missing, while the MQTT payload can + // label that case as a server-receipt fallback. + const timestamp = data.timestamp || new Date().toISOString(); + const camera = data.camera || null; + let plates = []; + + // Handle AI dump format if present + if (data.ai_dump) { + try { + const aiDumpArray = Array.isArray(data.ai_dump) + ? data.ai_dump + : [data.ai_dump]; + + // Find the ALPR response in the ai_dump array + const aiData = aiDumpArray.find((item) => item?.api === "alpr"); + + if (aiData?.found?.predictions) { + // Get all plate annotations for this batch + const allPlateAnnotations = aiData.found.predictions + .filter((pred) => pred.valid_ocr_annotation) + .map((pred) => pred.plate_annotation) + .filter(Boolean) + .join("&"); + + // Process each prediction + plates = aiData.found.predictions.map((prediction) => ({ + plate_number: prediction.plate?.toUpperCase(), + confidence: prediction.confidence.toFixed(2), + crop_coordinates: [ + prediction.x_min, + prediction.y_min, + prediction.x_max, + prediction.y_max, + ], + ...(prediction.valid_ocr_annotation && { + ocr_annotation: { + ocr_annotation: prediction.ocr_annotation, + }, + plate_annotation: allPlateAnnotations, + }), + })); + } + } catch { + context.setOutcome?.({ + outcome: "invalid_plate_payload", + errorCode: "INVALID_PLATE_PAYLOAD", + }); + plateIngressLogger.warn("plate_read_payload_invalid", { + requestId: context.requestId, + cameraName: camera, + errorCode: "INVALID_PLATE_PAYLOAD", + }); + return Response.json( + { error: "Invalid plate-read payload" }, + { status: 400 }, + ); + } + } + // Backwards compatibility for older formats + else if (data.memo) { + //extract plates from memo + plates = extractPlatesFromMemo(data.memo).map((plate) => ({ + plate_number: plate, + })); + } else if (data.plate_number) { + plates = [ + { + plate_number: data.plate_number.toUpperCase(), + confidence: context.axisEvent?.confidence ?? null, + }, + ]; + } + + if (plates.length === 0) { + context.setOutcome?.({ + outcome: "no_valid_plates", + errorCode: "NO_VALID_PLATES", + }); + return Response.json( + { error: "No valid plates found in request" }, + { status: 400 }, + ); + } + + let directionImageEligibility; + try { + directionImageEligibility = context.axisEvent + ? { eligible: false, evaluated: true, reason: "axis_camera_source" } + : await assessDirectionImageEligibility(data.Image); + } catch { + directionImageEligibility = { + eligible: false, + evaluated: false, + monochrome: false, + monochromeRatio: null, + reason: "direction_image_assessment_failed", + }; + plateIngressLogger.warn("direction_image_assessment_failed", { + requestId: context.requestId, + cameraName: camera, + errorCode: "DIRECTION_IMAGE_ASSESSMENT_FAILED", + }); + } + + // Get database connection + const pool = await getPool(); + dbClient = await pool.connect(); + await dbClient.query("BEGIN"); + transactionOpen = true; + if (!context.axisEvent && camera) { + await dbClient.query( + "SELECT pg_advisory_xact_lock(hashtextextended(LOWER(BTRIM($1)),1))", + [camera], + ); + const source = ( + await dbClient.query( + "SELECT source,enabled FROM public.camera_inputs WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1)) FOR UPDATE", + [camera], + ) + ).rows[0]; + if (source && (!source.enabled || source.source !== "blue_iris")) { + await dbClient.query("COMMIT"); + transactionOpen = false; + return Response.json( + { processed: [], duplicates: [], ignored: [], sourceIgnored: true }, + { status: 200 }, + ); + } + if (source) + await dbClient.query( + "UPDATE public.camera_inputs SET last_received_at=CURRENT_TIMESTAMP,connection_status='receiving',last_error=NULL WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1))", + [camera], + ); + } + + const config = await getConfig(); + const mqttRepository = new MqttRepository({ + pool, + executor: dbClient, + }); + const mqttService = new MqttAcceptedReadService({ + repository: mqttRepository, + logger: plateIngressLogger, + matchingSettings: config.plateMatching, + }); + const notificationService = new NotificationAcceptedReadService({ + repository: new NotificationRuntimeRepository({ executor: dbClient }), + mqttRepository, + logger: plateIngressLogger, + matchingSettings: config.plateMatching, + }); + const resolvedBlueIrisTriggerDirection = + await resolveBlueIrisTriggerDirectionForRead({ + query: (text, values) => dbClient.query(text, values), + camera, + value: data.trigger_type ?? data.triggerType ?? data.TYPE, + }); + const blueIrisTriggerDirection = applyBlueIrisDirectionEligibility( + resolvedBlueIrisTriggerDirection, + directionImageEligibility, + ); + const blueIrisTriggerColumns = blueIrisTriggerDirectionColumns( + blueIrisTriggerDirection, + ); + const overviewVehicleView = overviewReadQueueState({ + eligibility: directionImageEligibility, + directionStatus: blueIrisTriggerColumns.bi_trigger_direction_status, + directionLabel: blueIrisTriggerColumns.bi_trigger_direction_label, + }); + + const processedPlates = []; + const duplicatePlates = []; + const duplicateTargetReadIds = []; + const ignoredPlates = []; + const pendingEffects = []; + const duplicateReconciliations = []; + let overviewWorkQueued = false; + const blueIrisAlert = parseBlueIrisAlertPointer({ + clip: data.ALERT_CLIP, + path: data.ALERT_PATH, + camera, + }); + + for (const plateData of plates) { + const observedPlate = plateData.plate_number; + const alias = await resolvePlateAliasWithClient(dbClient, { + observedPlate, + cameraName: camera, + }); + const effectivePlate = alias?.target_plate || observedPlate; + const effectivePlateData = { + ...plateData, + observed_plate: observedPlate, + plate_number: effectivePlate, + }; + + // Ignore decisions use the effective identity so a reviewed alias inherits + // the known plate's behavior without altering the immutable observation. + const isIgnored = await isPlateIgnored(effectivePlate); + if (isIgnored) { + ignoredPlates.push(observedPlate); + continue; + } + + let imagePaths = { imagePath: null, thumbnailPath: null }; + if (data.Image) { + try { + imagePaths = await fileStorage.saveImage( + data.Image, + plateData.plate_number, + ); + } catch { + plateIngressLogger.error("plate_image_storage_failed", { + requestId: context.requestId, + cameraName: camera, + errorCode: "PLATE_IMAGE_STORAGE_FAILED", + }); + } + } + + // Track files as soon as they are created. Any failure between image + // storage and COMMIT must remove them along with the rolled-back row. + if (imagePaths.imagePath || imagePaths.thumbnailPath) { + transactionImages.push(imagePaths); + } + + const biPath = blueIrisAlert.playbackPath; + + const eventIdentity = + context.eventIdentity || + createPlateReadEventIdentity({ + plateNumber: observedPlate, + timestamp, + cameraName: camera, + }); + + const result = await dbClient.query( + `WITH new_plate AS ( + INSERT INTO plates (plate_number) + VALUES ($1) + ON CONFLICT (plate_number) DO NOTHING + ), + new_read AS ( + INSERT INTO plate_reads ( + plate_number, + observed_plate, + applied_alias_id, + review_status, + review_revision, + validated, + image_data, + image_path, + thumbnail_path, + timestamp, + camera_name, + bi_path, + bi_alert_clip, + bi_alert_path, + bi_alert_offset_ms, + bi_trigger_type, + bi_trigger_direction_status, + bi_trigger_direction_label, + bi_trigger_direction_profile_version, + bi_trigger_direction_algorithm, + bi_trigger_direction_error_code, + confidence, + crop_coordinates, + ocr_annotation, + plate_annotation, + event_identity, + vehicle_image_status, + vehicle_image_queue_kind, + vehicle_image_attempt_count, + vehicle_image_retryable, + vehicle_image_error_code, + vehicle_image_updated_at + ) + SELECT $1, $2::varchar, $3, + CASE WHEN $3::bigint IS NULL THEN 'unreviewed' ELSE 'alias_resolved' END, + CASE WHEN $3::bigint IS NULL THEN 0 ELSE 1 END, + ($3::bigint IS NOT NULL), + $4, $5, $6, $7, $8::varchar, $9, $10, $11, $12, + $18, $19, $20, $21, $22, $23, + $13, $14, $15, $16, $17::varchar, + $24, $25, 0, $26, $27, CURRENT_TIMESTAMP + WHERE NOT EXISTS ( + SELECT 1 FROM plate_reads + WHERE observed_plate = $2::varchar AND timestamp = $7 + AND camera_name IS NOT DISTINCT FROM $8::varchar + ${context.axisEvent ? "AND event_identity = $17::text" : ""} + ) + ON CONFLICT DO NOTHING + RETURNING id + ), + traffic_camera_observation AS ( + INSERT INTO public.camera_observations ( + source_key, camera_key, observation_kind, + observation_timestamp, received_at, direction_label, + blue_iris_timeline_path, plate_read_id, raw_payload, + idempotency_key + ) + SELECT 'plate-ingress', COALESCE(NULLIF(BTRIM($8::text), ''), 'unconfigured-camera'), + 'lpr', $7, CURRENT_TIMESTAMP, $20, + $11, new_read.id, + jsonb_build_object('eventIdentity', $17::text), + repeat(md5('plate-read:' || new_read.id::text), 2) + FROM new_read + ON CONFLICT (idempotency_key) DO NOTHING + RETURNING id + ) + SELECT id, NULL::bigint AS duplicate_target_read_id + FROM new_read + UNION ALL + SELECT NULL::bigint AS id, existing.id AS duplicate_target_read_id + FROM plate_reads existing + WHERE existing.observed_plate = $2::varchar + AND existing.timestamp = $7 + AND existing.camera_name IS NOT DISTINCT FROM $8::varchar + ${context.axisEvent ? "AND existing.event_identity = $17::text" : ""} + AND NOT EXISTS (SELECT 1 FROM new_read) + ORDER BY duplicate_target_read_id DESC NULLS LAST + LIMIT 1`, + [ + effectivePlate, + observedPlate, + alias?.id || null, + null, + imagePaths.imagePath, + imagePaths.thumbnailPath, + timestamp, + camera, + biPath, + blueIrisAlert.alertClip, + blueIrisAlert.alertPath, + blueIrisAlert.offsetMs, + effectivePlateData.confidence ?? null, + effectivePlateData.crop_coordinates || null, + effectivePlateData.ocr_annotation || null, + effectivePlateData.plate_annotation || null, + eventIdentity, + blueIrisTriggerColumns.bi_trigger_type, + blueIrisTriggerColumns.bi_trigger_direction_status, + blueIrisTriggerColumns.bi_trigger_direction_label, + blueIrisTriggerColumns.bi_trigger_direction_profile_version, + blueIrisTriggerColumns.bi_trigger_direction_algorithm, + blueIrisTriggerColumns.bi_trigger_direction_error_code, + overviewVehicleView.status, + overviewVehicleView.queueKind, + overviewVehicleView.retryable, + overviewVehicleView.errorCode, + ], + ); + + const resultRow = result.rows?.[0] || {}; + if (!resultRow.id) { + duplicatePlates.push(observedPlate); + const duplicateTargetReadId = Number.parseInt( + String(resultRow.duplicate_target_read_id ?? ""), + 10, + ); + if ( + Number.isSafeInteger(duplicateTargetReadId) && + duplicateTargetReadId > 0 && + !duplicateTargetReadIds.includes(duplicateTargetReadId) + ) { + duplicateTargetReadIds.push(duplicateTargetReadId); + } + + let reconciliation = null; + let directionNotificationResult = null; + if ( + Number.isSafeInteger(duplicateTargetReadId) && + duplicateTargetReadId > 0 + ) { + reconciliation = await reconcileLateDuplicateRead( + (text, values) => dbClient.query(text, values), + { + readId: duplicateTargetReadId, + imagePath: imagePaths.imagePath, + thumbnailPath: imagePaths.thumbnailPath, + alert: { + bi_path: biPath, + bi_alert_clip: blueIrisAlert.alertClip, + bi_alert_path: blueIrisAlert.alertPath, + bi_alert_offset_ms: blueIrisAlert.offsetMs, + }, + recognition: { + confidence: effectivePlateData.confidence ?? null, + crop_coordinates: effectivePlateData.crop_coordinates ?? null, + ocr_annotation: effectivePlateData.ocr_annotation ?? null, + plate_annotation: effectivePlateData.plate_annotation ?? null, + }, + direction: blueIrisTriggerColumns, + vehicleOverview: overviewVehicleView, + }, + ); + + if (reconciliation.directionAttached) { + const primaryDirection = + (await persistBlueIrisPrimaryDirectionForRead({ + query: (text, values) => dbClient.query(text, values), + readId: duplicateTargetReadId, + camera, + evidence: blueIrisTriggerDirection, + })); + if (primaryDirection) { + directionNotificationResult = + await notificationService.processVehicleDirection( + { + ...reconciliation.read, + id: duplicateTargetReadId, + persisted_timestamp: reconciliation.read.timestamp, + }, + primaryDirection, + ); + if ( + directionNotificationResult.status === "error" || + directionNotificationResult.status === "partial" + ) { + throw new Error( + `Blue Iris direction notification outbox handoff failed for reconciled read ${duplicateTargetReadId}`, + ); + } + } + } + + await context.onAcceptedRead?.( + (sql, values) => dbClient.query(sql, values), + duplicateTargetReadId, + (file) => transactionImages.push(file), + ); + + if (reconciliation.changed) { + duplicateReconciliations.push({ + reconciliation, + directionNotificationResult, + }); + if (reconciliation.overviewQueued) overviewWorkQueued = true; + } + } + + if (!reconciliation?.imageAttached) { + await fileStorage + .deleteImage(imagePaths.imagePath, imagePaths.thumbnailPath) + .catch(() => + plateIngressLogger.warn("duplicate_plate_image_cleanup_failed", { + requestId: context.requestId, + cameraName: camera, + errorCode: "DUPLICATE_IMAGE_CLEANUP_FAILED", + }), + ); + const trackedImageIndex = transactionImages.indexOf(imagePaths); + if (trackedImageIndex >= 0) { + transactionImages.splice(trackedImageIndex, 1); + } + } + } else { + const readId = resultRow.id; + await context.onAcceptedRead?.( + (sql, values) => dbClient.query(sql, values), + readId, + (file) => transactionImages.push(file), + ); + const primaryDirection = + context.axisDirection || + (await persistBlueIrisPrimaryDirectionForRead({ + query: (text, values) => dbClient.query(text, values), + readId, + camera, + evidence: blueIrisTriggerDirection, + })); + await recordAliasApplicationWithClient(dbClient, { + readId, + eventIdentity, + alias, + observedPlate, + }); + processedPlates.push({ + plate: effectivePlate, + observedPlate, + id: readId, + aliasApplied: Boolean(alias), + }); + if (overviewVehicleView.queueKind === "overview") + overviewWorkQueued = true; + + const acceptedRead = { + ...effectivePlateData, + id: readId, + plate_number: effectivePlate, + camera_name: camera, + timestamp: data.timestamp || null, + persisted_timestamp: timestamp, + image_path: imagePaths.imagePath, + thumbnail_path: imagePaths.thumbnailPath, + bi_path: biPath, + bi_alert_clip: blueIrisAlert.alertClip, + bi_alert_path: blueIrisAlert.alertPath, + bi_alert_offset_ms: blueIrisAlert.offsetMs, + ...blueIrisTriggerColumns, + }; + + const mqttResult = await mqttService.processAcceptedRead(acceptedRead); + if (mqttResult.status === "error" || mqttResult.status === "partial") { + throw new Error( + `MQTT outbox handoff failed for accepted read ${readId}`, + ); + } + const unifiedResult = + await notificationService.processAcceptedRead(acceptedRead); + if ( + unifiedResult.status === "error" || + unifiedResult.status === "partial" + ) { + throw new Error( + `Unified notification outbox handoff failed for accepted read ${readId}`, + ); + } + let directionResult = null; + if (primaryDirection) { + directionResult = await notificationService.processVehicleDirection( + acceptedRead, + primaryDirection, + ); + if ( + directionResult.status === "error" || + directionResult.status === "partial" + ) { + throw new Error( + `Blue Iris direction notification outbox handoff failed for accepted read ${readId}`, + ); + } + } + + pendingEffects.push({ + read: acceptedRead, + imageData: data.Image, + mqttResult, + unifiedResult, + directionResult, + aliasApplied: Boolean(alias), + imageStored: Boolean(imagePaths.imagePath), + thumbnailStored: Boolean(imagePaths.thumbnailPath), + alertPointerPresent: Boolean( + blueIrisAlert.alertClip || + blueIrisAlert.alertPath || + blueIrisAlert.playbackPath, + ), + direction: blueIrisTriggerColumns, + vehicleOverview: overviewVehicleView, + }); + } + } + + await dbClient.query("COMMIT"); + transactionOpen = false; + publishPlateReadChanges( + [...processedPlates.map(({ id }) => id), ...duplicateTargetReadIds], + processedPlates.length > 0 ? "ingested" : "duplicate_reconciled", + ); + for (const effect of pendingEffects) { + await recordReadPipelineEvents( + () => + buildAcceptedReadPipelineEvents({ + readId: effect.read.id, + requestId: context.requestId, + ingressReceiptId: context.ingressReceiptId, + aliasApplied: effect.aliasApplied, + imageStored: effect.imageStored, + thumbnailStored: effect.thumbnailStored, + alertPointerPresent: effect.alertPointerPresent, + direction: effect.direction, + mqttResult: effect.mqttResult, + notificationResult: effect.unifiedResult, + directionNotificationResult: effect.directionResult, + vehicleOverview: effect.vehicleOverview, + }), + { readId: effect.read.id, requestId: context.requestId }, + ); + } + for (const effect of duplicateReconciliations) { + await recordReadPipelineEvents( + () => [ + buildLateDuplicateReconciliationEvent({ + readId: effect.reconciliation.readId, + requestId: context.requestId, + ingressReceiptId: context.ingressReceiptId, + reconciliation: effect.reconciliation, + directionNotificationResult: effect.directionNotificationResult, + }), + ], + { readId: effect.reconciliation.readId, requestId: context.requestId }, + ); + } + if (overviewWorkQueued) wakeBlueIrisVehicleFrameWorker(); + + // Unified MQTT and Pushover handoffs committed with each read. The legacy + // Pushover path remains post-commit until every migrated rule is cut over. + for (const effect of pendingEffects) { + try { + const legacyResult = await processAcceptedPlateReadEffects({ + read: effect.read, + imageData: effect.imageData, + shouldSendPushover: checkPlateForNotification, + sendPushover: sendPushoverNotification, + processMqtt: async () => effect.mqttResult, + logger: plateIngressLogger, + }); + await recordReadPipelineEvents( + () => [ + buildLegacyPushoverPipelineEvent({ + readId: effect.read.id, + requestId: context.requestId, + ingressReceiptId: context.ingressReceiptId, + result: legacyResult, + }), + ], + { readId: effect.read.id, requestId: context.requestId }, + ); + } catch { + plateIngressLogger.error( + "accepted_plate_notification_processing_failed", + { + requestId: context.requestId, + processedCount: processedPlates.length, + errorCode: "ACCEPTED_READ_EFFECT_FAILED", + }, + ); + } + } + + const responseStatus = processedPlates.length > 0 ? 201 : 409; + const outcome = + processedPlates.length > 0 + ? "accepted" + : duplicatePlates.length > 0 + ? "duplicate" + : ignoredPlates.length > 0 + ? "ignored" + : "no_changes"; + const outcomeDetails = { + outcome, + processedReadIds: processedPlates.map(({ id }) => id), + processedCount: processedPlates.length, + duplicateCount: duplicatePlates.length, + duplicateTargetReadIds, + duplicateReconciledCount: duplicateReconciliations.length, + duplicateReconciledReadIds: duplicateReconciliations.map( + ({ reconciliation }) => reconciliation.readId, + ), + ignoredCount: ignoredPlates.length, + overviewWorkQueued, + }; + context.setOutcome?.(outcomeDetails); + plateIngressLogger.info("plate_read_ingress_completed", { + requestId: context.requestId, + cameraName: camera, + httpStatus: responseStatus, + triggerType: blueIrisTriggerColumns.bi_trigger_type, + directionStatus: blueIrisTriggerColumns.bi_trigger_direction_status, + directionLabel: blueIrisTriggerColumns.bi_trigger_direction_label, + directionErrorCode: + blueIrisTriggerColumns.bi_trigger_direction_error_code, + directionProfileVersion: + blueIrisTriggerColumns.bi_trigger_direction_profile_version, + directionAlgorithm: blueIrisTriggerColumns.bi_trigger_direction_algorithm, + ...outcomeDetails, + }); + + return Response.json( + { + processed: processedPlates, + duplicates: duplicatePlates, + ignored: ignoredPlates, + message: `Processed ${processedPlates.length} plates, ${duplicatePlates.length} duplicates, ${ignoredPlates.length} ignored`, + }, + { status: responseStatus }, + ); + } catch (error) { + const shouldDeleteTransactionImages = transactionOpen; + + if (dbClient && transactionOpen) { + try { + await dbClient.query("ROLLBACK"); + } catch { + plateIngressLogger.error("plate_read_transaction_rollback_failed", { + requestId: context.requestId, + errorCode: "PLATE_READ_ROLLBACK_FAILED", + }); + } + } + + if (shouldDeleteTransactionImages) { + await Promise.allSettled( + transactionImages.map(({ imagePath, thumbnailPath }) => + fileStorage.deleteImage(imagePath, thumbnailPath), + ), + ); + } + + throw error; + } finally { + if (dbClient) { + dbClient.release(); + } + } +} + +// Called inside the Axis update transaction when direction arrives after NEW. +export async function processCameraDirection(client, readId, direction) { + const pool = await getPool(); + const config = await getConfig(); + const read = ( + await client.query("SELECT * FROM public.plate_reads WHERE id=$1", [readId]) + ).rows[0]; + if (!read) return; + const service = new NotificationAcceptedReadService({ + repository: new NotificationRuntimeRepository({ executor: client }), + mqttRepository: new MqttRepository({ pool, executor: client }), + logger: plateIngressLogger, + matchingSettings: config.plateMatching, + }); + const result = await service.processVehicleDirection(read, direction); + if (result.status === "error" || result.status === "partial") + throw new Error("AXIS_DIRECTION_HANDOFF_FAILED"); +} diff --git a/lib/release-info.mjs b/lib/release-info.mjs index 2cb69b1..59684d2 100644 --- a/lib/release-info.mjs +++ b/lib/release-info.mjs @@ -4,9 +4,15 @@ import builtReleaseMetadata from "./built-release-metadata.mjs"; import { HELP_MANUAL } from "./help-manual.mjs"; export const CURRENT_RELEASE_NOTES = Object.freeze({ - title: "Resizable columns and compact actions", - publishedAt: "2026-10-21", + title: "Axis HTTP and MQTT camera inputs", + publishedAt: "2026-11-01", items: Object.freeze([ + "Choose Blue Iris or AXIS License Plate Verifier for each camera in Settings > Integrations > Camera Inputs; existing Blue Iris cameras continue automatically.", + "Receive Axis recognition through authenticated HTTP push, MQTT, or both, including camera-supplied plate and scene images.", + "Configure camera identity, broker and topic, image storage, movement direction labels, and immediate or finalized passage processing.", + "Persist incoming events before acknowledgement, deduplicate transports, retry processing, preserve human corrections, and apply later camera observations to the same passage.", + "Update User Guide 3.27 with setup, diagnostics, source compatibility and the remaining need for camera-specific hardware verification.", + "Update vulnerable application and tooling dependencies and remove unused legacy image and UI-generator packages.", "Resize Recognition Feed and Plate Database columns with draggable header dividers or the keyboard; remember widths separately for each table in this browser.", "Reset one column by double-clicking its divider, or restore the full layout with Reset widths.", "Show narrow text with ellipses and full-value hover text, protect minimum control widths, and scroll wider tables horizontally.", diff --git a/lib/settings-help-coverage.mjs b/lib/settings-help-coverage.mjs index 500f39d..abacf7d 100644 --- a/lib/settings-help-coverage.mjs +++ b/lib/settings-help-coverage.mjs @@ -1,4 +1,5 @@ export const SETTINGS_HELP_COVERAGE = Object.freeze([ + { sectionId: "camera-inputs", routes: ["/settings/integrations/camera-inputs"], requiredTerms: ["Blue Iris", "Axis", "HTTP push", "MQTT", "source credential", "QoS 1", "30-second inactivity", "seven days"] }, { sectionId: "general-settings", routes: ["/settings/general"], diff --git a/lib/storage-reconciliation-repository.mjs b/lib/storage-reconciliation-repository.mjs index 26b579a..6d2e8e6 100644 --- a/lib/storage-reconciliation-repository.mjs +++ b/lib/storage-reconciliation-repository.mjs @@ -51,6 +51,10 @@ async function referencedPathSet(client, paths) { SELECT storage_path AS path FROM public.vehicle_image_assets WHERE storage_path = ANY($1::text[]) UNION ALL SELECT storage_path AS path FROM public.vehicle_image_derivatives WHERE storage_path = ANY($1::text[]) + UNION ALL + SELECT scene_image_path AS path FROM public.camera_input_passages WHERE scene_image_path = ANY($1::text[]) + UNION ALL + SELECT scene_thumbnail_path AS path FROM public.camera_input_passages WHERE scene_thumbnail_path = ANY($1::text[]) ) referenced_paths WHERE path IS NOT NULL`, [paths] diff --git a/lib/vehicle-direction-repository.mjs b/lib/vehicle-direction-repository.mjs index bf76e23..3d2cac7 100644 --- a/lib/vehicle-direction-repository.mjs +++ b/lib/vehicle-direction-repository.mjs @@ -47,7 +47,7 @@ export class VehicleDirectionRepository { `SELECT status, orientation, orientation_confidence, direction_label, profile_version, sample_counts FROM public.current_vehicle_direction_observations - WHERE read_id = $1 AND classifier_version = $2 AND status = 'ready'`, + WHERE read_id = $1 AND classifier_version IN ($2,'axis-lpv-direction-v1') AND status = 'ready'`, [readId, classifierVersion] ); return result.rows[0] || null; @@ -771,7 +771,7 @@ export class VehicleDirectionRepository { direction_label = EXCLUDED.direction_label, sample_counts = EXCLUDED.sample_counts, source_embedding_id = EXCLUDED.source_embedding_id, evaluated_at = CURRENT_TIMESTAMP - WHERE public.vehicle_direction_observations.classifier_version IS DISTINCT FROM $11 + WHERE public.vehicle_direction_observations.classifier_version NOT IN ($11, 'axis-lpv-direction-v1') RETURNING read_id`, [readId, cameraName, embeddingModel, classifierVersion, profileVersion, result.status, result.orientation, result.confidence, directionLabel, diff --git a/migrations.sql b/migrations.sql index 9c0f57d..74f162e 100644 --- a/migrations.sql +++ b/migrations.sql @@ -7145,7 +7145,7 @@ WHERE labels.embedding_model = 'canonical-crop-direction-v2'; CREATE OR REPLACE VIEW public.current_vehicle_direction_observations AS SELECT observations.* FROM public.vehicle_direction_observations observations -WHERE observations.classifier_version = 'blue-iris-zone-crossing-v1' +WHERE observations.classifier_version IN ('blue-iris-zone-crossing-v1','axis-lpv-direction-v1') OR (observations.classifier_version = 'canonical-crop-orientation-knn-v2' AND EXISTS (SELECT 1 FROM public.vehicle_direction_sources source WHERE source.read_id = observations.read_id @@ -7153,7 +7153,7 @@ WHERE observations.classifier_version = 'blue-iris-zone-crossing-v1' -- Retire only derived predictions/calibration that cannot identify their crop. DELETE FROM public.vehicle_direction_observations - WHERE classifier_version <> 'blue-iris-zone-crossing-v1' AND source_embedding_id IS NULL; + WHERE classifier_version NOT IN ('blue-iris-zone-crossing-v1','axis-lpv-direction-v1') AND source_embedding_id IS NULL; DELETE FROM public.vehicle_orientation_labels WHERE source_embedding_id IS NULL; INSERT INTO public.schema_migrations(version, description) VALUES @@ -7732,3 +7732,75 @@ CREATE INDEX IF NOT EXISTS idx_plates_state_country_options INSERT INTO public.schema_migrations(version, description) VALUES ('2026102201_manual_plate_state_country', 'Add optional manually entered State/Country plate metadata.') ON CONFLICT(version) DO NOTHING; + + +-- Configurable incoming camera sources. Existing Blue Iris inputs remain implicit. +CREATE TABLE IF NOT EXISTS public.camera_inputs ( + id UUID PRIMARY KEY, + camera_name VARCHAR(30) NOT NULL, + source VARCHAR(16) NOT NULL CHECK(source IN ('blue_iris','axis')), + transport VARCHAR(8) NOT NULL CHECK(transport IN ('http','mqtt','both')), + enabled BOOLEAN NOT NULL DEFAULT TRUE, + device_id VARCHAR(64), + broker_id INTEGER REFERENCES public.mqttbrokers(id) ON DELETE RESTRICT, + topic_filter VARCHAR(512), + qos INTEGER NOT NULL DEFAULT 1 CHECK(qos IN (0,1)), + processing_mode VARCHAR(16) NOT NULL DEFAULT 'immediate' CHECK(processing_mode IN ('immediate','final')), + store_images BOOLEAN NOT NULL DEFAULT TRUE, + roi_filter VARCHAR(30), + direction_in VARCHAR(80) NOT NULL DEFAULT 'In', direction_out VARCHAR(80) NOT NULL DEFAULT 'Out', + credential_hash CHAR(64), + connection_status VARCHAR(32) NOT NULL DEFAULT 'waiting', + last_received_at TIMESTAMPTZ, last_imported_at TIMESTAMPTZ, last_error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK(source <> 'axis' OR device_id IS NOT NULL), + CHECK(transport NOT IN ('mqtt','both') OR (broker_id IS NOT NULL AND topic_filter IS NOT NULL)) +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_camera_inputs_name ON public.camera_inputs(LOWER(BTRIM(camera_name))); +CREATE UNIQUE INDEX IF NOT EXISTS uq_camera_inputs_device ON public.camera_inputs(device_id) WHERE source='axis'; +CREATE TABLE IF NOT EXISTS public.camera_input_events ( + id BIGSERIAL PRIMARY KEY, + input_id UUID NOT NULL REFERENCES public.camera_inputs(id) ON DELETE RESTRICT, + fingerprint CHAR(64) NOT NULL, + payload JSONB NOT NULL, + transport VARCHAR(8) NOT NULL CHECK(transport IN ('http','mqtt')), + status VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','processed','ignored')), + read_id INTEGER REFERENCES public.plate_reads(id) ON DELETE SET NULL, + received_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + processed_at TIMESTAMPTZ, + leased_until TIMESTAMPTZ, lease_token UUID, + revision INTEGER NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(input_id,fingerprint) +); +CREATE INDEX IF NOT EXISTS idx_camera_input_pending ON public.camera_input_events(next_attempt_at,id) WHERE status='pending'; +CREATE INDEX IF NOT EXISTS idx_camera_input_event_retention ON public.camera_input_events(processed_at,id) WHERE status<>'pending'; +CREATE TABLE IF NOT EXISTS public.camera_input_passages ( + id UUID PRIMARY KEY, + input_id UUID NOT NULL REFERENCES public.camera_inputs(id) ON DELETE RESTRICT, + car_id VARCHAR(64) NOT NULL, + source_camera VARCHAR(64) NOT NULL, + first_capture TIMESTAMPTZ NOT NULL, last_capture TIMESTAMPTZ NOT NULL, + last_event_id BIGINT REFERENCES public.camera_input_events(id) ON DELETE SET NULL, + last_state VARCHAR(12) NOT NULL, + last_seen TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + read_id INTEGER REFERENCES public.plate_reads(id) ON DELETE SET NULL, + finalized BOOLEAN NOT NULL DEFAULT FALSE, + direction_label VARCHAR(80), scene_image_path VARCHAR(255), scene_thumbnail_path VARCHAR(255) +); +CREATE INDEX IF NOT EXISTS idx_camera_input_passage_lookup ON public.camera_input_passages(input_id,car_id,last_capture DESC); +ALTER TABLE public.camera_input_events ADD COLUMN IF NOT EXISTS passage_id UUID + REFERENCES public.camera_input_passages(id) ON DELETE SET NULL; +CREATE INDEX IF NOT EXISTS idx_camera_input_event_passage ON public.camera_input_events(passage_id); +INSERT INTO public.schema_migrations(version,description) VALUES + ('2026110101_axis_camera_inputs','Configurable Blue Iris and Axis HTTP/MQTT inputs with durable Axis receipts and passage correlation.') +ON CONFLICT(version) DO NOTHING; + +ALTER TABLE public.vehicle_direction_observations DROP CONSTRAINT IF EXISTS vehicle_direction_ready_state; +ALTER TABLE public.vehicle_direction_observations ADD CONSTRAINT vehicle_direction_ready_state CHECK ( + (status='ready' AND direction_label IS NOT NULL AND + ((classifier_version='axis-lpv-direction-v1' AND orientation IN ('front','rear','unknown')) OR + (orientation IN ('front','rear') AND orientation_confidence IS NOT NULL))) OR + (status<>'ready' AND orientation='unknown' AND direction_label IS NULL) +) NOT VALID; diff --git a/package.json b/package.json index 21ff2c1..618c30d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blueiris-alpr-database", - "version": "0.1.58", + "version": "0.1.59", "private": true, "engines": { "node": ">=24.0.0 <25" @@ -15,6 +15,7 @@ "start": "next start", "lint": "eslint .", "test": "node --test --test-concurrency=1 test/*.test.mjs", + "test:camera-inputs:postgres": "node --experimental-loader ./scripts/camera-inputs-test-loader.mjs scripts/test-camera-inputs-postgres.mjs", "test:sanitize": "node scripts/check-community-sanitization.mjs", "test:runtime-image": "node scripts/verify-runtime-image.mjs", "migrate:postgres": "node scripts/postgres-major-migration.mjs", @@ -33,7 +34,6 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@hookform/resolvers": "^3.9.1", "@radix-ui/react-accordion": "^1.2.1", "@radix-ui/react-alert-dialog": "^1.1.2", "@radix-ui/react-aspect-ratio": "^1.1.0", @@ -71,16 +71,15 @@ "embla-carousel-react": "^8.3.1", "input-otp": "^1.4.1", "iron-session": "^8.0.4", - "jimp": "1.6.1", "jose": "^5.9.6", "js-yaml": "4.3.2", "lodash": "4.18.1", "lottie-react": "^2.4.1", "lucide-react": "^0.456.0", "mqtt": "5.15.2", - "next": "15.5.27", + "next": "15.5.28", "next-themes": "^0.4.3", - "nodemailer": "10.0.12", + "nodemailer": "10.1.4", "openvino-node": "2025.4.0", "perspective-transform": "^1.1.3", "pg": "^8.13.1", @@ -101,12 +100,10 @@ "tailwindcss-animate": "^1.0.7", "use-debounce": "^10.0.4", "vaul": "^1.1.1", - "winston": "^3.17.0", - "zod": "^3.23.8" + "winston": "^3.17.0" }, "devDependencies": { "@next/eslint-plugin-next": "16.2.12", - "@shadcn/ui": "^0.0.4", "@types/mqtt": "^2.5.0", "@types/react": "19.0.14", "@types/react-dom": "19.0.6", @@ -127,7 +124,9 @@ "mdast-util-to-hast": "13.2.1", "nanoid": "3.3.18", "brace-expansion": "5.0.12", - "ip-address": "10.7.1", + "ip-address": "10.7.4", + "minimatch": "11.0.1", + "zod": "4.6.6", "postcss": "8.5.23", "sharp": "0.35.5", "postcss-selector-parser": "7.1.6", diff --git a/scripts/camera-inputs-test-loader.mjs b/scripts/camera-inputs-test-loader.mjs new file mode 100644 index 0000000..29a3d4b --- /dev/null +++ b/scripts/camera-inputs-test-loader.mjs @@ -0,0 +1,27 @@ +import { pathToFileURL } from "node:url"; +import path from "node:path"; +import { existsSync } from "node:fs"; + +// Run the actual Next.js ingestion service against an isolated PostgreSQL +// database without starting the web server. Production does not use this loader. +export async function resolve(specifier, context, nextResolve) { + if (specifier.startsWith("@/")) { + const base = path.resolve(import.meta.dirname, "..", specifier.slice(2)); + for (const candidate of [ + base, + base + ".js", + base + ".mjs", + base + ".jsx", + ]) { + if (existsSync(candidate)) + return nextResolve(pathToFileURL(candidate).href, context); + } + } + try { + return await nextResolve(specifier, context); + } catch (error) { + if (specifier.startsWith("next/") && !specifier.endsWith(".js")) + return nextResolve(specifier + ".js", context); + throw error; + } +} diff --git a/scripts/test-camera-inputs-postgres.mjs b/scripts/test-camera-inputs-postgres.mjs new file mode 100644 index 0000000..0f5f48d --- /dev/null +++ b/scripts/test-camera-inputs-postgres.mjs @@ -0,0 +1,711 @@ +import assert from "node:assert/strict"; +import { readFile, mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pg from "pg"; +import { CameraInputRepository } from "../lib/camera-inputs/repository.mjs"; +import { CameraInputRuntime } from "../lib/camera-inputs/runtime.mjs"; +import { AxisEventProcessor } from "../lib/camera-inputs/processor.mjs"; + +const serverUrl = process.env.ALPR_AXIS_TEST_SERVER_URL; +if (!serverUrl) + throw new Error( + "Set ALPR_AXIS_TEST_SERVER_URL to an isolated local PostgreSQL test server. Never use a production server.", + ); +const parsed = new URL(serverUrl); +if (!["127.0.0.1", "localhost"].includes(parsed.hostname)) + throw new Error("This validation script requires a local test server"); +const admin = new pg.Pool({ connectionString: serverUrl }); +const database = `alpr_axis_test_${process.pid}`; +const temporary = await mkdtemp(path.join(tmpdir(), "alpr-axis-integration-")); +let pool; +let applicationPool; +let created = false; +try { + await admin.query(`CREATE DATABASE "${database}"`); + created = true; + const testUrl = new URL(serverUrl); + testUrl.pathname = `/${database}`; + pool = new pg.Pool({ connectionString: testUrl.href }); + process.env.DB_HOST = `${testUrl.hostname}:${testUrl.port}`; + process.env.DB_NAME = database; + process.env.DB_USER = decodeURIComponent(testUrl.username || "postgres"); + process.env.DB_PASSWORD = decodeURIComponent(testUrl.password || "test-only"); + process.env.ALPR_CONFIG_FILE_PATH = path.join(temporary, "settings.yaml"); + process.env.ALPR_AUTH_FILE_PATH = path.join(temporary, "auth.json"); + process.env.STORAGE_PATH = path.join(temporary, "storage"); + process.env.ALPR_LOG_DIR = path.join(temporary, "logs"); + await pool.query( + await readFile(new URL("../schema.sql", import.meta.url), "utf8"), + ); + await pool.query("SET search_path TO public"); + const migrations = await readFile( + new URL("../migrations.sql", import.meta.url), + "utf8", + ); + await pool.query(migrations); + const [ + { processPlateRead, processCameraDirection }, + { default: storage }, + { getPool }, + ] = await Promise.all([ + import("../lib/plate-read-ingestion.js"), + import("../lib/fileStorage.js"), + import("../lib/db.js"), + ]); + applicationPool = await getPool(); + const png = await ( + await import("sharp") + ) + .default({ + create: { width: 100, height: 32, channels: 3, background: "white" }, + }) + .jpeg() + .toBuffer(); + const image = png.toString("base64"); + const body = (input, values = {}) => ({ + plateText: "ABC123", + carID: "42", + carState: "new", + capture_timestamp: "1793286884000", + carMoveDirection: "unknown", + camera_info: { SerialNumber: input.device_id }, + plateConfidence: "0", + imageType: "plate", + ImageArray: [{ BinaryImage: image }], + ...values, + }); + const repository = new CameraInputRepository(pool); + let ingestions = 0; + let directionHandoffs = 0; + const processor = new AxisEventProcessor({ + pool, + storage, + notifyDirection: (...args) => { + directionHandoffs++; + return processCameraDirection(...args); + }, + ingest: (...args) => { + ingestions++; + return processPlateRead(...args); + }, + }); + async function deliver(input, event, transport = "http") { + const received = await repository.receive(input, event, transport); + if (received.eventId) { + const receipt = ( + await pool.query( + "SELECT * FROM public.camera_input_events WHERE id=$1", + [received.eventId], + ) + ).rows[0]; + assert.equal(await processor.process(receipt), true); + } + return received; + } + const old = await processPlateRead({ + plate_number: "OLD123", + camera: "Existing BI", + timestamp: "2026-10-29T15:00:00.000Z", + }); + assert.equal(old.status, 201); + const before = ( + await pool.query( + "SELECT * FROM public.plate_reads WHERE camera_name='Existing BI'", + ) + ).rows[0]; + assert.equal( + (await repository.list()).find((row) => row.camera_name === "Existing BI") + .legacy, + true, + ); + const saved = await repository.save({ + camera_name: "Axis Test", + source: "axis", + transport: "both", + device_id: "AABBCCDDEEFF", + broker_id: await (async () => { + const result = await pool.query( + "INSERT INTO public.mqttbrokers(name,broker,port,topic) VALUES ('Test broker','127.0.0.1',1883,'test') RETURNING id", + ); + return result.rows[0].id; + })(), + topic_filter: "axis/test/#", + }); + const input = await repository.get(saved.input.id); + assert.ok(saved.credential); + assert.equal(saved.input.credential_hash, undefined); + await deliver(input, body(input)); + assert.equal(ingestions, 1); + const read = ( + await pool.query("SELECT * FROM public.plate_reads WHERE camera_name=$1", [ + input.camera_name, + ]) + ).rows[0]; + assert.notEqual(read.confidence, null, "A reported zero is not missing confidence"); + assert.equal(Number(read.confidence), 0); + assert.ok(read.image_path); + // Exercise recovery through the duplicate branch of the shared ingestor. + const initialReceipt = (await pool.query( + "SELECT * FROM public.camera_input_events WHERE read_id=$1", [read.id], + )).rows[0]; + await pool.query("UPDATE public.camera_input_passages SET read_id=NULL WHERE read_id=$1", [read.id]); + await pool.query("UPDATE public.camera_input_events SET status='pending' WHERE id=$1", [initialReceipt.id]); + let duplicateHook = 0; + const recoveryProcessor = new AxisEventProcessor({ pool, storage, + ingest: (data, request, context) => processPlateRead(data, request, { + ...context, + onAcceptedRead: async (query, id, trackImage) => { + assert.equal(Number(id), read.id, "Duplicate hook receives the existing read ID"); + duplicateHook++; + return context.onAcceptedRead(query, id, trackImage); + }, + }), + }); + assert.equal(await recoveryProcessor.process(initialReceipt), true); + assert.equal(duplicateHook, 1); + assert.equal((await pool.query("SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE camera_name=$1", [input.camera_name])).rows[0].count, 1); + await deliver( + input, + body(input, { + plateText: "ABC128", + carState: "update", + capture_timestamp: "1793286884500", + carMoveDirection: "in", + }), + ); + const corrected = ( + await pool.query("SELECT * FROM public.plate_reads WHERE id=$1", [read.id]) + ).rows[0]; + assert.equal(corrected.plate_number, "ABC128"); + assert.equal(corrected.observed_plate, "ABC123"); + assert.equal(ingestions, 1); + assert.equal( + ( + await pool.query( + "SELECT direction_label FROM public.vehicle_direction_observations WHERE read_id=$1", + [read.id], + ) + ).rows[0].direction_label, + "In", + ); + await deliver( + input, + body(input, { + plateText: "ABC123", + carState: "new", + capture_timestamp: "1793286884000", + }), + ); + assert.equal( + ( + await pool.query( + "SELECT plate_number FROM public.plate_reads WHERE id=$1", + [read.id], + ) + ).rows[0].plate_number, + "ABC128", + ); + const mqttDuplicate = { + topic: "axis:CameraApplicationPlatform/ALPV.AllPlates", + message: { + data: { + text: "ABC128", + carID: "42", + carState: "update", + capture_timestamp: "1793286884500", + MACAddress: input.device_id, + carMoveDirection: "in", + lpImage: image, + }, + }, + }; + assert.equal((await deliver(input, mqttDuplicate, "mqtt")).duplicate, true); + await deliver( + input, + body(input, { + plateText: "ABC128", + carState: "lost", + capture_timestamp: "1793286884500", + carMoveDirection: "in", + }), + ); + await deliver( + input, + body(input, { + plateText: "NEW123", + carState: "new", + capture_timestamp: "1793286885000", + }), + ); + assert.equal( + ingestions, + 2, + "A new runtime carID occurrence after LOST creates a new passage", + ); + // A manual correction is authoritative over subsequent automatic OCR. + await pool.query("INSERT INTO public.plates(plate_number) VALUES ('MANUAL')"); + await pool.query( + "UPDATE public.plate_reads SET plate_number='MANUAL',review_status='corrected',validated=TRUE WHERE id=$1", + [read.id], + ); + const delayed = await deliver( + input, + body(input, { + plateText: "LATE123", + carState: "update", + capture_timestamp: "1793286884600", + carMoveDirection: "in", + }), + ); + assert.equal( + ( + await pool.query( + "SELECT plate_number FROM public.plate_reads WHERE id=$1", + [read.id], + ) + ).rows[0].plate_number, + "MANUAL", + ); + assert.equal( + ( + await pool.query( + "SELECT read_id FROM public.camera_input_events WHERE id=$1", + [delayed.eventId], + ) + ).rows[0].read_id, + read.id, + "Delayed observations remain attached to the earlier occurrence", + ); + assert.ok( + directionHandoffs > 0, + "Direction arriving on UPDATE goes through the durable direction pipeline", + ); + const finalSaved = await repository.save({ + camera_name: "Final Test", + source: "axis", + device_id: "112233445566", + processing_mode: "final", + }); + const finalInput = await repository.get(finalSaved.input.id); + await deliver(finalInput, body(finalInput)); + await assert.rejects( + () => repository.save({ device_id: "112233445577" }, finalInput.id), + (error) => error.status === 409, + "Buffered final-mode passages must finish before changing source identity", + ); + await assert.rejects( + () => repository.save({ processing_mode: "immediate" }, finalInput.id), + (error) => error.status === 409, + "Changing mode cannot strand buffered observations before their fallback runs", + ); + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE camera_name=$1", + [finalInput.camera_name], + ) + ).rows[0].count, + 0, + ); + await deliver( + finalInput, + body(finalInput, { + plateText: "FINAL12", + carState: "lost", + capture_timestamp: "1793286884700", + }), + ); + assert.equal( + ( + await pool.query( + "SELECT plate_number FROM public.plate_reads WHERE camera_name=$1", + [finalInput.camera_name], + ) + ).rows[0].plate_number, + "FINAL12", + ); + assert.equal((await pool.query( + `SELECT COUNT(*)::int AS count FROM public.camera_input_events WHERE input_id=$1 AND + (read_id IS NULL OR passage_id IS NULL OR payload ? 'image' OR payload ? 'sceneImage')`, [finalInput.id], + )).rows[0].count, 0, "Final import links buffered receipts and removes their embedded images"); + await deliver( + finalInput, + body(finalInput, { + carID: "77", + plateText: "FALL123", + capture_timestamp: "1793287994000", + }), + ); + await pool.query( + "UPDATE public.camera_input_passages SET last_seen=CURRENT_TIMESTAMP-INTERVAL '31 seconds' WHERE input_id=$1 AND car_id='77'", + [finalInput.id], + ); + const staleCandidate = (await pool.query( + `SELECT events.* FROM public.camera_input_passages passages JOIN public.camera_input_events events ON events.id=passages.last_event_id + WHERE passages.input_id=$1 AND passages.car_id='77'`, [finalInput.id], + )).rows[0]; + const queuedUpdate = await repository.receive(finalInput, body(finalInput, { + carID: "77", plateText: "FALL128", carState: "update", capture_timestamp: "1793287994500", + }), "http"); + await processor.process(staleCandidate, { finalize: true }); + assert.equal((await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number IN ('FALL123','FALL128')", + )).rows[0].count, 0, "A durable update still in the inbox prevents premature finalization"); + await processor.process((await pool.query( + "SELECT * FROM public.camera_input_events WHERE id=$1", [queuedUpdate.eventId], + )).rows[0]); + await processor.process(staleCandidate, { finalize: true }); + assert.equal((await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number IN ('FALL123','FALL128')", + )).rows[0].count, 0, "A newer observation invalidates an old fallback candidate"); + await pool.query( + "UPDATE public.camera_input_passages SET last_seen=CURRENT_TIMESTAMP-INTERVAL '31 seconds' WHERE input_id=$1 AND car_id='77'", [finalInput.id], + ); + const runtime = new CameraInputRuntime({ + pool, + storage, + ingest: processPlateRead, + mqttConnect: () => { + throw new Error("Unexpected network"); + }, + logger: {}, + }); + runtime.repository.mqttInputs = async () => []; + try { + await runtime.tick(); + } finally { + await runtime.stop(); + } + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number='FALL128'", + ) + ).rows[0].count, + 1, + "Final mode recovers when LOST is missing", + ); + // A second transport adds an image while the first receipt is being processed. + const sparse = body(input, { + carID: "80", + plateText: "ENRICH1", + capture_timestamp: "1793288994000", + ImageArray: [], + }); + const sparseReceipt = await repository.receive(input, sparse, "http"); + const enrichment = { + ...sparse, + ImageArray: [ + { ImageType: "plate", BinaryImage: image }, + { ImageType: "vehicle", BinaryImage: image }, + ], + }; + const enrichmentProcessor = new AxisEventProcessor({ + pool, + storage, + ingest: async (...args) => { + const richer = await repository.receive(input, enrichment, "http"); + assert.equal(richer.duplicate, true); + return processPlateRead(...args); + }, + }); + await enrichmentProcessor.process( + ( + await pool.query("SELECT * FROM public.camera_input_events WHERE id=$1", [ + sparseReceipt.eventId, + ]) + ).rows[0], + ); + const enrichedReceipt = ( + await pool.query("SELECT * FROM public.camera_input_events WHERE id=$1", [ + sparseReceipt.eventId, + ]) + ).rows[0]; + assert.equal( + enrichedReceipt.status, + "pending", + "A concurrent richer revision is not erased by the older worker", + ); + await processor.process(enrichedReceipt); + const enriched = ( + await pool.query( + "SELECT reads.image_path,passages.scene_image_path FROM public.plate_reads reads JOIN public.camera_input_passages passages ON passages.read_id=reads.id WHERE reads.plate_number='ENRICH1'", + ) + ).rows; + assert.equal(enriched.length, 1); + assert.ok(enriched[0].image_path); + assert.ok(enriched[0].scene_image_path); + const { storageReconciliationRepositoryInternals } = await import("../lib/storage-reconciliation-repository.mjs"); + const sceneReferences = await storageReconciliationRepositoryInternals.referencedPathSet(pool, [enriched[0].scene_image_path]); + assert.ok(sceneReferences.has(enriched[0].scene_image_path.replaceAll("\\", "/")), "Stored Axis scenes are not classified as orphan files"); + assert.equal( + (await repository.receive(input, enrichment, "http")).eventId, + null, + "Unchanged image redelivery does not enqueue work", + ); + const filtered = await repository.save( + { ...finalInput, roi_filter: "1" }, + finalInput.id, + ); + assert.equal( + ( + await repository.receive( + await repository.get(filtered.input.id), + body(finalInput, { roiID: "0" }), + "http", + ) + ).filtered, + true, + ); + const switched = await repository.save({ + camera_name: "Existing BI", + source: "axis", + device_id: "998877665544", + }); + assert.equal( + (await processPlateRead({ plate_number: "DUP123", camera: "Existing BI" })) + .status, + 200, + ); + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number='DUP123'", + ) + ).rows[0].count, + 0, + "Only the explicitly chosen recognition source imports reads", + ); + await repository.save({ source: "blue_iris" }, switched.input.id); + await deliver( + input, + body(input, { + carID: "100", + plateText: "SAME123", + capture_timestamp: "1793289994000", + }), + ); + await deliver( + input, + body(input, { + carID: "101", + plateText: "SAME123", + capture_timestamp: "1793289994000", + }), + ); + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number='SAME123'", + ) + ).rows[0].count, + 2, + "Distinct Axis passages remain distinct even at the same timestamp", + ); + await deliver( + input, + body(input, { + carID: "102", + plateText: "EARLY12", + capture_timestamp: "1793290994000", + }), + ); + await deliver( + input, + body(input, { + carID: "102", + plateText: "UPDATE1", + carState: "update", + capture_timestamp: "1793290994500", + }), + ); + await deliver( + input, + body(input, { + carID: "102", + plateText: "BEST123", + carState: "lost", + capture_timestamp: "1793290994000", + }), + ); + assert.equal( + ( + await pool.query( + "SELECT plate_number FROM public.plate_reads WHERE observed_plate='EARLY12'", + ) + ).rows[0].plate_number, + "BEST123", + "LOST is authoritative even when it reuses an earlier capture timestamp", + ); + // Failure inside the shared transaction must leave the durable receipt pending. + const failed = await repository.receive( + input, + body(input, { + carID: "99", + plateText: "RETRY12", + capture_timestamp: "1793286994000", + }), + "http", + ); + const receipt = ( + await pool.query("SELECT * FROM public.camera_input_events WHERE id=$1", [ + failed.eventId, + ]) + ).rows[0]; + const broken = new AxisEventProcessor({ + pool, + storage, + ingest: (data, request, context) => + processPlateRead(data, request, { + ...context, + onAcceptedRead: async () => { + throw new Error("Injected transaction failure"); + }, + }), + }); + await assert.rejects( + () => broken.process(receipt), + /Injected transaction failure/, + ); + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number='RETRY12'", + ) + ).rows[0].count, + 0, + ); + assert.equal( + ( + await pool.query( + "SELECT status FROM public.camera_input_events WHERE id=$1", + [receipt.id], + ) + ).rows[0].status, + "pending", + ); + await processor.process(receipt); + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number='RETRY12'", + ) + ).rows[0].count, + 1, + ); + const replaced = await repository.save( + { device_id: "C00000000001" }, + input.id, + ); + const replacedInput = await repository.get(replaced.input.id); + await deliver( + replacedInput, + body(replacedInput, { + plateText: "DEVICE1", + carState: "update", + capture_timestamp: "1793286884500", + }), + ); + assert.equal( + ( + await pool.query( + "SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE plate_number='DEVICE1'", + ) + ).rows[0].count, + 1, + "A changed physical camera never reuses the prior camera's runtime passage", + ); + for (let number = 1; number <= 5; number++) { + const firstDevice = `F0000000000${number}`; + const secondDevice = `F1000000000${number}`; + const configured = await repository.save({ + camera_name: `Concurrent ${number}`, + source: "axis", + device_id: firstDevice, + }); + const active = await repository.get(configured.input.id); + const outcomes = await Promise.allSettled([ + repository.receive( + active, + body(active, { + carID: "race", + plateText: `RACE${number}`, + capture_timestamp: String(1793291994000 + number), + }), + "http", + ), + repository.save({ device_id: secondDevice }, active.id), + ]); + assert.ok( + outcomes.some((outcome) => outcome.status === "rejected"), + "A source identity change cannot strand a concurrently accepted receipt", + ); + if (outcomes[0].status === "fulfilled") + assert.equal((await repository.get(active.id)).device_id, firstDevice); + } + await pool.query(migrations); + assert.deepEqual( + ( + await pool.query("SELECT * FROM public.plate_reads WHERE id=$1", [ + before.id, + ]) + ).rows[0], + before, + "Repeated upgrades preserve existing Blue Iris records", + ); + assert.equal( + ( + await pool.query( + "SELECT direction_label FROM public.current_vehicle_direction_observations WHERE read_id=$1", + [read.id], + ) + ).rows[0].direction_label, + "In", + "Repeated migrations preserve Axis camera direction", + ); + const after = await processPlateRead({ + plate_number: "OLD124", + camera: "Existing BI", + timestamp: "2026-10-29T15:01:00.000Z", + }); + assert.equal(after.status, 201); + console.log( + "PASS: real PostgreSQL schema/upgrade, existing Blue Iris ingestion, Axis HTTP/MQTT deduplication, corrections, immutable observations, image storage, finalization, carID reuse, manual review preservation, transaction rollback and retry.", + ); +} catch (error) { + console.error( + "Axis PostgreSQL validation failed:", + error.code, + error.message, + error.stack, + ); + try { + applicationPool ||= await (await import("../lib/db.js")).getPool(); + } catch {} + throw error; +} finally { + await applicationPool?.end(); + await pool?.end(); + try { + if (created) { + // Pool.end() can resolve before PostgreSQL has consumed every socket's + // Terminate message. Forcing DROP during that gap emits an idle-pool + // error on Linux. Wait for graceful disconnect and refuse a leaked pool. + const deadline = Date.now() + 5000; + while (true) { + const active = await admin.query( + "SELECT COUNT(*)::int AS count FROM pg_stat_activity WHERE datname=$1", + [database], + ); + if (active.rows[0].count === 0) break; + if (Date.now() >= deadline) + throw new Error("Test database still has active connections after pool shutdown"); + await new Promise((resolve) => setTimeout(resolve, 50)); + } + await admin.query(`DROP DATABASE "${database}"`); + } + } finally { + await admin.end(); + } +} diff --git a/test/accepted-plate-read-effects.test.mjs b/test/accepted-plate-read-effects.test.mjs index f1afa55..030afda 100644 --- a/test/accepted-plate-read-effects.test.mjs +++ b/test/accepted-plate-read-effects.test.mjs @@ -185,7 +185,7 @@ test("unexpected MQTT failures are returned and cannot block Pushover", async () test("the plate route commits each read and MQTT outbox handoff atomically", async () => { const [source, migrations] = await Promise.all([ - readFile(new URL("../app/api/plate-reads/route.js", import.meta.url), "utf8"), + readFile(new URL("../lib/plate-read-ingestion.js", import.meta.url), "utf8"), readFile(new URL("../migrations.sql", import.meta.url), "utf8"), ]); @@ -231,7 +231,7 @@ test("the plate route commits each read and MQTT outbox handoff atomically", asy const mqttHandoff = source.indexOf( "await mqttService.processAcceptedRead(acceptedRead)" ); - const commit = source.indexOf('await dbClient.query("COMMIT")'); + const commit = source.lastIndexOf('await dbClient.query("COMMIT")'); const acceptedEffects = source.indexOf("await processAcceptedPlateReadEffects"); const pipelineTimeline = source.indexOf("await recordReadPipelineEvents"); diff --git a/test/blue-iris-alert-pointer.test.mjs b/test/blue-iris-alert-pointer.test.mjs index 193e02a..32cdb7a 100644 --- a/test/blue-iris-alert-pointer.test.mjs +++ b/test/blue-iris-alert-pointer.test.mjs @@ -34,7 +34,7 @@ test("partial Blue Iris metadata remains usable for future API correlation", () test("ingestion and migrations preserve Blue Iris pointers without storing BVR content", async () => { const [route, migrations] = await Promise.all([ - readFile(new URL("../app/api/plate-reads/route.js", import.meta.url), "utf8"), + readFile(new URL("../lib/plate-read-ingestion.js", import.meta.url), "utf8"), readFile(new URL("../migrations.sql", import.meta.url), "utf8"), ]); diff --git a/test/blue-iris-trigger-direction.test.mjs b/test/blue-iris-trigger-direction.test.mjs index d0c696d..642371d 100644 --- a/test/blue-iris-trigger-direction.test.mjs +++ b/test/blue-iris-trigger-direction.test.mjs @@ -301,7 +301,7 @@ test("plate-read trigger lookup executes mapped, unmapped, invalid, and omitted test("plate ingestion promotes current mapped crossings while preserving legacy shadow data", async () => { const [route, migration, settings, readme] = await Promise.all([ - readFile(new URL("../app/api/plate-reads/route.js", import.meta.url), "utf8"), + readFile(new URL("../lib/plate-read-ingestion.js", import.meta.url), "utf8"), readFile(new URL("../migrations.sql", import.meta.url), "utf8"), readFile(new URL("../components/settings/VehicleIntelligenceSettings.jsx", import.meta.url), "utf8"), readFile(new URL("../README.md", import.meta.url), "utf8"), @@ -314,7 +314,7 @@ test("plate ingestion promotes current mapped crossings while preserving legacy assert.match(route, /applyBlueIrisDirectionEligibility/); assert.match(route, /triggerType: blueIrisTriggerColumns\.bi_trigger_type/); assert.match(route, /directionStatus: blueIrisTriggerColumns\.bi_trigger_direction_status/); - assert.match(route, /directionErrorCode: blueIrisTriggerColumns\.bi_trigger_direction_error_code/); + assert.match(route, /directionErrorCode:\s+blueIrisTriggerColumns\.bi_trigger_direction_error_code/); assert.match(route, /processVehicleDirection/); assert.match(route, /\.\.\.blueIrisTriggerColumns/); assert.match(migration, /2026080702_blue_iris_trigger_direction_shadow/); diff --git a/test/camera-inputs.test.mjs b/test/camera-inputs.test.mjs new file mode 100644 index 0000000..6e4ba23 --- /dev/null +++ b/test/camera-inputs.test.mjs @@ -0,0 +1,652 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { once } from "node:events"; +import net from "node:net"; +import mqtt from "mqtt"; +import mqttPacket from "mqtt-packet"; +import { + normalizeAxisEvent, + InputError, + readAxisRequest, + topicMatches, + validateTopicFilter, +} from "../lib/camera-inputs/axis.mjs"; +import { + hashCredential, + validateInput, + verifySourceCredential, +} from "../lib/camera-inputs/config.mjs"; +import { createAxisReceiver } from "../lib/camera-inputs/http.mjs"; +import { + CameraInputRuntime, + buildSubscriberOptions, +} from "../lib/camera-inputs/runtime.mjs"; +import { testMqttConnection } from "../lib/camera-inputs/connection-test.mjs"; +import { axisDirection } from "../lib/camera-inputs/processor.mjs"; +import { startCameraInputsWithRetry } from "../lib/camera-inputs/startup.mjs"; +import { createMiddlewareHandler } from "../lib/middleware-auth.mjs"; + +const png = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jf1kAAAAASUVORK5CYII="; +const input = { + id: "b41494f6-eec2-454e-9fcb-c2fc39b967f1", + source: "axis", + transport: "both", + enabled: true, + camera_name: "Test Gate", + device_id: "AABBCCDDEEFF", + store_images: true, + direction_in: "Entering", + direction_out: "Exiting", + credential_hash: hashCredential("test-only-source-secret"), +}; +function mqttEvent(overrides = {}) { + return { + topic: "axis:CameraApplicationPlatform/ALPV.AllPlates", + timestamp: 1793286884875, + message: { + source: {}, + key: {}, + data: { + text: "ABC123", + carID: "42", + carState: "update", + capture_timestamp: "1793286884875", + frame_timestamp: "1793286884", + MACAddress: "AA:BB:CC:DD:EE:FF", + lpConfidence: "0.000000", + vehicleConfidence: "47.3", + carMoveDirection: "in", + roiID: "0", + lpImage: png, + action: "Denied", + country: "USA", + region: "Example", + regionCode: "EX", + vehicleType: "TRUCK", + view: "front", + ...overrides, + }, + }, + }; +} +function httpEvent(overrides = {}) { + return { + plateText: "ABC123", + carID: "42", + carState: "update", + capture_timestamp: "1793286884875", + camera_info: { SerialNumber: input.device_id }, + plateConfidence: "0.000000", + carMoveDirection: "in", + roiID: "0", + imageType: "plate", + ImageArray: [{ BinaryImage: png }], + vehicle_info: { view: "front" }, + ...overrides, + }; +} + +test("Axis MQTT imports the existing nested payload, cropped image, zero confidence and denied access result", () => { + const event = normalizeAxisEvent(mqttEvent(), input); + assert.equal(event.plate, "ABC123"); + assert.equal(event.image, png); + assert.equal(event.confidence, 0); + assert.equal(event.timestamp, "2026-10-29T15:14:44.875Z"); + assert.equal(event.metadata.action, "Denied"); + assert.equal(axisDirection(input, event).directionLabel, "Entering"); +}); +test("HTTP and MQTT normalize the same physical event to the same idempotency identity", () => { + assert.equal( + normalizeAxisEvent(httpEvent(), input).fingerprint, + normalizeAxisEvent(mqttEvent(), input).fingerprint, + ); + assert.notEqual( + normalizeAxisEvent(mqttEvent({ text: "ABC128" }), input).fingerprint, + normalizeAxisEvent(mqttEvent(), input).fingerprint, + ); +}); +test("the documented blank HTTP ImageType uses the enclosing plate type without duplicating it as a scene", () => { + const event = normalizeAxisEvent(httpEvent({ ImageArray: [{ ImageType: "", BinaryImage: png }] }), input); + assert.equal(event.image, png); + assert.equal(event.sceneImage, null); +}); +test("camera identity, plate length, state, confidence, timestamp units and images are validated", () => { + for (const values of [ + { MACAddress: "112233445566" }, + { text: "A".repeat(11) }, + { text: "../oops" }, + { carState: "test" }, + { carID: "" }, + { capture_timestamp: "1793286884" }, + { capture_timestamp: "bad" }, + { lpConfidence: "NaN" }, + { lpImage: "not image data" }, + ]) + assert.throws(() => normalizeAxisEvent(mqttEvent(values), input)); +}); +test("disabled image storage discards received image data without requiring a separate image topic", () => { + const event = normalizeAxisEvent(mqttEvent(), { + ...input, + store_images: false, + }); + assert.equal(event.image, null); + assert.equal(event.sceneImage, null); +}); +test("malformed scalar and image fields are permanent input errors", () => { + for (const event of [ + null, [], "bad", mqttEvent({ text: { toString: "bad" } }), + mqttEvent({ capture_timestamp: { toString: "bad" } }), + mqttEvent({ lpConfidence: {} }), mqttEvent({ lpImage: {} }), + httpEvent({ ImageArray: [null] }), + httpEvent({ ImageArray: [{ ImageType: {} }] }), + ]) assert.throws(() => normalizeAxisEvent(event, input), InputError); +}); +test("direction labels remain independent of vehicle view", () => { + const event = normalizeAxisEvent( + mqttEvent({ view: "", carMoveDirection: "out" }), + input, + ); + assert.equal(axisDirection(input, event).orientation, "unknown"); + assert.equal(axisDirection(input, event).directionLabel, "Exiting"); + assert.equal(axisDirection(input, { ...event, direction: "unknown" }), null); +}); +test("configuration defaults are portable, reject invalid topics, and preserve existing camera names", () => { + assert.equal( + validateInput({ camera_name: "Existing", source: "blue_iris" }).transport, + "http", + ); + assert.throws( + () => validateInput({ camera_name: "Gate", source: "axis" }), + /serial|MAC/, + ); + for (const filter of [ + "", + "axis/#/plates", + "axis/a+", + "axis/a#", + "$share/group/axis/#", + ]) + assert.throws(() => validateTopicFilter(filter)); + for (const filter of ["axis/+/event/#", "axis/camera/ALPV.AllPlates"]) + assert.equal(validateTopicFilter(filter), filter); + assert.equal(topicMatches("axis/+/event/#", "axis/gate/event/a"), true); + assert.equal(topicMatches("axis/+/event", "axis/gate/event/a"), false); + assert.equal(topicMatches("#", "$SYS/status"), false); +}); +test("scoped receiver accepts Basic, Bearer and x-api-key, while rejecting URL credentials and disabled inputs", () => { + const url = `http://localhost/api/camera-inputs/axis/${input.id}`; + for (const headers of [ + { "x-api-key": "test-only-source-secret" }, + { authorization: "Bearer test-only-source-secret" }, + { + authorization: `Basic ${Buffer.from(`${input.id}:test-only-source-secret`).toString("base64")}`, + }, + ]) + assert.equal( + verifySourceCredential(new Request(url, { headers }), input), + true, + ); + assert.equal( + verifySourceCredential( + new Request(url, { headers: { authorization: "Bearer wrong" } }), + input, + ), + false, + ); + assert.equal( + verifySourceCredential( + new Request(url + "?api_key=test-only-source-secret"), + input, + ), + false, + ); + assert.equal( + verifySourceCredential( + new Request(url, { headers: { "x-api-key": "test-only-source-secret" } }), + { ...input, enabled: false }, + ), + false, + ); +}); +test("HTTP authentication occurs before body consumption and durable receipt precedes success", async () => { + let received = 0; + let bodyRead = false; + const receiver = createAxisReceiver({ + repository: { + get: async () => input, + receive: async () => { + received++; + return { duplicate: false }; + }, + }, + logger: {}, + }); + const unauthorized = { + url: "http://localhost/event", + headers: new Headers(), + get body() { + bodyRead = true; + throw new Error("Body must stay unread"); + }, + }; + assert.equal((await receiver(unauthorized, input.id)).status, 401); + assert.equal(bodyRead, false); + assert.equal(received, 0); + const request = new Request("http://localhost/event", { + method: "POST", + headers: { + "x-api-key": "test-only-source-secret", + "content-type": "application/json", + }, + body: JSON.stringify(httpEvent()), + }); + assert.equal((await receiver(request, input.id)).status, 200); + assert.equal(received, 1); + const broken = createAxisReceiver({ + repository: { + get: async () => input, + receive: async () => { + throw new Error("Database unavailable"); + }, + }, + logger: {}, + }); + assert.equal( + ( + await broken( + new Request(request.url, { + method: "POST", + headers: request.headers, + body: JSON.stringify(httpEvent()), + }), + input.id, + ) + ).status, + 503, + ); +}); +test("HTTP multipart preserves separate plate and scene images and enforces streamed size limits", async () => { + const form = new FormData(); + form.set( + "event", + new Blob( + [JSON.stringify(httpEvent({ ImageArray: [], imageType: "vehicle" }))], + { type: "application/json" }, + ), + "event.json", + ); + form.set( + "image", + new Blob([Buffer.from(png, "base64")], { type: "image/png" }), + "scene.png", + ); + form.set( + "image2", + new Blob([Buffer.from(png, "base64")], { type: "image/png" }), + "plate.png", + ); + const payload = await readAxisRequest( + new Request("http://localhost/event", { method: "POST", body: form }), + ); + const event = normalizeAxisEvent(payload, input); + assert.equal(event.image, png); + assert.equal(event.sceneImage, png); + await assert.rejects( + () => + readAxisRequest( + new Request("http://localhost/event", { + method: "POST", + body: "x".repeat(100), + }), + 20, + ), + /too large/, + ); + await assert.rejects( + () => + readAxisRequest( + new Request("http://localhost/event", { + method: "POST", + headers: { "content-type": "text/plain" }, + body: "{}", + }), + ), + /JSON or multipart/, + ); +}); +test("only exact Axis receiver routes bypass browser authentication; administration remains protected", async () => { + const handler = createMiddlewareHandler({ + next: () => ({ status: 200 }), + json: (body, init) => ({ body, ...init }), + redirect: () => ({ status: 302 }), + fetchImpl: async () => { + throw new Error("Unexpected request"); + }, + }); + const request = (path) => ({ + nextUrl: { pathname: path }, + url: `http://localhost${path}`, + headers: new Headers(), + cookies: { get: () => null }, + }); + assert.equal( + (await handler(request(`/api/camera-inputs/axis/${input.id}`))).status, + 200, + ); + for (const path of [ + "/api/camera-inputs", + `/api/camera-inputs/${input.id}/events`, + `/api/camera-inputs/axis/${input.id}/extra`, + "/api/camera-inputs/axis/not-a-uuid", + ]) + assert.equal((await handler(request(path))).status, 401); +}); +test("incoming subscribers use a stable dedicated client ID, persistent sessions and verified TLS", () => { + const options = buildSubscriberOptions(input); + assert.equal(options.clientId, `alpr-axis-${input.id}`); + assert.equal(options.clean, false); + assert.equal(options.rejectUnauthorized, true); +}); + +test("a wildcard subscription silently filters other cameras and physical camera identity binds event identity", async () => { + const runtime = new CameraInputRuntime({ + pool: {}, + mqttConnect() {}, + ingest() {}, + storage: {}, + logger: {}, + }); + let imported = 0; + runtime.repository = { + get: async () => input, + receive: async () => { + imported++; + }, + }; + await runtime.handlePacket( + { ...input, topic_filter: "axis/#" }, + { + topic: "axis/other/event", + payload: Buffer.from( + JSON.stringify(mqttEvent({ MACAddress: "112233445566" })), + ), + }, + ); + assert.equal(imported, 0); + const first = normalizeAxisEvent(mqttEvent(), input); + const second = normalizeAxisEvent(mqttEvent({ MACAddress: "112233445566" }), { + ...input, + device_id: "112233445566", + }); + assert.notEqual(first.fingerprint, second.fingerprint); +}); +test("startup retries are isolated and concurrent initialization is shared", async () => { + const stateHost = {}; + const timers = []; + let calls = 0; + const options = { + stateHost, + logger: {}, + schedule: (callback) => { + timers.push(callback); + return {}; + }, + startRuntime: async () => { + calls++; + if (calls === 1) throw new Error("Database not ready"); + }, + }; + const [a, b] = await Promise.all([ + startCameraInputsWithRetry(options), + startCameraInputsWithRetry(options), + ]); + assert.equal(a.status, "retry-scheduled"); + assert.equal(b.status, "retry-scheduled"); + assert.equal(calls, 1); + await startCameraInputsWithRetry(options); + assert.equal(calls, 2); +}); +test("MQTT connection test uses an independent session and reports subscription rejection", async () => { + let options; + const connect = (_url, value) => { + options = value; + const client = new EventEmitter(); + client.end = () => {}; + client.subscribe = (_topic, _options, callback) => + callback(null, [{ qos: 128 }]); + queueMicrotask(() => client.emit("connect")); + return client; + }; + const result = await testMqttConnection( + { + ...input, + broker: "localhost", + port: 1883, + topic_filter: "axis/#", + qos: 1, + }, + connect, + ); + assert.equal(result.ok, false); + assert.equal(options.clean, true); + assert.notEqual(options.clientId, buildSubscriberOptions(input).clientId); +}); + +test("real MQTT QoS 1 acknowledges poison input and persists valid input before PUBACK", async () => { + const sockets = new Set(); + let socket; + const acked = new Set(); + let persist; + let received; + const receivedGate = new Promise((resolve) => { + received = resolve; + }); + const persistGate = new Promise((resolve) => { + persist = resolve; + }); + let testServer; + const subscribed = new Promise((resolve) => { + const server = net.createServer((connection) => { + socket = connection; + sockets.add(connection); + const parser = mqttPacket.parser(); + connection.on("data", (chunk) => parser.parse(chunk)); + parser.on("packet", (packet) => { + if (packet.cmd === "connect") + connection.write( + mqttPacket.generate({ + cmd: "connack", + returnCode: 0, + sessionPresent: false, + }), + ); + if (packet.cmd === "subscribe") { + connection.write( + mqttPacket.generate({ + cmd: "suback", + messageId: packet.messageId, + granted: [1], + }), + ); + resolve(); + } + if (packet.cmd === "puback") acked.add(packet.messageId); + }); + }); + server.listen(0, "127.0.0.1"); + testServer = server; + }); + // A real wire broker exercises MQTT.js's handleMessage/PUBACK ordering. + await once(testServer, "listening"); + const runtime = new CameraInputRuntime({ + pool: {}, + mqttConnect: mqtt.connect, + ingest: async () => {}, + storage: {}, + logger: {}, + }); + const configured = { + ...input, + broker: "127.0.0.1", + port: testServer.address().port, + broker_enabled: true, + topic_filter: "axis/test/event", + qos: 1, + }; + runtime.repository = { + mqttInputs: async () => [configured], + get: async () => configured, + status: async () => {}, + receive: async (_input, event) => { + normalizeAxisEvent(event, configured); + received(); + await persistGate; + return {}; + }, + }; + try { + await runtime.sync(); + await subscribed; + for (const [index, event] of [null, mqttEvent({ lpImage: {} })].entries()) { + const messageId = index + 1; + socket.write(mqttPacket.generate({cmd: "publish", topic: configured.topic_filter, + payload: Buffer.from(JSON.stringify(event)), qos: 1, messageId, retain: false, dup: false})); + const until = Date.now() + 2000; + while (!acked.has(messageId) && Date.now() < until) + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.ok(acked.has(messageId), "Permanent malformed input must not block the subscription"); + } + socket.write( + mqttPacket.generate({ + cmd: "publish", + topic: configured.topic_filter, + payload: Buffer.from(JSON.stringify(mqttEvent())), + qos: 1, + messageId: 7, + retain: false, + dup: false, + }), + ); + await receivedGate; + assert.equal(acked.has(7), false); + persist(); + const until = Date.now() + 2000; + while (!acked.has(7) && Date.now() < until) + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(acked.has(7), true); + } finally { + persist(); + await runtime.stop(); + for (const connection of sockets) connection.destroy(); + await new Promise((resolve) => testServer.close(resolve)); + } +}); + +test("a database failure withholds MQTT acknowledgment and redelivery succeeds after reconnect", async () => { + const sockets = new Set(); + const identities = []; + let attempts = 0; + let persisted = 0; + let connections = 0; + let acknowledge; + const acknowledged = new Promise((resolve) => { + acknowledge = resolve; + }); + const server = net.createServer((connection) => { + sockets.add(connection); + const number = ++connections; + const parser = mqttPacket.parser(); + connection.on("data", (chunk) => parser.parse(chunk)); + parser.on("packet", (packet) => { + if (packet.cmd === "connect") { + identities.push({ id: packet.clientId, clean: packet.clean }); + connection.write( + mqttPacket.generate({ + cmd: "connack", + returnCode: 0, + sessionPresent: number > 1, + }), + ); + } + if (packet.cmd === "subscribe") { + connection.write( + mqttPacket.generate({ + cmd: "suback", + messageId: packet.messageId, + granted: [1], + }), + ); + connection.write( + mqttPacket.generate({ + cmd: "publish", + topic: "axis/test/event", + payload: Buffer.from(JSON.stringify(mqttEvent())), + qos: 1, + messageId: 15, + retain: false, + dup: number > 1, + }), + ); + } + if (packet.cmd === "puback") acknowledge(number); + }); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const runtime = new CameraInputRuntime({ + pool: {}, + mqttConnect: (url, options) => + mqtt.connect(url, { ...options, reconnectPeriod: 20 }), + ingest: async () => {}, + storage: {}, + logger: {}, + }); + const configured = { + ...input, + broker: "127.0.0.1", + port: server.address().port, + broker_enabled: true, + topic_filter: "axis/test/event", + qos: 1, + }; + runtime.repository = { + mqttInputs: async () => [configured], + get: async () => configured, + status: async () => {}, + receive: async () => { + attempts++; + if (attempts === 1) + throw Object.assign(new Error("Temporary test database failure"), { + code: "ECONNREFUSED", + }); + persisted++; + return {}; + }, + }; + let timeout; + try { + await runtime.sync(); + const connectionNumber = await Promise.race([ + acknowledged, + new Promise((_, reject) => { + timeout = setTimeout( + () => reject(new Error("Reconnect timed out")), + 4000, + ); + }), + ]); + assert.equal(connectionNumber, 2); + assert.equal(attempts, 2); + assert.equal(persisted, 1); + assert.equal(identities[0].id, identities[1].id); + assert.equal(identities[0].clean, false); + assert.equal(identities[1].clean, false); + } finally { + clearTimeout(timeout); + await runtime.stop(); + for (const socket of sockets) socket.destroy(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/test/help-manual.test.mjs b/test/help-manual.test.mjs index 94ea70d..58ccaf6 100644 --- a/test/help-manual.test.mjs +++ b/test/help-manual.test.mjs @@ -18,7 +18,7 @@ async function source(path) { } test("the user guide is structured, searchable, and role-aware", () => { - assert.equal(HELP_MANUAL.manualVersion, "3.26"); + assert.equal(HELP_MANUAL.manualVersion, "3.27"); assert.ok(HELP_MANUAL.sections.length >= 24); const ids = HELP_MANUAL.sections.map((section) => section.id); diff --git a/test/live-feed-events.test.mjs b/test/live-feed-events.test.mjs index ae93e83..de0ae57 100644 --- a/test/live-feed-events.test.mjs +++ b/test/live-feed-events.test.mjs @@ -35,7 +35,7 @@ test("Live Feed surfaces use a route-handler stream and ingestion publishes afte const fs = await import("node:fs/promises"); const [route, ingestion, wrapper, viewer, delta] = await Promise.all([ fs.readFile("app/api/sse/route.js", "utf8"), - fs.readFile("app/api/plate-reads/route.js", "utf8"), + fs.readFile("lib/plate-read-ingestion.js", "utf8"), fs.readFile("components/PlateTableWrapper.jsx", "utf8"), fs.readFile("components/LiveRecognitionViewer.jsx", "utf8"), fs.readFile("app/api/live-feed/changes/route.js", "utf8"), diff --git a/test/maintenance-worker.test.mjs b/test/maintenance-worker.test.mjs index 12d133f..09dbeeb 100644 --- a/test/maintenance-worker.test.mjs +++ b/test/maintenance-worker.test.mjs @@ -148,7 +148,7 @@ test("database advisory locking makes the durable preview single-flight", async test("ingestion no longer invokes cleanup and maintenance schema is dry-run constrained", async () => { const [route, database, fileStorage, obsoleteCleanup, migrations] = await Promise.all([ - readFile(new URL("../app/api/plate-reads/route.js", import.meta.url), "utf8"), + readFile(new URL("../lib/plate-read-ingestion.js", import.meta.url), "utf8"), readFile(new URL("../lib/db.js", import.meta.url), "utf8"), readFile(new URL("../lib/fileStorage.js", import.meta.url), "utf8"), readFile(new URL("../lib/cleanupService.js", import.meta.url), "utf8").catch(() => null), diff --git a/test/mqtt-startup.test.mjs b/test/mqtt-startup.test.mjs index a9bd38d..0d08a26 100644 --- a/test/mqtt-startup.test.mjs +++ b/test/mqtt-startup.test.mjs @@ -184,6 +184,7 @@ test("Node instrumentation starts MQTT and canonical image workers together", as let vehicleAssetAttributeCalls = 0; let vehicleReidLiveCalls = 0; const result = await registerNodeInstrumentation({ + loadCameraInputStartup: async () => ({ startCameraInputsWithRetry: async () => ({ status: "started" }) }), logger, async startMqtt(options) { mqttCalls += 1; @@ -310,6 +311,7 @@ test("a canonical embedding instrumentation import failure cannot prevent MQTT s const { logger, entries } = makeLogger(); let mqttCalls = 0; const result = await registerNodeInstrumentation({ + loadCameraInputStartup: async () => ({ startCameraInputsWithRetry: async () => ({ status: "started" }) }), logger, async startMqtt() { mqttCalls += 1; diff --git a/test/mqtt-v1-retirement.test.mjs b/test/mqtt-v1-retirement.test.mjs index 7b07280..0aaed72 100644 --- a/test/mqtt-v1-retirement.test.mjs +++ b/test/mqtt-v1-retirement.test.mjs @@ -10,7 +10,7 @@ test("obsolete MQTT v1 application code is no longer executable", async () => { const [actions, notificationsPage, plateRoute] = await Promise.all([ readSource("app/actions.js"), readSource("app/notifications/page.jsx"), - readSource("app/api/plate-reads/route.js"), + readSource("lib/plate-read-ingestion.js"), ]); const forbiddenActionTokens = [ diff --git a/test/notification-cutover.test.mjs b/test/notification-cutover.test.mjs index a45a841..d0a36bc 100644 --- a/test/notification-cutover.test.mjs +++ b/test/notification-cutover.test.mjs @@ -338,7 +338,7 @@ test("retired cutover UI code preserves safeguards without cluttering Notificati readFile(new URL("../components/NotificationCutoverPanel.jsx", import.meta.url), "utf8"), readFile(new URL("../app/notifications/page.jsx", import.meta.url), "utf8"), readFile(new URL("../migrations.sql", import.meta.url), "utf8"), - readFile(new URL("../app/api/plate-reads/route.js", import.meta.url), "utf8"), + readFile(new URL("../lib/plate-read-ingestion.js", import.meta.url), "utf8"), ]); assert.match(actions, /cutoverUnifiedNotificationRule[\s\S]*?requirePermission\("notification\.manage"\)/); assert.match(actions, /cutover_one_rule/); diff --git a/test/plate-review.test.mjs b/test/plate-review.test.mjs index c254852..2db9801 100644 --- a/test/plate-review.test.mjs +++ b/test/plate-review.test.mjs @@ -254,7 +254,7 @@ test("migration enforces immutable observations, append-only reviews, and disabl }); test("ingestion resolves aliases before known-plate behavior and durable notification handoff", async () => { - const route = await readFile(new URL("../app/api/plate-reads/route.js", import.meta.url), "utf8"); + const route = await readFile(new URL("../lib/plate-read-ingestion.js", import.meta.url), "utf8"); const resolveIndex = route.indexOf("resolvePlateAliasWithClient"); const ignoredIndex = route.indexOf("isPlateIgnored(effectivePlate)"); const recordIndex = route.indexOf("recordAliasApplicationWithClient"); diff --git a/test/release-info.test.mjs b/test/release-info.test.mjs index e69ca45..d9ec122 100644 --- a/test/release-info.test.mjs +++ b/test/release-info.test.mjs @@ -23,18 +23,18 @@ test("release information resolves a commit-pinned deployment image", () => { ALPR_RELEASE_CHANNEL: "staging", }); - assert.equal(release.version, "0.1.58"); - assert.equal(release.manualVersion, "3.26"); - assert.equal(release.manualUpdatedAt, "October 21, 2026"); + assert.equal(release.version, "0.1.59"); + assert.equal(release.manualVersion, "3.27"); + assert.equal(release.manualUpdatedAt, "November 1, 2026"); assert.equal(release.gitSha, "8cd2fa8"); assert.equal(release.channel, "staging"); assert.equal(release.source, "commit-pinned image"); assert.equal(release.readOnly, true); assert.equal( release.notes.title, - "Resizable columns and compact actions" + "Axis HTTP and MQTT camera inputs" ); - assert.equal(release.notes.publishedAt, "2026-10-21"); + assert.equal(release.notes.publishedAt, "2026-11-01"); assert.ok(release.notes.items.length >= 3); const notes = release.notes.items.join(" "); assert.match(notes, /draggable header dividers/); diff --git a/test/security-regressions.test.mjs b/test/security-regressions.test.mjs index 88cb99f..92e50fd 100644 --- a/test/security-regressions.test.mjs +++ b/test/security-regressions.test.mjs @@ -22,7 +22,7 @@ test("plate-read route delegates to the authentication-first wrapper", async () }); test("committed plate reads publish a lightweight feed event instead of revalidating the page", async () => { - const source = await fs.readFile("app/api/plate-reads/route.js", "utf8"); + const source = await fs.readFile("lib/plate-read-ingestion.js", "utf8"); assert.equal(source.includes('from "@/app/actions"'), false); assert.equal(source.includes('from "next/cache"'), false); diff --git a/test/windows-setup.test.mjs b/test/windows-setup.test.mjs index 7b1ee55..f177605 100644 --- a/test/windows-setup.test.mjs +++ b/test/windows-setup.test.mjs @@ -160,7 +160,7 @@ test("setup cleanup refuses a directory outside its recorded private workspace", await writeFile(path.join(fixture,"keep","important.txt"),"retained"); const result=ps("& ./scripts/windows/Setup.ps1 -Operation cleanup -WorkRoot (Join-Path $env:ALPR_TEST_ROOT 'keep')",{ALPR_TEST_ROOT:fixture}); assert.notEqual(result.status,0); - assert.match(result.stderr,/Unexpected private Setup workspace/); + assert.match(result.stderr,/Unexpected\s+private\s+Setup\s+workspace/); assert.equal(await readFile(path.join(fixture,"keep","important.txt"),"utf8"),"retained"); }); test("setup cleanup removes only its recorded attempt and preserves sibling data", {skip:!powershell}, async (t) => { diff --git a/yarn.lock b/yarn.lock index 90cf3a4..9662a24 100644 --- a/yarn.lock +++ b/yarn.lock @@ -151,11 +151,6 @@ "@babel/helper-string-parser" "^7.29.7" "@babel/helper-validator-identifier" "^7.29.7" -"@borewit/text-codec@^0.2.1": - version "0.2.2" - resolved "https://registry.yarnpkg.com/@borewit/text-codec/-/text-codec-0.2.2.tgz#75025f735c0983b3a871668804a57387e3649375" - integrity sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ== - "@colors/colors@1.6.0", "@colors/colors@^1.6.0": version "1.6.0" resolved "https://registry.yarnpkg.com/@colors/colors/-/colors-1.6.0.tgz#ec6cd237440700bc23ca23087f513c75508958b0" @@ -267,11 +262,6 @@ resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.2.8.tgz#21a907684723bbbaa5f0974cf7730bd797eb8e62" integrity sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig== -"@hookform/resolvers@^3.9.1": - version "3.9.1" - resolved "https://registry.yarnpkg.com/@hookform/resolvers/-/resolvers-3.9.1.tgz#a23883c40bfd449cb6c6ab5a0fa0729184c950ff" - integrity sha512-ud2HqmGBM0P0IABqoskKWI6PEf6ZDDBZkFqe2Vnl+mTHCEHzr3ISjjZyCwTjC/qpL25JC9aIDkloQejvMeq0ug== - "@humanfs/core@^0.19.2": version "0.19.2" resolved "https://registry.yarnpkg.com/@humanfs/core/-/core-0.19.2.tgz#a8272ca03b2acf492670222b2320b6c421bfde60" @@ -464,278 +454,10 @@ resolved "https://registry.yarnpkg.com/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz#1785356b8cb396e58430e03865281280acb818b1" integrity sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg== -"@jimp/core@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/core/-/core-1.6.1.tgz#cbe40c4c73c28c9236d9ec0b6fae1fd21546af79" - integrity sha512-+BoKC5G6hkrSy501zcJ2EpfnllP+avPevcBfRcZe/CW+EwEfY6X1EZ8QWyT7NpDIvEEJb1fdJnMMfUnFkxmw9A== - dependencies: - "@jimp/file-ops" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - await-to-js "^3.0.0" - exif-parser "^0.1.12" - file-type "^21.3.3" - mime "3" - -"@jimp/diff@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/diff/-/diff-1.6.1.tgz#148383c40e8a7c836603532b0e3ee9fce3ebe4c0" - integrity sha512-YkKDPdHjLgo1Api3+Bhc0GLAygldlpt97NfOKoNg1U6IUNXA6X2MgosCjPfSBiSvJvrrz1fsIR+/4cfYXBI/HQ== - dependencies: - "@jimp/plugin-resize" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - pixelmatch "^5.3.0" - -"@jimp/file-ops@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/file-ops/-/file-ops-1.6.1.tgz#3b8158a64ae1defad21dc2303306a43a393bd742" - integrity sha512-T+gX6osHjprbDRad0/B71Evyre7ZdVY1z/gFGEG9Z8KOtZPKboWvPeP2UjbZYWQLy9UKCPQX1FNAnDiOPkJL7w== - -"@jimp/js-bmp@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/js-bmp/-/js-bmp-1.6.1.tgz#bc33204a54642fa447b696cd63e99156810534bb" - integrity sha512-xzWzNT4/u5zGrTT3Tme9sGU7YzIKxi13+BCQwLqACbt5DXf9SAfdzRkopZQnmDko+6In5nqaT89Gjs43/WdnYQ== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - bmp-ts "^1.0.9" - -"@jimp/js-gif@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/js-gif/-/js-gif-1.6.1.tgz#389d5551596cebbbb33006c8128a80b92329960f" - integrity sha512-YjY2W26rQa05XhanYhRZ7dingCiNN+T2Ymb1JiigIbABY0B28wHE3v3Cf1/HZPWGu0hOg36ylaKgV5KxF2M58w== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - gifwrap "^0.10.1" - omggif "^1.0.10" - -"@jimp/js-jpeg@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/js-jpeg/-/js-jpeg-1.6.1.tgz#5aeadcc4661ed884f79389ea8753c2979db3209e" - integrity sha512-HT9H3yOmlOFzYmdI15IYdfy6ggQhSRIaHeA+OTJSEORXBqEo97sUZu/DsgHIcX5NJ7TkJBTgZ9BZXsV6UbsyMg== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - jpeg-js "^0.4.4" - -"@jimp/js-png@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/js-png/-/js-png-1.6.1.tgz#e3e08629e2236bd17a7176ea5ae170bc30d35b97" - integrity sha512-SZ/KVhI5UjcSzzlXsXdIi/LhJ7UShf2NkMOtVrbZQcGzsqNtynAelrOXeoTxcanfVqmNhAoVHg8yR2cYoqrYjA== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - pngjs "^7.0.0" - -"@jimp/js-tiff@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/js-tiff/-/js-tiff-1.6.1.tgz#12a3f0e5cf132452ed63d42ff9474a08f6534d14" - integrity sha512-jDG/eJquID1M4MBlKMmDRBmz2TpXMv7TUyu2nIRUxhlUc2ogC82T+VQUkca9GJH1BBJ9dx5sSE5dGkWNjIbZxw== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - utif2 "^4.1.0" - -"@jimp/plugin-blit@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-blit/-/plugin-blit-1.6.1.tgz#343b3e84a3b02cf4817b17ff30f5e807ed2c23db" - integrity sha512-MwnI7C7K81uWddY9FLw1fCOIy6SsPIUftUz36Spt7jisCn8/40DhQMlSxpxTNelnZb/2SnloFimQfRZAmHLOqQ== - dependencies: - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-blur@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-blur/-/plugin-blur-1.6.1.tgz#393ceb793aac5fc9254219f72e35c44f69e6ddb7" - integrity sha512-lIo7Tzp5jQu30EFFSK/phXANK3citKVEjepDjQ6ljHoIFtuMRrnybnmI2Md24ulvWlDaz+hh3n6qrMb8ydwhZQ== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/utils" "1.6.1" - -"@jimp/plugin-circle@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-circle/-/plugin-circle-1.6.1.tgz#db465654fc8890cb6b4e6d49056368a65a92f032" - integrity sha512-kK1PavY6cKHNNKce37vdV4Tmpc1/zDKngGoeOV3j+EMatoHFZUinV3s6F9aWryPs3A0xhCLZgdJ6Zeea1d5LCQ== - dependencies: - "@jimp/types" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-color@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-color/-/plugin-color-1.6.1.tgz#c8e9a9a1135d103d4170fb4b5100966ff83e05b1" - integrity sha512-LtUN1vAP+LRlZAtTNVhDRSiXx+26Kbz3zJaG6a5k59gQ95jgT5mknnF8lxkHcqJthM4MEk3/tPxkdJpEybyF/A== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - tinycolor2 "^1.6.0" - zod "^3.23.8" - -"@jimp/plugin-contain@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-contain/-/plugin-contain-1.6.1.tgz#f18a5eddab277de4de637d3a4ce970be3f7273df" - integrity sha512-m0qhrfA8jkTqretGv4w+T/ADFR4GwBpE0sCOC2uJ0dzr44/ddOMsIdrpi89kabqYiPYIrxkgdCVCLm3zn1Vkkg== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/plugin-blit" "1.6.1" - "@jimp/plugin-resize" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-cover@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-cover/-/plugin-cover-1.6.1.tgz#c2719352ea38dde64588aa4cb3779484217aff4d" - integrity sha512-hZytnsth0zoll6cPf434BrT+p/v569Wr5tyO6Dp0dH1IDPhzhB5F38sZGMLDo7bzQiN9JFVB3fxkcJ/WYCJ3Mg== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/plugin-crop" "1.6.1" - "@jimp/plugin-resize" "1.6.1" - "@jimp/types" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-crop@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-crop/-/plugin-crop-1.6.1.tgz#b52d3e5a1582708e6b373365b7dadff2506fcca9" - integrity sha512-EerRSLlclXyKDnYc/H9w/1amZW7b7v3OGi/VlerPd2M/pAu5X8TkyYWtfqYCXnNp1Ixtd8oCo9zGfY9zoXT4rg== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-displace@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-displace/-/plugin-displace-1.6.1.tgz#23456d68ad37069ae352fa0c48b68caab473bd17" - integrity sha512-K07QVl7xQwIfD6KfxRV/c3E9e7ZBXxUXdWuvoTWcKHL2qV48MOF5Nqbz/aJW4ThnQARIsxvYlZjPFiqkCjlU+g== - dependencies: - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-dither@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-dither/-/plugin-dither-1.6.1.tgz#6b6879abf315ba6b16ef43c28a0d94caf609f602" - integrity sha512-+2V+GCV2WycMoX1/z977TkZ8Zq/4MVSKElHYatgUqtwXMi2fDK2gKYU2g9V39IqFvTJsTIsK0+58VFz/ROBVew== - dependencies: - "@jimp/types" "1.6.1" - -"@jimp/plugin-fisheye@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-fisheye/-/plugin-fisheye-1.6.1.tgz#5df971d864eb5960f6d1fef9cfcd52083afcdfc4" - integrity sha512-XtS5ZyoZ0vxZxJ6gkqI63SivhtI58vX95foMPM+cyzYkRsJXMOYCr8DScxF5bp4Xr003NjYm/P+7+08tibwzHA== - dependencies: - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-flip@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-flip/-/plugin-flip-1.6.1.tgz#4ac6ff22c24ec54e061576d963ebd0229f7a34d9" - integrity sha512-ws38W/sGj7LobNRayQ83garxiktOyWxM5vO/y4a/2cy9v65SLEUzVkrj+oeAaUSSObdz4HcCEla7XtGlnAGAaA== - dependencies: - "@jimp/types" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-hash@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-hash/-/plugin-hash-1.6.1.tgz#b3d4aa754249edc420d3309a79a289be6afa7c34" - integrity sha512-sZt6ZcMX6i8vFWb4GYnw0pR/o9++ef0dTVcboTB5B/g7nrxCODIB4wfEkJ/YqZM5wUvol77K1qeS0/rVO6z21A== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/js-bmp" "1.6.1" - "@jimp/js-jpeg" "1.6.1" - "@jimp/js-png" "1.6.1" - "@jimp/js-tiff" "1.6.1" - "@jimp/plugin-color" "1.6.1" - "@jimp/plugin-resize" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - any-base "^1.1.0" - -"@jimp/plugin-mask@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-mask/-/plugin-mask-1.6.1.tgz#9b11fd552e93bba414d73330d7cc4e7f86b0fe6a" - integrity sha512-SIG0/FcmEj3tkwFxc7fAGLO8o4uNzMpSOdQOhbCgxefQKq5wOVMk9BQx/sdMPBwtMLr9WLq0GzLA/rk6t2v20A== - dependencies: - "@jimp/types" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-print@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-print/-/plugin-print-1.6.1.tgz#8f52abe183cd2f81d5401c67a63521401264d237" - integrity sha512-BYVz/X3Xzv8XYilVeDy11NOp0h7BTDjlOtu0BekIFHP1yHVd24AXNzbOy52XlzYZWQ0Dl36HOHEpl/nSNrzc6w== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/js-jpeg" "1.6.1" - "@jimp/js-png" "1.6.1" - "@jimp/plugin-blit" "1.6.1" - "@jimp/types" "1.6.1" - parse-bmfont-ascii "^1.0.6" - parse-bmfont-binary "^1.0.6" - parse-bmfont-xml "^1.1.6" - simple-xml-to-json "^1.2.2" - zod "^3.23.8" - -"@jimp/plugin-quantize@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-quantize/-/plugin-quantize-1.6.1.tgz#0621da6873d3c3fa14124416a85b5ab19e8fee79" - integrity sha512-J2En9PLURfP+vwYDtuZ9T8yBW6BWYZBScydAjRiPBmJfEhTcNQqiiQODrZf7EqbbX/Sy5H6dAeRiqkgoV9N6Ww== - dependencies: - image-q "^4.0.0" - zod "^3.23.8" - -"@jimp/plugin-resize@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-resize/-/plugin-resize-1.6.1.tgz#577626580db2d71dea307da520ac0bf8155637d9" - integrity sha512-CLkrtJoIz2HdWnpYiN6p8KYcPc00rCH/SUu6o+lfZL05Q4uhecJlnvXuj9x+U6mDn3ldPmJj6aZqMHuUJzdVqg== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/types" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-rotate@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-rotate/-/plugin-rotate-1.6.1.tgz#897b647c32b3d3fb24c755d34c656ee579669017" - integrity sha512-nOjVjbbj705B02ksysKnh0POAwEBXZtJ9zQ5qC+X7Tavl3JNn+P3BzQovbBxLPSbUSld6XID9z5ijin4PtOAUg== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/plugin-crop" "1.6.1" - "@jimp/plugin-resize" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/plugin-threshold@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/plugin-threshold/-/plugin-threshold-1.6.1.tgz#c2353305f3ed592d32973e3c8883ca3d22150f01" - integrity sha512-JOKv9F8s6tnVLf4sB/2fF0F339EFnHvgEdFYugO6VhowKLsap0pEZmLyE/DlRnYtIj2RddHZVxVMp/eKJ04l2Q== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/plugin-color" "1.6.1" - "@jimp/plugin-hash" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - zod "^3.23.8" - -"@jimp/types@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/types/-/types-1.6.1.tgz#5cf40ee1225f84aad65149544018a9abc8ee4f15" - integrity sha512-leI7YbveTNi565m910XgIOwXyuu074H5qazAD1357HImJSv2hqxnWXpwxQbadGWZ7goZRYBDZy5lpqud0p7q5w== - dependencies: - zod "^3.23.8" - -"@jimp/utils@1.6.1": - version "1.6.1" - resolved "https://registry.yarnpkg.com/@jimp/utils/-/utils-1.6.1.tgz#ccda86eebc7c95095f578fc954c487ecb09f6975" - integrity sha512-veFPRd93FCnS7AgmCkPgARVGoDRrJ9cm1ujuNyA+UfQ5VKbED2002sm5XfFLFwTsKC8j04heTrwe+tU1dluXOw== - dependencies: - "@jimp/types" "1.6.1" - tinycolor2 "^1.6.0" +"@isaacs/nonrecursive-glob-match@^1.0.1": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.3.tgz#7f6724fd8a6ca315d6bb7f63f0e4d079060da246" + integrity sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA== "@jridgewell/gen-mapping@^0.3.12", "@jridgewell/gen-mapping@^0.3.5": version "0.3.13" @@ -803,10 +525,10 @@ dependencies: "@types/pg" "8.11.6" -"@next/env@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/env/-/env-15.5.27.tgz#4c4ec6e4a38c5d654bae847426959e84bfca7229" - integrity sha512-WC5hvVqiuFOcRyz6gKPeJkiVvSMf3scNeAV49CdWtVqxmUlzh8UKR6YHt9yiNkh8LngtzqSlVz07/Ma3ZAzchA== +"@next/env@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/env/-/env-15.5.28.tgz#baeca1a42e756f461b676ff7efdb0bc9d6f6de44" + integrity sha512-xxW5EBI8fMPuVTPBW7LL980IRbuDXlbkUAwp9DDhtb4Lnich3nJ13uYpvrX4VE74hWPf6AvHHAMmGCidcHjbfg== "@next/eslint-plugin-next@16.2.12": version "16.2.12" @@ -815,45 +537,45 @@ dependencies: fast-glob "3.3.1" -"@next/swc-darwin-arm64@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.27.tgz#b119e1e3e6c3b8ceca7a8613021442f94ac9c4cb" - integrity sha512-fBA9QurmK4+uj4wNhmRTuO5zMVRaBHCvp6H93zTG/5i6Yi6TewbvbesXB8YQNj8T99Cwrow87hHiFV6wL/hyMA== - -"@next/swc-darwin-x64@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.27.tgz#c40d0c9866a3395e9abee09ad352cdec28724e6c" - integrity sha512-FGZwJwry8qZNHxD/nfwrCwCHHrqx6epqItkkxbYcBQEQ2uw5S43bY83fQB5zbAsZE7TELMjoYkbhsQ4oKM7wwg== - -"@next/swc-linux-arm64-gnu@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.27.tgz#44ace267964a522f7df666bbde2a9e241374b722" - integrity sha512-GQulAaJYNF1RYuatlsw9/uzbKz4if2V7Ic9nVO+P0ljYPm4yBRTFIl6g5YkKTw40lMLbpy9edLoH44g3jSHMYA== - -"@next/swc-linux-arm64-musl@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.27.tgz#a2867ac0fe08f14d0f35780d0b05ade53c36cb43" - integrity sha512-URFFsUmu8Pi0/1qdnUI7tx7keZw1Mt5zHfrIX1RfDG9Nih8DYxK54WZsDJUX2ZTlii1jgotL7qcbwKnSAES6xQ== - -"@next/swc-linux-x64-gnu@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.27.tgz#a9a98bc6e9093f1983325202718981cc8b98b089" - integrity sha512-aJp74z7uvU5jQhyH7lyk+4qSRcTdKbKT9NQE3jiO9kWYkoHZjKi0zzHDbCoZ+v2sJDEiJ/z58R0UlWMGWNF3HA== - -"@next/swc-linux-x64-musl@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.27.tgz#8f5e14ed78c4e12845383ddabad3c1473ce001d3" - integrity sha512-ILl2bQ8MbpvyMpY8AXljb3BXs0MJSC8HXZ6QV5AWpVS7ZELqNPtrHvhUk+SNarvjvICXX8bCS287TCi+gUFVYg== - -"@next/swc-win32-arm64-msvc@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.27.tgz#1f0542804a2b03e0748c59543cdcc911de3cb08d" - integrity sha512-1MB9Rh5y8TOPN2x7naNTJNkCZQav9c70AI7EBYXxsEewwOffC4DjjwBwKf20NBvcA+u+5jDv7nVmHxunlP2d7Q== - -"@next/swc-win32-x64-msvc@15.5.27": - version "15.5.27" - resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.27.tgz#d3f0e0fe2f0edd0611f1d68f78bb1e366a6546be" - integrity sha512-XtYgpGOswgnyBWXzOEG6q9RhvnSw0CEZ0MbWqCsl5PISgt9EzvJvNW5mU5n1PsphX/lnamzxjgQXH2GUJL8nqg== +"@next/swc-darwin-arm64@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.28.tgz#e1305f3c10199e950bb95b07cc426f29298d050d" + integrity sha512-dPoQYXcfSIqx5o+TOXVXO7kONK5qbtNRDeiTfII0bT3puGIT6VF5e0QwmxNZfEZ5Zety5f3m9P/p4xqwfiLlPg== + +"@next/swc-darwin-x64@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.28.tgz#f27a036f96c6b92d628779e2f563c112e3c17a75" + integrity sha512-RgCJ7buBivTH+6sddqaVm+/v8kwMHlFkobvdt3DfETutws5HrxnToMIWSN9X3MZ3aAi7BbKrGZZWUDQLEycXqw== + +"@next/swc-linux-arm64-gnu@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.28.tgz#268ab89d9413551796be6ae46138157b684dd9f4" + integrity sha512-OHXQe13olE59aKe++zHavGcJPh5SLHXi6Anret3BBeq1+qhSuOJDNAli/EDDfxs6UTqA4Qddo4uyYry2slyjiQ== + +"@next/swc-linux-arm64-musl@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.28.tgz#f12446fd30140e3b3fbe2fec16af34b6be98c62d" + integrity sha512-nTB7bB6vfn4ezCJNYP43ukt2o8L3+WxKF/sTcTxepdXsJh3SM9RhlU7wrZYbH7L4HO5M87dqDTwm8587vAkCiw== + +"@next/swc-linux-x64-gnu@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.28.tgz#d444703621a68461d0a74515951be9b05a209ce5" + integrity sha512-WXCfVI32rW3xCusoUX1RpZKtyChWU2Zwe27JUDmM3KrXwcDNc9vV4zEq0GKFAURnuQ/Ouo/XqPvB0yh445XZCg== + +"@next/swc-linux-x64-musl@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.28.tgz#058ea33f8156cdb0dda1cd114ef879a4d933c29f" + integrity sha512-Miq+NDb/HWsXuxseYxMM6fuEOQXgTziarkKIRpVKCn8W69cEfhQaQr+90pO+u4q2CbJR2wzXmUuCFyZaJs/Nng== + +"@next/swc-win32-arm64-msvc@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.28.tgz#aa695e94922faf09ac6cbd480d2dc870bf807d4a" + integrity sha512-5LR79lemgDlgxvG7MQJ+zHCkVcrUoQuO7CiIvq3I58vNW4goSOE2b+19Z6FujRWMouvni4gvudYFuFuNxolGWA== + +"@next/swc-win32-x64-msvc@15.5.28": + version "15.5.28" + resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.28.tgz#6f56363b38ad8cb76ab9421125a5f3afc2b92d65" + integrity sha512-GNipvXUYROSTf4PXEyH95FrWImIB5zdaK6uEOg0RP1/X2drnvoMwiBkJ0VWdzX7w3iiBm3y5g2TxkKDGVTOQcg== "@radix-ui/number@1.1.0": version "1.1.0" @@ -1640,20 +1362,6 @@ resolved "https://registry.yarnpkg.com/@radix-ui/rect/-/rect-1.1.0.tgz#f817d1d3265ac5415dadc67edab30ae196696438" integrity sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg== -"@shadcn/ui@^0.0.4": - version "0.0.4" - resolved "https://registry.yarnpkg.com/@shadcn/ui/-/ui-0.0.4.tgz#a0835202fa79073245bc2cb5f837bc514d96b4cb" - integrity sha512-0dtu/5ApsOZ24qgaZwtif8jVwqol7a4m1x5AxPuM1k5wxhqU7t/qEfBGtaSki1R8VlbTQfCj5PAlO45NKCa7Gg== - dependencies: - chalk "5.2.0" - commander "^10.0.0" - execa "^7.0.0" - fs-extra "^11.1.0" - node-fetch "^3.3.0" - ora "^6.1.2" - prompts "^2.4.2" - zod "^3.20.2" - "@swc/helpers@0.5.15": version "0.5.15" resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.5.15.tgz#79efab344c5819ecf83a43f3f9f811fc84b516d7" @@ -1775,19 +1483,6 @@ resolved "https://registry.yarnpkg.com/@techstark/opencv-js/-/opencv-js-4.10.0-release.1.tgz#5344c715c404c22419ac893c6a2d86727e2416fc" integrity sha512-S4XELidRiQeA0q1s9VQLo540wCxUo24r1O4C+LqZ6llX+sPCXvZCPv3Ice8dEIr0uavyZ8YZeKXSBdDgMXSXjw== -"@tokenizer/inflate@^0.4.1": - version "0.4.1" - resolved "https://registry.yarnpkg.com/@tokenizer/inflate/-/inflate-0.4.1.tgz#fa6cdb8366151b3cc8426bf9755c1ea03a2fba08" - integrity sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA== - dependencies: - debug "^4.4.3" - token-types "^6.1.1" - -"@tokenizer/token@^0.3.0": - version "0.3.0" - resolved "https://registry.yarnpkg.com/@tokenizer/token/-/token-0.3.0.tgz#fe98a93fe789247e998c75e74e9c7c63217aa276" - integrity sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A== - "@tybys/wasm-util@^0.10.2", "@tybys/wasm-util@^0.10.3": version "0.10.4" resolved "https://registry.yarnpkg.com/@tybys/wasm-util/-/wasm-util-0.10.4.tgz#3e85ecb266f9d1722250e89bc69528615720b154" @@ -1913,11 +1608,6 @@ dependencies: undici-types "~6.19.8" -"@types/node@16.9.1": - version "16.9.1" - resolved "https://registry.yarnpkg.com/@types/node/-/node-16.9.1.tgz#0611b37db4246c937feef529ddcc018cf8e35708" - integrity sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g== - "@types/pg@8.11.6": version "8.11.6" resolved "https://registry.yarnpkg.com/@types/pg/-/pg-8.11.6.tgz#a2d0fb0a14b53951a17df5197401569fb9c0c54b" @@ -2090,16 +1780,6 @@ ajv@^6.14.0: json-schema-traverse "^0.4.1" uri-js "^4.2.2" -ansi-regex@^6.0.1: - version "6.1.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.1.0.tgz#95ec409c69619d6cb1b8b34f14b660ef28ebd654" - integrity sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA== - -any-base@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/any-base/-/any-base-1.1.0.tgz#ae101a62bc08a597b4c9ab5b7089d456630549fe" - integrity sha512-uMgjozySS8adZZYePpaWs8cxB9/kdzmpX6SgJZ+wbz1K5eYk5QMYDVJaZKhxyIHUdnnJkfR7SVgStgH7LkGUyg== - argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" @@ -2124,11 +1804,6 @@ async@^3.2.3: resolved "https://registry.yarnpkg.com/async/-/async-3.2.6.tgz#1b0728e14929d51b85b449b7f06e27c1145e38ce" integrity sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA== -await-to-js@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/await-to-js/-/await-to-js-3.0.0.tgz#70929994185616f4675a91af6167eb61cc92868f" - integrity sha512-zJAaP9zxTcvTHRlejau3ZOY4V7SRpiByf3/dxx2uyKxxor19tpmpV2QRsTKikckwhaPmr2dVpxxMr7jOCYVp5g== - b4a@^1.6.4, b4a@^1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/b4a/-/b4a-1.8.1.tgz#7f16334ca80127aeb26064a28841acbf174840a4" @@ -2199,15 +1874,6 @@ bcrypt@^6.0.0: node-addon-api "^8.3.0" node-gyp-build "^4.8.4" -bl@^5.0.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/bl/-/bl-5.1.0.tgz#183715f678c7188ecef9fe475d90209400624273" - integrity sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ== - dependencies: - buffer "^6.0.3" - inherits "^2.0.4" - readable-stream "^3.4.0" - bl@^6.0.8: version "6.0.16" resolved "https://registry.yarnpkg.com/bl/-/bl-6.0.16.tgz#29b190f1a754e2d168de3dc8c74ed8d12bf78e6e" @@ -2218,12 +1884,7 @@ bl@^6.0.8: inherits "^2.0.4" readable-stream "^4.2.0" -bmp-ts@^1.0.9: - version "1.0.9" - resolved "https://registry.yarnpkg.com/bmp-ts/-/bmp-ts-1.0.9.tgz#0fd124ba812be9b786b29e5b186ee76d74ff5538" - integrity sha512-cTEHk2jLrPyi+12M3dhpEbnnPOsaZuq7C45ylbbQIiWgDFZq4UVYPEY5mlqjvsj/6gJv9qX5sa+ebDzLXT28Vw== - -brace-expansion@5.0.12, brace-expansion@^5.0.8: +brace-expansion@5.0.12, brace-expansion@^5.0.12: version "5.0.12" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-5.0.12.tgz#995fbb4750a77c4d16a7dc942ff2ca6ef8e675ec" integrity sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ== @@ -2293,16 +1954,6 @@ ccount@^2.0.0: resolved "https://registry.yarnpkg.com/ccount/-/ccount-2.0.1.tgz#17a3bf82302e0870d6da43a01311a8bc02a3ecf5" integrity sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg== -chalk@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-5.2.0.tgz#249623b7d66869c673699fb66d65723e54dfcfb3" - integrity sha512-ree3Gqw/nazQAPuJJEy+avdl7QfZMcUvmHIKgEZkGL+xOBzRvup5Hxo6LHuMceSxOabuJLJm5Yp/92R9eMmMvA== - -chalk@^5.0.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-5.3.0.tgz#67c20a7ebef70e7f3970a01f90fa210cb6860385" - integrity sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w== - character-entities-html4@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/character-entities-html4/-/character-entities-html4-2.1.0.tgz#1f1adb940c971a4b22ba39ddca6b618dc6e56b2b" @@ -2330,28 +1981,11 @@ class-variance-authority@^0.7.0: dependencies: clsx "2.0.0" -cli-cursor@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-4.0.0.tgz#3cecfe3734bf4fe02a8361cbdc0f6fe28c6a57ea" - integrity sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg== - dependencies: - restore-cursor "^4.0.0" - -cli-spinners@^2.6.1: - version "2.9.2" - resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.9.2.tgz#1773a8f4b9c4d6ac31563df53b3fc1d79462fe41" - integrity sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg== - client-only@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/client-only/-/client-only-0.0.1.tgz#38bba5d403c41ab150bff64a95c85013cf73bca1" integrity sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA== -clone@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" - integrity sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg== - clsx@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.0.0.tgz#12658f3fd98fafe62075595a5c30e43d18f3d00b" @@ -2418,11 +2052,6 @@ comma-separated-tokens@^2.0.0: resolved "https://registry.yarnpkg.com/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz#4e89c9458acb61bc8fef19f4529973b2392839ee" integrity sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg== -commander@^10.0.0: - version "10.0.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-10.0.1.tgz#881ee46b4f77d1c1dccc5823433aa39b022cbe06" - integrity sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug== - commist@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/commist/-/commist-3.2.0.tgz#da9c8e5f245ac21510badc4b10c46b5bcc9b56cd" @@ -2453,15 +2082,6 @@ core-util-is@~1.0.0: resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85" integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ== -cross-spawn@^7.0.3: - version "7.0.5" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.5.tgz#910aac880ff5243da96b728bc6521a5f6c2f2f82" - integrity sha512-ZVJrKKYunU38/76t0RMOulHOnUcbU9GbpWKAOZ0mhjr7CX6FVrH+4FrAapSOekrgFQ3f/8gwMEuIft0aKq6Hug== - dependencies: - path-key "^3.1.0" - shebang-command "^2.0.0" - which "^2.0.1" - cross-spawn@^7.0.6: version "7.0.6" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" @@ -2552,11 +2172,6 @@ d3-timer@^3.0.1: resolved "https://registry.yarnpkg.com/d3-timer/-/d3-timer-3.0.1.tgz#6284d2a2708285b1abb7e201eda4380af35e63b0" integrity sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA== -data-uri-to-buffer@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz#d8feb2b2881e6a4f58c2e08acfd0e2834e26222e" - integrity sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A== - date-fns@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-4.1.0.tgz#64b3d83fff5aa80438f5b1a633c2e83b8a1c2d14" @@ -2600,13 +2215,6 @@ deep-is@^0.1.3: resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831" integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== -defaults@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.4.tgz#b0b02062c1e2aa62ff5d9528f0f98baa90978d7a" - integrity sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A== - dependencies: - clone "^1.0.2" - dequal@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" @@ -2837,26 +2445,6 @@ events@^3.3.0: resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== -execa@^7.0.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/execa/-/execa-7.2.0.tgz#657e75ba984f42a70f38928cedc87d6f2d4fe4e9" - integrity sha512-UduyVP7TLB5IcAQl+OzLyLcS/l32W/GLg+AhHJ+ow40FOk2U3SAllPwR44v4vmdFwIWqpdwxxpQbF1n5ta9seA== - dependencies: - cross-spawn "^7.0.3" - get-stream "^6.0.1" - human-signals "^4.3.0" - is-stream "^3.0.0" - merge-stream "^2.0.0" - npm-run-path "^5.1.0" - onetime "^6.0.0" - signal-exit "^3.0.7" - strip-final-newline "^3.0.0" - -exif-parser@^0.1.12: - version "0.1.12" - resolved "https://registry.yarnpkg.com/exif-parser/-/exif-parser-0.1.12.tgz#58a9d2d72c02c1f6f02a0ef4a9166272b7760922" - integrity sha512-c2bQfLNbMzLPmzQuOr8fy0csy84WmwnER81W88DzTp9CYNPJ6yzOj2EZAh9pywYpqHnshVLHQJ8WzldAyfY+Iw== - extend@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" @@ -2921,14 +2509,6 @@ fecha@^4.2.0: resolved "https://registry.yarnpkg.com/fecha/-/fecha-4.2.3.tgz#4d9ccdbc61e8629b259fdca67e65891448d569fd" integrity sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw== -fetch-blob@^3.1.2, fetch-blob@^3.1.4: - version "3.2.0" - resolved "https://registry.yarnpkg.com/fetch-blob/-/fetch-blob-3.2.0.tgz#f09b8d4bbd45adc6f0c20b7e787e793e309dcce9" - integrity sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ== - dependencies: - node-domexception "^1.0.0" - web-streams-polyfill "^3.0.3" - file-entry-cache@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-8.0.0.tgz#7787bddcf1131bffb92636c69457bbc0edd6d81f" @@ -2936,16 +2516,6 @@ file-entry-cache@^8.0.0: dependencies: flat-cache "^4.0.0" -file-type@^21.3.3: - version "21.3.4" - resolved "https://registry.yarnpkg.com/file-type/-/file-type-21.3.4.tgz#e3f902faee8ec4aa152909fc902a7a77f9c06725" - integrity sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g== - dependencies: - "@tokenizer/inflate" "^0.4.1" - strtok3 "^10.3.4" - token-types "^6.1.1" - uint8array-extras "^1.4.0" - find-up@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc" @@ -2972,22 +2542,6 @@ fn.name@1.x.x: resolved "https://registry.yarnpkg.com/fn.name/-/fn.name-1.1.0.tgz#26cad8017967aea8731bc42961d04a3d5988accc" integrity sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw== -formdata-polyfill@^4.0.10: - version "4.0.10" - resolved "https://registry.yarnpkg.com/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz#24807c31c9d402e002ab3d8c720144ceb8848423" - integrity sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g== - dependencies: - fetch-blob "^3.1.2" - -fs-extra@^11.1.0: - version "11.2.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-11.2.0.tgz#e70e17dfad64232287d01929399e0ea7c86b0e5b" - integrity sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw== - dependencies: - graceful-fs "^4.2.0" - jsonfile "^6.0.1" - universalify "^2.0.0" - gensync@^1.0.0-beta.2: version "1.0.0-beta.2" resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" @@ -2998,19 +2552,6 @@ get-nonce@^1.0.0: resolved "https://registry.yarnpkg.com/get-nonce/-/get-nonce-1.0.1.tgz#fdf3f0278073820d2ce9426c18f07481b1e0cdf3" integrity sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q== -get-stream@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" - integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== - -gifwrap@^0.10.1: - version "0.10.1" - resolved "https://registry.yarnpkg.com/gifwrap/-/gifwrap-0.10.1.tgz#9ed46a5d51913b482d4221ce9c727080260b681e" - integrity sha512-2760b1vpJHNmLzZ/ubTtNnEx5WApN/PYWJvXvgS+tL1egTTthayFYIQQNi136FLEDcN/IyEY2EcGpIITD6eYUw== - dependencies: - image-q "^4.0.0" - omggif "^1.0.10" - glob-parent@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" @@ -3023,7 +2564,7 @@ globals@17.8.0: resolved "https://registry.yarnpkg.com/globals/-/globals-17.8.0.tgz#a1f213a06adcd0eec38004c5cd39fef7af7e0830" integrity sha512-Zz/LMDZScFmkakeL2cTHzf+PbWKdpU3uclqkZT7TjDG58j5WPt0PpA+n9uPI24fZtlw07q0OtEi84K+umsRzqQ== -graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.4: +graceful-fs@^4.2.4: version "4.2.11" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== @@ -3189,11 +2730,6 @@ https-proxy-agent@^7.0.2: agent-base "^7.1.2" debug "4" -human-signals@^4.3.0: - version "4.3.1" - resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-4.3.1.tgz#ab7f811e851fca97ffbd2c1fe9a958964de321b2" - integrity sha512-nZXjEF2nbo7lIw3mgYjItAfgQXog3OjJogSbKa2CQIIvSGWcKgeJnQlNXip6NglNzYH45nSRiEVimMvYL8DDqQ== - ieee754@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" @@ -3204,13 +2740,6 @@ ignore@^5.2.0: resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.2.tgz#3cd40e729f3643fd87cb04e50bf0eb722bc596f5" integrity sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g== -image-q@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/image-q/-/image-q-4.0.0.tgz#31e075be7bae3c1f42a85c469b4732c358981776" - integrity sha512-PfJGVgIfKQJuq3s0tTDOKtztksibuUEbJQIYT3by6wctQo+Rdlh7ef4evJ5NCdxY4CfMbvFkocEwbl4BF8RlJw== - dependencies: - "@types/node" "16.9.1" - imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" @@ -3243,10 +2772,10 @@ invariant@^2.2.4: dependencies: loose-envify "^1.0.0" -ip-address@10.7.1, ip-address@^10.1.1: - version "10.7.1" - resolved "https://registry.yarnpkg.com/ip-address/-/ip-address-10.7.1.tgz#df8031c20df6b7f1dcc9f68c4f4fa5ee71c45d39" - integrity sha512-4OUAqU9Z1i3vCnS05hzGiFnEMDpQ+62pAD/MVQOp83fYyNC8GleCqaS0QikQBmcWCrKFiUs/B8ztRRiYOAXuCA== +ip-address@10.7.4, ip-address@^10.1.1: + version "10.7.4" + resolved "https://registry.yarnpkg.com/ip-address/-/ip-address-10.7.4.tgz#a5e493fabce725c5d4b8b8f4d2ebb9009fbcf2e8" + integrity sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg== iron-session@^8.0.4: version "8.0.4" @@ -3312,11 +2841,6 @@ is-hexadecimal@^2.0.0: resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz#86b5bf668fca307498d319dfc03289d781a90027" integrity sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg== -is-interactive@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-2.0.0.tgz#40c57614593826da1100ade6059778d597f16e90" - integrity sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ== - is-plain-obj@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-4.1.0.tgz#d65025edec3657ce032fd7db63c97883eaed71f0" @@ -3327,16 +2851,6 @@ is-stream@^2.0.0: resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" integrity sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg== -is-stream@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-3.0.0.tgz#e6bfd7aa6bef69f4f472ce9bb681e3e57b4319ac" - integrity sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA== - -is-unicode-supported@^1.1.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz#d824984b616c292a2e198207d4a609983842f714" - integrity sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ== - isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" @@ -3347,39 +2861,6 @@ isexe@^2.0.0: resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== -jimp@1.6.1: - version "1.6.1" - resolved "https://registry.yarnpkg.com/jimp/-/jimp-1.6.1.tgz#fd8118493739ab62ec09715b588ae41a7687a85d" - integrity sha512-hNQh6rZtWfSVWSNVmvq87N5BPJsNH7k7I7qyrXf9DOma9xATQk3fsyHazCQe51nCjdkoWdTmh0vD7bjVSLoxxw== - dependencies: - "@jimp/core" "1.6.1" - "@jimp/diff" "1.6.1" - "@jimp/js-bmp" "1.6.1" - "@jimp/js-gif" "1.6.1" - "@jimp/js-jpeg" "1.6.1" - "@jimp/js-png" "1.6.1" - "@jimp/js-tiff" "1.6.1" - "@jimp/plugin-blit" "1.6.1" - "@jimp/plugin-blur" "1.6.1" - "@jimp/plugin-circle" "1.6.1" - "@jimp/plugin-color" "1.6.1" - "@jimp/plugin-contain" "1.6.1" - "@jimp/plugin-cover" "1.6.1" - "@jimp/plugin-crop" "1.6.1" - "@jimp/plugin-displace" "1.6.1" - "@jimp/plugin-dither" "1.6.1" - "@jimp/plugin-fisheye" "1.6.1" - "@jimp/plugin-flip" "1.6.1" - "@jimp/plugin-hash" "1.6.1" - "@jimp/plugin-mask" "1.6.1" - "@jimp/plugin-print" "1.6.1" - "@jimp/plugin-quantize" "1.6.1" - "@jimp/plugin-resize" "1.6.1" - "@jimp/plugin-rotate" "1.6.1" - "@jimp/plugin-threshold" "1.6.1" - "@jimp/types" "1.6.1" - "@jimp/utils" "1.6.1" - jiti@^2.7.0: version "2.7.0" resolved "https://registry.yarnpkg.com/jiti/-/jiti-2.7.0.tgz#974228f2f4ca2bc21885a1797b45fea68e950c64" @@ -3390,11 +2871,6 @@ jose@^5.9.6: resolved "https://registry.yarnpkg.com/jose/-/jose-5.9.6.tgz#77f1f901d88ebdc405e57cce08d2a91f47521883" integrity sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ== -jpeg-js@^0.4.4: - version "0.4.4" - resolved "https://registry.yarnpkg.com/jpeg-js/-/jpeg-js-0.4.4.tgz#a9f1c6f1f9f0fa80cdb3484ed9635054d28936aa" - integrity sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg== - js-sdsl@4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/js-sdsl/-/js-sdsl-4.3.0.tgz#aeefe32a451f7af88425b11fdb5f58c90ae1d711" @@ -3437,15 +2913,6 @@ json5@^2.2.3: resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== -jsonfile@^6.0.1: - version "6.1.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.1.0.tgz#bc55b2634793c679ec6403094eb13698a6ec0aae" - integrity sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ== - dependencies: - universalify "^2.0.0" - optionalDependencies: - graceful-fs "^4.1.6" - keyv@^4.5.4: version "4.5.4" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.4.tgz#a879a99e29452f942439f2a405e3af8b31d4de93" @@ -3453,11 +2920,6 @@ keyv@^4.5.4: dependencies: json-buffer "3.0.1" -kleur@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" - integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== - kuler@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/kuler/-/kuler-2.0.0.tgz#e2c570a3800388fb44407e851531c1d670b061b3" @@ -3557,14 +3019,6 @@ lodash@4.18.1, lodash@^4.17.21: resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.18.1.tgz#ff2b66c1f6326d59513de2407bf881439812771c" integrity sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q== -log-symbols@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-5.1.0.tgz#a20e3b9a5f53fac6aeb8e2bb22c07cf2c8f16d93" - integrity sha512-l0x2DvrW294C9uDCoQe1VSU4gf529FkSZ6leBl4TiqZH/e+0R7hSfHQBNut2mNygDgHwvYHfFLn6Oxb3VWj2rA== - dependencies: - chalk "^5.0.0" - is-unicode-supported "^1.1.0" - logform@^2.7.0: version "2.7.0" resolved "https://registry.yarnpkg.com/logform/-/logform-2.7.0.tgz#cfca97528ef290f2e125a08396805002b2d060d1" @@ -3819,11 +3273,6 @@ mdast-util-to-string@^4.0.0: dependencies: "@types/mdast" "^4.0.0" -merge-stream@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" - integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== - micromark-core-commonmark@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz#c691630e485021a68cf28dbc2b2ca27ebf678cd4" @@ -4097,27 +3546,13 @@ micromark@^4.0.0: micromark-util-symbol "^2.0.0" micromark-util-types "^2.0.0" -mime@3: - version "3.0.0" - resolved "https://registry.yarnpkg.com/mime/-/mime-3.0.0.tgz#b374550dca3a0c18443b0c950a6a58f1931cf7a7" - integrity sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A== - -mimic-fn@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" - integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== - -mimic-fn@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-4.0.0.tgz#60a90550d5cb0b239cca65d893b1a53b29871ecc" - integrity sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw== - -minimatch@^10.2.2, minimatch@^10.2.4, minimatch@^10.2.5: - version "10.2.6" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-10.2.6.tgz#fd956bbe0b77241e9f15ac5dccb1c638060968ef" - integrity sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A== +minimatch@11.0.1, minimatch@^10.2.2, minimatch@^10.2.4, minimatch@^10.2.5: + version "11.0.1" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-11.0.1.tgz#6958bb689808489c3b4320428537fda7ae2a881c" + integrity sha512-t+Vn6DX4wPCxS23y03C0uhF7S1jpi1GfqPrnlEipCJaA2ykiNbMkVlDutZtmvLfRcUN6R8AYVlzTsQrT4RZoLQ== dependencies: - brace-expansion "^5.0.8" + "@isaacs/nonrecursive-glob-match" "^1.0.1" + brace-expansion "^5.0.12" minimist@^1.2.8: version "1.2.8" @@ -4206,46 +3641,32 @@ next-themes@^0.4.3: resolved "https://registry.yarnpkg.com/next-themes/-/next-themes-0.4.3.tgz#ea54552d5986936d177eed393ea50b658ae44800" integrity sha512-nG84VPkTdUHR2YeD89YchvV4I9RbiMAql3GiLEQlPvq1ioaqPaIReK+yMRdg/zgiXws620qS1rU30TiWmmG9lA== -next@15.5.27: - version "15.5.27" - resolved "https://registry.yarnpkg.com/next/-/next-15.5.27.tgz#bd149e4dcc483bfff31fa390842cfb8b7ff9a522" - integrity sha512-F82CrlPZ8GRxBH9RIIoR3qU1t5RT3dv1K8moe8SjlDEquiFipvEI13R1Om90TaUOEwShkWCMlg8+gvTNzfMhvg== +next@15.5.28: + version "15.5.28" + resolved "https://registry.yarnpkg.com/next/-/next-15.5.28.tgz#0589d32fa30ba712e4647deebeaabaf936e8a272" + integrity sha512-JjhLBBY1PNnuwPtcZ7t8yxVeJVYvD2Jyp633J+gRCNbzSt7N0E+xqCf6uQiff3+3qmUkwcF/ksfSsK1xsZ76Tw== dependencies: - "@next/env" "15.5.27" + "@next/env" "15.5.28" "@swc/helpers" "0.5.15" caniuse-lite "^1.0.30001579" postcss "8.4.31" styled-jsx "5.1.6" optionalDependencies: - "@next/swc-darwin-arm64" "15.5.27" - "@next/swc-darwin-x64" "15.5.27" - "@next/swc-linux-arm64-gnu" "15.5.27" - "@next/swc-linux-arm64-musl" "15.5.27" - "@next/swc-linux-x64-gnu" "15.5.27" - "@next/swc-linux-x64-musl" "15.5.27" - "@next/swc-win32-arm64-msvc" "15.5.27" - "@next/swc-win32-x64-msvc" "15.5.27" - sharp "^0.34.3 || ^0.35.4" + "@next/swc-darwin-arm64" "15.5.28" + "@next/swc-darwin-x64" "15.5.28" + "@next/swc-linux-arm64-gnu" "15.5.28" + "@next/swc-linux-arm64-musl" "15.5.28" + "@next/swc-linux-x64-gnu" "15.5.28" + "@next/swc-linux-x64-musl" "15.5.28" + "@next/swc-win32-arm64-msvc" "15.5.28" + "@next/swc-win32-x64-msvc" "15.5.28" + sharp "^0.34.3 || ^0.35.5" node-addon-api@^8.3.0: version "8.3.1" resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-8.3.1.tgz#53bc8a4f8dbde3de787b9828059da94ba9fd4eed" integrity sha512-lytcDEdxKjGJPTLEfW4mYMigRezMlyJY8W4wxJK8zE533Jlb8L8dRuObJFWg2P+AuOIxoCgKF+2Oq4d4Zd0OUA== -node-domexception@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/node-domexception/-/node-domexception-1.0.0.tgz#6888db46a1f71c0b76b3f7555016b63fe64766e5" - integrity sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ== - -node-fetch@^3.3.0: - version "3.3.2" - resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-3.3.2.tgz#d1e889bacdf733b4ff3b2b243eb7a12866a0b78b" - integrity sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA== - dependencies: - data-uri-to-buffer "^4.0.0" - fetch-blob "^3.1.4" - formdata-polyfill "^4.0.10" - node-gyp-build@^4.3.0: version "4.8.2" resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.8.2.tgz#4f802b71c1ab2ca16af830e6c1ea7dd1ad9496fa" @@ -4261,17 +3682,10 @@ node-releases@^2.0.51: resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.51.tgz#cdc08433577f5b32ad01694481726e22eeb54aef" integrity sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ== -nodemailer@10.0.12: - version "10.0.12" - resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-10.0.12.tgz#f94e46bb0f450f515cca29ba1af139fb0d83a149" - integrity sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg== - -npm-run-path@^5.1.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-5.3.0.tgz#e23353d0ebb9317f174e93417e4a4d82d0249e9f" - integrity sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ== - dependencies: - path-key "^4.0.0" +nodemailer@10.1.4: + version "10.1.4" + resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-10.1.4.tgz#66063221b29cb146c987e325ea92776f534e6524" + integrity sha512-EsMnOR2oRv4LGnWvHgcVYkkQ4O2j8KO4WTw6l+PHR4sOXo8SAgIraxtEnGDmotjbhv0hDsu3IuDIFZm8iXwO4A== number-allocator@^1.0.14: version "1.0.14" @@ -4291,11 +3705,6 @@ obuf@~1.1.2: resolved "https://registry.yarnpkg.com/obuf/-/obuf-1.1.2.tgz#09bea3343d41859ebd446292d11c9d4db619084e" integrity sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg== -omggif@^1.0.10: - version "1.0.10" - resolved "https://registry.yarnpkg.com/omggif/-/omggif-1.0.10.tgz#ddaaf90d4a42f532e9e7cb3a95ecdd47f17c7b19" - integrity sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw== - once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -4310,20 +3719,6 @@ one-time@^1.0.0: dependencies: fn.name "1.x.x" -onetime@^5.1.0: - version "5.1.2" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" - integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== - dependencies: - mimic-fn "^2.1.0" - -onetime@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-6.0.0.tgz#7c24c18ed1fd2e9bca4bd26806a33613c77d34b4" - integrity sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ== - dependencies: - mimic-fn "^4.0.0" - openvino-node@2025.4.0: version "2025.4.0" resolved "https://registry.yarnpkg.com/openvino-node/-/openvino-node-2025.4.0.tgz#6fc3aedca7f0138863dd3b04d34571063f63c196" @@ -4345,21 +3740,6 @@ optionator@^0.9.3: type-check "^0.4.0" word-wrap "^1.2.5" -ora@^6.1.2: - version "6.3.1" - resolved "https://registry.yarnpkg.com/ora/-/ora-6.3.1.tgz#a4e9e5c2cf5ee73c259e8b410273e706a2ad3ed6" - integrity sha512-ERAyNnZOfqM+Ao3RAvIXkYh5joP220yf59gVe2X/cI6SiCxIdi4c9HZKZD8R6q/RDXEje1THBju6iExiSsgJaQ== - dependencies: - chalk "^5.0.0" - cli-cursor "^4.0.0" - cli-spinners "^2.6.1" - is-interactive "^2.0.0" - is-unicode-supported "^1.1.0" - log-symbols "^5.1.0" - stdin-discarder "^0.1.0" - strip-ansi "^7.0.1" - wcwidth "^1.0.1" - p-limit@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" @@ -4374,34 +3754,11 @@ p-locate@^5.0.0: dependencies: p-limit "^3.0.2" -pako@^1.0.11: - version "1.0.11" - resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf" - integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw== - pako@~0.2.0: version "0.2.9" resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75" integrity sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA== -parse-bmfont-ascii@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/parse-bmfont-ascii/-/parse-bmfont-ascii-1.0.6.tgz#11ac3c3ff58f7c2020ab22769079108d4dfa0285" - integrity sha512-U4RrVsUFCleIOBsIGYOMKjn9PavsGOXxbvYGtMOEfnId0SVNsgehXh1DxUdVPLoxd5mvcEtvmKs2Mmf0Mpa1ZA== - -parse-bmfont-binary@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/parse-bmfont-binary/-/parse-bmfont-binary-1.0.6.tgz#d038b476d3e9dd9db1e11a0b0e53a22792b69006" - integrity sha512-GxmsRea0wdGdYthjuUeWTMWPqm2+FAd4GI8vCvhgJsFnoGhTrLhXDDupwTo7rXVAgaLIGoVHDZS9p/5XbSqeWA== - -parse-bmfont-xml@^1.1.6: - version "1.1.6" - resolved "https://registry.yarnpkg.com/parse-bmfont-xml/-/parse-bmfont-xml-1.1.6.tgz#016b655da7aebe6da38c906aca16bf0415773767" - integrity sha512-0cEliVMZEhrFDwMh4SxIyVJpqYoOWDJ9P895tFuS+XuNzI5UBmBk5U5O4KuJdTnZpSBI4LFA2+ZiJaiwfSwlMA== - dependencies: - xml-parse-from-string "^1.0.0" - xml2js "^0.5.0" - parse-entities@^4.0.0: version "4.0.2" resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-4.0.2.tgz#61d46f5ed28e4ee62e9ddc43d6b010188443f159" @@ -4432,11 +3789,6 @@ path-key@^3.1.0: resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== -path-key@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-4.0.0.tgz#295588dc3aee64154f877adb9d780b81c554bf18" - integrity sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ== - peek-stream@^1.1.0: version "1.1.3" resolved "https://registry.yarnpkg.com/peek-stream/-/peek-stream-1.1.3.tgz#3b35d84b7ccbbd262fff31dc10da56856ead6d67" @@ -4535,23 +3887,6 @@ picomatch@^4.0.4: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.5.tgz#51ea57a17d86f605f81039595fbc40ed06a55fab" integrity sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A== -pixelmatch@^5.3.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/pixelmatch/-/pixelmatch-5.3.0.tgz#5e5321a7abedfb7962d60dbf345deda87cb9560a" - integrity sha512-o8mkY4E/+LNUf6LzX96ht6k6CEDi65k9G2rjMtBe9Oo+VPKSvl+0GKHuH/AlG+GA5LPG/i5hrekkxUc3s2HU+Q== - dependencies: - pngjs "^6.0.0" - -pngjs@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-6.0.0.tgz#ca9e5d2aa48db0228a52c419c3308e87720da821" - integrity sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg== - -pngjs@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-7.0.0.tgz#a8b7446020ebbc6ac739db6c5415a65d17090e26" - integrity sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow== - postcss-selector-parser@7.1.6: version "7.1.6" resolved "https://registry.yarnpkg.com/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz#45e970f2d93d4547d6754167ed1132f43012c4bf" @@ -4633,14 +3968,6 @@ process@^0.11.10: resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== -prompts@^2.4.2: - version "2.4.2" - resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.2.tgz#7b57e73b3a48029ad10ebd44f74b01722a4cb069" - integrity sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q== - dependencies: - kleur "^3.0.3" - sisteransi "^1.0.5" - prop-types@^15.6.2, prop-types@^15.8.1: version "15.8.1" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5" @@ -4955,14 +4282,6 @@ remark-stringify@^11.0.0: mdast-util-to-markdown "^2.0.0" unified "^11.0.0" -restore-cursor@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-4.0.0.tgz#519560a4318975096def6e609d44100edaa4ccb9" - integrity sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg== - dependencies: - onetime "^5.1.0" - signal-exit "^3.0.2" - rfdc@^1.3.0, rfdc@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.4.1.tgz#778f76c4fb731d93414e8f925fbecf64cce7f6ca" @@ -4983,11 +4302,6 @@ safe-stable-stringify@^2.3.1: resolved "https://registry.yarnpkg.com/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz#4ca2f8e385f2831c432a719b108a3bf7af42a1dd" integrity sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA== -sax@>=0.6.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/sax/-/sax-1.4.1.tgz#44cc8988377f126304d3b3fc1010c733b929ef0f" - integrity sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg== - scheduler@^0.25.0: version "0.25.0" resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.25.0.tgz#336cd9768e8cceebf52d3c80e3dcf5de23e7e015" @@ -5003,7 +4317,7 @@ semver@^7.7.3, semver@^7.8.5: resolved "https://registry.yarnpkg.com/semver/-/semver-7.8.5.tgz#39b646037dd50c14fb451e7e4cac58ed8b863f69" integrity sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA== -sharp@0.35.5, "sharp@^0.34.3 || ^0.35.4": +sharp@0.35.5, "sharp@^0.34.3 || ^0.35.5": version "0.35.5" resolved "https://registry.yarnpkg.com/sharp/-/sharp-0.35.5.tgz#43fb539872ec5f53cc7162eb850dbf6514692fbf" integrity sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g== @@ -5050,11 +4364,6 @@ shebang-regex@^3.0.0: resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== -signal-exit@^3.0.2, signal-exit@^3.0.7: - version "3.0.7" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" - integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== - simple-swizzle@^0.2.2: version "0.2.2" resolved "https://registry.yarnpkg.com/simple-swizzle/-/simple-swizzle-0.2.2.tgz#a4da6b635ffcccca33f70d17cb92592de95e557a" @@ -5062,16 +4371,6 @@ simple-swizzle@^0.2.2: dependencies: is-arrayish "^0.3.1" -simple-xml-to-json@^1.2.2: - version "1.2.3" - resolved "https://registry.yarnpkg.com/simple-xml-to-json/-/simple-xml-to-json-1.2.3.tgz#79c7188ff99ae209a267b70ee0db06b0e4597787" - integrity sha512-kWJDCr9EWtZ+/EYYM5MareWj2cRnZGF93YDNpH4jQiHB+hBIZnfPFSQiVMzZOdk+zXWqTZ/9fTeQNu2DqeiudA== - -sisteransi@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" - integrity sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg== - smart-buffer@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/smart-buffer/-/smart-buffer-4.2.0.tgz#6e1d71fa4f18c05f7d0ff216dd16a481d0e8d9ae" @@ -5110,13 +4409,6 @@ stack-trace@0.0.x: resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" integrity sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg== -stdin-discarder@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/stdin-discarder/-/stdin-discarder-0.1.0.tgz#22b3e400393a8e28ebf53f9958f3880622efde21" - integrity sha512-xhV7w8S+bUwlPTb4bAOUQhv8/cSS5offJuX8GQGq32ONF0ZtDWKfkdomM3HMRA+LhX6um/FZ0COqlwsjD53LeQ== - dependencies: - bl "^5.0.0" - stream-shift@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.3.tgz#85b8fab4d71010fc3ba8772e8046cc49b8a3864b" @@ -5153,25 +4445,6 @@ stringify-entities@^4.0.0: character-entities-html4 "^2.0.0" character-entities-legacy "^3.0.0" -strip-ansi@^7.0.1: - version "7.1.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" - integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== - dependencies: - ansi-regex "^6.0.1" - -strip-final-newline@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-3.0.0.tgz#52894c313fbff318835280aed60ff71ebf12b8fd" - integrity sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw== - -strtok3@^10.3.4: - version "10.3.5" - resolved "https://registry.yarnpkg.com/strtok3/-/strtok3-10.3.5.tgz#7213285da0dc3dec0fc8ce5df4b8b7a733f14360" - integrity sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA== - dependencies: - "@tokenizer/token" "^0.3.0" - style-to-js@^1.0.0: version "1.1.17" resolved "https://registry.yarnpkg.com/style-to-js/-/style-to-js-1.1.17.tgz#488b1558a8c1fd05352943f088cc3ce376813d83" @@ -5266,11 +4539,6 @@ tiny-invariant@^1.3.1: resolved "https://registry.yarnpkg.com/tiny-invariant/-/tiny-invariant-1.3.3.tgz#46680b7a873a0d5d10005995eb90a70d74d60127" integrity sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg== -tinycolor2@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/tinycolor2/-/tinycolor2-1.6.0.tgz#f98007460169b0263b97072c5ae92484ce02d09e" - integrity sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw== - tinyglobby@^0.2.15: version "0.2.17" resolved "https://registry.yarnpkg.com/tinyglobby/-/tinyglobby-0.2.17.tgz#562a9a6c9eb2b3b123d39719f9af5bb44fcd7631" @@ -5279,15 +4547,6 @@ tinyglobby@^0.2.15: fdir "^6.5.0" picomatch "^4.0.4" -token-types@^6.1.1: - version "6.1.2" - resolved "https://registry.yarnpkg.com/token-types/-/token-types-6.1.2.tgz#18d0fd59b996d421f9f83914d6101c201bd08129" - integrity sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww== - dependencies: - "@borewit/text-codec" "^0.2.1" - "@tokenizer/token" "^0.3.0" - ieee754 "^1.2.1" - trim-lines@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/trim-lines/-/trim-lines-3.0.1.tgz#d802e332a07df861c48802c04321017b1bd87338" @@ -5330,11 +4589,6 @@ typescript@5.6.3: resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.6.3.tgz#5f3449e31c9d94febb17de03cc081dd56d81db5b" integrity sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw== -uint8array-extras@^1.4.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/uint8array-extras/-/uint8array-extras-1.5.0.tgz#10d2a85213de3ada304fea1c454f635c73839e86" - integrity sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A== - uncrypto@^0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/uncrypto/-/uncrypto-0.1.3.tgz#e1288d609226f2d02d8d69ee861fa20d8348ef2b" @@ -5404,11 +4658,6 @@ unist-util-visit@^5.0.0: unist-util-is "^6.0.0" unist-util-visit-parents "^6.0.0" -universalify@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.1.tgz#168efc2180964e6386d061e094df61afe239b18d" - integrity sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw== - update-browserslist-db@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz#64d76db58713136acbeb4c49114366cc6cc2e80d" @@ -5459,13 +4708,6 @@ use-sidecar@^1.1.3: detect-node-es "^1.1.0" tslib "^2.0.0" -utif2@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/utif2/-/utif2-4.1.0.tgz#e768d37bd619b995d56d9780b5d2b4611a3d932b" - integrity sha512-+oknB9FHrJ7oW7A2WZYajOcv4FcDR4CfoGB0dPNfxbi4GO05RRnFmt5oa23+9w32EanrYcSJWspUiJkLMs+37w== - dependencies: - pako "^1.0.11" - util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" @@ -5522,23 +4764,11 @@ victory-vendor@^36.6.8: d3-time "^3.0.0" d3-timer "^3.0.1" -wcwidth@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" - integrity sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg== - dependencies: - defaults "^1.0.3" - web-namespaces@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/web-namespaces/-/web-namespaces-2.0.1.tgz#1010ff7c650eccb2592cebeeaf9a1b253fd40692" integrity sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ== -web-streams-polyfill@^3.0.3: - version "3.3.3" - resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz#2073b91a2fdb1fbfbd401e7de0ac9f8214cecb4b" - integrity sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw== - which@^2.0.1: version "2.0.2" resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" @@ -5654,24 +4884,6 @@ ws@8.21.1, ws@^8.17.1, ws@^8.18.3: resolved "https://registry.yarnpkg.com/ws/-/ws-8.21.1.tgz#045650cd4b1207809e7547146223c3814a9af586" integrity sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw== -xml-parse-from-string@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/xml-parse-from-string/-/xml-parse-from-string-1.0.1.tgz#a9029e929d3dbcded169f3c6e28238d95a5d5a28" - integrity sha512-ErcKwJTF54uRzzNMXq2X5sMIy88zJvfN2DmdoQvy7PAFJ+tPRU6ydWuOKNMyfmOjdyBQTFREi60s0Y0SyI0G0g== - -xml2js@^0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.5.0.tgz#d9440631fbb2ed800203fad106f2724f62c493b7" - integrity sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA== - dependencies: - sax ">=0.6.0" - xmlbuilder "~11.0.0" - -xmlbuilder@~11.0.0: - version "11.0.1" - resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" - integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== - xtend@^4.0.0, xtend@~4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" @@ -5692,15 +4904,10 @@ yocto-queue@^0.1.0: resolved "https://registry.yarnpkg.com/zod-validation-error/-/zod-validation-error-4.0.2.tgz#bc605eba49ce0fcd598c127fee1c236be3f22918" integrity sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ== -zod@^3.20.2, zod@^3.23.8: - version "3.23.8" - resolved "https://registry.yarnpkg.com/zod/-/zod-3.23.8.tgz#e37b957b5d52079769fb8097099b592f0ef4067d" - integrity sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g== - -"zod@^3.25.0 || ^4.0.0": - version "4.4.3" - resolved "https://registry.yarnpkg.com/zod/-/zod-4.4.3.tgz#b680f172885d18bbebf21a834ea25e55a1bbf356" - integrity sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ== +zod@4.6.6, "zod@^3.25.0 || ^4.0.0": + version "4.6.6" + resolved "https://registry.yarnpkg.com/zod/-/zod-4.6.6.tgz#0bb0cf57b87011a71ec28ed2e1b51f6455563f9a" + integrity sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA== zwitch@^2.0.0: version "2.0.4"