@camstack/addon-provider-reolink 1.2.148 → 1.2.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +820 -44
  2. package/dist/addon.mjs +820 -44
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -5390,7 +5390,7 @@ var ZodIssueCode = {
5390
5390
  var ZodFirstPartyTypeKind;
5391
5391
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5392
5392
  //#endregion
5393
- //#region ../types/dist/sleep-CaB_hL5g.mjs
5393
+ //#region ../types/dist/sleep-BVhJDJka.mjs
5394
5394
  /**
5395
5395
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5396
5396
  * window to float samples (D455).
@@ -6961,6 +6961,18 @@ function systemMethod(input, output, options) {
6961
6961
  systemOnly: true
6962
6962
  };
6963
6963
  }
6964
+ /**
6965
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
6966
+ * on `InferProvider`. The `providerOptional: true` literal is what
6967
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
6968
+ * for when this is the honest answer and when it is a soft stub.
6969
+ */
6970
+ function optionalMethod(input, output, options) {
6971
+ return {
6972
+ ...method(input, output, options),
6973
+ providerOptional: true
6974
+ };
6975
+ }
6964
6976
  /** Shorthand to define an event schema */
6965
6977
  function event(data) {
6966
6978
  return { data };
@@ -25346,6 +25358,77 @@ var ClipPlaybackSchema = object({
25346
25358
  * which days it asked for and got nothing — "no clips" would be a lie about a
25347
25359
  * card that is full of them.
25348
25360
  */
25361
+ /**
25362
+ * The operator's authorisation to WAKE a sleeping camera for one clip read.
25363
+ *
25364
+ * ONE value, absent by default, and it is a `force`-shaped operator signal in
25365
+ * exactly the sense `snapshot-wake-gate.ts` uses the word: *"`snapshot.getSnapshot`'s
25366
+ * `force` flag, and nothing else… a background caller must never set it…
25367
+ * Stale but honest beats woken"*. A scheduler, a retry, a reconcile and a
25368
+ * prefetch never set it; a surface sets it only behind the same confirm the
25369
+ * "Wake and refresh" gesture uses, and it is refused below 15 % battery
25370
+ * exactly as that gesture is.
25371
+ *
25372
+ * The gate is decided BEFORE `getApi()`, because on UDP the login IS the wake
25373
+ * (D549) — a read that opened a session and then checked would have woken the
25374
+ * camera to find out it was not allowed to.
25375
+ *
25376
+ * **One authorised yes is one wake.** `next-natural` — take the clip the next
25377
+ * time the camera is awake for its own reasons — is deliberately not a member:
25378
+ * it was proposed, it is free on the battery, and the operator declined it on
25379
+ * 2026-09-20 (*"Quando un export viene richiesto si sveglia la camera."*,
25380
+ * D558 "Considered and not taken").
25381
+ */
25382
+ var ClipWakeSchema = _enum(["authorised"]);
25383
+ /**
25384
+ * Hard ceiling on ONE {@link videoclipsCapability.methods.readClipBytes} — the
25385
+ * same 50 MiB `RECORDING_EXPORT_MAX_READ_BYTES` uses, and for the same second
25386
+ * reason: the envelope is unary, so a base64 payload is held whole (~1.33× its
25387
+ * size) in the provider AND in the caller, on a hub this repo has already
25388
+ * OOM'd once (D9/D18).
25389
+ *
25390
+ * Measured clips sit far below it — 92 KB–2.29 MB for a sub twin, 455 KB for a
25391
+ * 16 s main clip — so the bound bites rarely. "Rarely" is not "never": a long
25392
+ * 4K main twin can exceed it, and above the bound the provider REFUSES with
25393
+ * the size in the message, never truncates. Half a video is worse than an
25394
+ * honest refusal.
25395
+ *
25396
+ * The clean follow-on is a CHUNKED read so a `high` twin of a long clip stops
25397
+ * being refusable at all. That is a later slice, named here so the bound is
25398
+ * not mistaken for a design ceiling.
25399
+ */
25400
+ var VIDEOCLIPS_MAX_READ_BYTES = 50 * 1024 * 1024;
25401
+ /**
25402
+ * A clip's finished bytes, inline — the twin of `recordingExport.readExportBytes`.
25403
+ *
25404
+ * `bytes` is the DECODED length, so nobody infers it from the base64 length,
25405
+ * and `served` says which twin the caller actually got.
25406
+ */
25407
+ var ClipBytesSchema = object({
25408
+ base64: string(),
25409
+ contentType: string(),
25410
+ /** Suggested filename, extension included. */
25411
+ name: string(),
25412
+ bytes: number().int().nonnegative(),
25413
+ /**
25414
+ * Which twin was actually served — the same contract
25415
+ * {@link ClipPlaybackSchema.served} carries, and REQUIRED here because the
25416
+ * export record persists it: a row read a week later must say the same thing
25417
+ * the panel said at the moment of the tap. A missing main twin is never
25418
+ * served silently as if it were the asked-for quality (D549 15).
25419
+ */
25420
+ served: CamProfileSchema,
25421
+ /**
25422
+ * The DECODED duration of the delivered file, when the fetch measured one.
25423
+ *
25424
+ * A clip fetch verifies its own completion against the catalog row and
25425
+ * retries a materially short pass (D568); this is that measurement, carried
25426
+ * so a consumer can say the same thing rather than re-deriving it. Absent
25427
+ * when the producer did not measure — never zero, which would say the file
25428
+ * is empty.
25429
+ */
25430
+ durationMs: number().positive().optional()
25431
+ });
25349
25432
  var ClipSourceAvailabilitySchema = object({
25350
25433
  state: _enum([
25351
25434
  "ok",
@@ -25517,6 +25600,68 @@ var videoclipsCapability = {
25517
25600
  }), ClipPlaybackSchema, {
25518
25601
  kind: "query",
25519
25602
  auth: "protected"
25603
+ }),
25604
+ /**
25605
+ * This clip's BYTES, base64, bounded — the by-handle read a clip EXPORT
25606
+ * pulls once (D558).
25607
+ *
25608
+ * `getClipPlayback` is the right answer for a player: it hands back a URL
25609
+ * on a plane the hub serves `access:'authenticated'`, which a browser and a
25610
+ * viewer session satisfy. It is the wrong answer for another ADDON. There
25611
+ * is no addon→addon byte transport in this framework — `AddonDataPlane`
25612
+ * only lets an addon SERVE, on `127.0.0.1` behind a per-listener secret
25613
+ * only the hub may present — so a recorder that wants a camera's clip
25614
+ * cannot fetch that URL. This method is the one seam that exists for it,
25615
+ * and it is deliberately the same shape (and the same bound) as
25616
+ * `recordingExport.readExportBytes`, which exists for the mirror-image
25617
+ * reason.
25618
+ *
25619
+ * Routing needs no `provider` pin: the id is source-prefixed and
25620
+ * self-contained, so `device-collection-dispatch.ts` rule 3 hands the call
25621
+ * to the source that claims it — and an id nobody claims is REFUSED rather
25622
+ * than answered by another source.
25623
+ *
25624
+ * The producer reuses the fetch path it already has, completion rules
25625
+ * included: a clip is taken by cmd 5 and finished on a short idle window
25626
+ * whose result is PROVED against the catalog row's own span, retried once
25627
+ * when it comes up materially short, and served-and-named when it is still
25628
+ * short (D568). A second fetch with different completion rules is exactly
25629
+ * the second authority D558 refuses to create.
25630
+ *
25631
+ * Every refusal THROWS with its reason and none of them is silent — the
25632
+ * sleep gate (decided before `getApi()`, liftable only by
25633
+ * {@link ClipWakeSchema}), a catalog row nobody claims, a clip with no
25634
+ * bytes behind it, a mux that failed, and the size bound. The caller turns
25635
+ * that reason into an operator-facing one; a truncated file is never an
25636
+ * answer.
25637
+ */
25638
+ readClipBytes: optionalMethod(object({
25639
+ deviceId: number(),
25640
+ clipId: string().min(1),
25641
+ /**
25642
+ * Which twin to fetch, on the mapping D549 15 already fixed:
25643
+ * `low | mid` → the sub file, `high` → the main twin. `auto` is not
25644
+ * accepted here for the same reason it is not accepted by
25645
+ * `getClipPlayback` — a stored file has no broker session, so the
25646
+ * adaptive tier cannot be resolved for it.
25647
+ */
25648
+ profile: CamProfileSchema.optional(),
25649
+ /**
25650
+ * The CALLER's byte bound, so an over-size clip is refused before it is
25651
+ * read and encoded rather than after. Capped by
25652
+ * {@link VIDEOCLIPS_MAX_READ_BYTES} whatever is passed; absent means
25653
+ * that ceiling.
25654
+ */
25655
+ maxBytes: number().int().positive().optional(),
25656
+ /**
25657
+ * The operator's authorisation to wake a sleeping camera for this
25658
+ * read. Absent — the default — means a sleeping standalone battery
25659
+ * camera is REFUSED by name, before any session is opened.
25660
+ */
25661
+ wake: ClipWakeSchema.optional()
25662
+ }), ClipBytesSchema, {
25663
+ kind: "query",
25664
+ auth: "protected"
25520
25665
  })
25521
25666
  }
25522
25667
  };
@@ -33470,13 +33615,101 @@ var ExportStateSchema = _enum([
33470
33615
  "expired",
33471
33616
  "deleted"
33472
33617
  ]);
33473
- /** One export job / history row. */
33618
+ /**
33619
+ * WHAT an export is — the authority, as opposed to the four top-level fields
33620
+ * the Library sorts and labels on (D558 § 2.2).
33621
+ *
33622
+ * Read it through {@link exportSubjectOf}, never off the record directly: the
33623
+ * field is optional for the history rows written before it existed, and that
33624
+ * absence has exactly one interpreter.
33625
+ */
33626
+ var ExportSubjectSchema = discriminatedUnion("kind", [object({
33627
+ kind: literal("footage"),
33628
+ deviceId: number(),
33629
+ profiles: array(string()).min(1),
33630
+ fromMs: number(),
33631
+ toMs: number()
33632
+ }), object({
33633
+ kind: literal("clip"),
33634
+ deviceId: number(),
33635
+ provider: string().min(1),
33636
+ source: string().min(1),
33637
+ sourceLabel: string().min(1),
33638
+ clipId: string().min(1),
33639
+ /**
33640
+ * WHERE IN THE CATALOG to confirm this clip — the day window the surface was
33641
+ * already listing when the operator picked the segment.
33642
+ *
33643
+ * It is **not** a time range control and it never becomes one: the record's
33644
+ * `fromMs`/`toMs` come from the catalog ROW and from nothing a caller
33645
+ * supplied (D558 § 5.4.3), and a window that does not contain the clip is a
33646
+ * `catalog-miss`, not a silently wider search. It exists because
33647
+ * `videoclips.listClips` takes `since`/`until` and has no by-handle twin:
33648
+ * the catalog check D558 asks for is literally that call, and a call needs a
33649
+ * window. The surface has one — `ClipsBrowser`'s `dayWindow`, one local
33650
+ * wall-clock day, which is also the only width measured to be cheap (one
33651
+ * day on 592 lists 171 clips in 712 ms, a busy day 546 in 2.0 s; twenty days
33652
+ * of one child's events took 3.6–5.4 s).
33653
+ */
33654
+ catalogWindow: object({
33655
+ sinceMs: number(),
33656
+ untilMs: number()
33657
+ }),
33658
+ profile: _enum([
33659
+ "high",
33660
+ "mid",
33661
+ "low"
33662
+ ]),
33663
+ /**
33664
+ * The operator's authorisation to wake a sleeping camera for this export.
33665
+ * ONE definition, in the cap that owns the clip read ({@link ClipWakeSchema}),
33666
+ * because the gate that honours it is the clip provider's sleep gate — a
33667
+ * second enum here would be a second contract. Absent by default; never
33668
+ * settable by a scheduler or a retry.
33669
+ *
33670
+ * **One authorised yes is ONE wake.** A failed clip export is retried only by
33671
+ * an operator act that asks again; a queued job that outlived its wake fails
33672
+ * with a reason rather than waking on its turn; and this subject carries
33673
+ * exactly one profile precisely so one tap is never two fetches (D558 § 5.2).
33674
+ */
33675
+ wake: ClipWakeSchema.optional()
33676
+ })]);
33677
+ /**
33678
+ * One export job / history row.
33679
+ *
33680
+ * **`subject` is the AUTHORITY on what was exported. `deviceId`, `profile`,
33681
+ * `fromMs` and `toMs` are its PROJECTION** — kept top-level because the whole
33682
+ * Library sorts and labels on them (`library-items.ts` orders an export by
33683
+ * `fromMs`; `export-format.ts` draws `rangeLabel` from the pair), and a row
33684
+ * that did not fill them would sort under the epoch and render a blank range.
33685
+ * Write to the subject and read from the projection and the two will disagree;
33686
+ * the projection is derived at creation and never edited afterwards.
33687
+ *
33688
+ * And they mean DIFFERENT FACTS for the two kinds, which is the part a reader
33689
+ * who knows only the recording export will get wrong:
33690
+ *
33691
+ * | field | `kind:'footage'` | `kind:'clip'` |
33692
+ * | --- | --- | --- |
33693
+ * | `fromMs`/`toMs` | the stretch the operator ASKED for | the camera's own boundaries, always `clip.timeRange`, never anything a caller supplied |
33694
+ * | `profile` | the stream rendered | the twin actually SERVED (`subject.profile` is the one asked for) |
33695
+ *
33696
+ * Same type, different fact — the shape this repo keeps getting wrong (D385's
33697
+ * two authorities, D224's second copy).
33698
+ */
33474
33699
  var ExportRecordSchema = object({
33475
33700
  id: string(),
33476
33701
  deviceId: number(),
33477
33702
  profile: string(),
33478
33703
  fromMs: number(),
33479
33704
  toMs: number(),
33705
+ /**
33706
+ * What this export IS. Optional ONLY for the rows written before D558: the
33707
+ * store parses every row through this schema on every read, so a required
33708
+ * field would make the export AUDIT — which is the whole reason rows survive
33709
+ * file deletion — unreadable in one release. Absence means `footage`, and
33710
+ * {@link exportSubjectOf} is the one place that says so.
33711
+ */
33712
+ subject: ExportSubjectSchema.optional(),
33480
33713
  options: ExportOptionsSchema,
33481
33714
  state: ExportStateSchema,
33482
33715
  /** 0–100 while rendering; null otherwise. */
@@ -33493,6 +33726,22 @@ var ExportRecordSchema = object({
33493
33726
  /** Failure reason when state is 'failed'; null otherwise. */
33494
33727
  error: string().nullable()
33495
33728
  });
33729
+ _enum([
33730
+ "catalog-miss",
33731
+ "catalog-unreachable",
33732
+ "no-file-for-window",
33733
+ "clip-in-progress",
33734
+ "unsupported-option",
33735
+ "sleeping",
33736
+ "camera-refused",
33737
+ "fetch-failed",
33738
+ "too-large-to-transfer",
33739
+ "wake-expired"
33740
+ ]);
33741
+ /** `<token>: <prose>` — the ONE composition of a clip export's failure string. */
33742
+ function clipExportFailure(code, detail) {
33743
+ return detail.length > 0 ? `${code}: ${detail}` : code;
33744
+ }
33496
33745
  /** Candidate download URLs (LAN first, then operator extra hosts). */
33497
33746
  var ExportDownloadSchema = object({
33498
33747
  url: string(),
@@ -33511,16 +33760,50 @@ var ExportBytesSchema = object({
33511
33760
  name: string(),
33512
33761
  bytes: number().int().nonnegative()
33513
33762
  });
33763
+ /** Canonical `profiles[]`, falling back to the legacy singular `profile`. */
33764
+ function resolveExportProfiles(input) {
33765
+ if (input.profiles !== void 0 && input.profiles.length > 0) return [...input.profiles];
33766
+ if (typeof input.profile === "string" && input.profile.length > 0) return [input.profile];
33767
+ return [];
33768
+ }
33514
33769
  method(object({
33515
33770
  deviceId: number(),
33516
33771
  /** @deprecated Prefer `profiles`. Kept so timelapse/notifiers keep working. */
33517
33772
  profile: string().optional(),
33518
33773
  profiles: array(string()).min(1).optional(),
33519
- fromMs: number(),
33520
- toMs: number(),
33774
+ /** Footage only — a clip's boundaries are the camera's. */
33775
+ fromMs: number().optional(),
33776
+ toMs: number().optional(),
33777
+ /** What to export. Absent means the legacy flat footage request. */
33778
+ subject: ExportSubjectSchema.optional(),
33521
33779
  options: ExportOptionsSchema
33522
33780
  }).superRefine((v, ctx) => {
33523
- if ((v.profiles !== void 0 && v.profiles.length > 0 ? v.profiles : v.profile !== void 0 ? [v.profile] : []).length < 1) ctx.addIssue({
33781
+ if (v.subject?.kind === "clip") {
33782
+ if (v.subject.deviceId !== v.deviceId) ctx.addIssue({
33783
+ code: ZodIssueCode.custom,
33784
+ message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId}) — the top-level field is what per-device scope enforcement reads`,
33785
+ path: ["subject", "deviceId"]
33786
+ });
33787
+ if (v.fromMs !== void 0 || v.toMs !== void 0) ctx.addIssue({
33788
+ code: ZodIssueCode.custom,
33789
+ message: "a clip export asks for no time range: the camera chose the boundaries and they are read from the catalog row",
33790
+ path: ["fromMs"]
33791
+ });
33792
+ return;
33793
+ }
33794
+ if (v.subject?.kind === "footage" && v.subject.deviceId !== v.deviceId) ctx.addIssue({
33795
+ code: ZodIssueCode.custom,
33796
+ message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId})`,
33797
+ path: ["subject", "deviceId"]
33798
+ });
33799
+ const fromMs = v.subject?.kind === "footage" ? v.subject.fromMs : v.fromMs;
33800
+ const toMs = v.subject?.kind === "footage" ? v.subject.toMs : v.toMs;
33801
+ if (typeof fromMs !== "number" || typeof toMs !== "number") ctx.addIssue({
33802
+ code: ZodIssueCode.custom,
33803
+ message: "a footage export needs fromMs and toMs",
33804
+ path: ["fromMs"]
33805
+ });
33806
+ if ((v.subject?.kind === "footage" ? [...v.subject.profiles] : resolveExportProfiles(v)).length < 1) ctx.addIssue({
33524
33807
  code: ZodIssueCode.custom,
33525
33808
  message: "pass profiles[] (min 1) or legacy profile",
33526
33809
  path: ["profiles"]
@@ -44062,6 +44345,12 @@ Object.freeze({
44062
44345
  addonId: null,
44063
44346
  access: "view"
44064
44347
  },
44348
+ "videoclips.readClipBytes": {
44349
+ capName: "videoclips",
44350
+ capScope: "device",
44351
+ addonId: null,
44352
+ access: "view"
44353
+ },
44065
44354
  "viewerUi.getStaticDir": {
44066
44355
  capName: "viewer-ui",
44067
44356
  capScope: "system",
@@ -46080,6 +46369,11 @@ Object.freeze({
46080
46369
  form: "single",
46081
46370
  optional: false
46082
46371
  }],
46372
+ "videoclips.readClipBytes": [{
46373
+ name: "deviceId",
46374
+ form: "single",
46375
+ optional: false
46376
+ }],
46083
46377
  "waterHeater.setAway": [{
46084
46378
  name: "deviceId",
46085
46379
  form: "single",
@@ -147645,6 +147939,21 @@ var ClipArtifactStore = class {
147645
147939
  };
147646
147940
  //#endregion
147647
147941
  //#region src/clips/clip-addressing.ts
147942
+ /**
147943
+ * The camera's uid, from the fresh copy where there is one.
147944
+ *
147945
+ * An empty or whitespace-only value is ABSENT, never a uid: it is how a
147946
+ * cleared settings field arrives, and passed on it addresses no camera at all
147947
+ * while making the refusal name the wrong cause.
147948
+ */
147949
+ function resolveCameraUid(sources) {
147950
+ return usable(sources.metadataUid) ?? usable(sources.configUid);
147951
+ }
147952
+ function usable(value) {
147953
+ if (typeof value !== "string") return void 0;
147954
+ const trimmed = value.trim();
147955
+ return trimmed.length === 0 ? void 0 : trimmed;
147956
+ }
147648
147957
  /** Does addressing this camera's catalog REQUIRE a persisted uid? */
147649
147958
  function uidIsRequired(subject) {
147650
147959
  return subject.isHubChild;
@@ -148439,6 +148748,43 @@ var ClipThumbQueue = class {
148439
148748
  }
148440
148749
  };
148441
148750
  //#endregion
148751
+ //#region src/clips/clip-prefetch.ts
148752
+ /** The longest a device may stay quiet after refusals, whatever its interval. */
148753
+ var PREFETCH_QUIET_MAX_MS = 720 * 6e4;
148754
+ /**
148755
+ * How long a device that refused stays un-asked, in INTERVALS rather than
148756
+ * wall-clock: the refresh interval is an operator setting (5 min – 24 h), and
148757
+ * a quiet period in minutes would be either no gap at all at one end or a day
148758
+ * at the other. One refusal skips the next two passes, two skips four, and so
148759
+ * on, capped.
148760
+ */
148761
+ function prefetchQuietMs(consecutiveRefusals, intervalMs) {
148762
+ if (consecutiveRefusals <= 0) return 0;
148763
+ const doubled = intervalMs * 2 ** consecutiveRefusals;
148764
+ return Number.isFinite(doubled) ? Math.min(doubled, PREFETCH_QUIET_MAX_MS) : PREFETCH_QUIET_MAX_MS;
148765
+ }
148766
+ /**
148767
+ * May this camera's stills be prefetched right now?
148768
+ *
148769
+ * The topology comes first and is absolute: no amount of idle host or empty
148770
+ * ladder makes a still on a standalone battery camera free.
148771
+ */
148772
+ function decideClipPrefetch(input) {
148773
+ if (input.mode === "forced-wake") return {
148774
+ kind: "skip",
148775
+ reason: "battery-wake-cost"
148776
+ };
148777
+ if (input.quiet) return {
148778
+ kind: "skip",
148779
+ reason: "quiet-after-refusal"
148780
+ };
148781
+ if (input.hostBusy) return {
148782
+ kind: "skip",
148783
+ reason: "host-busy"
148784
+ };
148785
+ return { kind: "run" };
148786
+ }
148787
+ //#endregion
148442
148788
  //#region src/clips/clip-identity.ts
148443
148789
  /**
148444
148790
  * A Reolink clip's IDENTITY — the id the operator's surface carries around and
@@ -149030,6 +149376,18 @@ function normaliseHour(hour) {
149030
149376
  }
149031
149377
  //#endregion
149032
149378
  //#region src/clips/reolink-videoclips-provider.ts
149379
+ /**
149380
+ * The filename an export carries away, from the camera's own handle.
149381
+ *
149382
+ * A hub child's handle is a full path (`/mnt/sda/U10…/RecS02_….mp4`) and a
149383
+ * standalone's is a bare name, so only the last segment is a name; the
149384
+ * extension is re-stated because what we produce is an MP4 whatever the
149385
+ * camera called its file.
149386
+ */
149387
+ function clipFileLabel(fileName) {
149388
+ const stem = (fileName.split("/").at(-1) ?? fileName).replace(/\.[^.]+$/, "");
149389
+ return `${stem === "" ? "clip" : stem}.mp4`;
149390
+ }
149033
149391
  function createReolinkVideoclipsProvider(deps) {
149034
149392
  /** Last known availability per `deviceId|source`, written by every read. */
149035
149393
  const health = /* @__PURE__ */ new Map();
@@ -149350,6 +149708,120 @@ function createReolinkVideoclipsProvider(deps) {
149350
149708
  format: "mp4",
149351
149709
  served: prepared.served
149352
149710
  };
149711
+ },
149712
+ /**
149713
+ * This clip's BYTES, base64, bounded — the producing half of a clip
149714
+ * export (D558 § 3, D572).
149715
+ *
149716
+ * ## What it refuses, and in whose words
149717
+ *
149718
+ * Every exit throws `clipExportFailure(<token>, <prose>)`. The engine
149719
+ * recovers the token with `clipExportFailureOf` and BELIEVES it; anything
149720
+ * that does not parse becomes `fetch-failed` with the prose kept verbatim.
149721
+ * So a refusal this side can name is named here — a `sleeping` that
149722
+ * arrives as prose is a `sleeping` the modal cannot render.
149723
+ *
149724
+ * ## The order of the questions, and why it is this order
149725
+ *
149726
+ * The cheap ones come first and none of them touches the camera: the id,
149727
+ * the row, whether the file is still being written, which twin exists, and
149728
+ * the SIZE the catalog already declared for it. A main twin over the bound
149729
+ * is refused for nothing — no session, no transfer, no mux — which is the
149730
+ * rule bulk work over stored media already follows (D54). Only then does
149731
+ * `prepareBytes` reach a camera, behind the sleep gate that has to sit in
149732
+ * front of the login.
149733
+ *
149734
+ * ## `high` against a 50 MiB ceiling
149735
+ *
149736
+ * A missing main twin is a DIVERGENCE, not a refusal: the sub is served
149737
+ * and `served` says `low`, exactly as the player does (D549 15), because
149738
+ * 17 of 546 clips on 592 have no main copy and an export of the copy that
149739
+ * exists beats no export. A main twin that exists and is too BIG is the
149740
+ * other case and is refused by name — the cap's own docblock settles it
149741
+ * ("above the bound the provider REFUSES with the size in the message,
149742
+ * never truncates"), the operator keeps the unbounded playback route for
149743
+ * that file, and the chunked read the cap names is what removes the
149744
+ * refusal rather than a silent 33× quality substitution.
149745
+ */
149746
+ readClipBytes: async ({ deviceId, clipId, profile, maxBytes, wake }) => {
149747
+ const tags = { deviceId };
149748
+ const refuse = (code, detail, meta) => {
149749
+ deps.logger.warn("videoclips: refusing a clip byte read", {
149750
+ tags,
149751
+ meta: {
149752
+ clipId,
149753
+ branch: code,
149754
+ ...meta
149755
+ }
149756
+ });
149757
+ throw new Error(clipExportFailure(code, detail));
149758
+ };
149759
+ const parsed = parseClipId(clipId);
149760
+ if (parsed === null) return refuse("catalog-miss", `clip id "${clipId}" was not minted by the Reolink provider`, {});
149761
+ const clipKey = clipKeyFor(parsed.channel, parsed.fileName);
149762
+ const row = rowsByKey.get(`${deviceId}|${clipKey}`);
149763
+ if (row === void 0) return refuse("catalog-miss", `clip "${clipId}" is not in this node's catalog for device ${deviceId} — list the day that holds it first`, { clipKey });
149764
+ if (row.inProgress === true) return refuse("clip-in-progress", `clip "${clipId}" is still being written, so it has no end to export`, { clipKey });
149765
+ const mainFileName = profile === "high" ? row.mainFileName : void 0;
149766
+ if (profile === "high" && mainFileName === void 0) deps.logger.warn("videoclips: no main twin for this clip — serving the sub copy", {
149767
+ tags,
149768
+ meta: {
149769
+ clipId,
149770
+ clipKey,
149771
+ branch: "no-main-twin",
149772
+ asked: profile
149773
+ }
149774
+ });
149775
+ const twin = mainFileName === void 0 ? "sub" : "main";
149776
+ const fileName = mainFileName ?? row.subFileName;
149777
+ if (fileName === "") return refuse("no-file-for-window", `clip "${clipId}" is listed with no byte handle behind it`, {
149778
+ clipKey,
149779
+ twin
149780
+ });
149781
+ const served = twin === "main" ? "high" : "low";
149782
+ const bound = Math.min(maxBytes ?? 52428800, VIDEOCLIPS_MAX_READ_BYTES);
149783
+ const declaredBytes = twin === "main" ? row.mainBytes : row.subBytes;
149784
+ if (declaredBytes !== void 0 && declaredBytes > bound) return refuse("too-large-to-transfer", `the camera lists the ${twin} file of clip "${clipId}" as ${declaredBytes} bytes, over the ${bound}-byte bound for an inline read — play it from its playback URL instead`, {
149785
+ clipKey,
149786
+ twin,
149787
+ declaredBytes,
149788
+ bound
149789
+ });
149790
+ const outcome = await deps.prepareBytes({
149791
+ deviceId,
149792
+ row,
149793
+ fileName,
149794
+ twin,
149795
+ ...wake !== void 0 ? { wake } : {}
149796
+ });
149797
+ if (outcome.kind === "refused") throw new Error(clipExportFailure(outcome.code, outcome.detail));
149798
+ if (outcome.bytes.byteLength > bound) return refuse("too-large-to-transfer", `clip "${clipId}" muxed to ${outcome.bytes.byteLength} bytes, over the ${bound}-byte bound for an inline read`, {
149799
+ clipKey,
149800
+ twin,
149801
+ bytes: outcome.bytes.byteLength,
149802
+ bound
149803
+ });
149804
+ deps.logger.info("videoclips: served a Reolink clip inline", {
149805
+ tags,
149806
+ meta: {
149807
+ clipId,
149808
+ clipKey,
149809
+ twin,
149810
+ served,
149811
+ asked: profile ?? null,
149812
+ bytes: outcome.bytes.byteLength,
149813
+ durationMs: outcome.durationMs,
149814
+ wake: wake ?? "none"
149815
+ }
149816
+ });
149817
+ return {
149818
+ base64: outcome.bytes.toString("base64"),
149819
+ contentType: "video/mp4",
149820
+ name: clipFileLabel(fileName),
149821
+ bytes: outcome.bytes.byteLength,
149822
+ served,
149823
+ ...outcome.durationMs !== null ? { durationMs: outcome.durationMs } : {}
149824
+ };
149353
149825
  }
149354
149826
  };
149355
149827
  /**
@@ -149611,6 +150083,12 @@ var ClipCatalogRefreshScheduler = class {
149611
150083
  lastRunAt = /* @__PURE__ */ new Map();
149612
150084
  /** Cameras whose refresh has not come back yet. */
149613
150085
  inFlight = /* @__PURE__ */ new Set();
150086
+ /** Consecutive prefetch passes this camera stopped on a refusal. Cleared by
150087
+ * the first pass that lands, so a camera that recovers is asked again on
150088
+ * the very next tick. */
150089
+ prefetchRefusals = /* @__PURE__ */ new Map();
150090
+ /** Until when this camera's prefetch stays un-asked. */
150091
+ prefetchQuietUntil = /* @__PURE__ */ new Map();
149614
150092
  constructor(deps) {
149615
150093
  this.deps = deps;
149616
150094
  }
@@ -149680,6 +150158,7 @@ var ClipCatalogRefreshScheduler = class {
149680
150158
  elapsedMs: this.deps.now() - now
149681
150159
  }
149682
150160
  });
150161
+ await this.prefetch(target, mode);
149683
150162
  } catch (err) {
149684
150163
  this.deps.markStale(target.deviceId);
149685
150164
  this.deps.logger.warn("videoclips: catalog refresh failed — the catalog stays as it was", {
@@ -149694,10 +150173,92 @@ var ClipCatalogRefreshScheduler = class {
149694
150173
  this.inFlight.delete(target.deviceId);
149695
150174
  }
149696
150175
  }
150176
+ /**
150177
+ * The still prefetch for a camera whose catalog was just re-read.
150178
+ *
150179
+ * It NEVER throws — a prefetch is an enhancement to a refresh that already
150180
+ * landed, and letting it reach the refresh's own catch would mark a catalog
150181
+ * stale that is not. Every exit says which branch it took, per camera.
150182
+ */
150183
+ async prefetch(target, mode) {
150184
+ const deviceId = target.deviceId;
150185
+ const tags = { deviceId };
150186
+ const quietUntil = this.prefetchQuietUntil.get(deviceId) ?? 0;
150187
+ const decision = decideClipPrefetch({
150188
+ mode,
150189
+ hostBusy: this.deps.hostBusy(target.hostKey),
150190
+ quiet: quietUntil > this.deps.now()
150191
+ });
150192
+ if (decision.kind === "skip") {
150193
+ this.deps.logger.info("videoclips: still prefetch skipped", {
150194
+ tags,
150195
+ meta: {
150196
+ branch: `prefetch-${decision.reason}`,
150197
+ mode,
150198
+ host: target.hostKey,
150199
+ quietForMs: Math.max(0, quietUntil - this.deps.now())
150200
+ }
150201
+ });
150202
+ return;
150203
+ }
150204
+ try {
150205
+ const outcome = await this.deps.prefetchStills(deviceId);
150206
+ if (outcome.stop === "refused") {
150207
+ this.quieten(target, {
150208
+ branch: "prefetch-refused",
150209
+ mode,
150210
+ minted: outcome.minted,
150211
+ scanned: outcome.scanned,
150212
+ alreadyHeld: outcome.alreadyHeld,
150213
+ code: outcome.refusal?.code ?? null,
150214
+ disposition: outcome.refusal?.disposition ?? null,
150215
+ clipKey: outcome.refusal?.clipKey ?? null
150216
+ });
150217
+ return;
150218
+ }
150219
+ this.prefetchRefusals.delete(deviceId);
150220
+ this.prefetchQuietUntil.delete(deviceId);
150221
+ this.deps.logger.info("videoclips: stills prefetched", {
150222
+ tags,
150223
+ meta: {
150224
+ branch: `prefetch-${outcome.stop}`,
150225
+ mode,
150226
+ minted: outcome.minted,
150227
+ scanned: outcome.scanned,
150228
+ alreadyHeld: outcome.alreadyHeld
150229
+ }
150230
+ });
150231
+ } catch (err) {
150232
+ this.quieten(target, {
150233
+ branch: "prefetch-failed",
150234
+ mode,
150235
+ error: errMessage$1(err)
150236
+ });
150237
+ }
150238
+ }
150239
+ /** Arm the doubling quiet period and say so, with what the pass reported. */
150240
+ quieten(target, meta) {
150241
+ const deviceId = target.deviceId;
150242
+ const refusals = (this.prefetchRefusals.get(deviceId) ?? 0) + 1;
150243
+ this.prefetchRefusals.set(deviceId, refusals);
150244
+ const quietForMs = prefetchQuietMs(refusals, target.intervalMinutes * 6e4);
150245
+ this.prefetchQuietUntil.set(deviceId, this.deps.now() + quietForMs);
150246
+ this.deps.logger.warn("videoclips: still prefetch stopped — the host is not serving stills", {
150247
+ tags: { deviceId },
150248
+ meta: {
150249
+ ...meta,
150250
+ host: target.hostKey,
150251
+ consecutiveRefusals: refusals,
150252
+ quietForMs
150253
+ }
150254
+ });
150255
+ }
149697
150256
  };
149698
150257
  function errMessage$1(err) {
149699
150258
  return err instanceof Error ? err.message : String(err);
149700
150259
  }
150260
+ //#endregion
150261
+ //#region src/clips/clip-service.ts
149701
150262
  function createClipService(deps) {
149702
150263
  const now = deps.now ?? (() => Date.now());
149703
150264
  const cache = new ClipCatalogCache({ now });
@@ -149720,8 +150281,15 @@ function createClipService(deps) {
149720
150281
  ffmpegBinaryPath: deps.ffmpegBinaryPath ?? "ffmpeg",
149721
150282
  spawnFn: node_child_process.spawn
149722
150283
  });
149723
- /** One prepare per clip: two clicks on one row must not pay cmd 5 twice. */
149724
- const preparing = /* @__PURE__ */ new Map();
150284
+ /**
150285
+ * One production per `(device, clip, twin)`: two clicks on one row — or a
150286
+ * click and an EXPORT of the same row — must not pay cmd 5 twice. It is
150287
+ * keyed by the twin because the two files are different bytes, and it is
150288
+ * shared by the player and the byte read because those two are the only
150289
+ * callers there are: an in-flight map per caller would be a second wake on
150290
+ * a battery camera the operator authorised once.
150291
+ */
150292
+ const producing = /* @__PURE__ */ new Map();
149725
150293
  const rowFor = (deviceId, clipKey) => {
149726
150294
  return cache.findBy(deviceId, (row) => row.clipKey === clipKey);
149727
150295
  };
@@ -149788,14 +150356,14 @@ function createClipService(deps) {
149788
150356
  * transfer, and that window is short. What makes it safe is not the window,
149789
150357
  * it is the decoded duration judged against the row that asked for it.
149790
150358
  */
149791
- const fetchVerifiedClipBytes = async (device, row, clipKey) => {
150359
+ const fetchVerifiedClipBytes = async (device, row, clipKey, fileName) => {
149792
150360
  const deviceId = device.deviceId;
149793
150361
  const api = await device.getApi();
149794
150362
  const fetchPass = (idleTimeoutMs) => fetchClipBytes({
149795
150363
  download: () => api.downloadRecordingDemuxed({
149796
150364
  channel: device.channel,
149797
150365
  ...device.uid !== void 0 ? { uid: device.uid } : {},
149798
- fileName: row.subFileName,
150366
+ fileName,
149799
150367
  idleTimeoutMs
149800
150368
  }),
149801
150369
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
@@ -149870,43 +150438,100 @@ function createClipService(deps) {
149870
150438
  });
149871
150439
  return kept;
149872
150440
  };
149873
- const prepareClip = async (deviceId, clipKey) => {
149874
- const ready = await media.pathIfPresent(deviceId, clipKey);
149875
- if (ready !== null) return ready;
149876
- const key = `${deviceId}|${clipKey}`;
149877
- const inFlight = preparing.get(key);
149878
- if (inFlight !== void 0) return inFlight;
149879
- const run = prepareClipOnce(deviceId, clipKey).finally(() => {
149880
- preparing.delete(key);
149881
- });
149882
- preparing.set(key, run);
149883
- return run;
149884
- };
149885
- const prepareClipOnce = async (deviceId, clipKey) => {
150441
+ /**
150442
+ * ONE production of one twin's MP4 — the only place a clip's bytes are made.
150443
+ *
150444
+ * The player and `readClipBytes` are both served from here, which is the
150445
+ * whole point: D568's completion rules (the 300 ms window, the decoded
150446
+ * duration proved against the row, the single retry on 2 000 ms) and D567's
150447
+ * mux (the MEASURED rate, the AAC copy, `+faststart`) exist once. A byte
150448
+ * read with its own fetch would be the second authority those records were
150449
+ * written to prevent.
150450
+ *
150451
+ * It never throws for a gated branch: every exit is a NAMED refusal in the
150452
+ * clip-export vocabulary, so the provider can hand the engine a token it
150453
+ * believes rather than prose it has to guess at (D572).
150454
+ */
150455
+ const produceTwin = async (input) => {
150456
+ const { deviceId, row, fileName, twin } = input;
150457
+ const clipKey = row.clipKey;
150458
+ const tags = { deviceId };
149886
150459
  const device = await deps.resolveDevice(deviceId);
149887
- if (device === null) return null;
150460
+ if (device === null) {
150461
+ deps.logger.warn("videoclips: no Reolink camera here to fetch this clip from", {
150462
+ tags,
150463
+ meta: {
150464
+ clipKey,
150465
+ twin,
150466
+ branch: "unknown-device"
150467
+ }
150468
+ });
150469
+ return {
150470
+ kind: "refused",
150471
+ code: "catalog-unreachable",
150472
+ detail: `device ${deviceId} is not a Reolink camera on this node`
150473
+ };
150474
+ }
149888
150475
  if (device.isBattery && device.sleeping && !device.isHubChild) {
149889
- deps.logger.warn("videoclips: refusing to fetch a clip from a sleeping camera", {
149890
- tags: { deviceId },
150476
+ if (input.wake !== "authorised") {
150477
+ deps.logger.warn("videoclips: refusing to fetch a clip from a sleeping camera", {
150478
+ tags,
150479
+ meta: {
150480
+ clipKey,
150481
+ twin,
150482
+ branch: "sleeping"
150483
+ }
150484
+ });
150485
+ return {
150486
+ kind: "refused",
150487
+ code: "sleeping",
150488
+ detail: `device ${deviceId} is a standalone battery camera and is sleeping — fetching a clip would wake it, and no operator authorisation was carried`
150489
+ };
150490
+ }
150491
+ deps.logger.warn("videoclips: waking a sleeping battery camera on an authorised clip read", {
150492
+ tags,
149891
150493
  meta: {
149892
150494
  clipKey,
149893
- branch: "sleeping"
150495
+ twin,
150496
+ branch: "wake-authorised"
149894
150497
  }
149895
150498
  });
149896
- return null;
149897
150499
  }
149898
- const row = rowFor(deviceId, clipKey);
149899
- if (row === null) {
149900
- deps.logger.warn("videoclips: no catalog row for this clip", {
149901
- tags: { deviceId },
150500
+ if (uidIsMissing(device)) {
150501
+ deps.logger.warn("videoclips: no uid for this camera — its clip cannot be addressed", {
150502
+ tags,
149902
150503
  meta: {
149903
150504
  clipKey,
149904
- branch: "no-catalog-row"
150505
+ twin,
150506
+ branch: "uid-missing"
149905
150507
  }
149906
150508
  });
149907
- return null;
150509
+ return {
150510
+ kind: "refused",
150511
+ code: "catalog-unreachable",
150512
+ detail: UID_MISSING_REASON
150513
+ };
150514
+ }
150515
+ let downloaded;
150516
+ try {
150517
+ downloaded = await fetchVerifiedClipBytes(device, row, clipKey, fileName);
150518
+ } catch (err) {
150519
+ const reason = err instanceof Error ? err.message : String(err);
150520
+ deps.logger.warn("videoclips: the camera never delivered this clip", {
150521
+ tags,
150522
+ meta: {
150523
+ clipKey,
150524
+ twin,
150525
+ branch: "camera-refused",
150526
+ error: reason
150527
+ }
150528
+ });
150529
+ return {
150530
+ kind: "refused",
150531
+ code: "camera-refused",
150532
+ detail: reason
150533
+ };
149908
150534
  }
149909
- const downloaded = await fetchVerifiedClipBytes(device, row, clipKey);
149910
150535
  const audio = decideClipAudio(downloaded.audio);
149911
150536
  if (audio.kind === "silent") deps.logger.warn("videoclips: serving a clip with no sound", {
149912
150537
  tags: { deviceId },
@@ -149950,14 +150575,24 @@ function createClipService(deps) {
149950
150575
  tags: { deviceId },
149951
150576
  meta: {
149952
150577
  clipKey,
150578
+ twin,
149953
150579
  branch: "mux-failed",
149954
150580
  error: failure
149955
150581
  }
149956
150582
  });
149957
- return null;
150583
+ return {
150584
+ kind: "refused",
150585
+ code: "fetch-failed",
150586
+ detail: failure
150587
+ };
149958
150588
  }
149959
150589
  const muxed = await (0, node_fs_promises.readFile)(outPath);
149960
- return await media.put(deviceId, clipKey, muxed);
150590
+ const decoded = downloaded.stats.durationSeconds;
150591
+ return {
150592
+ kind: "ok",
150593
+ bytes: muxed,
150594
+ durationMs: decoded !== null && Number.isFinite(decoded) && decoded > 0 ? Math.round(decoded * 1e3) : null
150595
+ };
149961
150596
  } finally {
149962
150597
  await (0, node_fs_promises.rm)(scratch, {
149963
150598
  recursive: true,
@@ -149965,6 +150600,85 @@ function createClipService(deps) {
149965
150600
  });
149966
150601
  }
149967
150602
  };
150603
+ /** {@link produceTwin}, deduplicated per `(device, clip, twin)`. */
150604
+ const produceOnce = (input) => {
150605
+ const key = `${input.deviceId}|${input.row.clipKey}|${input.twin}`;
150606
+ const inFlight = producing.get(key);
150607
+ if (inFlight !== void 0) return inFlight;
150608
+ const run = produceTwin(input).finally(() => {
150609
+ producing.delete(key);
150610
+ });
150611
+ producing.set(key, run);
150612
+ return run;
150613
+ };
150614
+ /**
150615
+ * The PLAYER's path: the sub twin, filed in the scratch, served by URL.
150616
+ *
150617
+ * `null` for every refusal — the playback route answers a status code and
150618
+ * has no vocabulary to carry a token; the named reason is already in the log
150619
+ * line `produceTwin` wrote.
150620
+ */
150621
+ const prepareClip = async (deviceId, clipKey) => {
150622
+ const ready = await media.pathIfPresent(deviceId, clipKey);
150623
+ if (ready !== null) return ready;
150624
+ const row = rowFor(deviceId, clipKey);
150625
+ if (row === null) {
150626
+ deps.logger.warn("videoclips: no catalog row for this clip", {
150627
+ tags: { deviceId },
150628
+ meta: {
150629
+ clipKey,
150630
+ branch: "no-catalog-row"
150631
+ }
150632
+ });
150633
+ return null;
150634
+ }
150635
+ const outcome = await produceOnce({
150636
+ deviceId,
150637
+ row,
150638
+ fileName: row.subFileName,
150639
+ twin: "sub"
150640
+ });
150641
+ if (outcome.kind !== "ok") return null;
150642
+ return media.put(deviceId, clipKey, outcome.bytes);
150643
+ };
150644
+ /**
150645
+ * The EXPORT's path: the asked twin's bytes, in memory, once.
150646
+ *
150647
+ * The scratch is the PLAYER's cache and its key
150648
+ * (`clipKeyFor(channel, subFileName)`) carries no twin, so it holds exactly
150649
+ * one thing: the sub file. A `sub` read therefore reuses it and warms it — a
150650
+ * clip the operator just watched costs no second cmd 5, and one he exports
150651
+ * first is already there when he plays it. A `main` read BYPASSES it in both
150652
+ * directions: writing a main file under that key would serve 33× the bytes
150653
+ * to every `low` playback of the clip, and filing it under a second key
150654
+ * would evict the sub clips the player really does re-read (10 files /
150655
+ * 200 MiB per device) to cache a one-shot export nobody reads twice.
150656
+ */
150657
+ const prepareBytes = async (input) => {
150658
+ const { deviceId, row, twin } = input;
150659
+ if (twin === "sub") {
150660
+ const cached = await media.read(deviceId, row.clipKey);
150661
+ if (cached !== null) {
150662
+ deps.logger.info("videoclips: a clip byte read was served from the scratch", {
150663
+ tags: { deviceId },
150664
+ meta: {
150665
+ clipKey: row.clipKey,
150666
+ twin,
150667
+ branch: "scratch-hit",
150668
+ bytes: cached.byteLength
150669
+ }
150670
+ });
150671
+ return {
150672
+ kind: "ok",
150673
+ bytes: cached,
150674
+ durationMs: null
150675
+ };
150676
+ }
150677
+ }
150678
+ const outcome = await produceOnce(input);
150679
+ if (outcome.kind === "ok" && twin === "sub") await media.put(deviceId, row.clipKey, outcome.bytes);
150680
+ return outcome;
150681
+ };
149968
150682
  const provider = createReolinkVideoclipsProvider({
149969
150683
  now,
149970
150684
  cache,
@@ -149976,6 +150690,7 @@ function createClipService(deps) {
149976
150690
  playbackUrl: `/addon/${REOLINK_ADDON_ID}/${CLIP_MEDIA_PREFIX}/${device.deviceId}/${clipKey}.mp4`,
149977
150691
  served: profile === "high" ? "high" : "low"
149978
150692
  }),
150693
+ prepareBytes,
149979
150694
  logger: deps.logger
149980
150695
  });
149981
150696
  return {
@@ -150002,15 +150717,36 @@ function createClipService(deps) {
150002
150717
  resolvePath: (deviceId, clipKey, _req) => prepareClip(deviceId, clipKey),
150003
150718
  logger: deps.logger
150004
150719
  }),
150005
- prefetchThumbnails: async (deviceId, limit = 20) => {
150006
- const rows = cache.allRows(deviceId).toSorted((a, b) => b.startMs - a.startMs).slice(0, limit);
150720
+ prefetchThumbnails: async (deviceId, limit = 60) => {
150721
+ const rows = cache.allRows(deviceId).toSorted((a, b) => b.startMs - a.startMs);
150007
150722
  let minted = 0;
150723
+ let scanned = 0;
150724
+ let alreadyHeld = 0;
150725
+ const outcome = (stop, refusal = null) => ({
150726
+ minted,
150727
+ scanned,
150728
+ alreadyHeld,
150729
+ stop,
150730
+ refusal
150731
+ });
150732
+ if (!await thumbs.hasHeadroomForPrefetch(deviceId)) return outcome("no-headroom");
150008
150733
  for (const row of rows) {
150009
- if (!await thumbs.hasHeadroomForPrefetch(deviceId)) break;
150010
- if (await thumbs.has(deviceId, row.clipKey)) continue;
150011
- if ((await mintThumbnail(deviceId, row.clipKey, "prefetch")).ok) minted += 1;
150734
+ scanned += 1;
150735
+ if (await thumbs.has(deviceId, row.clipKey)) {
150736
+ alreadyHeld += 1;
150737
+ continue;
150738
+ }
150739
+ if (minted >= limit) return outcome("budget");
150740
+ const result = await mintThumbnail(deviceId, row.clipKey, "prefetch");
150741
+ if (!result.ok) return outcome("refused", {
150742
+ code: result.code,
150743
+ disposition: result.disposition,
150744
+ clipKey: row.clipKey
150745
+ });
150746
+ minted += 1;
150747
+ if (minted % 16 === 0 && !await thumbs.hasHeadroomForPrefetch(deviceId)) return outcome("no-headroom");
150012
150748
  }
150013
- return minted;
150749
+ return outcome("rows-exhausted");
150014
150750
  }
150015
150751
  };
150016
150752
  }
@@ -150795,6 +151531,32 @@ var reolinkDebugActions = defineCustomActions({ debugRawRead: customAction(RawRe
150795
151531
  auth: "admin"
150796
151532
  }) });
150797
151533
  //#endregion
151534
+ //#region src/device-meta-uid.ts
151535
+ function asDeviceMetaApi(api) {
151536
+ return typeof api === "object" && api !== null ? api : void 0;
151537
+ }
151538
+ function metadataUidOf(device) {
151539
+ if (typeof device !== "object" || device === null) return void 0;
151540
+ const metadata = device.metadata;
151541
+ if (typeof metadata !== "object" || metadata === null) return void 0;
151542
+ const uid = metadata.uid;
151543
+ return typeof uid === "string" ? uid : void 0;
151544
+ }
151545
+ /**
151546
+ * This device's `metadata.uid`, or `undefined` for every way of not having
151547
+ * one — absent, not a string, the RPC refused, the route missing. Never
151548
+ * throws.
151549
+ */
151550
+ async function readDeviceMetaUid(api, deviceId) {
151551
+ const query = asDeviceMetaApi(api)?.deviceManager?.getDevice?.query;
151552
+ if (query === void 0) return void 0;
151553
+ try {
151554
+ return metadataUidOf(await query({ deviceId }));
151555
+ } catch {
151556
+ return;
151557
+ }
151558
+ }
151559
+ //#endregion
150798
151560
  //#region src/battery-charging.ts
150799
151561
  /**
150800
151562
  * Da `adapterStatus` + `chargeStatus` alla sorgente di alimentazione.
@@ -154784,6 +155546,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
154784
155546
  meta: { error: err instanceof Error ? err.message : String(err) }
154785
155547
  });
154786
155548
  });
155549
+ this.metadataUid = await readDeviceMetaUid(this.ctx.api, this.id);
154787
155550
  await this.refreshNetworkLinkFromApi(api, "probe");
154788
155551
  }
154789
155552
  /**
@@ -155232,12 +155995,24 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
155232
155995
  async wakeForClipCatalogRefresh() {
155233
155996
  if (!await this.wakeIfSleeping()) throw new Error(`ReolinkCamera ${this.id}: the authorised clip-refresh wake did not bring the camera up`);
155234
155997
  }
155998
+ /**
155999
+ * `deviceMeta.metadata.uid`, read once per addon start in {@link onProbe}.
156000
+ *
156001
+ * In memory, never persisted: a third copy of a fact the device manager
156002
+ * already owns is the very thing that produced this defect (D224). A
156003
+ * physical camera's uid does not change, so one read per process is enough,
156004
+ * and until it lands the adoption copy is what answers.
156005
+ */
156006
+ metadataUid = void 0;
155235
156007
  getClipDeviceRef() {
155236
- const uid = this.config.get("uid");
156008
+ const configUid = this.config.get("uid");
155237
156009
  return {
155238
156010
  deviceId: this.id,
155239
156011
  channel: this.getChannel(),
155240
- uid: typeof uid === "string" && uid.length > 0 ? uid : void 0,
156012
+ uid: resolveCameraUid({
156013
+ metadataUid: this.metadataUid,
156014
+ configUid: typeof configUid === "string" ? configUid : void 0
156015
+ }),
155241
156016
  isHubChild: this.isHubChild(),
155242
156017
  isBattery: this.isBattery,
155243
156018
  sleeping: this.sleeping,
@@ -164149,6 +164924,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
164149
164924
  if (!(device instanceof ReolinkCamera)) throw new Error(`clip refresh: device ${String(deviceId)} is not a Reolink camera here`);
164150
164925
  await device.wakeForClipCatalogRefresh();
164151
164926
  },
164927
+ prefetchStills: async (deviceId) => service.prefetchThumbnails(deviceId),
164152
164928
  hostBusy: (hostKey) => service.hostBusy(hostKey),
164153
164929
  logger: this.ctx.logger
164154
164930
  });