@valbuild/server 0.140.0 → 0.141.0

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.
@@ -20,6 +20,7 @@ var net = require('node:net');
20
20
  var sizeOf = require('image-size');
21
21
  var zodValidationError = require('zod-validation-error');
22
22
  var os = require('os');
23
+ var buffer = require('buffer');
23
24
  var sucrase = require('sucrase');
24
25
  var http$1 = require('http');
25
26
  var https$1 = require('https');
@@ -3218,6 +3219,291 @@ function readableError(error) {
3218
3219
  }
3219
3220
  }
3220
3221
 
3222
+ /**
3223
+ * The `Range` request header, for the one route that serves bytes a player
3224
+ * seeks in: `/files`.
3225
+ *
3226
+ * A `<video>` element asks for ranges as a matter of course, and Safari will
3227
+ * not play a video at all from a server that does not answer them. An HLS
3228
+ * stream whose segments are byte ranges of one file (`#EXT-X-BYTERANGE`) asks
3229
+ * for nothing else.
3230
+ *
3231
+ * Only a single range is honoured. A multi-range request (`bytes=0-1,5-6`) is
3232
+ * answered with the whole file, which RFC 9110 permits, and nothing that plays
3233
+ * media sends one. A header that does not parse is ignored the same way.
3234
+ */
3235
+
3236
+ function parseRangeHeader(header, size) {
3237
+ if (!header) {
3238
+ return {
3239
+ kind: "none"
3240
+ };
3241
+ }
3242
+ const match = /^\s*bytes\s*=\s*(.*)$/i.exec(header);
3243
+ if (!match) {
3244
+ return {
3245
+ kind: "none"
3246
+ };
3247
+ }
3248
+ const spec = match[1].trim();
3249
+ if (spec.includes(",")) {
3250
+ return {
3251
+ kind: "none"
3252
+ };
3253
+ }
3254
+ const suffix = /^-(\d+)$/.exec(spec);
3255
+ if (suffix) {
3256
+ const length = Number(suffix[1]);
3257
+ if (length === 0 || size === 0) {
3258
+ return {
3259
+ kind: "unsatisfiable"
3260
+ };
3261
+ }
3262
+ return {
3263
+ kind: "range",
3264
+ start: Math.max(0, size - length),
3265
+ end: size - 1
3266
+ };
3267
+ }
3268
+ const bounded = /^(\d+)-(\d*)$/.exec(spec);
3269
+ if (!bounded) {
3270
+ return {
3271
+ kind: "none"
3272
+ };
3273
+ }
3274
+ const start = Number(bounded[1]);
3275
+ const end = bounded[2] === "" ? undefined : Number(bounded[2]);
3276
+ if (end !== undefined && end < start) {
3277
+ // Syntactically invalid (RFC 9110 §14.1.1): ignored, not refused.
3278
+ return {
3279
+ kind: "none"
3280
+ };
3281
+ }
3282
+ if (start >= size) {
3283
+ return {
3284
+ kind: "unsatisfiable"
3285
+ };
3286
+ }
3287
+ return {
3288
+ kind: "range",
3289
+ start,
3290
+ end: Math.min(end ?? size - 1, size - 1)
3291
+ };
3292
+ }
3293
+
3294
+ /**
3295
+ * The little of HLS (RFC 8216) the server has to read: the variants of a
3296
+ * master playlist, the segment durations of a media playlist, and every URI a
3297
+ * playlist names.
3298
+ *
3299
+ * Deliberately a line scanner rather than a parser. The playlists Val reads are
3300
+ * the ones the Studio wrote, and the questions asked of them are small — "how
3301
+ * big is the largest rendition", "how long is it", "where does each URI
3302
+ * point" — so a full model of the format would be code nothing exercises.
3303
+ */
3304
+
3305
+ /** One `#EXT-X-STREAM-INF` entry of a master playlist. */
3306
+
3307
+ /** Lines of a playlist, with Windows line endings tolerated. */
3308
+ function linesOf(text) {
3309
+ return text.split(/\r?\n/);
3310
+ }
3311
+
3312
+ /**
3313
+ * The attributes of a tag, e.g. the part after `#EXT-X-STREAM-INF:`.
3314
+ *
3315
+ * Quoted values may contain commas (`CODECS="avc1.64001f,mp4a.40.2"`), which
3316
+ * is why this is not a `split(",")`. Quotes are removed from the values.
3317
+ */
3318
+ function parseHlsAttributes(list) {
3319
+ const attributes = {};
3320
+ const re = /([A-Z0-9-]+)=("[^"]*"|[^,]*)/g;
3321
+ let match;
3322
+ while ((match = re.exec(list)) !== null) {
3323
+ const [, name, rawValue] = match;
3324
+ attributes[name] = rawValue.startsWith('"') && rawValue.endsWith('"') ? rawValue.slice(1, -1) : rawValue.trim();
3325
+ }
3326
+ return attributes;
3327
+ }
3328
+
3329
+ /** Whether a playlist is a master (multivariant) playlist. */
3330
+ function isHlsMasterPlaylist(text) {
3331
+ return linesOf(text).some(line => line.trim().startsWith("#EXT-X-STREAM-INF:"));
3332
+ }
3333
+
3334
+ /** The variants of a master playlist, in the order they are listed. */
3335
+ function parseHlsMasterVariants(text) {
3336
+ const variants = [];
3337
+ let pending = null;
3338
+ for (const rawLine of linesOf(text)) {
3339
+ const line = rawLine.trim();
3340
+ if (line === "") {
3341
+ continue;
3342
+ }
3343
+ if (line.startsWith("#EXT-X-STREAM-INF:")) {
3344
+ const attributes = parseHlsAttributes(line.slice("#EXT-X-STREAM-INF:".length));
3345
+ const variant = {};
3346
+ const bandwidth = Number(attributes["BANDWIDTH"]);
3347
+ if (attributes["BANDWIDTH"] !== undefined && Number.isFinite(bandwidth)) {
3348
+ variant.bandwidth = bandwidth;
3349
+ }
3350
+ const resolution = /^(\d+)x(\d+)$/.exec(attributes["RESOLUTION"] ?? "");
3351
+ if (resolution) {
3352
+ variant.width = Number(resolution[1]);
3353
+ variant.height = Number(resolution[2]);
3354
+ }
3355
+ pending = variant;
3356
+ continue;
3357
+ }
3358
+ if (line.startsWith("#")) {
3359
+ continue;
3360
+ }
3361
+ // The URI line that follows a STREAM-INF tag belongs to it.
3362
+ if (pending) {
3363
+ variants.push({
3364
+ ...pending,
3365
+ uri: line
3366
+ });
3367
+ pending = null;
3368
+ }
3369
+ }
3370
+ return variants;
3371
+ }
3372
+
3373
+ /**
3374
+ * The variant whose dimensions describe the video: the largest picture, and
3375
+ * among equally large ones the highest bandwidth. `undefined` when no variant
3376
+ * declares a `RESOLUTION`.
3377
+ */
3378
+ function largestHlsVariant(variants) {
3379
+ let best;
3380
+ for (const variant of variants) {
3381
+ const {
3382
+ width,
3383
+ height
3384
+ } = variant;
3385
+ if (width === undefined || height === undefined) {
3386
+ continue;
3387
+ }
3388
+ if (!best || width * height > best.width * best.height || width * height === best.width * best.height && (variant.bandwidth ?? 0) > (best.bandwidth ?? 0)) {
3389
+ best = {
3390
+ ...variant,
3391
+ width,
3392
+ height
3393
+ };
3394
+ }
3395
+ }
3396
+ return best;
3397
+ }
3398
+
3399
+ /**
3400
+ * The sum of a media playlist's `#EXTINF` durations, in seconds, or
3401
+ * `undefined` when it has none (a master playlist, or not a playlist).
3402
+ */
3403
+ function sumHlsSegmentDurations(text) {
3404
+ let total = 0;
3405
+ let found = false;
3406
+ for (const rawLine of linesOf(text)) {
3407
+ const line = rawLine.trim();
3408
+ if (!line.startsWith("#EXTINF:")) {
3409
+ continue;
3410
+ }
3411
+ const seconds = Number.parseFloat(line.slice("#EXTINF:".length));
3412
+ if (Number.isFinite(seconds)) {
3413
+ total += seconds;
3414
+ found = true;
3415
+ }
3416
+ }
3417
+ return found ? total : undefined;
3418
+ }
3419
+
3420
+ /**
3421
+ * Rewrite every URI a playlist names, leaving everything else byte for byte.
3422
+ *
3423
+ * URIs are the non-comment lines (segments, variant playlists) and the `URI`
3424
+ * attribute of tags such as `#EXT-X-MAP` and `#EXT-X-MEDIA`. Line endings are
3425
+ * kept as they were.
3426
+ */
3427
+ function mapHlsUris(text, map) {
3428
+ return text.split(/(\r?\n)/).map(part => {
3429
+ if (part === "\n" || part === "\r\n") {
3430
+ return part;
3431
+ }
3432
+ const trimmed = part.trim();
3433
+ if (trimmed === "") {
3434
+ return part;
3435
+ }
3436
+ if (trimmed.startsWith("#")) {
3437
+ // Only an attribute that is exactly `URI` — preceded by the tag's
3438
+ // colon or a comma — and not, say, a `KEYFORMAT-URI` lookalike.
3439
+ return part.replace(/([:,]\s*)URI="([^"]*)"/g, (_match, before, uri) => `${before}URI="${map(uri)}"`);
3440
+ }
3441
+ const leading = part.slice(0, part.indexOf(trimmed));
3442
+ const trailing = part.slice(part.indexOf(trimmed) + trimmed.length);
3443
+ return `${leading}${map(trimmed)}${trailing}`;
3444
+ }).join("");
3445
+ }
3446
+
3447
+ /**
3448
+ * An HLS playlist served as a DRAFT, with every URI in it pointed at the draft
3449
+ * endpoint.
3450
+ *
3451
+ * Why this exists: a draft is served from `/api/val/files<path>?patch_id=…`,
3452
+ * and a player resolves the playlist's URIs against that URL. A RELATIVE URI
3453
+ * (`720p.m3u8`, how a local stream is written so it works wherever the
3454
+ * directory is served from) resolves to `/api/val/files/public/val/x/720p.m3u8`
3455
+ * — the query string is dropped by URL resolution, so the `patch_id` is gone,
3456
+ * and the endpoint looks for a PUBLISHED file that does not exist yet. An
3457
+ * ABSOLUTE remote ref (how a remote stream is written, because the content host
3458
+ * addresses files by hash) points at the content host, which has nothing until
3459
+ * publish. Either way the master plays and nothing it names does.
3460
+ *
3461
+ * So each URI is rewritten to the URL `Internal.mediaUrl` gives the same file
3462
+ * as a draft. Every file of one upload is in the same patch, so they share the
3463
+ * `patch_id` the playlist itself was requested with.
3464
+ *
3465
+ * What is NOT rewritten, and why:
3466
+ * - an absolute URL that is not a Val remote ref (another host's stream): it
3467
+ * was never in a patch;
3468
+ * - a root-relative URI (`/val/x/720p.mp4`): the Studio never writes one, and
3469
+ * it already names a published URL, so it is not this function's to guess at.
3470
+ *
3471
+ * Pure, and the whole rule: the `/files` route calls it and nothing else.
3472
+ */
3473
+ function rewriteDraftPlaylist(playlist, options) {
3474
+ return mapHlsUris(playlist, uri => rewriteUri(uri, options));
3475
+ }
3476
+ function rewriteUri(uri, {
3477
+ playlistPath,
3478
+ patchId,
3479
+ remote
3480
+ }) {
3481
+ if (core.Internal.remote.splitRemoteRef(uri).status === "success") {
3482
+ return core.Internal.mediaUrl({
3483
+ path: uri,
3484
+ patch_id: patchId
3485
+ });
3486
+ }
3487
+ if (/^[a-z][a-z0-9+.-]*:/i.test(uri) || uri.startsWith("/")) {
3488
+ // Another scheme (https:, data:, …), protocol-relative or root-relative.
3489
+ return uri;
3490
+ }
3491
+ // The query and fragment of a relative URI address the published file; the
3492
+ // draft endpoint has its own query, and fragments do not reach a server.
3493
+ const relative = uri.split(/[?#]/)[0];
3494
+ if (relative === "") {
3495
+ return uri;
3496
+ }
3497
+ // `join` from an absolute directory stays absolute: `..` stops at the root.
3498
+ const resolved = path__namespace["default"].posix.join(path__namespace["default"].posix.dirname(playlistPath), relative);
3499
+ return `/api/val/files${resolved}?patch_id=${patchId}${remote ? "&remote=true" : ""}`;
3500
+ }
3501
+
3502
+ /** Whether a served file is an HLS playlist, by its extension. */
3503
+ function isHlsPlaylistPath(filePath) {
3504
+ return filePath.split("?")[0].toLowerCase().endsWith(".m3u8");
3505
+ }
3506
+
3221
3507
  /* eslint-disable @typescript-eslint/no-unused-vars */
3222
3508
  const jsonOps = new patch.JSONOps();
3223
3509
  /**
@@ -4041,9 +4327,20 @@ class ValOps {
4041
4327
  // when constructing the url we use the patch id (and the file path)
4042
4328
  // to fetch the right file
4043
4329
  // NOTE: overwrite and use last patch_id if multiple patches modify the same file
4044
- fileFixOps[op.path.join("/")] = [{
4330
+ //
4331
+ // Keyed by where the patch_id LANDS — the field's path plus
4332
+ // `nestedFilePath` — not by the field's path alone. A video's
4333
+ // poster and caption files are file ops on the video's own path
4334
+ // with `nestedFilePath` ["poster"] / ["captions", "0"]; keyed by
4335
+ // `op.path` they overwrote the video's entry (and each other),
4336
+ // so only one of the files got a patch_id and the rest were
4337
+ // looked for at a published URL that holds nothing. JSON rather
4338
+ // than a "/" join because a segment can contain "/" (a gallery
4339
+ // key is a file path).
4340
+ const patchIdPath = op.path.concat(...(op.nestedFilePath || [])).concat("patch_id");
4341
+ fileFixOps[JSON.stringify(patchIdPath)] = [{
4045
4342
  op: "add",
4046
- path: op.path.concat(...(op.nestedFilePath || [])).concat("patch_id"),
4343
+ path: patchIdPath,
4047
4344
  value: patchId
4048
4345
  }];
4049
4346
  }
@@ -4241,7 +4538,7 @@ class ValOps {
4241
4538
  };
4242
4539
  if (validationErrors) {
4243
4540
  for (const validationError of validationErrors) {
4244
- var _validationError$fixe, _validationError$fixe2, _validationError$fixe3, _validationError$fixe4, _validationError$fixe5, _validationError$fixe6;
4541
+ var _validationError$fixe, _validationError$fixe2, _validationError$fixe3, _validationError$fixe4, _validationError$fixe5, _validationError$fixe6, _validationError$fixe7, _validationError$fixe8;
4245
4542
  if (isOnlyFileCheckValidationError(validationError)) {
4246
4543
  if (files[sourcePath]) {
4247
4544
  addError({
@@ -4261,7 +4558,7 @@ class ValOps {
4261
4558
  addError(resolved.error);
4262
4559
  }
4263
4560
  // resolved.status === "resolved" → drop silently
4264
- } else if ((_validationError$fixe3 = validationError.fixes) !== null && _validationError$fixe3 !== void 0 && _validationError$fixe3.includes("images:check-unique-folder") || (_validationError$fixe4 = validationError.fixes) !== null && _validationError$fixe4 !== void 0 && _validationError$fixe4.includes("files:check-unique-folder")) {
4561
+ } else if ((_validationError$fixe3 = validationError.fixes) !== null && _validationError$fixe3 !== void 0 && _validationError$fixe3.includes("images:check-unique-folder") || (_validationError$fixe4 = validationError.fixes) !== null && _validationError$fixe4 !== void 0 && _validationError$fixe4.includes("files:check-unique-folder") || (_validationError$fixe5 = validationError.fixes) !== null && _validationError$fixe5 !== void 0 && _validationError$fixe5.includes("videos:check-unique-folder")) {
4265
4562
  const TYPE_ERROR_MESSAGE = `This is most likely a Val version mismatch or Val bug.`;
4266
4563
  if (!validationError.value || typeof validationError.value !== "object") {
4267
4564
  addError({
@@ -4286,7 +4583,7 @@ class ValOps {
4286
4583
  // If conflictingModules is empty, directory is unique — silently drop the error.
4287
4584
  }
4288
4585
  }
4289
- } else if ((_validationError$fixe5 = validationError.fixes) !== null && _validationError$fixe5 !== void 0 && _validationError$fixe5.includes("images:check-all-files") || (_validationError$fixe6 = validationError.fixes) !== null && _validationError$fixe6 !== void 0 && _validationError$fixe6.includes("files:check-all-files")) ; else {
4586
+ } else if ((_validationError$fixe6 = validationError.fixes) !== null && _validationError$fixe6 !== void 0 && _validationError$fixe6.includes("images:check-all-files") || (_validationError$fixe7 = validationError.fixes) !== null && _validationError$fixe7 !== void 0 && _validationError$fixe7.includes("files:check-all-files") || (_validationError$fixe8 = validationError.fixes) !== null && _validationError$fixe8 !== void 0 && _validationError$fixe8.includes("videos:check-all-files")) ; else {
4290
4587
  addError(validationError);
4291
4588
  }
4292
4589
  }
@@ -5391,6 +5688,19 @@ class ValOps {
5391
5688
  async saveBinaryFileFromPatch(filePath, parentRef, patchId, bytes, mimeType, type, metadata) {
5392
5689
  return this.saveBase64EncodedBinaryFileFromPatch(filePath, parentRef, patchId, `data:${mimeType};base64,${bytes.toString("base64")}`, type, metadata);
5393
5690
  }
5691
+ /**
5692
+ * A file's bytes as something a `Range` request can be answered from
5693
+ * without reading the rest: a video is seeked in by many small ranges, and
5694
+ * each used to load the whole file.
5695
+ *
5696
+ * This default holds the whole file, which is all a mode that only gets
5697
+ * whole files can do (`ValOpsHttp`: the content service answers with the
5698
+ * file in a JSON body). `ValOpsFS` reads only the asked-for range off disk.
5699
+ */
5700
+ async openBinaryFile(filePath, fromPatch) {
5701
+ const buffer = fromPatch ? await this.getBase64EncodedBinaryFileFromPatch(filePath, fromPatch.patchId, fromPatch.remote) : await this.getBinaryFile(filePath);
5702
+ return buffer === null ? null : bufferReader(buffer);
5703
+ }
5394
5704
 
5395
5705
  // #region history
5396
5706
  //
@@ -5441,8 +5751,8 @@ class ValOps {
5441
5751
  // #endregion history
5442
5752
  }
5443
5753
  function isOnlyFileCheckValidationError(validationError) {
5444
- var _validationError$fixe7;
5445
- if ((_validationError$fixe7 = validationError.fixes) !== null && _validationError$fixe7 !== void 0 && _validationError$fixe7.every(f => f === "file:check-metadata" || f === "image:check-metadata")) {
5754
+ var _validationError$fixe9;
5755
+ if ((_validationError$fixe9 = validationError.fixes) !== null && _validationError$fixe9 !== void 0 && _validationError$fixe9.every(f => f === "file:check-metadata" || f === "image:check-metadata")) {
5446
5756
  return true;
5447
5757
  }
5448
5758
  return false;
@@ -5632,6 +5942,15 @@ function bufferFromDataUrl(dataUrl) {
5632
5942
  }
5633
5943
  }
5634
5944
 
5945
+ /** A file of known size whose bytes are read a range at a time. */
5946
+
5947
+ function bufferReader(buffer) {
5948
+ return {
5949
+ size: buffer.length,
5950
+ read: async (start, end) => buffer.subarray(start, end + 1)
5951
+ };
5952
+ }
5953
+
5635
5954
  /**
5636
5955
  * The `*.val.json` files backing a `.jsonValues()` module's entries, as paths
5637
5956
  * relative to the project root.
@@ -8066,6 +8385,26 @@ class ValOpsFS extends ValOps {
8066
8385
  errors
8067
8386
  };
8068
8387
  }
8388
+ async openBinaryFile(filePath, fromPatch) {
8389
+ let absPath;
8390
+ if (fromPatch) {
8391
+ const patchesDir = this.getPatchesDir();
8392
+ absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, fromPatch.patchId, filePath), stagedPatchBinaryFile(patchesDir, fromPatch.patchId, filePath));
8393
+ } else {
8394
+ absPath = path__namespace["default"].join(this.rootDir, ...filePath.split("/"));
8395
+ if (!this.host.fileExists(absPath)) {
8396
+ absPath = null;
8397
+ }
8398
+ }
8399
+ if (absPath === null) {
8400
+ return null;
8401
+ }
8402
+ const path = absPath;
8403
+ return {
8404
+ size: this.host.binaryFileSize(path),
8405
+ read: async (start, end) => this.host.readBinaryFileRange(path, start, end)
8406
+ };
8407
+ }
8069
8408
  async getBinaryFile(filePath) {
8070
8409
  const absPath = path__namespace["default"].join(this.rootDir, ...filePath.split("/"));
8071
8410
  if (!this.host.fileExists(absPath)) {
@@ -8188,6 +8527,30 @@ class FSOpsHost {
8188
8527
  readBinaryFile(path) {
8189
8528
  return fs__default["default"].readFileSync(path);
8190
8529
  }
8530
+ binaryFileSize(path) {
8531
+ return fs__default["default"].statSync(path).size;
8532
+ }
8533
+
8534
+ /** Bytes `start` to `end` inclusive, and only those, read off disk. */
8535
+ async readBinaryFileRange(path, start, end) {
8536
+ const handle = await fs__default["default"].promises.open(path, "r");
8537
+ try {
8538
+ const buffer$1 = buffer.Buffer.alloc(Math.max(0, end - start + 1));
8539
+ let filled = 0;
8540
+ while (filled < buffer$1.length) {
8541
+ const {
8542
+ bytesRead
8543
+ } = await handle.read(buffer$1, filled, buffer$1.length - filled, start + filled);
8544
+ if (bytesRead === 0) {
8545
+ break;
8546
+ }
8547
+ filled += bytesRead;
8548
+ }
8549
+ return buffer$1.subarray(0, filled);
8550
+ } finally {
8551
+ await handle.close();
8552
+ }
8553
+ }
8191
8554
  readUtf8File(path) {
8192
8555
  return fs__default["default"].readFileSync(path, "utf-8");
8193
8556
  }
@@ -8489,6 +8852,8 @@ const GetApplicablePatches = z.z.object({
8489
8852
  * Optional for the same reason.
8490
8853
  */
8491
8854
  headVersion: z.z.number().optional(),
8855
+ /** Of `patches`, the ones a running publish holds. See `OrderedPatches.publishingPatches`. */
8856
+ publishingPatches: z.z.array(internal.PatchId).optional(),
8492
8857
  commits: z.z.array(z.z.object({
8493
8858
  commitSha: z.z.string(),
8494
8859
  /*
@@ -9373,6 +9738,13 @@ class ValOpsHttp extends ValOps {
9373
9738
  deployments: allPatchData.deployments || [],
9374
9739
  patches,
9375
9740
  appliedPatches,
9741
+ /*
9742
+ * Absent, not empty, from a content service that does not say: an empty
9743
+ * list would claim no publish is running when it cannot know.
9744
+ */
9745
+ ...(allPatchData.publishingPatches !== undefined ? {
9746
+ publishingPatches: allPatchData.publishingPatches
9747
+ } : {}),
9376
9748
  /*
9377
9749
  * The CHAIN head, not the publish head below. Spread: absent is a content
9378
9750
  * service that does not report it, which is not the same as `null`.
@@ -9740,6 +10112,9 @@ class ValOpsHttp extends ValOps {
9740
10112
  } : {}),
9741
10113
  ...(data.headVersion !== undefined ? {
9742
10114
  headVersion: data.headVersion
10115
+ } : {}),
10116
+ ...(data.publishingPatches !== undefined ? {
10117
+ publishingPatches: data.publishingPatches
9743
10118
  } : {})
9744
10119
  };
9745
10120
  }
@@ -12317,6 +12692,15 @@ const DEFAULT_VAL_BUILD_URL = "https://admin.val.build";
12317
12692
  */
12318
12693
  const VAL_APP_ENV = "app";
12319
12694
 
12695
+ /**
12696
+ * What the Val app says when a project does not store its media remotely.
12697
+ *
12698
+ * Exported so that `val publish` -- which publishes to the app, and so is
12699
+ * the last place to catch this before a build goes out -- refuses with the
12700
+ * same sentence the deployed server would.
12701
+ */
12702
+ const APP_MODE_REQUIRES_REMOTE_FILES = "This project runs in the Val app, which stores every image, file and " + "video on Val's remote content host -- there is no repository for an " + "upload to go into. Add `files: { remote: true }` to `initVal` in " + "val.config.ts, so that `s.image()`, `s.file()`, `s.video()` and the " + "sets are remote everywhere this project is read. Images already in the " + "project then fail validation until they are uploaded: `npx val validate " + "--fix` does that.";
12703
+
12320
12704
  /** Which mode the environment SAYS this is, and which variable said so. */
12321
12705
 
12322
12706
  /**
@@ -12463,7 +12847,7 @@ async function initHandlerOptions(route, opts, config) {
12463
12847
  valContentUrl
12464
12848
  });
12465
12849
  if (isProxyMode) {
12466
- var _opts$versions, _opts$versions2;
12850
+ var _config$files, _opts$versions, _opts$versions2;
12467
12851
  /*
12468
12852
  * Why this app is in http mode, in the message that says what is missing.
12469
12853
  *
@@ -12516,6 +12900,27 @@ async function initHandlerOptions(route, opts, config) {
12516
12900
  if (!maybeValProject) {
12517
12901
  throw new Error("Proxy mode does not work unless the 'project' option in val.config is defined or the VAL_PROJECT env var is set." + because);
12518
12902
  }
12903
+ /*
12904
+ * The Val app has no repository for an uploaded file to go into, so every
12905
+ * image, file and video in it is remote -- and the project has to SAY so,
12906
+ * in `val.config.ts`, rather than this server deciding it.
12907
+ *
12908
+ * Deciding it here would be easy and wrong. The schemas are built when
12909
+ * `val.config.ts` and the modules are evaluated, before this function
12910
+ * sees anything, and the same file is evaluated by `val validate`, the VS
12911
+ * Code extension and `pnpm dev`. A switch only the app could see would
12912
+ * leave every one of those reading the project's media as local: every
12913
+ * remote image reported as a mistake, and `val validate --fix` downloading
12914
+ * it back into the repository.
12915
+ *
12916
+ * So this refuses rather than covers for it. Without the check, the
12917
+ * failure is quieter and later: a local upload that the app has nowhere
12918
+ * to put, found at a publish.
12919
+ */
12920
+ // `config?.`: `initVal()` with no argument hands back no config at all.
12921
+ if (isAppEnv && (config === null || config === void 0 || (_config$files = config.files) === null || _config$files === void 0 ? void 0 : _config$files.remote) !== true) {
12922
+ throw new Error(APP_MODE_REQUIRES_REMOTE_FILES);
12923
+ }
12519
12924
  const coreVersion = (_opts$versions = opts.versions) === null || _opts$versions === void 0 ? void 0 : _opts$versions.core;
12520
12925
  if (!coreVersion) {
12521
12926
  throw new Error("Could not determine version of @valbuild/core");
@@ -12848,6 +13253,12 @@ async function resolveRemoteFileAuth(options) {
12848
13253
 
12849
13254
  /** What a publish reports back, in either shape. */
12850
13255
 
13256
+ /**
13257
+ * Where a local file a publish commits is written. Fixed: it was configurable
13258
+ * (`files.directory` in val.config.ts), nobody configured it, and the schemas
13259
+ * have their own `dir` for any collection that wants somewhere else.
13260
+ */
13261
+ const FILES_DIRECTORY = "/public/val";
12851
13262
  const ValServer = (valModules, options, callbacks) => {
12852
13263
  var _options$git;
12853
13264
  const AIContentBlock = z.z.union([z.z.object({
@@ -14864,7 +15275,6 @@ const ValServer = (valModules, options, callbacks) => {
14864
15275
  },
14865
15276
  "/publish-job-prepare": {
14866
15277
  POST: async req => {
14867
- var _options$config$files2;
14868
15278
  const auth = getAuth(req.cookies);
14869
15279
  if (auth.error) {
14870
15280
  return {
@@ -14911,7 +15321,6 @@ const ValServer = (valModules, options, callbacks) => {
14911
15321
  * push either way.
14912
15322
  */
14913
15323
  if (serverOps.sourceMode() === "connected") {
14914
- var _options$config$files;
14915
15324
  const jobPatches = await serverOps.fetchPatches({
14916
15325
  patchIds,
14917
15326
  excludePatchOps: false
@@ -14964,7 +15373,7 @@ const ValServer = (valModules, options, callbacks) => {
14964
15373
  const deploymentFiles = commit === undefined ? await serverOps.embeddedValSourceShas() : null;
14965
15374
  const sent = await serverOps.prepareJob(jobId, {
14966
15375
  tab,
14967
- filesDirectory: ((_options$config$files = options.config.files) === null || _options$config$files === void 0 ? void 0 : _options$config$files.directory) || "/public/val",
15376
+ filesDirectory: FILES_DIRECTORY,
14968
15377
  ...split.archive,
14969
15378
  ...(commit !== undefined ? {
14970
15379
  gitCommit: commit
@@ -14993,7 +15402,7 @@ const ValServer = (valModules, options, callbacks) => {
14993
15402
  } = built;
14994
15403
  const sent = await serverOps.prepareJob(jobId, {
14995
15404
  tab,
14996
- filesDirectory: ((_options$config$files2 = options.config.files) === null || _options$config$files2 === void 0 ? void 0 : _options$config$files2.directory) || "/public/val",
15405
+ filesDirectory: FILES_DIRECTORY,
14997
15406
  ...split.archive
14998
15407
  });
14999
15408
  return jobPrepareAnswer(sent, {
@@ -15481,17 +15890,14 @@ const ValServer = (valModules, options, callbacks) => {
15481
15890
  */
15482
15891
  const managedBranch = serverOps.sourceMode() === "managed" ? serverOps.projectBranch() : null;
15483
15892
  const committedBinaries = serverOps.sourceMode() === "managed" ? await readCommittedBinaryFiles(serverOps, preparedCommit.patchedBinaryFilesDescriptors) : null;
15484
- const commitToGit = () => {
15485
- var _options$config$files3;
15486
- return serverOps.commit(preparedCommit, message, auth.id, ((_options$config$files3 = options.config.files) === null || _options$config$files3 === void 0 ? void 0 : _options$config$files3.directory) || "/public/val", undefined,
15487
- /*
15488
- * Forwarded verbatim, and only the client can decide it: the
15489
- * content API closes the group it is named without checking
15490
- * that the commit shipped all of it, and whether it did needs
15491
- * the patch sets, which live in the browser.
15492
- */
15493
- body.patchGroupId);
15494
- };
15893
+ const commitToGit = () => serverOps.commit(preparedCommit, message, auth.id, FILES_DIRECTORY, undefined,
15894
+ /*
15895
+ * Forwarded verbatim, and only the client can decide it: the
15896
+ * content API closes the group it is named without checking
15897
+ * that the commit shipped all of it, and whether it did needs
15898
+ * the patch sets, which live in the browser.
15899
+ */
15900
+ body.patchGroupId);
15495
15901
  /*
15496
15902
  * A host may publish somewhere other than the repository.
15497
15903
  *
@@ -16478,34 +16884,18 @@ const ValServer = (valModules, options, callbacks) => {
16478
16884
  // nothing fetches it backend-to-backend. Neither half of the argument
16479
16885
  // above transfers. See architecture/media.md, "Why /files has no auth,
16480
16886
  // and /history/files does".
16481
- let fileBuffer;
16482
- let mimeType;
16483
16887
  const remote = query.remote === "true";
16484
- if (query.patch_id) {
16485
- fileBuffer = await serverOps.getBase64EncodedBinaryFileFromPatch(filePath, query.patch_id, remote);
16486
- mimeType = core.Internal.filenameToMimeType(filePath);
16487
- } else {
16488
- if (serverOps instanceof ValOpsHttp && remote) {
16489
- console.error(`Remote file: ${filePath} requested without patch id. This is most likely a bug in Val.`);
16490
- }
16491
- fileBuffer = await serverOps.getBinaryFile(filePath);
16888
+ const patchId = query.patch_id;
16889
+ if (!patchId && serverOps instanceof ValOpsHttp && remote) {
16890
+ console.error(`Remote file: ${filePath} requested without patch id. This is most likely a bug in Val.`);
16492
16891
  }
16493
- if (fileBuffer) {
16494
- return {
16495
- status: 200,
16496
- headers: {
16497
- // TODO: we could use ETag and return 304 instead
16498
- "Content-Type": mimeType || "application/octet-stream",
16499
- // TODO: a file requested with a patch_id is immutable for that
16500
- // patch, so it could be served "public, max-age=20000, immutable"
16501
- // instead. There used to be a `cacheControl` variable here for
16502
- // that, but its only assignment was commented out, so every
16503
- // response has always taken the revalidate branch.
16504
- "Cache-Control": "public, max-age=0, must-revalidate"
16505
- },
16506
- body: bufferToReadableStream(fileBuffer)
16507
- };
16508
- } else {
16892
+ // Opened, not read: a video is seeked in by many small ranges, and
16893
+ // only the asked-for bytes are read where the mode can (fs).
16894
+ const opened = await serverOps.openBinaryFile(filePath, patchId ? {
16895
+ patchId: patchId,
16896
+ remote
16897
+ } : null);
16898
+ if (!opened) {
16509
16899
  return {
16510
16900
  status: 404,
16511
16901
  json: {
@@ -16513,6 +16903,62 @@ const ValServer = (valModules, options, callbacks) => {
16513
16903
  }
16514
16904
  };
16515
16905
  }
16906
+ // A DRAFT playlist names files that are drafts too, at URLs that only
16907
+ // resolve once published. See `rewriteDraftPlaylist`. Playlists are
16908
+ // small, so one is read whole to be rewritten.
16909
+ const file = patchId && isHlsPlaylistPath(filePath) ? bufferReader(Buffer.from(rewriteDraftPlaylist((await opened.read(0, opened.size - 1)).toString("utf-8"), {
16910
+ playlistPath: filePath,
16911
+ patchId,
16912
+ remote
16913
+ }), "utf-8")) : opened;
16914
+ const headers = {
16915
+ // TODO: we could use ETag and return 304 instead
16916
+ // From the extension, published or draft: a `<video>` and an HLS
16917
+ // player both decide what they are holding by it, and it used to be
16918
+ // set for drafts only.
16919
+ "Content-Type": core.Internal.filenameToMimeType(filePath) || "application/octet-stream",
16920
+ // TODO: a file requested with a patch_id is immutable for that
16921
+ // patch, so it could be served "public, max-age=20000, immutable"
16922
+ // instead. There used to be a `cacheControl` variable here for
16923
+ // that, but its only assignment was commented out, so every
16924
+ // response has always taken the revalidate branch.
16925
+ "Cache-Control": "public, max-age=0, must-revalidate",
16926
+ "Accept-Ranges": "bytes"
16927
+ };
16928
+ const range = parseRangeHeader(req.headers.range, file.size);
16929
+ if (range.kind === "unsatisfiable") {
16930
+ return {
16931
+ status: 416,
16932
+ headers: {
16933
+ ...headers,
16934
+ "Content-Range": `bytes */${file.size}`
16935
+ },
16936
+ json: {
16937
+ message: `Range not satisfiable: ${req.headers.range}`
16938
+ }
16939
+ };
16940
+ }
16941
+ if (range.kind === "range") {
16942
+ const slice = await file.read(range.start, range.end);
16943
+ return {
16944
+ status: 206,
16945
+ headers: {
16946
+ ...headers,
16947
+ "Content-Range": `bytes ${range.start}-${range.end}/${file.size}`,
16948
+ "Content-Length": String(slice.length)
16949
+ },
16950
+ body: bufferToReadableStream(slice)
16951
+ };
16952
+ }
16953
+ const body = file.size === 0 ? Buffer.alloc(0) : await file.read(0, file.size - 1);
16954
+ return {
16955
+ status: 200,
16956
+ headers: {
16957
+ ...headers,
16958
+ "Content-Length": String(body.length)
16959
+ },
16960
+ body: bufferToReadableStream(body)
16961
+ };
16516
16962
  }
16517
16963
  }
16518
16964
  };
@@ -17860,301 +18306,2692 @@ class ValFSHost {
17860
18306
  }
17861
18307
  }
17862
18308
 
17863
- async function extractImageMetadata(filename, input) {
17864
- const imageSize = sizeOf__default["default"](new Uint8Array(input));
17865
- let mimeType = null;
17866
- if (imageSize.type) {
17867
- const possibleMimeType = `image/${imageSize.type}`;
17868
- if (core.Internal.MIME_TYPES_TO_EXT[possibleMimeType]) {
17869
- mimeType = possibleMimeType;
17870
- }
17871
- const filenameBasedLookup = core.Internal.filenameToMimeType(filename);
17872
- if (filenameBasedLookup) {
17873
- mimeType = filenameBasedLookup;
17874
- }
17875
- }
17876
- if (!mimeType) {
17877
- mimeType = "application/octet-stream";
17878
- }
17879
- let {
17880
- width,
17881
- height
17882
- } = imageSize;
17883
- if (!width || !height) {
17884
- width = 0;
17885
- height = 0;
17886
- }
18309
+ /**
18310
+ * The size and length of an ISO base media file (`.mp4`, `.m4v`, `.mov`),
18311
+ * read from its headers. Nothing is decoded.
18312
+ *
18313
+ * Hand-written rather than a media library, deliberately: `@valbuild/server`
18314
+ * is loaded by every app that runs Val, and the four numbers wanted here are
18315
+ * three small boxes away from the start of the `moov` box:
18316
+ *
18317
+ * moov > mvhd timescale and duration (version 0 and 1)
18318
+ * moov > mvex > mehd duration of a FRAGMENTED file, whose mvhd says 0
18319
+ * moov > trak > tkhd width and height (16.16 fixed point) and the
18320
+ * display matrix, for a rotated phone video
18321
+ * moov > trak > mdia > hdlr `vide`: which trak is the picture
18322
+ *
18323
+ * Only the box headers are read on the way to `moov`, and then `moov` itself,
18324
+ * so a multi-GB file costs a few small reads: `mdat` is seeked past, never
18325
+ * loaded. That is what {@link ByteSource} is for.
18326
+ */
18327
+
18328
+ /** Random access to a file's bytes, so a large `mdat` can be skipped. */
18329
+
18330
+ function bufferByteSource(buffer) {
17887
18331
  return {
17888
- width,
17889
- height,
17890
- mimeType
18332
+ size: buffer.length,
18333
+ read: (offset, length) => buffer.subarray(offset, offset + length)
17891
18334
  };
17892
18335
  }
17893
- async function extractFileMetadata(filename, _input // TODO: use buffer to determine mimetype
17894
- ) {
17895
- let mimeType = core.Internal.filenameToMimeType(filename);
17896
- if (!mimeType) {
17897
- mimeType = "application/octet-stream";
18336
+
18337
+ /**
18338
+ * Run `read` against a file on disk, reading only what it asks for. The file
18339
+ * is closed afterwards whatever happens.
18340
+ */
18341
+ function withFileByteSource(absolutePath, read) {
18342
+ const fd = fs__default["default"].openSync(absolutePath, "r");
18343
+ try {
18344
+ const size = fs__default["default"].fstatSync(fd).size;
18345
+ return read({
18346
+ size,
18347
+ read: (offset, length) => {
18348
+ const wanted = Math.max(0, Math.min(length, size - offset));
18349
+ const buffer = Buffer.alloc(wanted);
18350
+ let filled = 0;
18351
+ while (filled < wanted) {
18352
+ const n = fs__default["default"].readSync(fd, buffer, filled, wanted - filled, offset + filled);
18353
+ if (n === 0) {
18354
+ break;
18355
+ }
18356
+ filled += n;
18357
+ }
18358
+ return buffer.subarray(0, filled);
18359
+ }
18360
+ });
18361
+ } finally {
18362
+ fs__default["default"].closeSync(fd);
17898
18363
  }
17899
- return {
17900
- mimeType
17901
- };
17902
18364
  }
17903
-
17904
18365
  /**
17905
- * A gallery entry's key, read as what it actually is.
17906
- *
17907
- * A gallery is a record keyed by its entries' file paths. A REMOTE gallery keys
17908
- * an uploaded entry by the remote URL instead — which encodes that same path —
17909
- * so every entry has a local path, and the interesting question is whether the
17910
- * bytes are expected to be at it.
17911
- *
17912
- * **They are not, for a remote entry added the ordinary way.** `saveOrUploadFiles`
17913
- * uploads the remote descriptors to the content host and copies only the local
17914
- * ones into the working tree, so an image added through the Studio (or over MCP)
17915
- * and published has no file in the repo, by design — putting one there is what
17916
- * remote storage exists to avoid. A remote entry CAN have one, because
17917
- * `val validate --fix` promotes a local file to a remote ref and leaves the file
17918
- * where it was; so "remote" means "do not require it", never "there is not one".
17919
- *
17920
- * One copy, in its own file, because this used to be two: a `remoteKeyToLocalPath`
17921
- * in `fixHandlers` and a `galleryKeyToLocalPath` in `createFixPatch`, each
17922
- * normalising the key correctly and each then treating the result as a file that
17923
- * must exist. That agreement is what made a published remote image report as
17924
- * missing from both sides at once.
18366
+ * A `moov` larger than this is not a header worth reading into memory. A
18367
+ * two-hour film's is a few MB; this is far past any real one.
17925
18368
  */
18369
+ const MAX_MOOV_SIZE = 64 * 1024 * 1024;
17926
18370
 
17927
18371
  /**
17928
- * A key that names somewhere else, whether or not it is a ref we can read.
17929
- *
17930
- * Case-insensitive, because a scheme is (RFC 3986) — and because
17931
- * `splitRemoteRef`'s pattern is not, so `HTTPS://…` is precisely one of the
17932
- * spellings that arrives here unparsed and must not be mistaken for a path.
18372
+ * Whatever of {@link IsoBmffMetadata} the file declares. A field that cannot be
18373
+ * read is absent; nothing here throws on a file that is not ISO BMFF.
17933
18374
  */
17934
- function isRemoteUrl(key) {
17935
- return /^https?:\/\//i.test(key);
17936
- }
17937
- function galleryEntryOf(key) {
17938
- const remoteRefRes = core.Internal.remote.splitRemoteRef(key);
18375
+ function readIsoBmffMetadata(source) {
18376
+ const moov = findTopLevelBox(source, "moov");
18377
+ if (!moov) {
18378
+ return {};
18379
+ }
18380
+ const metadata = {};
18381
+ const mvhd = childBox(moov, "mvhd");
18382
+ const timescaleAndDuration = mvhd ? readMvhd(mvhd) : undefined;
18383
+ if (timescaleAndDuration) {
18384
+ const {
18385
+ timescale,
18386
+ duration
18387
+ } = timescaleAndDuration;
18388
+ if (duration > 0) {
18389
+ metadata.duration = duration / timescale;
18390
+ } else {
18391
+ // A fragmented file (CMAF) says 0 in mvhd and puts the length in mehd,
18392
+ // in the same timescale.
18393
+ const mehd = childBox(childBox(moov, "mvex"), "mehd");
18394
+ const fragmentDuration = mehd ? readMehd(mehd) : undefined;
18395
+ if (fragmentDuration !== undefined && fragmentDuration > 0) {
18396
+ metadata.duration = fragmentDuration / timescale;
18397
+ }
18398
+ }
18399
+ }
18400
+ for (const trak of childBoxes(moov, "trak")) {
18401
+ const hdlr = childBox(childBox(trak, "mdia"), "hdlr");
18402
+ if (!hdlr || hdlr.length < 12 || hdlr.toString("latin1", 8, 12) !== "vide") {
18403
+ continue;
18404
+ }
18405
+ const tkhd = childBox(trak, "tkhd");
18406
+ const size = tkhd ? readTkhd(tkhd) : undefined;
18407
+ if (size && size.width > 0 && size.height > 0) {
18408
+ metadata.width = size.width;
18409
+ metadata.height = size.height;
18410
+ break;
18411
+ }
18412
+ }
18413
+ return metadata;
18414
+ }
18415
+
18416
+ /** The payload (after the header) of the first top-level box of a type. */
18417
+ function findTopLevelBox(source, type) {
18418
+ let offset = 0;
18419
+ while (offset + 8 <= source.size) {
18420
+ const header = source.read(offset, 16);
18421
+ if (header.length < 8) {
18422
+ return undefined;
18423
+ }
18424
+ let size = header.readUInt32BE(0);
18425
+ const boxType = header.toString("latin1", 4, 8);
18426
+ let headerSize = 8;
18427
+ if (size === 1) {
18428
+ if (header.length < 16) {
18429
+ return undefined;
18430
+ }
18431
+ size = Number(header.readBigUInt64BE(8));
18432
+ headerSize = 16;
18433
+ } else if (size === 0) {
18434
+ size = source.size - offset;
18435
+ }
18436
+ if (size < headerSize) {
18437
+ return undefined;
18438
+ }
18439
+ if (boxType === type) {
18440
+ if (size - headerSize > MAX_MOOV_SIZE) {
18441
+ return undefined;
18442
+ }
18443
+ const payload = source.read(offset + headerSize, size - headerSize);
18444
+ return payload.length === size - headerSize ? payload : undefined;
18445
+ }
18446
+ offset += size;
18447
+ }
18448
+ return undefined;
18449
+ }
18450
+
18451
+ /** Each child box of a container payload, as `[type, payload]`. */
18452
+ function* boxesIn(payload) {
18453
+ let offset = 0;
18454
+ while (offset + 8 <= payload.length) {
18455
+ let size = payload.readUInt32BE(offset);
18456
+ const type = payload.toString("latin1", offset + 4, offset + 8);
18457
+ let headerSize = 8;
18458
+ if (size === 1) {
18459
+ if (offset + 16 > payload.length) {
18460
+ return;
18461
+ }
18462
+ size = Number(payload.readBigUInt64BE(offset + 8));
18463
+ headerSize = 16;
18464
+ } else if (size === 0) {
18465
+ size = payload.length - offset;
18466
+ }
18467
+ if (size < headerSize || offset + size > payload.length) {
18468
+ return;
18469
+ }
18470
+ yield [type, payload.subarray(offset + headerSize, offset + size)];
18471
+ offset += size;
18472
+ }
18473
+ }
18474
+ function childBoxes(payload, type) {
18475
+ if (!payload) {
18476
+ return [];
18477
+ }
18478
+ const found = [];
18479
+ for (const [boxType, child] of boxesIn(payload)) {
18480
+ if (boxType === type) {
18481
+ found.push(child);
18482
+ }
18483
+ }
18484
+ return found;
18485
+ }
18486
+ function childBox(payload, type) {
18487
+ return childBoxes(payload, type)[0];
18488
+ }
18489
+
18490
+ /** "Unknown" in a version 1 box. Not a literal: `0x…n` needs an ES2020 target. */
18491
+ const ALL_ONES_64 = BigInt("0xffffffffffffffff");
18492
+ function readMvhd(mvhd) {
18493
+ const version = mvhd[0];
18494
+ if (version === 1) {
18495
+ if (mvhd.length < 32) return undefined;
18496
+ const timescale = mvhd.readUInt32BE(20);
18497
+ const duration = mvhd.readBigUInt64BE(24);
18498
+ if (timescale === 0 || duration === ALL_ONES_64) {
18499
+ return undefined;
18500
+ }
18501
+ return {
18502
+ timescale,
18503
+ duration: Number(duration)
18504
+ };
18505
+ }
18506
+ if (mvhd.length < 20) return undefined;
18507
+ const timescale = mvhd.readUInt32BE(12);
18508
+ const duration = mvhd.readUInt32BE(16);
18509
+ // All ones means "unknown" in a version 0 box.
18510
+ if (timescale === 0 || duration === 0xffffffff) {
18511
+ return undefined;
18512
+ }
18513
+ return {
18514
+ timescale,
18515
+ duration
18516
+ };
18517
+ }
18518
+ function readMehd(mehd) {
18519
+ if (mehd[0] === 1) {
18520
+ return mehd.length >= 12 ? Number(mehd.readBigUInt64BE(4)) : undefined;
18521
+ }
18522
+ return mehd.length >= 8 ? mehd.readUInt32BE(4) : undefined;
18523
+ }
18524
+
18525
+ /**
18526
+ * The size a track is SHOWN at: tkhd's width and height, swapped when the
18527
+ * display matrix turns the picture a quarter turn — a phone records upright
18528
+ * video sideways and says so here, and a page lays it out as it is shown.
18529
+ */
18530
+ function readTkhd(tkhd) {
18531
+ // Past the version-specific times and ids, then 16 bytes of reserved,
18532
+ // layer, alternate group, volume and reserved, then the 36-byte matrix.
18533
+ const matrixAt = tkhd[0] === 1 ? 4 + 32 + 16 : 4 + 20 + 16;
18534
+ const widthAt = matrixAt + 36;
18535
+ if (tkhd.length < widthAt + 8) {
18536
+ return undefined;
18537
+ }
18538
+ const a = tkhd.readInt32BE(matrixAt);
18539
+ const b = tkhd.readInt32BE(matrixAt + 4);
18540
+ const c = tkhd.readInt32BE(matrixAt + 12);
18541
+ const d = tkhd.readInt32BE(matrixAt + 16);
18542
+ const width = Math.round(tkhd.readUInt32BE(widthAt) / 0x10000);
18543
+ const height = Math.round(tkhd.readUInt32BE(widthAt + 4) / 0x10000);
18544
+ const quarterTurn = a === 0 && d === 0 && b !== 0 && c !== 0;
18545
+ return quarterTurn ? {
18546
+ width: height,
18547
+ height: width
18548
+ } : {
18549
+ width,
18550
+ height
18551
+ };
18552
+ }
18553
+
18554
+ /**
18555
+ * The size and length of a Matroska file (`.webm`, and `.mkv`, which is the
18556
+ * same container), read from its headers. Nothing is decoded.
18557
+ *
18558
+ * Hand-written for the same reason `isoBmff.ts` is: `@valbuild/server` is
18559
+ * loaded by every app that runs Val, and what is wanted here is a handful of
18560
+ * integers two levels into the file:
18561
+ *
18562
+ * EBML the header; a file without one is not Matroska
18563
+ * Segment > Info TimecodeScale and Duration
18564
+ * Segment > Tracks > TrackEntry TrackType 1 (video) >
18565
+ * Video PixelWidth / PixelHeight, and DisplayWidth /
18566
+ * DisplayHeight when they are in pixels
18567
+ *
18568
+ * Matroska is EBML: every element is a variable-length ID, a variable-length
18569
+ * size and a payload. Only element HEADERS are read on the way through the
18570
+ * Segment, and then the payloads of Info and Tracks, which are a few hundred
18571
+ * bytes. The Clusters — the frames, which are the file — are never read: the
18572
+ * walk stops at the first one.
18573
+ *
18574
+ * That is allowed because the spec (RFC 9559, section 6.3) requires the first
18575
+ * Info and Tracks to come before the first Cluster, or to be named by a
18576
+ * SeekHead that does. A file written by a browser's MediaRecorder, or by
18577
+ * anything else that streams, does not know its own length when it starts:
18578
+ * its Segment and Clusters have the "unknown" size, and its Info has no
18579
+ * Duration. The Segment is then read as running to the end of the file, and
18580
+ * the duration is left out rather than counted from the Clusters — a caller
18581
+ * reports it, as it does for a fragmented mp4.
18582
+ */
18583
+
18584
+ const EBML_HEADER = 0x1a45dfa3;
18585
+ const SEGMENT = 0x18538067;
18586
+ const SEEK_HEAD = 0x114d9b74;
18587
+ const SEEK = 0x4dbb;
18588
+ const SEEK_ID = 0x53ab;
18589
+ const SEEK_POSITION = 0x53ac;
18590
+ const INFO = 0x1549a966;
18591
+ const TIMECODE_SCALE = 0x2ad7b1;
18592
+ const DURATION = 0x4489;
18593
+ const TRACKS = 0x1654ae6b;
18594
+ const TRACK_ENTRY = 0xae;
18595
+ const TRACK_TYPE = 0x83;
18596
+ const VIDEO = 0xe0;
18597
+ const PIXEL_WIDTH = 0xb0;
18598
+ const PIXEL_HEIGHT = 0xba;
18599
+ const DISPLAY_WIDTH = 0x54b0;
18600
+ const DISPLAY_HEIGHT = 0x54ba;
18601
+ const DISPLAY_UNIT = 0x54b2;
18602
+ const CLUSTER = 0x1f43b675;
18603
+ const TRACK_TYPE_VIDEO = 1;
18604
+ const DISPLAY_UNIT_PIXELS = 0;
18605
+ /** Nanoseconds per tick, when Info does not say. */
18606
+ const DEFAULT_TIMECODE_SCALE = 1_000_000;
18607
+
18608
+ /**
18609
+ * Info, Tracks or a SeekHead larger than this is not a header worth reading
18610
+ * into memory. Tracks is the big one, for its codec private data, and that is
18611
+ * kilobytes.
18612
+ */
18613
+ const MAX_HEADER_ELEMENT_SIZE = 16 * 1024 * 1024;
18614
+
18615
+ /**
18616
+ * Whatever of {@link EbmlMetadata} the file declares. A field that cannot be
18617
+ * read is absent; nothing here throws on a file that is not Matroska.
18618
+ */
18619
+ function readEbmlMetadata(source) {
18620
+ const header = readElementHeader(source, 0);
18621
+ if (!header || header.id !== EBML_HEADER || header.size === undefined) {
18622
+ return {};
18623
+ }
18624
+ const segment = findSegment(source, header.dataStart + header.size);
18625
+ if (!segment) {
18626
+ return {};
18627
+ }
18628
+ const segmentStart = segment.dataStart;
18629
+ const segmentEnd = segment.size === undefined ? source.size : Math.min(source.size, segmentStart + segment.size);
18630
+ let info;
18631
+ let tracks;
18632
+ const seekPositions = new Map();
18633
+ let offset = segmentStart;
18634
+ while (offset < segmentEnd && !(info && tracks)) {
18635
+ const element = readElementHeader(source, offset);
18636
+ if (!element || element.id === CLUSTER) {
18637
+ break;
18638
+ }
18639
+ if (element.id === INFO && !info) {
18640
+ info = readPayload(source, element);
18641
+ } else if (element.id === TRACKS && !tracks) {
18642
+ tracks = readPayload(source, element);
18643
+ } else if (element.id === SEEK_HEAD) {
18644
+ const seekHead = readPayload(source, element);
18645
+ if (seekHead) {
18646
+ readSeekHead(seekHead, seekPositions);
18647
+ }
18648
+ }
18649
+ if (element.size === undefined) {
18650
+ // Only a Segment or a Cluster may have an unknown size, and an element
18651
+ // whose end is unknown cannot be stepped over.
18652
+ break;
18653
+ }
18654
+ offset = element.dataStart + element.size;
18655
+ }
18656
+ // Not before the first Cluster: the SeekHead says where.
18657
+ if (!info) {
18658
+ info = readSought(source, segmentStart, seekPositions, INFO);
18659
+ }
18660
+ if (!tracks) {
18661
+ tracks = readSought(source, segmentStart, seekPositions, TRACKS);
18662
+ }
18663
+ const metadata = {};
18664
+ const duration = info ? readDuration(info) : undefined;
18665
+ if (duration !== undefined) {
18666
+ metadata.duration = duration;
18667
+ }
18668
+ const size = tracks ? readVideoSize(tracks) : undefined;
18669
+ if (size) {
18670
+ metadata.width = size.width;
18671
+ metadata.height = size.height;
18672
+ }
18673
+ return metadata;
18674
+ }
18675
+ /** The first Segment among the top-level elements after the EBML header. */
18676
+ function findSegment(source, from) {
18677
+ let offset = from;
18678
+ while (offset < source.size) {
18679
+ const element = readElementHeader(source, offset);
18680
+ if (!element) {
18681
+ return undefined;
18682
+ }
18683
+ if (element.id === SEGMENT) {
18684
+ return element;
18685
+ }
18686
+ if (element.size === undefined) {
18687
+ return undefined;
18688
+ }
18689
+ offset = element.dataStart + element.size;
18690
+ }
18691
+ return undefined;
18692
+ }
18693
+ function readElementHeader(source, offset) {
18694
+ // At most 4 bytes of ID and 8 of size.
18695
+ const bytes = source.read(offset, 12);
18696
+ const id = readVint(bytes, 0, 4);
18697
+ if (!id) {
18698
+ return undefined;
18699
+ }
18700
+ const size = readVint(bytes, id.length, 8);
18701
+ if (!size) {
18702
+ return undefined;
18703
+ }
18704
+ return {
18705
+ id: id.raw,
18706
+ size: size.unknown ? undefined : size.value,
18707
+ dataStart: offset + id.length + size.length
18708
+ };
18709
+ }
18710
+ function readPayload(source, element) {
18711
+ const {
18712
+ size
18713
+ } = element;
18714
+ if (size === undefined || size > MAX_HEADER_ELEMENT_SIZE) {
18715
+ return undefined;
18716
+ }
18717
+ const payload = source.read(element.dataStart, size);
18718
+ return payload.length === size ? payload : undefined;
18719
+ }
18720
+ /**
18721
+ * An EBML variable-length integer: the number of leading zero bits of the
18722
+ * first byte, plus one, is its length in bytes. Built with arithmetic rather
18723
+ * than shifts, which are 32-bit and signed in JavaScript.
18724
+ */
18725
+ function readVint(bytes, offset, maxLength) {
18726
+ if (offset >= bytes.length) {
18727
+ return undefined;
18728
+ }
18729
+ const first = bytes[offset];
18730
+ if (first === 0) {
18731
+ return undefined;
18732
+ }
18733
+ const length = Math.clz32(first) - 23;
18734
+ if (length > maxLength || offset + length > bytes.length) {
18735
+ return undefined;
18736
+ }
18737
+ const valueMask = 0xff >> length;
18738
+ let raw = first;
18739
+ let value = first & valueMask;
18740
+ let unknown = value === valueMask;
18741
+ for (let i = 1; i < length; i++) {
18742
+ const byte = bytes[offset + i];
18743
+ raw = raw * 256 + byte;
18744
+ value = value * 256 + byte;
18745
+ unknown = unknown && byte === 0xff;
18746
+ }
18747
+ return {
18748
+ length,
18749
+ raw,
18750
+ value,
18751
+ unknown
18752
+ };
18753
+ }
18754
+
18755
+ /** Each child element of a master element's payload, as `[id, payload]`. */
18756
+ function* elementsIn(payload) {
18757
+ let offset = 0;
18758
+ while (offset < payload.length) {
18759
+ const id = readVint(payload, offset, 4);
18760
+ if (!id) {
18761
+ return;
18762
+ }
18763
+ const size = readVint(payload, offset + id.length, 8);
18764
+ if (!size || size.unknown) {
18765
+ return;
18766
+ }
18767
+ const dataStart = offset + id.length + size.length;
18768
+ const end = dataStart + size.value;
18769
+ if (end > payload.length) {
18770
+ return;
18771
+ }
18772
+ yield [id.raw, payload.subarray(dataStart, end)];
18773
+ offset = end;
18774
+ }
18775
+ }
18776
+ function child(payload, id) {
18777
+ for (const [childId, data] of elementsIn(payload)) {
18778
+ if (childId === id) {
18779
+ return data;
18780
+ }
18781
+ }
18782
+ return undefined;
18783
+ }
18784
+ function readUint(data) {
18785
+ if (!data || data.length > 8) {
18786
+ return undefined;
18787
+ }
18788
+ let value = 0;
18789
+ for (const byte of data) {
18790
+ value = value * 256 + byte;
18791
+ }
18792
+ return value;
18793
+ }
18794
+ function readFloat(data) {
18795
+ if ((data === null || data === void 0 ? void 0 : data.length) === 4) {
18796
+ return data.readFloatBE(0);
18797
+ }
18798
+ if ((data === null || data === void 0 ? void 0 : data.length) === 8) {
18799
+ return data.readDoubleBE(0);
18800
+ }
18801
+ return undefined;
18802
+ }
18803
+
18804
+ /** Where each top-level element a SeekHead names is, from the Segment's data. */
18805
+ function readSeekHead(seekHead, into) {
18806
+ for (const [id, seek] of elementsIn(seekHead)) {
18807
+ if (id !== SEEK) {
18808
+ continue;
18809
+ }
18810
+ const seekId = child(seek, SEEK_ID);
18811
+ const position = readUint(child(seek, SEEK_POSITION));
18812
+ if (seekId && seekId.length <= 4 && position !== undefined) {
18813
+ const target = readUint(seekId);
18814
+ if (target !== undefined && !into.has(target)) {
18815
+ into.set(target, position);
18816
+ }
18817
+ }
18818
+ }
18819
+ }
18820
+ function readSought(source, segmentStart, seekPositions, id) {
18821
+ const position = seekPositions.get(id);
18822
+ if (position === undefined) {
18823
+ return undefined;
18824
+ }
18825
+ const element = readElementHeader(source, segmentStart + position);
18826
+ return (element === null || element === void 0 ? void 0 : element.id) === id ? readPayload(source, element) : undefined;
18827
+ }
18828
+
18829
+ /**
18830
+ * Info's Duration is a float in ticks of TimecodeScale nanoseconds. Absent in
18831
+ * a file written as it was recorded, and then absent here too.
18832
+ */
18833
+ function readDuration(info) {
18834
+ const duration = readFloat(child(info, DURATION));
18835
+ if (duration === undefined || !Number.isFinite(duration) || duration <= 0) {
18836
+ return undefined;
18837
+ }
18838
+ const scale = readUint(child(info, TIMECODE_SCALE)) ?? DEFAULT_TIMECODE_SCALE;
18839
+ if (scale <= 0) {
18840
+ return undefined;
18841
+ }
18842
+ return duration * scale / 1e9;
18843
+ }
18844
+
18845
+ /**
18846
+ * The size the first video track is SHOWN at. DisplayWidth and DisplayHeight
18847
+ * are what a non-square-pixel (anamorphic) video is laid out at, so they win
18848
+ * over the stored PixelWidth and PixelHeight — but only when DisplayUnit says
18849
+ * they are pixels. The other units (centimetres, inches, a bare aspect ratio)
18850
+ * are not a size a page can use, so the pixel size is reported instead.
18851
+ */
18852
+ function readVideoSize(tracks) {
18853
+ for (const [id, entry] of elementsIn(tracks)) {
18854
+ if (id !== TRACK_ENTRY || readUint(child(entry, TRACK_TYPE)) !== TRACK_TYPE_VIDEO) {
18855
+ continue;
18856
+ }
18857
+ const video = child(entry, VIDEO);
18858
+ if (!video) {
18859
+ continue;
18860
+ }
18861
+ const pixelWidth = readUint(child(video, PIXEL_WIDTH));
18862
+ const pixelHeight = readUint(child(video, PIXEL_HEIGHT));
18863
+ const displayUnit = readUint(child(video, DISPLAY_UNIT)) ?? DISPLAY_UNIT_PIXELS;
18864
+ if (displayUnit === DISPLAY_UNIT_PIXELS) {
18865
+ const displayWidth = readUint(child(video, DISPLAY_WIDTH));
18866
+ const displayHeight = readUint(child(video, DISPLAY_HEIGHT));
18867
+ if (displayWidth && displayHeight) {
18868
+ return {
18869
+ width: displayWidth,
18870
+ height: displayHeight
18871
+ };
18872
+ }
18873
+ }
18874
+ if (pixelWidth && pixelHeight) {
18875
+ return {
18876
+ width: pixelWidth,
18877
+ height: pixelHeight
18878
+ };
18879
+ }
18880
+ }
18881
+ return undefined;
18882
+ }
18883
+
18884
+ async function extractImageMetadata(filename, input) {
18885
+ const imageSize = sizeOf__default["default"](new Uint8Array(input));
18886
+ let mimeType = null;
18887
+ if (imageSize.type) {
18888
+ const possibleMimeType = `image/${imageSize.type}`;
18889
+ if (core.Internal.MIME_TYPES_TO_EXT[possibleMimeType]) {
18890
+ mimeType = possibleMimeType;
18891
+ }
18892
+ const filenameBasedLookup = core.Internal.filenameToMimeType(filename);
18893
+ if (filenameBasedLookup) {
18894
+ mimeType = filenameBasedLookup;
18895
+ }
18896
+ }
18897
+ if (!mimeType) {
18898
+ mimeType = "application/octet-stream";
18899
+ }
18900
+ let {
18901
+ width,
18902
+ height
18903
+ } = imageSize;
18904
+ if (!width || !height) {
18905
+ width = 0;
18906
+ height = 0;
18907
+ }
18908
+ return {
18909
+ width,
18910
+ height,
18911
+ mimeType
18912
+ };
18913
+ }
18914
+ async function extractFileMetadata(filename, _input // TODO: use buffer to determine mimetype
18915
+ ) {
18916
+ let mimeType = core.Internal.filenameToMimeType(filename);
18917
+ if (!mimeType) {
18918
+ mimeType = "application/octet-stream";
18919
+ }
18920
+ return {
18921
+ mimeType
18922
+ };
18923
+ }
18924
+
18925
+ /**
18926
+ * What `val validate --fix` writes into a video: `mimeType`, `width`, `height`
18927
+ * and `duration`, read from the file. A field that cannot be read is left out
18928
+ * rather than guessed, and the caller reports it — see
18929
+ * {@link unreadableVideoMetadataMessage}.
18930
+ *
18931
+ * `mimeType` always comes from the file EXTENSION: validation compares the two,
18932
+ * so any other answer is one validation rejects. The rest depends on the kind
18933
+ * of file:
18934
+ *
18935
+ * - **ISO BMFF** (`.mp4`, `.m4v`, `.mov`): read from the `moov` box by a small
18936
+ * parser of our own (`isoBmff.ts`). No media library: this package is loaded
18937
+ * by every app that runs Val.
18938
+ * - **WebM / Matroska** (`.webm`, `.mkv`): read from the Segment's Info and Tracks by another
18939
+ * (`ebml.ts`). A WebM recorded in a browser does not declare its length, and
18940
+ * then `duration` is left out — the frames are not counted to find it.
18941
+ * - **An HLS master playlist** (`.m3u8`): the dimensions are the largest
18942
+ * rendition's `RESOLUTION`, and the duration is the sum of the `#EXTINF`s of
18943
+ * the first media playlist it names, read from disk beside it — which is why
18944
+ * `filename` must be the playlist's path on disk.
18945
+ * - **Anything else**: the mime type and nothing more. The Studio reads those
18946
+ * in the browser when they are uploaded.
18947
+ */
18948
+ async function extractVideoMetadata(filename, input, readFile = readFileOrUndefined$2) {
18949
+ if (isHlsPath(filename)) {
18950
+ return extractHlsMetadata(filename, input.toString("utf-8"), readFile);
18951
+ }
18952
+ return extractFromByteSource(filename, bufferByteSource(input));
18953
+ }
18954
+
18955
+ /**
18956
+ * {@link extractVideoMetadata} for a file on disk, reading only the headers
18957
+ * it needs: a video's frames (an mp4's `mdat`, a WebM's Clusters) are most of
18958
+ * the file, and are skipped, not loaded.
18959
+ */
18960
+ async function extractVideoMetadataFromFile(absolutePath) {
18961
+ if (isHlsPath(absolutePath)) {
18962
+ return extractVideoMetadata(absolutePath, fs__default["default"].readFileSync(absolutePath));
18963
+ }
18964
+ return withFileByteSource(absolutePath, source => extractFromByteSource(absolutePath, source));
18965
+ }
18966
+ const ISO_BMFF_EXTENSIONS = [".mp4", ".m4v", ".mov"];
18967
+ const EBML_EXTENSIONS = [".webm", ".mkv"];
18968
+
18969
+ /** The extensions whose size and length Val reads itself. */
18970
+ const READABLE_VIDEO_EXTENSIONS = [...ISO_BMFF_EXTENSIONS, ...EBML_EXTENSIONS, ".m3u8"];
18971
+
18972
+ /**
18973
+ * What to tell someone whose video's `fields` could not be read. Names the
18974
+ * way out, because "could not read" alone leaves them nowhere to go.
18975
+ */
18976
+ function unreadableVideoMetadataMessage(fileRef, fields) {
18977
+ const extension = extensionOf(fileRef);
18978
+ if (!canReadVideoMetadata(fileRef)) {
18979
+ return `Val cannot read the size and length of a ${extension || "file without an extension"} file on the command line. Upload it again in the Val Studio, or add ${listOf(fields)} by hand.`;
18980
+ }
18981
+ return `Val could not read the ${listOf(fields)} of ${fileRef}. Upload it again in the Val Studio, or add ${listOf(fields)} by hand.`;
18982
+ }
18983
+
18984
+ /** Whether Val reads this video's size and length itself, by its extension. */
18985
+ function canReadVideoMetadata(fileRef) {
18986
+ return READABLE_VIDEO_EXTENSIONS.includes(extensionOf(fileRef));
18987
+ }
18988
+ function extensionOf(fileRef) {
18989
+ return path__namespace["default"].extname(fileRef.split("?")[0]).toLowerCase();
18990
+ }
18991
+ function listOf(fields) {
18992
+ return fields.length <= 1 ? fields.join("") : `${fields.slice(0, -1).join(", ")} and ${fields[fields.length - 1]}`;
18993
+ }
18994
+ function isHlsPath(filename) {
18995
+ return path__namespace["default"].extname(filename).toLowerCase() === ".m3u8";
18996
+ }
18997
+ function extractFromByteSource(filename, source) {
18998
+ const metadata = {};
18999
+ const mimeType = core.Internal.filenameToMimeType(filename);
19000
+ if (mimeType) {
19001
+ metadata.mimeType = mimeType;
19002
+ }
19003
+ const extension = extensionOf(filename);
19004
+ const read = ISO_BMFF_EXTENSIONS.includes(extension) ? readIsoBmffMetadata(source) : EBML_EXTENSIONS.includes(extension) ? readEbmlMetadata(source) : undefined;
19005
+ if (!read) {
19006
+ return metadata;
19007
+ }
19008
+ if (read.width !== undefined && read.height !== undefined) {
19009
+ metadata.width = read.width;
19010
+ metadata.height = read.height;
19011
+ }
19012
+ const duration = roundSeconds(read.duration);
19013
+ if (duration !== undefined) {
19014
+ metadata.duration = duration;
19015
+ }
19016
+ return metadata;
19017
+ }
19018
+
19019
+ /**
19020
+ * An HLS stream's metadata from its master playlist's text, and — for the
19021
+ * duration — the first media playlist it names, which `readMediaPlaylist`
19022
+ * fetches by the URI the master gives (relative to it, or a remote ref). The
19023
+ * one implementation for a stream on disk and one on Val Remote.
19024
+ */
19025
+ async function readHlsMetadata(text, readMediaPlaylist) {
19026
+ const metadata = {
19027
+ mimeType: core.Internal.media.HLS_MIME_TYPE
19028
+ };
19029
+ if (!isHlsMasterPlaylist(text)) {
19030
+ // A media playlist on its own: it knows how long it is, not how big.
19031
+ const duration = roundSeconds(sumHlsSegmentDurations(text));
19032
+ if (duration !== undefined) {
19033
+ metadata.duration = duration;
19034
+ }
19035
+ return metadata;
19036
+ }
19037
+ const variants = parseHlsMasterVariants(text);
19038
+ const largest = largestHlsVariant(variants);
19039
+ if (largest) {
19040
+ metadata.width = largest.width;
19041
+ metadata.height = largest.height;
19042
+ }
19043
+ // Every rendition is the same length, so the first one listed is as good as
19044
+ // any.
19045
+ const first = variants[0];
19046
+ if (first) {
19047
+ const mediaPlaylist = await readMediaPlaylist(first.uri);
19048
+ if (mediaPlaylist !== undefined) {
19049
+ const duration = roundSeconds(sumHlsSegmentDurations(mediaPlaylist));
19050
+ if (duration !== undefined) {
19051
+ metadata.duration = duration;
19052
+ }
19053
+ }
19054
+ }
19055
+ return metadata;
19056
+ }
19057
+ function extractHlsMetadata(filename, text, readFile) {
19058
+ // Only a relative URI can be read from disk: the Studio writes relative
19059
+ // URIs into a local stream.
19060
+ return readHlsMetadata(text, async uri => {
19061
+ var _readFile;
19062
+ return isRelativeUri(uri) ? (_readFile = readFile(path__namespace["default"].resolve(path__namespace["default"].dirname(filename), uri.split(/[?#]/)[0]))) === null || _readFile === void 0 ? void 0 : _readFile.toString("utf-8") : undefined;
19063
+ });
19064
+ }
19065
+ function isRelativeUri(uri) {
19066
+ return !/^[a-z][a-z0-9+.-]*:/i.test(uri) && !uri.startsWith("/");
19067
+ }
19068
+
19069
+ /**
19070
+ * Seconds to the millisecond. A duration summed from `#EXTINF`s or computed
19071
+ * from timestamps carries float noise (`5.999999999`), and this value is
19072
+ * written into a `.val.ts` someone reads.
19073
+ */
19074
+ function roundSeconds(seconds) {
19075
+ if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {
19076
+ return undefined;
19077
+ }
19078
+ return Math.round(seconds * 1000) / 1000;
19079
+ }
19080
+ function readFileOrUndefined$2(absolutePath) {
19081
+ try {
19082
+ return fs__default["default"].readFileSync(absolutePath);
19083
+ } catch {
19084
+ return undefined;
19085
+ }
19086
+ }
19087
+
19088
+ /**
19089
+ * A remote video's size and length, read over HTTP without downloading it.
19090
+ *
19091
+ * The parsers (`isoBmff.ts`, `ebml.ts`) are synchronous and ask a
19092
+ * {@link ByteSource} for the few header bytes they need. Here that source is
19093
+ * a cache of byte ranges fetched with `Range` requests: when the parser asks
19094
+ * for bytes the cache does not hold, the read throws {@link NeedBytes}, the
19095
+ * missing range is fetched, and the parser runs again from the start. Parsing
19096
+ * headers is microseconds and fetching is milliseconds, so re-running is the
19097
+ * cheap side of that trade — and it keeps ONE parser for files on disk and
19098
+ * files on Val Remote, rather than an async copy of each.
19099
+ *
19100
+ * An mp4 with `moov` first costs one request; one with `moov` after `mdat`
19101
+ * costs about three (the start, the box header past `mdat`, and `moov`
19102
+ * itself), however large the file. An HLS stream is its master playlist and
19103
+ * one media playlist.
19104
+ */
19105
+
19106
+ /** How much to fetch past what was asked for: box headers come in runs. */
19107
+ const READ_AHEAD = 64 * 1024;
19108
+ /** A parser that needs more fetches than this is not reading headers. */
19109
+ const MAX_FETCHES = 16;
19110
+ /** Thrown by a cached read that needs bytes not fetched yet. */
19111
+ class NeedBytes {
19112
+ constructor(offset, length) {
19113
+ this.offset = offset;
19114
+ this.length = length;
19115
+ }
19116
+ }
19117
+
19118
+ /**
19119
+ * Read `url`'s metadata. `nameForType` is the file name its type is read off —
19120
+ * for a remote ref, the `/public/...` path inside it, since the ref's own URL
19121
+ * ends in the same name but is not where a reader would look for it.
19122
+ */
19123
+ async function extractVideoMetadataFromUrl(url, nameForType, fetchImpl = fetch) {
19124
+ if (nameForType.split("?")[0].toLowerCase().endsWith(".m3u8")) {
19125
+ const master = await fetchText(url, fetchImpl);
19126
+ return readHlsMetadata(master, uri => fetchText(new URL(uri, url).toString(), fetchImpl).catch(() => undefined));
19127
+ }
19128
+ const cache = new RangeCache(url, fetchImpl);
19129
+ for (let fetches = 0;; fetches++) {
19130
+ const source = await cache.source();
19131
+ try {
19132
+ return extractFromByteSource(nameForType, source);
19133
+ } catch (err) {
19134
+ if (!(err instanceof NeedBytes)) {
19135
+ throw err;
19136
+ }
19137
+ if (fetches >= MAX_FETCHES) {
19138
+ throw new Error(`Reading the headers of ${url} took more than ${MAX_FETCHES} requests`, {
19139
+ cause: err
19140
+ });
19141
+ }
19142
+ await cache.fetch(err.offset, err.length);
19143
+ }
19144
+ }
19145
+ }
19146
+
19147
+ /** The local `/public/...` path a remote ref names, for its file type. */
19148
+ function nameForTypeOf(ref) {
19149
+ const split = core.Internal.remote.splitRemoteRef(ref);
19150
+ return split.status === "success" ? `/${split.filePath}` : ref;
19151
+ }
19152
+ async function fetchText(url, fetchImpl) {
19153
+ const res = await fetchImpl(url, {
19154
+ headers: {}
19155
+ });
19156
+ if (!res.ok) {
19157
+ throw new Error(`Could not read ${url}: HTTP ${res.status}`);
19158
+ }
19159
+ return res.text();
19160
+ }
19161
+ class RangeCache {
19162
+ /** Fetched ranges, as [start, bytes]. Few, so a list is enough. */
19163
+ chunks = [];
19164
+ size;
19165
+ constructor(url, fetchImpl) {
19166
+ this.url = url;
19167
+ this.fetchImpl = fetchImpl;
19168
+ }
19169
+
19170
+ /** A source over what is cached, after fetching the start if nothing is. */
19171
+ async source() {
19172
+ if (this.size === undefined) {
19173
+ await this.fetch(0, READ_AHEAD);
19174
+ }
19175
+ const size = this.size ?? 0;
19176
+ return {
19177
+ size,
19178
+ read: (offset, length) => {
19179
+ const end = Math.min(offset + length, size);
19180
+ if (end <= offset) {
19181
+ return Buffer.alloc(0);
19182
+ }
19183
+ for (const [start, bytes] of this.chunks) {
19184
+ if (start <= offset && end <= start + bytes.length) {
19185
+ return bytes.subarray(offset - start, end - start);
19186
+ }
19187
+ }
19188
+ throw new NeedBytes(offset, end - offset);
19189
+ }
19190
+ };
19191
+ }
19192
+ async fetch(offset, length) {
19193
+ const last = offset + Math.max(length, READ_AHEAD) - 1;
19194
+ const res = await this.fetchImpl(this.url, {
19195
+ headers: {
19196
+ Range: `bytes=${offset}-${last}`
19197
+ }
19198
+ });
19199
+ if (res.status === 200) {
19200
+ // The server ignored the range and sent the whole file. That answers
19201
+ // every read there will be.
19202
+ const whole = Buffer.from(await res.arrayBuffer());
19203
+ this.chunks = [[0, whole]];
19204
+ this.size = whole.length;
19205
+ return;
19206
+ }
19207
+ if (res.status !== 206) {
19208
+ throw new Error(`Could not read ${this.url}: HTTP ${res.status}`);
19209
+ }
19210
+ // `bytes 0-65535/1234567`: where the bytes start, and how big the file is.
19211
+ const range = /^bytes (\d+)-(\d+)\/(\d+|\*)$/.exec(res.headers.get("content-range") ?? "");
19212
+ if (!range) {
19213
+ throw new Error(`Could not read ${this.url}: a partial answer without a Content-Range`);
19214
+ }
19215
+ const bytes = Buffer.from(await res.arrayBuffer());
19216
+ if (range[3] !== "*") {
19217
+ this.size = Number(range[3]);
19218
+ } else if (this.size === undefined) {
19219
+ throw new Error(`Could not read ${this.url}: its size is not known`);
19220
+ }
19221
+ this.chunks.push([Number(range[1]), bytes]);
19222
+ }
19223
+ }
19224
+
19225
+ /**
19226
+ * A gallery entry's key, read as what it actually is.
19227
+ *
19228
+ * A gallery is a record keyed by its entries' file paths. A REMOTE gallery keys
19229
+ * an uploaded entry by the remote URL instead — which encodes that same path —
19230
+ * so every entry has a local path, and the interesting question is whether the
19231
+ * bytes are expected to be at it.
19232
+ *
19233
+ * **They are not, for a remote entry added the ordinary way.** `saveOrUploadFiles`
19234
+ * uploads the remote descriptors to the content host and copies only the local
19235
+ * ones into the working tree, so an image added through the Studio (or over MCP)
19236
+ * and published has no file in the repo, by design — putting one there is what
19237
+ * remote storage exists to avoid. A remote entry CAN have one, because
19238
+ * `val validate --fix` promotes a local file to a remote ref and leaves the file
19239
+ * where it was; so "remote" means "do not require it", never "there is not one".
19240
+ *
19241
+ * One copy, in its own file, because this used to be two: a `remoteKeyToLocalPath`
19242
+ * in `fixHandlers` and a `galleryKeyToLocalPath` in `createFixPatch`, each
19243
+ * normalising the key correctly and each then treating the result as a file that
19244
+ * must exist. That agreement is what made a published remote image report as
19245
+ * missing from both sides at once.
19246
+ */
19247
+
19248
+ /**
19249
+ * A key that names somewhere else, whether or not it is a ref we can read.
19250
+ *
19251
+ * Case-insensitive, because a scheme is (RFC 3986) — and because
19252
+ * `splitRemoteRef`'s pattern is not, so `HTTPS://…` is precisely one of the
19253
+ * spellings that arrives here unparsed and must not be mistaken for a path.
19254
+ */
19255
+ function isRemoteUrl(key) {
19256
+ return /^https?:\/\//i.test(key);
19257
+ }
19258
+ function galleryEntryOf(key) {
19259
+ const remoteRefRes = core.Internal.remote.splitRemoteRef(key);
17939
19260
  if (remoteRefRes.status === "success") {
17940
19261
  return {
17941
- localPath: `/${remoteRefRes.filePath}`,
17942
- remote: true
19262
+ localPath: `/${remoteRefRes.filePath}`,
19263
+ remote: true
19264
+ };
19265
+ }
19266
+ if (isRemoteUrl(key)) {
19267
+ // A URL that is not a ref this version can read: truncated by a hand edit,
19268
+ // a path outside `public/`, a `..` segment — or written by a core version
19269
+ // whose format `splitRemoteRef` rejects.
19270
+ //
19271
+ // Still not a path in the working tree, so the on-disk checks must not run
19272
+ // against it. They would find nothing at `<projectRoot>/https://…`, report
19273
+ // the entry as missing, and `--fix` would DELETE it — the exact failure
19274
+ // this module exists to prevent, arriving at the one moment the key is the
19275
+ // only remaining record of where the bytes went.
19276
+ //
19277
+ // Nothing is being hidden by this: a malformed key is already reported, by
19278
+ // the record schema's own "Invalid remote URL format". That is an error for
19279
+ // a person to look at, not a file for `--fix` to go missing.
19280
+ return {
19281
+ localPath: key,
19282
+ remote: true
19283
+ };
19284
+ }
19285
+ return {
19286
+ localPath: key,
19287
+ remote: false
19288
+ };
19289
+ }
19290
+
19291
+ /**
19292
+ * The media path a validation error is about, if it is about media at all.
19293
+ *
19294
+ * There is no schema in hand here — a `ValidationError` carries only the value
19295
+ * it flagged — so the shape is all there is to go on.
19296
+ */
19297
+ function getValidationErrorFileRef(validationError) {
19298
+ const maybePath = validationError.value && typeof validationError.value === "object" && "path" in validationError.value && typeof validationError.value.path === "string" ? validationError.value.path : undefined;
19299
+ if (!maybePath) {
19300
+ return null;
19301
+ }
19302
+ return maybePath;
19303
+ }
19304
+
19305
+ const textEncoder$1 = new TextEncoder();
19306
+ async function checkRemoteRef(remoteHost, ref, projectRoot, schema, metadata) {
19307
+ const remoteRefDataRes = core.Internal.remote.splitRemoteRef(ref);
19308
+ if (remoteRefDataRes.status === "error") {
19309
+ return remoteRefDataRes;
19310
+ }
19311
+ const fileHash = remoteRefDataRes.fileHash;
19312
+ if (!fileHash) {
19313
+ return {
19314
+ status: "error",
19315
+ error: `File hash is missing in remote ref: ${ref}`
19316
+ };
19317
+ }
19318
+ const relativeFilePath = remoteRefDataRes.filePath;
19319
+ if (!relativeFilePath) {
19320
+ return {
19321
+ status: "error",
19322
+ error: `File path is missing in remote ref: ${ref}`
19323
+ };
19324
+ }
19325
+ if (!relativeFilePath.startsWith("public/")) {
19326
+ return {
19327
+ status: "error",
19328
+ error: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
19329
+ };
19330
+ }
19331
+ const coreVersion = core.Internal.VERSION.core || "unknown";
19332
+ const fileExt = getFileExt(relativeFilePath);
19333
+ const currentValidationHash = core.Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata,
19334
+ // TODO: validate
19335
+ fileHash, textEncoder$1);
19336
+ const validationHashFromRemoteRefValues = core.Internal.remote.getValidationHash(remoteRefDataRes.version, schema, getFileExt(remoteRefDataRes.filePath), metadata,
19337
+ // TODO: validate
19338
+ fileHash, textEncoder$1);
19339
+ if (
19340
+ // Current validation hash is the same as the remote validation hash
19341
+ // We assume the uploaded file exists and is correct
19342
+ currentValidationHash === remoteRefDataRes.validationHash &&
19343
+ // This can happen if the version or fileExt has been tampered with
19344
+ // (or if the way it is computed has changed)
19345
+ validationHashFromRemoteRefValues === remoteRefDataRes.validationHash) {
19346
+ return {
19347
+ status: "success"
19348
+ };
19349
+ }
19350
+ // Validation hash does not match, so we need to re-validate the remote content
19351
+ const fileBufferRes = await getFileBufferFromRemote(ref, fileExt, remoteRefDataRes.fileHash, projectRoot);
19352
+
19353
+ // We could not download the remote file for some reason (for example, the file hash is wrong)
19354
+ if (fileBufferRes.status === "error") {
19355
+ return fileBufferRes;
19356
+ }
19357
+
19358
+ // At this point we have the file buffer and we know the correct file hash
19359
+ // We must create a new ref since something has changed
19360
+
19361
+ let currentMetadata;
19362
+ try {
19363
+ if (schema.type === "image") {
19364
+ currentMetadata = await extractImageMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
19365
+ } else if (schema.type === "file") {
19366
+ currentMetadata = await extractFileMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
19367
+ } else {
19368
+ const exhaustiveCheck = schema;
19369
+ return {
19370
+ status: "error",
19371
+ error: `Unknown schema type: ${JSON.stringify(exhaustiveCheck)}`
19372
+ };
19373
+ }
19374
+ } catch (err) {
19375
+ return {
19376
+ status: "error",
19377
+ error: `Failed to extract metadata from remote file: ${err instanceof Error ? err.message : "Unknown error"}. Cached file: ${fileBufferRes.cachedFilePath}`
19378
+ };
19379
+ }
19380
+ const updatedMetadata = {
19381
+ ...metadata,
19382
+ ...currentMetadata
19383
+ };
19384
+ const nextValidationHash = core.Internal.remote.getValidationHash(coreVersion, schema, fileExt, updatedMetadata, fileBufferRes.fileHash, textEncoder$1);
19385
+ if (!updatedMetadata.mimeType) {
19386
+ return {
19387
+ status: "error",
19388
+ error: `MIME type is missing in metadata: ${JSON.stringify(updatedMetadata)}`
19389
+ };
19390
+ }
19391
+ const newFileExt = core.Internal.mimeTypeToFileExt(updatedMetadata.mimeType);
19392
+ const newFilePath = relativeFilePath.slice(0, -fileExt.length) + newFileExt;
19393
+ return {
19394
+ status: "fix-required",
19395
+ metadata: updatedMetadata,
19396
+ ref: core.Internal.remote.createRemoteRef(remoteHost, {
19397
+ publicProjectId: remoteRefDataRes.projectId,
19398
+ coreVersion,
19399
+ bucket: remoteRefDataRes.bucket,
19400
+ validationHash: nextValidationHash,
19401
+ fileHash: fileBufferRes.fileHash,
19402
+ filePath: newFilePath
19403
+ })
19404
+ };
19405
+ }
19406
+ function getCachedRemoteFileDir(projectRoot) {
19407
+ // store in projectRoot/.val/remote-file-cache
19408
+ const remoteFileCacheDir = path__namespace["default"].join(projectRoot, ".val", "remote-file-cache");
19409
+ return remoteFileCacheDir;
19410
+ }
19411
+ function getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir) {
19412
+ const remoteFilePath = path__namespace["default"].join(remoteFileCacheDir, currentFileHash + "." + fileExt);
19413
+ return remoteFilePath;
19414
+ }
19415
+ async function getFileBufferFromRemote(ref, fileExt, currentFileHash, projectRoot) {
19416
+ const remoteFileCacheDir = getCachedRemoteFileDir(projectRoot);
19417
+ const remoteFilePath = getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir);
19418
+ try {
19419
+ const fileBuffer = await fs__default["default"].promises.readFile(remoteFilePath);
19420
+ const computedFileHash = core.Internal.remote.getFileHash(fileBuffer);
19421
+ if (computedFileHash !== currentFileHash) {
19422
+ await fs__default["default"].promises.unlink(remoteFilePath);
19423
+ throw Error(`Cached file hash does not match the expected hash: ${computedFileHash} !== ${currentFileHash}`);
19424
+ }
19425
+ } catch {
19426
+ try {
19427
+ await fs__default["default"].promises.mkdir(remoteFileCacheDir, {
19428
+ recursive: true
19429
+ });
19430
+ await downloadFileFromRemote(ref, remoteFilePath);
19431
+ } catch (err) {
19432
+ try {
19433
+ // try to delete in case of partial download
19434
+ await fs__default["default"].promises.unlink(remoteFilePath);
19435
+ } catch {
19436
+ //
19437
+ }
19438
+ return {
19439
+ status: "error",
19440
+ error: `Failed to download remote file: ${err instanceof Error ? err.message : "Unknown error"}`
19441
+ };
19442
+ }
19443
+ }
19444
+ const fileBuffer = await fs__default["default"].promises.readFile(remoteFilePath);
19445
+ const computedFileHash = core.Internal.remote.getFileHash(fileBuffer);
19446
+ return {
19447
+ status: "success",
19448
+ fileBuffer,
19449
+ fileHash: computedFileHash,
19450
+ cachedFilePath: remoteFilePath
19451
+ };
19452
+ }
19453
+ async function downloadFileFromRemote(ref, filePath) {
19454
+ return new Promise((resolve, reject) => {
19455
+ const url = new URL(ref);
19456
+ const client = url.protocol === "https:" ? https__default$1["default"] : http__default$1["default"];
19457
+ const request = client.get(url, response => {
19458
+ if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
19459
+ // Handle redirects
19460
+ return downloadFileFromRemote(response.headers.location, filePath).then(resolve).catch(reject);
19461
+ }
19462
+ if (response.statusCode == 404) {
19463
+ return reject(new Error(`${ref}. File not found. The URL is most likely incorrect.`));
19464
+ }
19465
+ if (response.statusCode !== 200) {
19466
+ return reject(new Error(`${ref}. Failed to download file. HTTP Status: ${response.statusCode}`));
19467
+ }
19468
+ const writeStream = fs__default["default"].createWriteStream(filePath);
19469
+ response.pipe(writeStream);
19470
+ writeStream.on("finish", () => resolve({
19471
+ status: "success",
19472
+ filePath
19473
+ }));
19474
+ writeStream.on("error", err => reject(new Error(`${ref}. Error writing file: ${err.message}`)));
19475
+ });
19476
+ request.on("error", err => reject(new Error(`${ref}. Download error: ${err.message}`)));
19477
+ request.end();
19478
+ });
19479
+ }
19480
+
19481
+ const textEncoder = new TextEncoder();
19482
+
19483
+ /**
19484
+ * Everything an upload to Val Remote needs before it has any bytes: the
19485
+ * developer's token, the project's public id and a bucket. Opened once per
19486
+ * fix, so a video's dozen files go up under one session and into one bucket
19487
+ * rather than a bucket each.
19488
+ */
19489
+
19490
+ async function openRemoteUploadSession(ctx) {
19491
+ const fail = errorMessage => ({
19492
+ success: false,
19493
+ result: {
19494
+ success: false,
19495
+ errorMessage
19496
+ }
19497
+ });
19498
+ const patFile = getPersonalAccessTokenPath(ctx.projectRoot);
19499
+ if (!ctx.fs.fileExists(patFile)) {
19500
+ return fail(`File: ${path__namespace["default"].join(ctx.projectRoot, ctx.file)} has remote files that are not uploaded and you are not logged in.\n\nFix this error by logging in:\n\t"npx val login"\n`);
19501
+ }
19502
+ const patFileContent = ctx.fs.readFile(patFile);
19503
+ if (patFileContent === undefined) {
19504
+ return fail(`Could not read personal access token file at ${patFile}`);
19505
+ }
19506
+ const parsedPatFile = parsePersonalAccessTokenFile(patFileContent);
19507
+ if (!parsedPatFile.success) {
19508
+ return fail(`Error parsing personal access token file: ${parsedPatFile.error}. You need to login again.`);
19509
+ }
19510
+ const {
19511
+ pat
19512
+ } = parsedPatFile.data;
19513
+ const projectName = ctx.project;
19514
+ let publicProjectId = ctx.publicProjectId;
19515
+ let remoteFileBuckets = ctx.remoteFileBuckets;
19516
+ let remoteFilesCounter = ctx.remoteFilesCounter;
19517
+ if (!publicProjectId || !remoteFileBuckets) {
19518
+ if (!projectName) {
19519
+ return fail("Project name not found. Add project name to val.config or set the VAL_PROJECT environment variable");
19520
+ }
19521
+ const settingsRes = await ctx.remote.getSettings(projectName, {
19522
+ pat
19523
+ });
19524
+ if (!settingsRes.success) {
19525
+ return fail(`Could not get public project id: ${settingsRes.message}.`);
19526
+ }
19527
+ publicProjectId = settingsRes.data.publicProjectId;
19528
+ remoteFileBuckets = settingsRes.data.remoteFileBuckets.map(b => b.bucket);
19529
+ }
19530
+ if (!publicProjectId) {
19531
+ return fail("Could not get public project id");
19532
+ }
19533
+ if (!projectName) {
19534
+ return fail(`Could not get project. Check that your val.config has the 'project' field set, or set it using the VAL_PROJECT environment variable`);
19535
+ }
19536
+ remoteFilesCounter += 1;
19537
+ const bucket = remoteFileBuckets[remoteFilesCounter % remoteFileBuckets.length];
19538
+ if (!bucket) {
19539
+ return fail(`Internal error: could not allocate a bucket for the remote file located at ${ctx.sourcePath}`);
19540
+ }
19541
+ return {
19542
+ success: true,
19543
+ session: {
19544
+ pat,
19545
+ projectName,
19546
+ publicProjectId,
19547
+ bucket,
19548
+ remoteFileBuckets,
19549
+ remoteFilesCounter
19550
+ }
19551
+ };
19552
+ }
19553
+
19554
+ /**
19555
+ * Upload one file's bytes and return the ref they are served at.
19556
+ *
19557
+ * `relativeFilePath` is the file's path under the project (`public/...`),
19558
+ * which the ref encodes; the bytes need not be the bytes on disk there — a
19559
+ * video's playlists are uploaded REWRITTEN, naming the refs of what they list.
19560
+ */
19561
+ async function uploadBytesToRemote(ctx, session, relativeFilePath, fileBuffer, metadata, schema) {
19562
+ if (!relativeFilePath.startsWith("public/")) {
19563
+ return {
19564
+ success: false,
19565
+ error: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
19566
+ };
19567
+ }
19568
+ const fileHash = core.Internal.remote.getFileHash(fileBuffer);
19569
+ const coreVersion = core.Internal.VERSION.core || "unknown";
19570
+ const fileExt = getFileExt(relativeFilePath);
19571
+ const ref = core.Internal.remote.createRemoteRef(ctx.remote.remoteHost, {
19572
+ publicProjectId: session.publicProjectId,
19573
+ coreVersion,
19574
+ bucket: session.bucket,
19575
+ validationHash: core.Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata, fileHash, textEncoder),
19576
+ fileHash,
19577
+ filePath: relativeFilePath
19578
+ });
19579
+ const remoteFileUpload = await ctx.remote.uploadFile(session.projectName, session.bucket, fileHash, fileExt, fileBuffer, {
19580
+ pat: session.pat
19581
+ });
19582
+ if (!remoteFileUpload.success) {
19583
+ return {
19584
+ success: false,
19585
+ error: `Could not upload remote file: '${ref}'. Error: ${remoteFileUpload.error}`
19586
+ };
19587
+ }
19588
+ return {
19589
+ success: true,
19590
+ ref
19591
+ };
19592
+ }
19593
+
19594
+ /**
19595
+ * Every file a video value names, as refs (`/public/…`, or a remote URL as
19596
+ * written): the video, its poster, each caption track — and, for a LOCAL HLS
19597
+ * stream, every file its playlists name, followed from the master down through
19598
+ * each media playlist to the segment files, init sections and audio tracks.
19599
+ *
19600
+ * Followed rather than "everything in the master's directory": the Studio
19601
+ * gives each stream a directory of its own, but nothing stops a hand-placed
19602
+ * `/public/val/clip.m3u8`, and the directory of THAT one is every file in
19603
+ * `/public/val`. A file in a stream's directory that no playlist names is not
19604
+ * used by the stream either, so calling it unused is right.
19605
+ *
19606
+ * A remote stream's playlists are on the content host, so its master is all
19607
+ * that is named here.
19608
+ *
19609
+ * The one place that answers this, so `list-unused-files` and anything else
19610
+ * asking "is this file used" agree on what a video holds.
19611
+ */
19612
+ function filesOfVideo(video, options) {
19613
+ if (!isObject(video) || typeof video.path !== "string") {
19614
+ return [];
19615
+ }
19616
+ const refs = new Set([video.path]);
19617
+ if (isObject(video.poster) && typeof video.poster.path === "string") {
19618
+ refs.add(video.poster.path);
19619
+ }
19620
+ if (Array.isArray(video.captions)) {
19621
+ for (const track of video.captions) {
19622
+ if (isObject(track) && typeof track.path === "string") {
19623
+ refs.add(track.path);
19624
+ }
19625
+ }
19626
+ }
19627
+ const mimeType = typeof video.mimeType === "string" ? video.mimeType : undefined;
19628
+ if (!core.Internal.isRemoteMediaPath(video.path) && core.Internal.media.isHlsVideo({
19629
+ path: video.path,
19630
+ mimeType
19631
+ })) {
19632
+ const readFile = options.readFile ?? readFileOrUndefined$1;
19633
+ const pending = [video.path.split("?")[0]];
19634
+ const visited = new Set();
19635
+ while (pending.length > 0) {
19636
+ var _readFile;
19637
+ const playlist = pending.pop();
19638
+ if (visited.has(playlist)) {
19639
+ continue;
19640
+ }
19641
+ visited.add(playlist);
19642
+ const text = (_readFile = readFile(path__namespace["default"].join(options.projectRoot, ...playlist.split("/")))) === null || _readFile === void 0 ? void 0 : _readFile.toString("utf-8");
19643
+ if (text === undefined) {
19644
+ continue;
19645
+ }
19646
+ mapHlsUris(text, uri => {
19647
+ const ref = localRefOf(uri, playlist);
19648
+ if (ref !== undefined) {
19649
+ refs.add(ref);
19650
+ if (ref.toLowerCase().endsWith(".m3u8")) {
19651
+ pending.push(ref);
19652
+ }
19653
+ }
19654
+ return uri;
19655
+ });
19656
+ }
19657
+ }
19658
+ return [...refs];
19659
+ }
19660
+
19661
+ /** A playlist URI as a local ref, when it is relative; otherwise undefined. */
19662
+ function localRefOf(uri, playlist) {
19663
+ if (/^[a-z][a-z0-9+.-]*:/i.test(uri) || uri.startsWith("/")) {
19664
+ return undefined;
19665
+ }
19666
+ const relative = uri.split(/[?#]/)[0];
19667
+ if (relative === "") {
19668
+ return undefined;
19669
+ }
19670
+ return path__namespace["default"].posix.join(path__namespace["default"].posix.dirname(playlist), relative);
19671
+ }
19672
+ function isObject(value) {
19673
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19674
+ }
19675
+ function readFileOrUndefined$1(absolutePath) {
19676
+ try {
19677
+ return fs__default["default"].readFileSync(absolutePath);
19678
+ } catch {
19679
+ return undefined;
19680
+ }
19681
+ }
19682
+
19683
+ /**
19684
+ * `video:upload-remote` and `video:download-remote`: move a video between the
19685
+ * repository and Val Remote.
19686
+ *
19687
+ * A video is the one media value that names several files — the video, its
19688
+ * poster, its caption tracks, and for an HLS stream every playlist and segment
19689
+ * its master names — so one fix moves all of them, and the patch then rewrites
19690
+ * every `path` the value holds. Moving only some would leave a video that is
19691
+ * half on each side, which validation rejects and no page can play.
19692
+ *
19693
+ * HLS is the part that is not a copy. The content host serves a file by its
19694
+ * HASH, so a relative name in a playlist resolves to nothing there: on the way
19695
+ * UP every playlist is rewritten to name the refs of what it lists, bottom-up
19696
+ * (a playlist's ref is the hash of its rewritten bytes, so what it names must
19697
+ * be uploaded first). On the way DOWN the same playlists are rewritten back to
19698
+ * relative names, which is what lets a published stream be plain static files.
19699
+ */
19700
+ function isRecord$2(value) {
19701
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19702
+ }
19703
+ function isPlaylist$1(ref) {
19704
+ return ref.split("?")[0].toLowerCase().endsWith(".m3u8");
19705
+ }
19706
+
19707
+ /** The paths a video value holds, each with where in the value it sits. */
19708
+ function videoPathsOf(video) {
19709
+ if (!isRecord$2(video) || typeof video.path !== "string") {
19710
+ return [];
19711
+ }
19712
+ const found = [{
19713
+ at: ["path"],
19714
+ path: video.path
19715
+ }];
19716
+ if (isRecord$2(video.poster) && typeof video.poster.path === "string") {
19717
+ found.push({
19718
+ at: ["poster", "path"],
19719
+ path: video.poster.path
19720
+ });
19721
+ }
19722
+ if (Array.isArray(video.captions)) {
19723
+ video.captions.forEach((track, index) => {
19724
+ if (isRecord$2(track) && typeof track.path === "string") {
19725
+ found.push({
19726
+ at: ["captions", String(index), "path"],
19727
+ path: track.path
19728
+ });
19729
+ }
19730
+ });
19731
+ }
19732
+ return found;
19733
+ }
19734
+
19735
+ /**
19736
+ * The patch that points a video at where its files now are: one `add` per
19737
+ * path that moved, so the authored fields beside them — the description, the
19738
+ * times, the caption labels — are never rewritten.
19739
+ */
19740
+ function rewriteVideoPathsPatch(sourcePath, video, moved) {
19741
+ const base = patch.sourceToPatchPath(sourcePath);
19742
+ const patch$1 = [];
19743
+ for (const {
19744
+ at,
19745
+ path: current
19746
+ } of videoPathsOf(video)) {
19747
+ const to = moved[current];
19748
+ if (to !== undefined && to !== current) {
19749
+ patch$1.push({
19750
+ op: "add",
19751
+ path: base.concat(at),
19752
+ value: to
19753
+ });
19754
+ }
19755
+ }
19756
+ return patch$1;
19757
+ }
19758
+
19759
+ /** A relative playlist URI as a `/public/...` ref, or undefined if it is not one. */
19760
+ function resolvePlaylistUri(uri, playlist) {
19761
+ if (/^[a-z][a-z0-9+.-]*:/i.test(uri) || uri.startsWith("/")) {
19762
+ return undefined;
19763
+ }
19764
+ const relative = uri.split(/[?#]/)[0];
19765
+ if (relative === "") {
19766
+ return undefined;
19767
+ }
19768
+ return path__namespace["default"].posix.join(path__namespace["default"].posix.dirname(playlist), relative);
19769
+ }
19770
+ function playlistUris(text) {
19771
+ const uris = [];
19772
+ mapHlsUris(text, uri => {
19773
+ if (!uris.includes(uri)) uris.push(uri);
19774
+ return uri;
19775
+ });
19776
+ return uris;
19777
+ }
19778
+
19779
+ /** What a file is to the video that names it, which decides its hash basis. */
19780
+
19781
+ /**
19782
+ * What a file's validation hash is computed from — the same as the Studio
19783
+ * computes for an upload (`createVideoPatch`), so a video moved by the CLI and
19784
+ * one uploaded in the Studio carry refs of the same kind.
19785
+ */
19786
+ function metadataOf(localRef, role, video) {
19787
+ const mimeType = core.Internal.filenameToMimeType(localRef);
19788
+ if (role === "video") {
19789
+ return {
19790
+ mimeType,
19791
+ width: video.width,
19792
+ height: video.height
19793
+ };
19794
+ }
19795
+ if (role === "poster" && isRecord$2(video.poster)) {
19796
+ return {
19797
+ mimeType: video.poster.mimeType ?? mimeType,
19798
+ width: video.poster.width,
19799
+ height: video.poster.height
19800
+ };
19801
+ }
19802
+ return {
19803
+ mimeType
19804
+ };
19805
+ }
19806
+
19807
+ /**
19808
+ * Places a video's local files on Val Remote, each once, and remembers where.
19809
+ *
19810
+ * The one implementation of "upload a video" for every fix that does it: a
19811
+ * video field (`video:upload-remote`), and an entry of an `s.videoset()`
19812
+ * (`videos:upload-remote`). What differs between the two is which files go up
19813
+ * and what their refs are hashed against, so those are the arguments.
19814
+ *
19815
+ * A playlist goes up AFTER everything it names, rewritten to name their refs:
19816
+ * the content host serves a file by its hash, so a relative name in a playlist
19817
+ * resolves to nothing there — and a playlist's own ref is the hash of its
19818
+ * rewritten bytes, so what it names must have refs first.
19819
+ */
19820
+ function createVideoUploader(ctx, session, schema, metadataFor) {
19821
+ const moved = new Map();
19822
+ const events = [];
19823
+ const put = async (localRef, role) => {
19824
+ const already = moved.get(localRef);
19825
+ if (already !== undefined) {
19826
+ return already;
19827
+ }
19828
+ const absolute = path__namespace["default"].join(ctx.projectRoot, localRef);
19829
+ const buffer = ctx.fs.readBuffer(absolute);
19830
+ if (buffer === undefined) {
19831
+ throw new Error(`Error reading file: ${absolute}`);
19832
+ }
19833
+ let bytes = buffer;
19834
+ if (isPlaylist$1(localRef)) {
19835
+ // Bottom-up: what this playlist names goes up first, so the refs it is
19836
+ // rewritten to exist — and so its own hash is of the rewritten bytes.
19837
+ const text = buffer.toString("utf-8");
19838
+ const refs = new Map();
19839
+ for (const uri of playlistUris(text)) {
19840
+ const target = resolvePlaylistUri(uri, localRef);
19841
+ if (target !== undefined) {
19842
+ refs.set(uri, await put(target, "stream"));
19843
+ }
19844
+ }
19845
+ bytes = Buffer.from(mapHlsUris(text, uri => refs.get(uri) ?? uri), "utf-8");
19846
+ }
19847
+ const uploaded = await uploadBytesToRemote(ctx, session, localRef.replace(/^\//, ""), bytes, metadataFor(localRef, role), schema);
19848
+ if (!uploaded.success) {
19849
+ throw new Error(uploaded.error);
19850
+ }
19851
+ moved.set(localRef, uploaded.ref);
19852
+ events.push({
19853
+ type: "remote-uploaded",
19854
+ ref: uploaded.ref
19855
+ });
19856
+ return uploaded.ref;
19857
+ };
19858
+ return {
19859
+ put,
19860
+ moved,
19861
+ events
19862
+ };
19863
+ }
19864
+
19865
+ /**
19866
+ * The first of `refs` — and of every file an HLS stream among them names —
19867
+ * that is not on disk, as an absolute path.
19868
+ *
19869
+ * Asked before anything goes up: a missing segment found after the master's
19870
+ * siblings were uploaded leaves bytes on the content host that nothing names.
19871
+ */
19872
+ function firstMissingVideoFile(ctx, refs) {
19873
+ for (const ref of refs) {
19874
+ const files = filesOfVideo({
19875
+ path: ref.path,
19876
+ mimeType: ref.mimeType
19877
+ }, {
19878
+ projectRoot: ctx.projectRoot,
19879
+ readFile: absolute => ctx.fs.readBuffer(absolute)
19880
+ });
19881
+ for (const file of files) {
19882
+ const absolute = path__namespace["default"].join(ctx.projectRoot, file);
19883
+ if (!ctx.fs.fileExists(absolute)) {
19884
+ return absolute;
19885
+ }
19886
+ }
19887
+ }
19888
+ return undefined;
19889
+ }
19890
+ function resolveVideo(ctx) {
19891
+ var _resolved$schema;
19892
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(ctx.sourcePath);
19893
+ if (!ctx.valModule.source || !ctx.valModule.schema) {
19894
+ return {
19895
+ success: false,
19896
+ result: {
19897
+ success: false,
19898
+ errorMessage: `Could not resolve source or schema for ${ctx.sourcePath}`
19899
+ }
19900
+ };
19901
+ }
19902
+ const resolved = core.Internal.resolvePath(modulePath, ctx.valModule.source, ctx.valModule.schema);
19903
+ const video = resolved.source;
19904
+ if (((_resolved$schema = resolved.schema) === null || _resolved$schema === void 0 ? void 0 : _resolved$schema.type) !== "video" || !isRecord$2(video) || typeof video.path !== "string") {
19905
+ return {
19906
+ success: false,
19907
+ result: {
19908
+ success: false,
19909
+ errorMessage: `Expected a video at ${ctx.sourcePath}`
19910
+ }
19911
+ };
19912
+ }
19913
+ return {
19914
+ success: true,
19915
+ video,
19916
+ schema: resolved.schema
19917
+ };
19918
+ }
19919
+
19920
+ /**
19921
+ * The paths of a video FIELD that its fix moves.
19922
+ *
19923
+ * All of them for a video of its own. For a field picked from an
19924
+ * `s.videoset()` (`referencedModule`), only the poster and the captions: the
19925
+ * video file is the set's — its key there — and moving it from here would
19926
+ * leave the field naming a file the set does not have. The set's own fix
19927
+ * (`videos:upload-remote`) moves it, and rewrites the fields that name it.
19928
+ */
19929
+ function movablePathsOf(video, schema) {
19930
+ const setBacked = schema.referencedModule !== undefined;
19931
+ return videoPathsOf(video).filter(({
19932
+ at
19933
+ }) => !setBacked || at[0] !== "path");
19934
+ }
19935
+ async function handleVideoUploadRemote(ctx) {
19936
+ if (!ctx.fix) {
19937
+ return {
19938
+ success: false,
19939
+ errorMessage: `Video needs to be uploaded to Val Remote (use --fix to upload)`
19940
+ };
19941
+ }
19942
+ const resolved = resolveVideo(ctx);
19943
+ if (!resolved.success) {
19944
+ return resolved.result;
19945
+ }
19946
+ const {
19947
+ video,
19948
+ schema
19949
+ } = resolved;
19950
+ if (ctx.remoteFiles[ctx.sourcePath]) {
19951
+ return {
19952
+ success: true,
19953
+ shouldApplyPatch: true,
19954
+ events: [{
19955
+ type: "remote-already-uploaded",
19956
+ filePath: String(video.path)
19957
+ }]
17943
19958
  };
17944
19959
  }
17945
- if (isRemoteUrl(key)) {
17946
- // A URL that is not a ref this version can read: truncated by a hand edit,
17947
- // a path outside `public/`, a `..` segment — or written by a core version
17948
- // whose format `splitRemoteRef` rejects.
17949
- //
17950
- // Still not a path in the working tree, so the on-disk checks must not run
17951
- // against it. They would find nothing at `<projectRoot>/https://…`, report
17952
- // the entry as missing, and `--fix` would DELETE it — the exact failure
17953
- // this module exists to prevent, arriving at the one moment the key is the
17954
- // only remaining record of where the bytes went.
17955
- //
17956
- // Nothing is being hidden by this: a malformed key is already reported, by
17957
- // the record schema's own "Invalid remote URL format". That is an error for
17958
- // a person to look at, not a file for `--fix` to go missing.
19960
+ const toUpload = movablePathsOf(video, schema).filter(({
19961
+ path: ref
19962
+ }) => !core.Internal.isRemoteMediaPath(ref));
19963
+ // Every file is checked before any goes up: a missing caption found after
19964
+ // the video was uploaded leaves bytes on the content host that nothing names.
19965
+ const missing = firstMissingVideoFile(ctx, toUpload.map(({
19966
+ at,
19967
+ path: ref
19968
+ }) => ({
19969
+ path: ref,
19970
+ ...(at[0] === "path" && typeof video.mimeType === "string" ? {
19971
+ mimeType: video.mimeType
19972
+ } : {})
19973
+ })));
19974
+ if (missing !== undefined) {
19975
+ return {
19976
+ success: false,
19977
+ errorMessage: `File ${missing} does not exist`
19978
+ };
19979
+ }
19980
+ const opened = await openRemoteUploadSession(ctx);
19981
+ if (!opened.success) {
19982
+ return opened.result;
19983
+ }
19984
+ const {
19985
+ session
19986
+ } = opened;
19987
+ const uploader = createVideoUploader(ctx, session, schema, (localRef, role) => metadataOf(localRef, role, video));
19988
+ try {
19989
+ for (const {
19990
+ at,
19991
+ path: ref
19992
+ } of toUpload) {
19993
+ await uploader.put(ref, at[0] === "poster" ? "poster" : at[0] === "captions" ? "caption" : "video");
19994
+ }
19995
+ } catch (err) {
19996
+ return {
19997
+ success: false,
19998
+ errorMessage: err instanceof Error ? err.message : String(err)
19999
+ };
20000
+ }
20001
+ const refs = Object.fromEntries(uploader.moved);
20002
+ ctx.remoteFiles[ctx.sourcePath] = {
20003
+ ref: refs[String(video.path)] ?? String(video.path),
20004
+ refs
20005
+ };
20006
+ return {
20007
+ success: true,
20008
+ shouldApplyPatch: true,
20009
+ publicProjectId: session.publicProjectId,
20010
+ remoteFileBuckets: session.remoteFileBuckets,
20011
+ remoteFilesCounter: session.remoteFilesCounter,
20012
+ events: uploader.events
20013
+ };
20014
+ }
20015
+ async function handleVideoDownloadRemote(ctx) {
20016
+ if (!ctx.fix) {
20017
+ return {
20018
+ success: false,
20019
+ errorMessage: `Video ${ctx.sourcePath} needs to be downloaded (use --fix to download)`
20020
+ };
20021
+ }
20022
+ const resolved = resolveVideo(ctx);
20023
+ if (!resolved.success) {
20024
+ return resolved.result;
20025
+ }
20026
+ const {
20027
+ video,
20028
+ schema
20029
+ } = resolved;
20030
+ const moved = new Map();
20031
+ const fetchTo = async ref => {
20032
+ const already = moved.get(ref);
20033
+ if (already !== undefined) {
20034
+ return already;
20035
+ }
20036
+ const split = core.Internal.remote.splitRemoteRef(ref);
20037
+ if (split.status === "error") {
20038
+ throw new Error(`Not a Val Remote ref: ${ref} (${split.error})`);
20039
+ }
20040
+ if (!split.filePath.startsWith("public/")) {
20041
+ throw new Error(`Cannot download ${ref}: its file path must start with public/ (got ${split.filePath})`);
20042
+ }
20043
+ const localRef = `/${split.filePath}`;
20044
+ const absolute = path__namespace["default"].join(ctx.projectRoot, split.filePath);
20045
+ await fs__default["default"].promises.mkdir(path__namespace["default"].dirname(absolute), {
20046
+ recursive: true
20047
+ });
20048
+ const res = await downloadFileFromRemote(ref, absolute);
20049
+ if (res.status === "error") {
20050
+ throw new Error(res.error);
20051
+ }
20052
+ moved.set(ref, localRef);
20053
+ if (isPlaylist$1(localRef)) {
20054
+ // Back to relative names: a local stream is plain static files, and the
20055
+ // draft endpoint rewrites relative names, not refs.
20056
+ const text = fs__default["default"].readFileSync(absolute, "utf-8");
20057
+ const local = new Map();
20058
+ for (const uri of playlistUris(text)) {
20059
+ if (core.Internal.remote.splitRemoteRef(uri).status === "success") {
20060
+ const target = await fetchTo(uri);
20061
+ local.set(uri, path__namespace["default"].posix.relative(path__namespace["default"].posix.dirname(localRef), target));
20062
+ }
20063
+ }
20064
+ fs__default["default"].writeFileSync(absolute, mapHlsUris(text, uri => local.get(uri) ?? uri), "utf-8");
20065
+ }
20066
+ return localRef;
20067
+ };
20068
+ try {
20069
+ for (const {
20070
+ path: ref
20071
+ } of movablePathsOf(video, schema)) {
20072
+ if (core.Internal.isRemoteMediaPath(ref)) {
20073
+ await fetchTo(ref);
20074
+ }
20075
+ }
20076
+ } catch (err) {
20077
+ return {
20078
+ success: false,
20079
+ errorMessage: err instanceof Error ? err.message : String(err)
20080
+ };
20081
+ }
20082
+ const refs = Object.fromEntries(moved);
20083
+ ctx.remoteFiles[ctx.sourcePath] = {
20084
+ ref: refs[String(video.path)] ?? String(video.path),
20085
+ refs
20086
+ };
20087
+ return {
20088
+ success: true,
20089
+ shouldApplyPatch: true,
20090
+ events: [{
20091
+ type: "remote-downloading",
20092
+ sourcePath: ctx.sourcePath
20093
+ }]
20094
+ };
20095
+ }
20096
+
20097
+ /**
20098
+ * What is out of step between a gallery's entries and its directory.
20099
+ *
20100
+ * Two questions, and they treat a remote entry differently — which is the whole
20101
+ * reason this is separate from the handler around it:
20102
+ *
20103
+ * - **Missing**: an entry with no bytes at its local path. Asked of LOCAL
20104
+ * entries only. A remote entry's bytes live on the content host, and nothing
20105
+ * puts a copy in the working tree: `saveOrUploadFiles` uploads the remote
20106
+ * descriptors and copies only the local ones into the tree, so a remote entry
20107
+ * added through the Studio (or over MCP) has no local file by design, and
20108
+ * demanding one would mean committing remote bytes to git — which is what
20109
+ * remote storage exists to avoid. Whether those bytes really are on the host
20110
+ * is a different check, `image:check-remote`, which already runs for exactly
20111
+ * these entries.
20112
+ * - **Untracked**: a file in the directory that no entry claims. Asked of every
20113
+ * entry, remote included, and that is why they are normalised to their local
20114
+ * path: `val validate --fix` promotes a local file to a remote ref and leaves
20115
+ * the file where it was, so a remote entry can perfectly well have one.
20116
+ *
20117
+ * An entry can claim more than its key. A video set's HLS stream is keyed by
20118
+ * its master playlist, and the media playlists and segments it names are the
20119
+ * same entry — so `filesOfEntry` says what else an entry holds, and those are
20120
+ * not untracked either.
20121
+ *
20122
+ * Its own module rather than a part of `fixHandlers.ts`, so the video set's
20123
+ * fixes can use it without importing the handler registry they are part of.
20124
+ */
20125
+ function checkGalleryFiles(input) {
20126
+ const {
20127
+ dir,
20128
+ projectRoot,
20129
+ fs,
20130
+ filesOfEntry
20131
+ } = input;
20132
+ const entries = input.entryKeys.map(key => ({
20133
+ key,
20134
+ entry: galleryEntryOf(key)
20135
+ }));
20136
+ const trackedFiles = new Set();
20137
+ for (const {
20138
+ key,
20139
+ entry
20140
+ } of entries) {
20141
+ trackedFiles.add(entry.localPath);
20142
+ for (const file of (filesOfEntry === null || filesOfEntry === void 0 ? void 0 : filesOfEntry(entry, key)) ?? []) {
20143
+ trackedFiles.add(file);
20144
+ }
20145
+ }
20146
+ const missingTrackedFiles = entries.filter(({
20147
+ entry
20148
+ }) => !entry.remote && !fs.fileExists(path__namespace["default"].join(projectRoot, entry.localPath))).map(({
20149
+ entry
20150
+ }) => entry.localPath);
20151
+ return {
20152
+ missingTrackedFiles,
20153
+ untrackedFiles: filesInDirectory({
20154
+ dir,
20155
+ projectRoot,
20156
+ fs
20157
+ }).filter(f => !trackedFiles.has(f))
20158
+ };
20159
+ }
20160
+
20161
+ /**
20162
+ * The LOCAL entries whose key is there but some of what they hold is not: a
20163
+ * stream missing a segment plays up to the gap and then stops. Separate from
20164
+ * `checkGalleryFiles`' "missing" because a fix does not remove these — the
20165
+ * entry still names a video someone uploaded and may have the rest of.
20166
+ */
20167
+ function incompleteGalleryEntries(input) {
20168
+ const exists = file => input.fs.fileExists(path__namespace["default"].join(input.projectRoot, file));
20169
+ const incomplete = [];
20170
+ for (const key of input.entryKeys) {
20171
+ const entry = galleryEntryOf(key);
20172
+ if (entry.remote || !exists(entry.localPath)) {
20173
+ continue;
20174
+ }
20175
+ const missing = input.filesOfEntry(entry, key).filter(file => file !== entry.localPath && !exists(file));
20176
+ if (missing.length > 0) {
20177
+ incomplete.push({
20178
+ key,
20179
+ missing
20180
+ });
20181
+ }
20182
+ }
20183
+ return incomplete;
20184
+ }
20185
+
20186
+ /** Every file under `dir`, as `/public/…` refs; none for a directory not there. */
20187
+ function filesInDirectory({
20188
+ dir,
20189
+ projectRoot,
20190
+ fs
20191
+ }) {
20192
+ const filesInDir = [];
20193
+ try {
20194
+ const found = fs.readDirectory(path__namespace["default"].join(projectRoot, dir), undefined, undefined, ["**/*"]);
20195
+ for (const entry of found) {
20196
+ filesInDir.push("/" + path__namespace["default"].relative(projectRoot, entry).split(path__namespace["default"].sep).join("/"));
20197
+ }
20198
+ } catch {
20199
+ // directory doesn't exist — no untracked files possible
20200
+ }
20201
+ return filesInDir;
20202
+ }
20203
+
20204
+ /**
20205
+ * The fixes of an `s.videoset()` — the video twin of an image gallery.
20206
+ *
20207
+ * A set is a record keyed by each video's file path (an HLS stream by its
20208
+ * master playlist), so most of this is the gallery fixes again with the key as
20209
+ * the file. Three things are not, and they are why this is a module of its own
20210
+ * rather than another branch in `fixHandlers.ts`:
20211
+ *
20212
+ * - **An entry is several files.** A stream's key is its master playlist, and
20213
+ * the media playlists and segments it names belong to the same entry. They
20214
+ * are tracked by it, uploaded with it, and none of them is an entry itself.
20215
+ * - **The set's directory holds files that are not entries.** A field picked
20216
+ * from the set (`s.video(videosVal)`) keeps its own poster and caption
20217
+ * tracks, and the Studio puts them where the set keeps its videos. A file a
20218
+ * video field names is accounted for, not untracked.
20219
+ * - **Fields elsewhere name an entry by its key.** Uploading an entry renames
20220
+ * its key to the remote ref, and every `s.video(videosVal)` whose `path` was
20221
+ * the old key would then name a video the set does not have. So the upload
20222
+ * rewrites them too (`otherModulePatches`).
20223
+ *
20224
+ * Nothing here imports `fixHandlers.ts` at runtime: that module registers
20225
+ * these handlers, and a cycle would hand it undefined ones.
20226
+ */
20227
+
20228
+ /** The fields of a set entry that are read from the bytes, in the order written. */
20229
+ const VIDEO_METADATA_FIELDS$1 = ["mimeType", "width", "height", "duration"];
20230
+
20231
+ /** What of a `Service` the project-wide walks need. */
20232
+
20233
+ function isRecord$1(value) {
20234
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20235
+ }
20236
+ function isPlaylist(ref) {
20237
+ return ref.split("?")[0].toLowerCase().endsWith(".m3u8");
20238
+ }
20239
+ function readFileOrUndefined(absolutePath) {
20240
+ try {
20241
+ return fs__default["default"].readFileSync(absolutePath);
20242
+ } catch {
20243
+ return undefined;
20244
+ }
20245
+ }
20246
+
20247
+ /** See `Internal.videosetEntryVideoSchema`: the Studio hashes against it too. */
20248
+ function videosetEntryVideoSchema(record) {
20249
+ return core.Internal.videosetEntryVideoSchema(record);
20250
+ }
20251
+
20252
+ /** The key of the set entry at `sourcePath`: its last module path segment. */
20253
+ function entryKeyOf(sourcePath) {
20254
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(sourcePath);
20255
+ const parts = core.Internal.splitModulePath(modulePath);
20256
+ return parts[parts.length - 1];
20257
+ }
20258
+
20259
+ /**
20260
+ * The patch path of `sourcePath`. Not `sourceToPatchPath`: a set's keys are
20261
+ * file paths, and their dots do not survive its `split(".")`.
20262
+ */
20263
+ function patchPathOf(sourcePath) {
20264
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(sourcePath);
20265
+ return core.Internal.splitModulePath(modulePath);
20266
+ }
20267
+
20268
+ /**
20269
+ * Every file a set entry holds: its key's file and, for an HLS stream, every
20270
+ * playlist and segment its master names — read from the LOCAL copy, which a
20271
+ * remote entry promoted by `--fix` still has, and which is the only place a
20272
+ * stream's tree can be followed from at all.
20273
+ */
20274
+ function filesOfVideosetEntry(entry, metadata, options) {
20275
+ const fields = isRecord$1(metadata) ? metadata : {};
20276
+ const mimeType = typeof fields.mimeType === "string" ? fields.mimeType : undefined;
20277
+ // The entry's poster and captions are its defaults' files: the set holds
20278
+ // them as it holds the video, so they are tracked by the entry — a remote
20279
+ // one by the local path it was uploaded from, as the key is.
20280
+ return filesOfVideo({
20281
+ path: entry.localPath,
20282
+ mimeType,
20283
+ poster: fields.poster,
20284
+ captions: fields.captions
20285
+ }, options).map(ref => galleryEntryOf(ref).localPath);
20286
+ }
20287
+
20288
+ /**
20289
+ * An entry with every file it names that `moved` has a new ref for pointed
20290
+ * at that ref: the poster and the captions, which a remote set keeps on the
20291
+ * content host with the video.
20292
+ */
20293
+ function withMovedFiles(entry, moved) {
20294
+ const movedPath = file => isRecord$1(file) && typeof file.path === "string" && moved.has(file.path) ? {
20295
+ ...file,
20296
+ path: moved.get(file.path)
20297
+ } : file;
20298
+ return {
20299
+ ...entry,
20300
+ ...(entry.poster !== undefined ? {
20301
+ poster: movedPath(entry.poster)
20302
+ } : {}),
20303
+ ...(Array.isArray(entry.captions) ? {
20304
+ captions: entry.captions.map(movedPath)
20305
+ } : {})
20306
+ };
20307
+ }
20308
+
20309
+ /** The entry's poster and caption files that are still local. */
20310
+ function localFilesOfEntry(entry) {
20311
+ const files = [];
20312
+ if (isRecord$1(entry.poster) && typeof entry.poster.path === "string") {
20313
+ files.push({
20314
+ path: entry.poster.path,
20315
+ role: "poster"
20316
+ });
20317
+ }
20318
+ if (Array.isArray(entry.captions)) {
20319
+ for (const track of entry.captions) {
20320
+ if (isRecord$1(track) && typeof track.path === "string") {
20321
+ files.push({
20322
+ path: track.path,
20323
+ role: "caption"
20324
+ });
20325
+ }
20326
+ }
20327
+ }
20328
+ return files.filter(file => !core.Internal.isRemoteMediaPath(file.path));
20329
+ }
20330
+
20331
+ /**
20332
+ * The untracked files of a set's directory, sorted into the ones `--fix` can
20333
+ * make entries of and the ones a person has to decide about.
20334
+ *
20335
+ * - `videos`: an untracked stream (keyed by its master playlist — the media
20336
+ * playlists and segments it names are part of it and listed nowhere), and a
20337
+ * progressive video the set accepts.
20338
+ * - `others`: everything else — a poster or caption no video field names, a
20339
+ * media playlist without a master, a video of a type the set does not
20340
+ * accept. `--fix` does not add these: none of them is a video the set could
20341
+ * hold, and deleting someone's file is not a fix.
20342
+ */
20343
+ function classifyUntrackedVideosetFiles({
20344
+ untracked,
20345
+ accept,
20346
+ projectRoot,
20347
+ readFile = readFileOrUndefined
20348
+ }) {
20349
+ const masters = untracked.filter(file => {
20350
+ var _readFile;
20351
+ if (!isPlaylist(file)) {
20352
+ return false;
20353
+ }
20354
+ const text = (_readFile = readFile(path__namespace["default"].join(projectRoot, file))) === null || _readFile === void 0 ? void 0 : _readFile.toString("utf-8");
20355
+ return text !== undefined && isHlsMasterPlaylist(text);
20356
+ });
20357
+ const partOfAStream = new Set();
20358
+ for (const master of masters) {
20359
+ for (const file of filesOfVideo({
20360
+ path: master
20361
+ }, {
20362
+ projectRoot,
20363
+ readFile
20364
+ })) {
20365
+ if (file !== master) {
20366
+ partOfAStream.add(file);
20367
+ }
20368
+ }
20369
+ }
20370
+ const videos = [];
20371
+ const others = [];
20372
+ for (const file of untracked) {
20373
+ if (partOfAStream.has(file)) {
20374
+ continue;
20375
+ }
20376
+ if (masters.includes(file)) {
20377
+ videos.push(file);
20378
+ continue;
20379
+ }
20380
+ const mimeType = core.Internal.filenameToMimeType(file);
20381
+ if (mimeType !== undefined && mimeType.startsWith("video/") && core.Internal.mimeTypeMatchesAccept(mimeType, accept)) {
20382
+ videos.push(file);
20383
+ } else {
20384
+ others.push(file);
20385
+ }
20386
+ }
20387
+ return {
20388
+ videos,
20389
+ others
20390
+ };
20391
+ }
20392
+
20393
+ /** Whether a serialized schema has a video field anywhere in it. */
20394
+ function hasVideoField(schema) {
20395
+ if (Array.isArray(schema)) {
20396
+ return schema.some(hasVideoField);
20397
+ }
20398
+ if (!isRecord$1(schema)) {
20399
+ return false;
20400
+ }
20401
+ if (schema.type === "video") {
20402
+ return true;
20403
+ }
20404
+ return Object.values(schema).some(hasVideoField);
20405
+ }
20406
+ /**
20407
+ * Every video field in the project, with its value.
20408
+ *
20409
+ * Validated reads for the modules that have one, because only those come back
20410
+ * with their `.jsonValues()` entries loaded — an unvalidated read hands back
20411
+ * each entry as a marker, and a field inside one would be invisible. Modules
20412
+ * without a video are read once, unvalidated, to find that out.
20413
+ */
20414
+ async function videoFieldsOf(service) {
20415
+ const found = [];
20416
+ for (const moduleFilePath of service.getModuleFilePaths()) {
20417
+ const shallow = await service.get(moduleFilePath, "", {
20418
+ validate: false
20419
+ });
20420
+ if (!hasVideoField(shallow.schema)) {
20421
+ continue;
20422
+ }
20423
+ const loaded = await service.get(moduleFilePath, "", {
20424
+ validate: true
20425
+ });
20426
+ if (loaded.source === undefined || !loaded.schema) {
20427
+ continue;
20428
+ }
20429
+ internal.traverseSchemaSource(loaded.source, loaded.schema, moduleFilePath, ({
20430
+ source,
20431
+ schema,
20432
+ path: sourcePath
20433
+ }) => {
20434
+ if (schema.type === "video") {
20435
+ found.push({
20436
+ moduleFilePath,
20437
+ sourcePath,
20438
+ source,
20439
+ schema
20440
+ });
20441
+ }
20442
+ });
20443
+ }
20444
+ return found;
20445
+ }
20446
+
20447
+ /**
20448
+ * The files video fields name — a video of its own, and the poster and
20449
+ * captions of every field — as `/public/…` refs, a remote one by the local
20450
+ * path it was uploaded from.
20451
+ */
20452
+ async function filesNamedByVideoFields(service, options) {
20453
+ const files = new Set();
20454
+ for (const field of await videoFieldsOf(service)) {
20455
+ for (const ref of filesOfVideo(field.source, options)) {
20456
+ // A remote ref by the path it encodes: `--fix` uploads a poster and
20457
+ // leaves the file where it was, exactly as it does a set's entry, and
20458
+ // that file is the field's — not something the set forgot.
20459
+ files.add(galleryEntryOf(ref).localPath);
20460
+ }
20461
+ }
20462
+ return files;
20463
+ }
20464
+
20465
+ /**
20466
+ * The patches that point every `s.video(set)` field at a set entry's new key.
20467
+ *
20468
+ * One `add` on each field's `path`, so the description, poster, times and
20469
+ * captions beside it are never rewritten. A field of another set, or of no
20470
+ * set, is left alone even when its path is the same string: it names its own
20471
+ * file.
20472
+ */
20473
+ async function videosetReferencePatches(service, setModuleFilePath, renamed) {
20474
+ const byModule = new Map();
20475
+ for (const field of await videoFieldsOf(service)) {
20476
+ if (field.schema.referencedModule !== setModuleFilePath) {
20477
+ continue;
20478
+ }
20479
+ const value = field.source;
20480
+ const current = isRecord$1(value) ? value.path : undefined;
20481
+ if (typeof current !== "string" || !(current in renamed)) {
20482
+ continue;
20483
+ }
20484
+ const patch = byModule.get(field.moduleFilePath) ?? [];
20485
+ patch.push({
20486
+ op: "add",
20487
+ path: patchPathOf(field.sourcePath).concat("path"),
20488
+ value: renamed[current]
20489
+ });
20490
+ byModule.set(field.moduleFilePath, patch);
20491
+ }
20492
+ return [...byModule].map(([moduleFilePath, patch]) => ({
20493
+ moduleFilePath,
20494
+ patch
20495
+ }));
20496
+ }
20497
+
20498
+ /** The record at `sourcePath` and its entries, or why it could not be read. */
20499
+ function resolveVideoset(module, sourcePath) {
20500
+ var _resolved$schema;
20501
+ if (module.source === undefined || !module.schema) {
20502
+ return {
20503
+ success: false,
20504
+ errorMessage: `Could not resolve source or schema for ${sourcePath}`
20505
+ };
20506
+ }
20507
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(sourcePath);
20508
+ const resolved = core.Internal.resolvePath(modulePath, module.source, module.schema);
20509
+ if (((_resolved$schema = resolved.schema) === null || _resolved$schema === void 0 ? void 0 : _resolved$schema.type) !== "record" || resolved.schema.mediaType !== "videos") {
20510
+ var _resolved$schema2;
20511
+ return {
20512
+ success: false,
20513
+ errorMessage: `Expected a video set at ${sourcePath}, got ${((_resolved$schema2 = resolved.schema) === null || _resolved$schema2 === void 0 ? void 0 : _resolved$schema2.type) ?? "nothing"}`
20514
+ };
20515
+ }
20516
+ return {
20517
+ success: true,
20518
+ record: resolved.schema,
20519
+ entries: isRecord$1(resolved.source) ? resolved.source : {}
20520
+ };
20521
+ }
20522
+
20523
+ /**
20524
+ * `videos:add-metadata`: the entry's KEY is its file, and it must be on disk
20525
+ * (or on Val Remote, read over HTTP) and a kind Val can read the size and
20526
+ * length of here — the same preconditions as `video:add-metadata`, asked of
20527
+ * the key instead of `path`.
20528
+ */
20529
+ async function handleVideosetMetadata(ctx) {
20530
+ const key = entryKeyOf(ctx.sourcePath);
20531
+ if (key === undefined) {
17959
20532
  return {
17960
- localPath: key,
17961
- remote: true
20533
+ success: false,
20534
+ errorMessage: `Expected a video set entry at ${ctx.sourcePath}`
20535
+ };
20536
+ }
20537
+ const absolute = path__namespace["default"].join(ctx.projectRoot, key);
20538
+ if (!galleryEntryOf(key).remote && !ctx.fs.fileExists(absolute)) {
20539
+ return {
20540
+ success: false,
20541
+ errorMessage: `File ${absolute} does not exist`
20542
+ };
20543
+ }
20544
+ const entry = ctx.validationError.value;
20545
+ const missing = ["width", "height", "duration"].filter(field => !isRecord$1(entry) || entry[field] === undefined);
20546
+ if (missing.length > 0 && !canReadVideoMetadata(key)) {
20547
+ return {
20548
+ success: false,
20549
+ errorMessage: unreadableVideoMetadataMessage(key, missing)
17962
20550
  };
17963
20551
  }
17964
20552
  return {
17965
- localPath: key,
17966
- remote: false
20553
+ success: true,
20554
+ shouldApplyPatch: true
17967
20555
  };
17968
20556
  }
17969
20557
 
17970
20558
  /**
17971
- * The media path a validation error is about, if it is about media at all.
17972
- *
17973
- * There is no schema in hand here — a `ValidationError` carries only the value
17974
- * it flagged — so the shape is all there is to go on.
20559
+ * `videos:check-remote`: a key that is wrong as a key — a remote URL in a set
20560
+ * that is not `.remote()`, one that does not parse, one outside the set's
20561
+ * directory. There is nothing to look up and nothing to move, so the error is
20562
+ * reported as it is, for a person: only they know which of the set's options
20563
+ * or the key is the mistake.
17975
20564
  */
17976
- function getValidationErrorFileRef(validationError) {
17977
- const maybePath = validationError.value && typeof validationError.value === "object" && "path" in validationError.value && typeof validationError.value.path === "string" ? validationError.value.path : undefined;
17978
- if (!maybePath) {
17979
- return null;
17980
- }
17981
- return maybePath;
20565
+ async function handleVideosetCheckRemote(ctx) {
20566
+ return {
20567
+ success: false,
20568
+ errorMessage: ctx.validationError.message
20569
+ };
17982
20570
  }
17983
20571
 
17984
- const textEncoder$1 = new TextEncoder();
17985
- async function checkRemoteRef(remoteHost, ref, projectRoot, schema, metadata) {
17986
- const remoteRefDataRes = core.Internal.remote.splitRemoteRef(ref);
17987
- if (remoteRefDataRes.status === "error") {
17988
- return remoteRefDataRes;
20572
+ /**
20573
+ * `videos:upload-remote`: an entry of a `.remote()` set still keyed by a local
20574
+ * path. Every file it holds goes up — a stream bottom-up, as the Studio places
20575
+ * one — and `createFixPatch` renames the key to the ref, the same way
20576
+ * `images:upload-remote` does. The fields that name the entry by its old key
20577
+ * are rewritten too: without that they name a video the set no longer has.
20578
+ *
20579
+ * The entry's poster and captions — its defaults' files — go up with it, and
20580
+ * are what is left to do for an entry whose key is already remote: the key
20581
+ * stays, and the entry is written back with their refs.
20582
+ */
20583
+ async function handleVideosetUploadRemote(ctx) {
20584
+ if (!ctx.fix) {
20585
+ return {
20586
+ success: false,
20587
+ // No sourcePath in the message: the reported location already points at it.
20588
+ errorMessage: `Video needs to be uploaded to Val Remote (use --fix to upload)`
20589
+ };
17989
20590
  }
17990
- const fileHash = remoteRefDataRes.fileHash;
17991
- if (!fileHash) {
20591
+ const key = ctx.validationError.value;
20592
+ if (typeof key !== "string") {
17992
20593
  return {
17993
- status: "error",
17994
- error: `File hash is missing in remote ref: ${ref}`
20594
+ success: false,
20595
+ errorMessage: `Expected a local file path for the video set entry at ${ctx.sourcePath}`
17995
20596
  };
17996
20597
  }
17997
- const relativeFilePath = remoteRefDataRes.filePath;
17998
- if (!relativeFilePath) {
20598
+ if (ctx.remoteFiles[ctx.sourcePath]) {
17999
20599
  return {
18000
- status: "error",
18001
- error: `File path is missing in remote ref: ${ref}`
20600
+ success: true,
20601
+ shouldApplyPatch: true,
20602
+ events: [{
20603
+ type: "remote-already-uploaded",
20604
+ filePath: key
20605
+ }]
18002
20606
  };
18003
20607
  }
18004
- if (!relativeFilePath.startsWith("public/")) {
20608
+ const set = resolveVideoset(ctx.valModule, core.Internal.parentOfSourcePath(ctx.sourcePath));
20609
+ if (!set.success) {
20610
+ return set;
20611
+ }
20612
+ const entry = set.entries[key];
20613
+ if (!isRecord$1(entry)) {
18005
20614
  return {
18006
- status: "error",
18007
- error: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
20615
+ success: false,
20616
+ errorMessage: `The video set has no entry '${key}' at ${ctx.sourcePath}`
18008
20617
  };
18009
20618
  }
18010
- const coreVersion = core.Internal.VERSION.core || "unknown";
18011
- const fileExt = getFileExt(relativeFilePath);
18012
- const currentValidationHash = core.Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata,
18013
- // TODO: validate
18014
- fileHash, textEncoder$1);
18015
- const validationHashFromRemoteRefValues = core.Internal.remote.getValidationHash(remoteRefDataRes.version, schema, getFileExt(remoteRefDataRes.filePath), metadata,
18016
- // TODO: validate
18017
- fileHash, textEncoder$1);
18018
- if (
18019
- // Current validation hash is the same as the remote validation hash
18020
- // We assume the uploaded file exists and is correct
18021
- currentValidationHash === remoteRefDataRes.validationHash &&
18022
- // This can happen if the version or fileExt has been tampered with
18023
- // (or if the way it is computed has changed)
18024
- validationHashFromRemoteRefValues === remoteRefDataRes.validationHash) {
20619
+ // The key is local (the entry goes up whole), or the key is already on the
20620
+ // content host and only the entry's poster or captions are still here.
20621
+ const keyIsLocal = !core.Internal.isRemoteMediaPath(key);
20622
+ const entryFiles = localFilesOfEntry(entry);
20623
+ const missing = firstMissingVideoFile(ctx, [...(keyIsLocal ? [{
20624
+ path: key,
20625
+ ...(typeof entry.mimeType === "string" ? {
20626
+ mimeType: entry.mimeType
20627
+ } : {})
20628
+ }] : []), ...entryFiles.map(file => ({
20629
+ path: file.path
20630
+ }))]);
20631
+ if (missing !== undefined) {
18025
20632
  return {
18026
- status: "success"
20633
+ success: false,
20634
+ errorMessage: `File ${missing} does not exist`
18027
20635
  };
18028
20636
  }
18029
- // Validation hash does not match, so we need to re-validate the remote content
18030
- const fileBufferRes = await getFileBufferFromRemote(ref, fileExt, remoteRefDataRes.fileHash, projectRoot);
18031
-
18032
- // We could not download the remote file for some reason (for example, the file hash is wrong)
18033
- if (fileBufferRes.status === "error") {
18034
- return fileBufferRes;
20637
+ const opened = await openRemoteUploadSession(ctx);
20638
+ if (!opened.success) {
20639
+ return opened.result;
18035
20640
  }
18036
-
18037
- // At this point we have the file buffer and we know the correct file hash
18038
- // We must create a new ref since something has changed
18039
-
18040
- let currentMetadata;
20641
+ const {
20642
+ session
20643
+ } = opened;
20644
+ const uploader = createVideoUploader(ctx, session, videosetEntryVideoSchema(set.record), (localRef, role) => metadataOf(localRef, role, entry));
20645
+ let ref;
18041
20646
  try {
18042
- if (schema.type === "image") {
18043
- currentMetadata = await extractImageMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
18044
- } else if (schema.type === "file") {
18045
- currentMetadata = await extractFileMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
18046
- } else {
18047
- const exhaustiveCheck = schema;
18048
- return {
18049
- status: "error",
18050
- error: `Unknown schema type: ${JSON.stringify(exhaustiveCheck)}`
18051
- };
20647
+ ref = keyIsLocal ? await uploader.put(key, "video") : key;
20648
+ for (const file of entryFiles) {
20649
+ await uploader.put(file.path, file.role);
18052
20650
  }
18053
20651
  } catch (err) {
18054
20652
  return {
18055
- status: "error",
18056
- error: `Failed to extract metadata from remote file: ${err instanceof Error ? err.message : "Unknown error"}. Cached file: ${fileBufferRes.cachedFilePath}`
20653
+ success: false,
20654
+ errorMessage: err instanceof Error ? err.message : String(err)
18057
20655
  };
18058
20656
  }
18059
- const updatedMetadata = {
18060
- ...metadata,
18061
- ...currentMetadata
20657
+ ctx.remoteFiles[ctx.sourcePath] = {
20658
+ ref,
20659
+ metadata: withMovedFiles(entry, uploader.moved),
20660
+ refs: Object.fromEntries(uploader.moved)
18062
20661
  };
18063
- const nextValidationHash = core.Internal.remote.getValidationHash(coreVersion, schema, fileExt, updatedMetadata, fileBufferRes.fileHash, textEncoder$1);
18064
- if (!updatedMetadata.mimeType) {
20662
+ const otherModulePatches = ref === key ? [] : await videosetReferencePatches(ctx.service, ctx.moduleFilePath, {
20663
+ [key]: ref
20664
+ });
20665
+ return {
20666
+ success: true,
20667
+ shouldApplyPatch: true,
20668
+ publicProjectId: session.publicProjectId,
20669
+ remoteFileBuckets: session.remoteFileBuckets,
20670
+ remoteFilesCounter: session.remoteFilesCounter,
20671
+ events: uploader.events,
20672
+ ...(otherModulePatches.length > 0 ? {
20673
+ otherModulePatches
20674
+ } : {})
20675
+ };
20676
+ }
20677
+
20678
+ /**
20679
+ * `videos:check-all-files`: the set's entries against its directory.
20680
+ *
20681
+ * What only this handler can answer is which untracked files are accounted
20682
+ * for ELSEWHERE — a poster or caption a video field names — because that needs
20683
+ * every module in the project. Those are fine. An untracked file that is not
20684
+ * a video and that no field names is for a person to look at, and is reported
20685
+ * here. Everything `--fix` can do something about — an entry whose file has
20686
+ * gone, a video in the directory the set does not list — is left to
20687
+ * `createFixPatch` (see {@link videosetCheckAllFilesPatch}), which reports it
20688
+ * per entry, or repairs it.
20689
+ */
20690
+ async function handleVideosetCheckAllFiles(ctx) {
20691
+ const value = ctx.validationError.value;
20692
+ const dir = isRecord$1(value) ? value.dir : undefined;
20693
+ if (typeof dir !== "string") {
18065
20694
  return {
18066
- status: "error",
18067
- error: `MIME type is missing in metadata: ${JSON.stringify(updatedMetadata)}`
20695
+ success: false,
20696
+ errorMessage: `Unexpected value in check-all-files for ${ctx.sourcePath}`
18068
20697
  };
18069
20698
  }
18070
- const newFileExt = core.Internal.mimeTypeToFileExt(updatedMetadata.mimeType);
18071
- const newFilePath = relativeFilePath.slice(0, -fileExt.length) + newFileExt;
18072
- return {
18073
- status: "fix-required",
18074
- metadata: updatedMetadata,
18075
- ref: core.Internal.remote.createRemoteRef(remoteHost, {
18076
- publicProjectId: remoteRefDataRes.projectId,
18077
- coreVersion,
18078
- bucket: remoteRefDataRes.bucket,
18079
- validationHash: nextValidationHash,
18080
- fileHash: fileBufferRes.fileHash,
18081
- filePath: newFilePath
20699
+ const set = resolveVideoset(ctx.valModule, ctx.sourcePath);
20700
+ if (!set.success) {
20701
+ return set;
20702
+ }
20703
+ const readFile = absolute => ctx.fs.readBuffer(absolute);
20704
+ const incompleteEntries = incompleteGalleryEntries({
20705
+ entryKeys: Object.keys(set.entries),
20706
+ projectRoot: ctx.projectRoot,
20707
+ fs: ctx.fs,
20708
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20709
+ projectRoot: ctx.projectRoot,
20710
+ readFile
18082
20711
  })
20712
+ });
20713
+ const {
20714
+ untrackedFiles
20715
+ } = checkGalleryFiles({
20716
+ entryKeys: Object.keys(set.entries),
20717
+ dir,
20718
+ projectRoot: ctx.projectRoot,
20719
+ fs: ctx.fs,
20720
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20721
+ projectRoot: ctx.projectRoot,
20722
+ readFile
20723
+ })
20724
+ });
20725
+ if (incompleteEntries.length > 0) {
20726
+ return {
20727
+ success: false,
20728
+ errorMessage: incompleteMessage(incompleteEntries)
20729
+ };
20730
+ }
20731
+ if (untrackedFiles.length === 0) {
20732
+ return {
20733
+ success: true,
20734
+ shouldApplyPatch: true
20735
+ };
20736
+ }
20737
+ const named = await filesNamedByVideoFields(ctx.service, {
20738
+ projectRoot: ctx.projectRoot,
20739
+ readFile
20740
+ });
20741
+ const {
20742
+ others
20743
+ } = classifyUntrackedVideosetFiles({
20744
+ untracked: untrackedFiles.filter(file => !named.has(file)),
20745
+ accept: set.record.accept ?? "video/*",
20746
+ projectRoot: ctx.projectRoot,
20747
+ readFile
20748
+ });
20749
+ if (others.length > 0) {
20750
+ return {
20751
+ success: false,
20752
+ errorMessage: `Video set in ${ctx.moduleFilePath} has files in '${dir}' that are not in the set, and that no video field uses: ${others.join(", ")}. They are not videos the set accepts, so --fix will not add them: move them out of the directory or remove them.`
20753
+ };
20754
+ }
20755
+ return {
20756
+ success: true,
20757
+ shouldApplyPatch: true
18083
20758
  };
18084
20759
  }
18085
- function getCachedRemoteFileDir(projectRoot) {
18086
- // store in projectRoot/.val/remote-file-cache
18087
- const remoteFileCacheDir = path__namespace["default"].join(projectRoot, ".val", "remote-file-cache");
18088
- return remoteFileCacheDir;
18089
- }
18090
- function getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir) {
18091
- const remoteFilePath = path__namespace["default"].join(remoteFileCacheDir, currentFileHash + "." + fileExt);
18092
- return remoteFilePath;
18093
- }
18094
- async function getFileBufferFromRemote(ref, fileExt, currentFileHash, projectRoot) {
18095
- const remoteFileCacheDir = getCachedRemoteFileDir(projectRoot);
18096
- const remoteFilePath = getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir);
18097
- try {
18098
- const fileBuffer = await fs__default["default"].promises.readFile(remoteFilePath);
18099
- const computedFileHash = core.Internal.remote.getFileHash(fileBuffer);
18100
- if (computedFileHash !== currentFileHash) {
18101
- await fs__default["default"].promises.unlink(remoteFilePath);
18102
- throw Error(`Cached file hash does not match the expected hash: ${computedFileHash} !== ${currentFileHash}`);
20760
+
20761
+ /**
20762
+ * The `createFixPatch` half of `videos:check-all-files`: drop the entries
20763
+ * whose file has gone, and add the videos in the directory that the set does
20764
+ * not list — with what is read from their bytes, or not at all.
20765
+ *
20766
+ * What is stored for an entry that IS on disk is not compared against its
20767
+ * bytes, unlike an image gallery's. The Studio reads a video's size and length
20768
+ * in the browser from the file as it was picked, and that is not what a header
20769
+ * parse of what is on disk says: a stream's largest rendition is not the
20770
+ * upload's size whenever the upload was larger than the largest rendition, and
20771
+ * two readers round a duration differently. Correcting one from the other
20772
+ * would rewrite every streamed video in the project, every run. A missing
20773
+ * value is `videos:add-metadata`'s, and is reported on the entry.
20774
+ */
20775
+ async function videosetCheckAllFilesPatch({
20776
+ projectRoot,
20777
+ apply,
20778
+ sourcePath,
20779
+ validationError,
20780
+ moduleSource,
20781
+ moduleSchema
20782
+ }) {
20783
+ const patch$1 = [];
20784
+ const remainingErrors = [];
20785
+ const fail = message => ({
20786
+ patch: patch$1,
20787
+ remainingErrors: [{
20788
+ ...validationError,
20789
+ message,
20790
+ fixes: undefined
20791
+ }]
20792
+ });
20793
+ const value = validationError.value;
20794
+ const dir = isRecord$1(value) ? value.dir : undefined;
20795
+ if (typeof dir !== "string") {
20796
+ return fail(`Unexpected value in check-all-files for ${sourcePath}`);
20797
+ }
20798
+ if (moduleSource === undefined || moduleSchema === undefined) {
20799
+ return fail("Unexpected error while checking a video set (no module source or schema)");
20800
+ }
20801
+ const set = resolveVideoset({
20802
+ source: moduleSource,
20803
+ schema: moduleSchema
20804
+ }, sourcePath);
20805
+ if (!set.success) {
20806
+ return fail(set.errorMessage);
20807
+ }
20808
+ const recordPath = patchPathOf(sourcePath);
20809
+ const incompleteEntries = incompleteGalleryEntries({
20810
+ entryKeys: Object.keys(set.entries),
20811
+ projectRoot,
20812
+ fs: ts__default["default"].sys,
20813
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20814
+ projectRoot
20815
+ })
20816
+ });
20817
+ const {
20818
+ missingTrackedFiles,
20819
+ untrackedFiles
20820
+ } = checkGalleryFiles({
20821
+ entryKeys: Object.keys(set.entries),
20822
+ dir,
20823
+ projectRoot,
20824
+ // The host `createDefaultValFSHost` gives the handlers, and so the same
20825
+ // listing the handler half of this check saw.
20826
+ fs: ts__default["default"].sys,
20827
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20828
+ projectRoot
20829
+ })
20830
+ });
20831
+ if (incompleteEntries.length > 0) {
20832
+ remainingErrors.push({
20833
+ ...validationError,
20834
+ message: incompleteMessage(incompleteEntries),
20835
+ fixes: undefined
20836
+ });
20837
+ }
20838
+ for (const missing of missingTrackedFiles) {
20839
+ if (apply) {
20840
+ const removePath = recordPath.concat(missing);
20841
+ if (patch.isNotRoot(removePath)) {
20842
+ patch$1.push({
20843
+ op: "remove",
20844
+ path: removePath
20845
+ });
20846
+ }
20847
+ } else {
20848
+ remainingErrors.push({
20849
+ ...validationError,
20850
+ message: `Video '${missing}' is in the set, but its file does not exist. Use --fix to remove it from the set.`,
20851
+ sourcePath: core.Internal.createValPathOfItem(sourcePath, missing),
20852
+ keyError: true
20853
+ });
18103
20854
  }
18104
- } catch {
20855
+ }
20856
+ const {
20857
+ videos
20858
+ } = classifyUntrackedVideosetFiles({
20859
+ untracked: untrackedFiles,
20860
+ accept: set.record.accept ?? "video/*",
20861
+ projectRoot
20862
+ });
20863
+ for (const file of videos) {
20864
+ let metadata;
18105
20865
  try {
18106
- await fs__default["default"].promises.mkdir(remoteFileCacheDir, {
18107
- recursive: true
20866
+ metadata = await extractVideoMetadataFromFile(path__namespace["default"].join(projectRoot, file));
20867
+ } catch (err) {
20868
+ remainingErrors.push({
20869
+ ...validationError,
20870
+ message: `Video '${file}' is in '${dir}' but not in the set, and its metadata could not be read: ${err instanceof Error ? err.message : String(err)}`,
20871
+ fixes: undefined
20872
+ });
20873
+ continue;
20874
+ }
20875
+ const unreadable = VIDEO_METADATA_FIELDS$1.filter(field => metadata[field] === undefined);
20876
+ if (unreadable.length > 0) {
20877
+ // All or nothing, as for `video:add-metadata`: an entry with a mime type
20878
+ // and no size is no closer to valid, and reads as one someone finished.
20879
+ remainingErrors.push({
20880
+ ...validationError,
20881
+ message: `Video '${file}' is in '${dir}' but not in the set. ${unreadableVideoMetadataMessage(file, unreadable)}`,
20882
+ fixes: undefined
20883
+ });
20884
+ continue;
20885
+ }
20886
+ if (!apply) {
20887
+ remainingErrors.push({
20888
+ ...validationError,
20889
+ message: `Video '${file}' is in '${dir}' but not in the set. Use --fix to add it.`
20890
+ });
20891
+ continue;
20892
+ }
20893
+ const entry = {};
20894
+ for (const field of VIDEO_METADATA_FIELDS$1) {
20895
+ const read = metadata[field];
20896
+ if (read !== undefined) {
20897
+ entry[field] = read;
20898
+ }
20899
+ }
20900
+ // What an upload writes when nobody has described the video yet.
20901
+ entry.alt = null;
20902
+ const addPath = recordPath.concat(file);
20903
+ if (patch.isNotRoot(addPath)) {
20904
+ patch$1.push({
20905
+ op: "add",
20906
+ path: addPath,
20907
+ value: entry
20908
+ });
20909
+ }
20910
+ }
20911
+ return {
20912
+ patch: patch$1,
20913
+ remainingErrors
20914
+ };
20915
+ }
20916
+
20917
+ /**
20918
+ * The `createFixPatch` half of `videos:add-metadata`: read what is missing
20919
+ * from the file at the entry's KEY, and write only that, one op per field —
20920
+ * `alt` and anything already there are someone's, and stay.
20921
+ */
20922
+ async function videosetAddMetadataPatch({
20923
+ projectRoot,
20924
+ sourcePath,
20925
+ validationError,
20926
+ moduleSource,
20927
+ moduleSchema
20928
+ }) {
20929
+ const fail = message => ({
20930
+ patch: [],
20931
+ remainingErrors: [{
20932
+ ...validationError,
20933
+ message,
20934
+ fixes: undefined
20935
+ }]
20936
+ });
20937
+ const key = entryKeyOf(sourcePath);
20938
+ if (key === undefined) {
20939
+ return fail(`Expected a video set entry at ${sourcePath}`);
20940
+ }
20941
+ let current = validationError.value;
20942
+ if (moduleSource !== undefined && moduleSchema !== undefined) {
20943
+ const parent = resolveVideoset({
20944
+ source: moduleSource,
20945
+ schema: moduleSchema
20946
+ }, core.Internal.parentOfSourcePath(sourcePath));
20947
+ if (!parent.success) {
20948
+ return fail(`Could not add video metadata: ${parent.errorMessage}`);
20949
+ }
20950
+ current = parent.entries[key];
20951
+ }
20952
+ if (!isRecord$1(current)) {
20953
+ return fail("Video set entry is not an object!");
20954
+ }
20955
+ let metadata;
20956
+ try {
20957
+ metadata = galleryEntryOf(key).remote ? await extractVideoMetadataFromUrl(key, nameForTypeOf(key)) : await extractVideoMetadataFromFile(path__namespace["default"].join(projectRoot, key));
20958
+ } catch (err) {
20959
+ return fail(`Failed to read video metadata from ${key}: ${err instanceof Error ? err.message : String(err)}`);
20960
+ }
20961
+ const entry = current;
20962
+ const missing = VIDEO_METADATA_FIELDS$1.filter(field => entry[field] === undefined);
20963
+ const unreadable = missing.filter(field => metadata[field] === undefined);
20964
+ if (unreadable.length > 0) {
20965
+ return fail(unreadableVideoMetadataMessage(key, unreadable));
20966
+ }
20967
+ const entryPath = patchPathOf(sourcePath);
20968
+ const patch = [];
20969
+ for (const field of missing) {
20970
+ const read = metadata[field];
20971
+ if (read !== undefined) {
20972
+ patch.push({
20973
+ op: "add",
20974
+ path: entryPath.concat(field),
20975
+ value: read
18108
20976
  });
18109
- await downloadFileFromRemote(ref, remoteFilePath);
18110
- } catch (err) {
18111
- try {
18112
- // try to delete in case of partial download
18113
- await fs__default["default"].promises.unlink(remoteFilePath);
18114
- } catch {
18115
- //
18116
- }
18117
- return {
18118
- status: "error",
18119
- error: `Failed to download remote file: ${err instanceof Error ? err.message : "Unknown error"}`
18120
- };
18121
20977
  }
18122
20978
  }
18123
- const fileBuffer = await fs__default["default"].promises.readFile(remoteFilePath);
18124
- const computedFileHash = core.Internal.remote.getFileHash(fileBuffer);
18125
20979
  return {
18126
- status: "success",
18127
- fileBuffer,
18128
- fileHash: computedFileHash,
18129
- cachedFilePath: remoteFilePath
20980
+ patch,
20981
+ remainingErrors: []
18130
20982
  };
18131
20983
  }
18132
- async function downloadFileFromRemote(ref, filePath) {
18133
- return new Promise((resolve, reject) => {
18134
- const url = new URL(ref);
18135
- const client = url.protocol === "https:" ? https__default$1["default"] : http__default$1["default"];
18136
- const request = client.get(url, response => {
18137
- if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
18138
- // Handle redirects
18139
- return downloadFileFromRemote(response.headers.location, filePath).then(resolve).catch(reject);
18140
- }
18141
- if (response.statusCode == 404) {
18142
- return reject(new Error(`${ref}. File not found. The URL is most likely incorrect.`));
18143
- }
18144
- if (response.statusCode !== 200) {
18145
- return reject(new Error(`${ref}. Failed to download file. HTTP Status: ${response.statusCode}`));
18146
- }
18147
- const writeStream = fs__default["default"].createWriteStream(filePath);
18148
- response.pipe(writeStream);
18149
- writeStream.on("finish", () => resolve({
18150
- status: "success",
18151
- filePath
18152
- }));
18153
- writeStream.on("error", err => reject(new Error(`${ref}. Error writing file: ${err.message}`)));
18154
- });
18155
- request.on("error", err => reject(new Error(`${ref}. Download error: ${err.message}`)));
18156
- request.end();
18157
- });
20984
+
20985
+ /**
20986
+ * What to say about streams whose master is there and some of whose files are
20987
+ * not. Not fixable: the entry still names a video someone uploaded, and only
20988
+ * they have the rest of it.
20989
+ */
20990
+ function incompleteMessage(incomplete) {
20991
+ return incomplete.map(({
20992
+ key,
20993
+ missing
20994
+ }) => `Video '${key}' is missing ${missing.length === 1 ? "a file it names" : `${missing.length} files it names`}: ${missing.join(", ")}. It stops playing where they are. Upload it again, or put the files back.`).join(" ");
18158
20995
  }
18159
20996
 
18160
20997
  // A remaining error may optionally carry a more specific `sourcePath` than the
@@ -18320,6 +21157,86 @@ async function createFixPatch(config, apply, sourcePath, validationError, remote
18320
21157
  value: fileMetadata.mimeType ?? null
18321
21158
  });
18322
21159
  }
21160
+ } else if (fix === "video:add-metadata") {
21161
+ // Only the fields that are MISSING, one op each: a video's `alt`,
21162
+ // `poster`, `captions` and times are authored and sit in the same
21163
+ // object, and a field already there is not re-read (see the comment on
21164
+ // the fix code in core — reading a video is not cheap).
21165
+ const current = currentVideoValue(sourcePath, validationError, moduleSource, moduleSchema);
21166
+ if (current.status === "error") {
21167
+ remainingErrors.push({
21168
+ ...validationError,
21169
+ message: current.message,
21170
+ fixes: undefined
21171
+ });
21172
+ continue;
21173
+ }
21174
+ const fileRef = current.value.path;
21175
+ if (typeof fileRef !== "string") {
21176
+ remainingErrors.push({
21177
+ ...validationError,
21178
+ message: `Cannot read video metadata: the video has no path`,
21179
+ fixes: undefined
21180
+ });
21181
+ continue;
21182
+ }
21183
+ let metadata;
21184
+ try {
21185
+ metadata = await getVideoMetadata(config.projectRoot, fileRef);
21186
+ } catch (err) {
21187
+ remainingErrors.push({
21188
+ ...validationError,
21189
+ message: `Failed to read video metadata from ${fileRef}: ${err instanceof Error ? err.message : String(err)}`,
21190
+ fixes: undefined
21191
+ });
21192
+ continue;
21193
+ }
21194
+ const missing = VIDEO_METADATA_FIELDS.filter(field => current.value[field] === undefined);
21195
+ const unreadable = missing.filter(field => metadata[field] === undefined);
21196
+ if (unreadable.length > 0) {
21197
+ // All or nothing: a video with a mime type but no size is no closer
21198
+ // to valid, and a half-written value reads as one someone finished.
21199
+ remainingErrors.push({
21200
+ ...validationError,
21201
+ message: unreadableVideoMetadataMessage(fileRef, unreadable),
21202
+ fixes: undefined
21203
+ });
21204
+ continue;
21205
+ }
21206
+ const patchPath = patch.sourceToPatchPath(sourcePath);
21207
+ for (const field of missing) {
21208
+ const value = metadata[field];
21209
+ if (value !== undefined) {
21210
+ patch$1.push({
21211
+ op: "add",
21212
+ path: patchPath.concat(field),
21213
+ value
21214
+ });
21215
+ }
21216
+ }
21217
+ } else if (fix === "videos:add-metadata") {
21218
+ // A set entry's twin of `video:add-metadata`: the file is the entry's
21219
+ // KEY, and only what is missing is written.
21220
+ const fixed = await videosetAddMetadataPatch({
21221
+ projectRoot: config.projectRoot,
21222
+ sourcePath,
21223
+ validationError,
21224
+ moduleSource,
21225
+ moduleSchema
21226
+ });
21227
+ patch$1.push(...fixed.patch);
21228
+ remainingErrors.push(...fixed.remainingErrors);
21229
+ } else if (fix === "videos:check-all-files") {
21230
+ const fixed = await videosetCheckAllFilesPatch({
21231
+ projectRoot: config.projectRoot,
21232
+ apply,
21233
+ sourcePath,
21234
+ validationError,
21235
+ moduleSource,
21236
+ moduleSchema
21237
+ });
21238
+ patch$1.push(...fixed.patch);
21239
+ remainingErrors.push(...fixed.remainingErrors);
18323
21240
  } else if (fix === "image:upload-remote" || fix === "file:upload-remote") {
18324
21241
  const remoteFile = remoteFiles[sourcePath];
18325
21242
  let metadata = remoteFile.metadata;
@@ -18349,10 +21266,30 @@ async function createFixPatch(config, apply, sourcePath, validationError, remote
18349
21266
  path: patch.sourceToPatchPath(sourcePath)
18350
21267
  });
18351
21268
  }
18352
- } else if (fix === "images:upload-remote" || fix === "files:upload-remote") {
21269
+ } else if (fix === "video:upload-remote" || fix === "video:download-remote") {
21270
+ var _remoteFiles$sourcePa;
21271
+ // The handler moved the files (`videoRemote.ts`); what is left is to
21272
+ // point each path the value holds at where its file now is. Read from
21273
+ // the module rather than the error, which carries the value as it was
21274
+ // validated.
21275
+ const moved = (_remoteFiles$sourcePa = remoteFiles[sourcePath]) === null || _remoteFiles$sourcePa === void 0 ? void 0 : _remoteFiles$sourcePa.refs;
21276
+ if (!moved) {
21277
+ remainingErrors.push({
21278
+ ...validationError,
21279
+ message: fix === "video:upload-remote" ? "Cannot point the video at Val Remote: its files were not uploaded" : "Cannot point the video at its local files: they were not downloaded",
21280
+ fixes: undefined
21281
+ });
21282
+ continue;
21283
+ }
21284
+ const current = moduleSource !== undefined && moduleSchema !== undefined ? core.Internal.resolvePath(core.Internal.splitModuleFilePathAndModulePath(sourcePath)[1], moduleSource, moduleSchema).source : validationError.value;
21285
+ patch$1.push(...rewriteVideoPathsPatch(sourcePath, current, moved));
21286
+ } else if (fix === "images:upload-remote" || fix === "files:upload-remote" || fix === "videos:upload-remote") {
18353
21287
  // Gallery entry: the record is keyed by the file path, so uploading to
18354
21288
  // remote means renaming the key from the local path to the remote URL
18355
- // (remove the old key, add the new one with the same metadata).
21289
+ // (remove the old key, add the new one with the same metadata). A video
21290
+ // set's entry is renamed to its MASTER playlist's ref for a stream: the
21291
+ // playlists and segments it names went up with it, and are named by the
21292
+ // uploaded master, not by the set.
18356
21293
  const remoteFile = remoteFiles[sourcePath];
18357
21294
  if (!remoteFile) {
18358
21295
  remainingErrors.push({
@@ -18711,6 +21648,52 @@ function getRemoteValueFromValidationError(v) {
18711
21648
  metadata
18712
21649
  };
18713
21650
  }
21651
+
21652
+ /** The fields of a video that are read from its bytes, in the order written. */
21653
+ const VIDEO_METADATA_FIELDS = ["mimeType", "width", "height", "duration"];
21654
+
21655
+ /**
21656
+ * The video a `video:add-metadata` error is about, read from the module at its
21657
+ * path when the module is at hand — the schema there decides that it IS a
21658
+ * video — and from the error's own value otherwise.
21659
+ */
21660
+ function currentVideoValue(sourcePath, validationError, moduleSource, moduleSchema) {
21661
+ if (moduleSource !== undefined && moduleSchema !== undefined) {
21662
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(sourcePath);
21663
+ const resolved = core.Internal.resolvePath(modulePath, moduleSource, moduleSchema);
21664
+ if (resolved.schema.type !== "video") {
21665
+ return {
21666
+ status: "error",
21667
+ message: `Could not add video metadata: schema at ${sourcePath} is '${resolved.schema.type}', not a video`
21668
+ };
21669
+ }
21670
+ const value = mediaValueOf(resolved.source);
21671
+ return value ? {
21672
+ status: "ok",
21673
+ value
21674
+ } : {
21675
+ status: "error",
21676
+ message: "Video is not an object!"
21677
+ };
21678
+ }
21679
+ const value = mediaValueOf(validationError.value);
21680
+ return value ? {
21681
+ status: "ok",
21682
+ value
21683
+ } : {
21684
+ status: "error",
21685
+ message: "Video is not an object!"
21686
+ };
21687
+ }
21688
+ async function getVideoMetadata(projectRoot, fileRef) {
21689
+ // Not read into memory: only the headers are, and a video is mostly not
21690
+ // headers. A remote video's headers are read over HTTP, with Range
21691
+ // requests, so it is not downloaded either.
21692
+ if (core.Internal.isRemoteMediaPath(fileRef)) {
21693
+ return extractVideoMetadataFromUrl(fileRef, nameForTypeOf(fileRef));
21694
+ }
21695
+ return extractVideoMetadataFromFile(path__namespace["default"].join(projectRoot, fileRef));
21696
+ }
18714
21697
  async function getImageMetadata(projectRoot, validationError) {
18715
21698
  const fileRef = getValidationErrorFileRef(validationError);
18716
21699
  if (!fileRef) {
@@ -18884,10 +21867,17 @@ function formatOpsError(error, sourceFile) {
18884
21867
  * What stays in the CLI is the driver: the `runValidation` async generator that
18885
21868
  * walks every module, decides what to report, and renders it to a terminal.
18886
21869
  */
18887
- const textEncoder = new TextEncoder();
18888
21870
 
18889
21871
  // Types for handler system
18890
21872
 
21873
+ /**
21874
+ * Where a fix moved a media value's file. `refs` is for a value that names
21875
+ * SEVERAL files — a video's poster, captions and stream — keyed by the path
21876
+ * the value held, so the patch can rewrite each one where it is.
21877
+ */
21878
+
21879
+ /** A patch, and the module it is for. */
21880
+
18891
21881
  // Handler functions
18892
21882
  async function handleFileMetadata(ctx) {
18893
21883
  var _fileSource$source;
@@ -18921,6 +21911,53 @@ async function handleFileMetadata(ctx) {
18921
21911
  };
18922
21912
  }
18923
21913
 
21914
+ /**
21915
+ * `video:add-metadata`: the bytes must be on disk, or on Val Remote (read
21916
+ * over HTTP, headers only — see `remoteVideoMetadata.ts`), and they must be a
21917
+ * kind of file Val can read the size and length of here: mp4/mov boxes,
21918
+ * WebM/Matroska headers and HLS playlists. Anything else is refused with what
21919
+ * to do instead, unless all that is missing is the mime type, which the
21920
+ * extension answers.
21921
+ */
21922
+ async function handleVideoMetadata(ctx) {
21923
+ const exists = isRemoteVideoAt(ctx) ? {
21924
+ success: true,
21925
+ shouldApplyPatch: true
21926
+ } : await handleFileMetadata(ctx);
21927
+ if (!exists.success) {
21928
+ return exists;
21929
+ }
21930
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(ctx.sourcePath);
21931
+ if (!ctx.valModule.source || !ctx.valModule.schema) {
21932
+ return exists;
21933
+ }
21934
+ const video = core.Internal.resolvePath(modulePath, ctx.valModule.source, ctx.valModule.schema).source;
21935
+ if (!isRecord(video) || typeof video.path !== "string") {
21936
+ return exists;
21937
+ }
21938
+ const missing = ["width", "height", "duration"].filter(field => video[field] === undefined);
21939
+ if (missing.length > 0 && !canReadVideoMetadata(video.path)) {
21940
+ return {
21941
+ success: false,
21942
+ errorMessage: unreadableVideoMetadataMessage(video.path, missing)
21943
+ };
21944
+ }
21945
+ return exists;
21946
+ }
21947
+
21948
+ /** Whether the video at the error's path is on Val Remote. */
21949
+ function isRemoteVideoAt(ctx) {
21950
+ if (!ctx.valModule.source || !ctx.valModule.schema) {
21951
+ return false;
21952
+ }
21953
+ const [, modulePath] = core.Internal.splitModuleFilePathAndModulePath(ctx.sourcePath);
21954
+ const video = core.Internal.resolvePath(modulePath, ctx.valModule.source, ctx.valModule.schema).source;
21955
+ return isRecord(video) && typeof video.path === "string" && core.Internal.isRemoteMediaPath(video.path);
21956
+ }
21957
+ function isRecord(value) {
21958
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21959
+ }
21960
+
18924
21961
  // Shared upload core used by both the single-field (handleRemoteFileUpload)
18925
21962
  // and gallery (handleRemoteGalleryFileUpload) handlers. The two differ only in
18926
21963
  // how they derive the local file ref, metadata and serialized image/file
@@ -18933,30 +21970,6 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
18933
21970
  errorMessage: `File ${filePath} does not exist`
18934
21971
  };
18935
21972
  }
18936
- const patFile = getPersonalAccessTokenPath(ctx.projectRoot);
18937
- if (!ctx.fs.fileExists(patFile)) {
18938
- return {
18939
- success: false,
18940
- errorMessage: `File: ${path__namespace["default"].join(ctx.projectRoot, ctx.file)} has remote images that are not uploaded and you are not logged in.\n\nFix this error by logging in:\n\t"npx val login"\n`
18941
- };
18942
- }
18943
- const patFileContent = ctx.fs.readFile(patFile);
18944
- if (patFileContent === undefined) {
18945
- return {
18946
- success: false,
18947
- errorMessage: `Could not read personal access token file at ${patFile}`
18948
- };
18949
- }
18950
- const parsedPatFile = parsePersonalAccessTokenFile(patFileContent);
18951
- if (!parsedPatFile.success) {
18952
- return {
18953
- success: false,
18954
- errorMessage: `Error parsing personal access token file: ${parsedPatFile.error}. You need to login again.`
18955
- };
18956
- }
18957
- const {
18958
- pat
18959
- } = parsedPatFile.data;
18960
21973
  if (ctx.remoteFiles[ctx.sourcePath]) {
18961
21974
  return {
18962
21975
  success: true,
@@ -18966,49 +21979,13 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
18966
21979
  }]
18967
21980
  };
18968
21981
  }
18969
- const projectName = ctx.project;
18970
- let publicProjectId = ctx.publicProjectId;
18971
- let remoteFileBuckets = ctx.remoteFileBuckets;
18972
- let remoteFilesCounter = ctx.remoteFilesCounter;
18973
- if (!publicProjectId || !remoteFileBuckets) {
18974
- if (!projectName) {
18975
- return {
18976
- success: false,
18977
- errorMessage: "Project name not found. Add project name to val.config or set the VAL_PROJECT environment variable"
18978
- };
18979
- }
18980
- const settingsRes = await ctx.remote.getSettings(projectName, {
18981
- pat
18982
- });
18983
- if (!settingsRes.success) {
18984
- return {
18985
- success: false,
18986
- errorMessage: `Could not get public project id: ${settingsRes.message}.`
18987
- };
18988
- }
18989
- publicProjectId = settingsRes.data.publicProjectId;
18990
- remoteFileBuckets = settingsRes.data.remoteFileBuckets.map(b => b.bucket);
18991
- }
18992
- if (!publicProjectId) {
18993
- return {
18994
- success: false,
18995
- errorMessage: "Could not get public project id"
18996
- };
18997
- }
18998
- if (!projectName) {
18999
- return {
19000
- success: false,
19001
- errorMessage: `Could not get project. Check that your val.config has the 'project' field set, or set it using the VAL_PROJECT environment variable`
19002
- };
19003
- }
19004
- remoteFilesCounter += 1;
19005
- const bucket = remoteFileBuckets[remoteFilesCounter % remoteFileBuckets.length];
19006
- if (!bucket) {
19007
- return {
19008
- success: false,
19009
- errorMessage: `Internal error: could not allocate a bucket for the remote file located at ${ctx.sourcePath}`
19010
- };
21982
+ const opened = await openRemoteUploadSession(ctx);
21983
+ if (!opened.success) {
21984
+ return opened.result;
19011
21985
  }
21986
+ const {
21987
+ session
21988
+ } = opened;
19012
21989
  const fileBuffer = ctx.fs.readBuffer(filePath);
19013
21990
  if (fileBuffer === undefined) {
19014
21991
  return {
@@ -19017,32 +21994,16 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
19017
21994
  };
19018
21995
  }
19019
21996
  const relativeFilePath = path__namespace["default"].relative(ctx.projectRoot, filePath).split(path__namespace["default"].sep).join("/");
19020
- if (!relativeFilePath.startsWith("public/")) {
19021
- return {
19022
- success: false,
19023
- errorMessage: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
19024
- };
19025
- }
19026
- const fileHash = core.Internal.remote.getFileHash(fileBuffer);
19027
- const coreVersion = core.Internal.VERSION.core || "unknown";
19028
- const fileExt = getFileExt(filePath);
19029
- const ref = core.Internal.remote.createRemoteRef(ctx.remote.remoteHost, {
19030
- publicProjectId,
19031
- coreVersion,
19032
- bucket,
19033
- validationHash: core.Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata, fileHash, textEncoder),
19034
- fileHash,
19035
- filePath: relativeFilePath
19036
- });
19037
- const remoteFileUpload = await ctx.remote.uploadFile(projectName, bucket, fileHash, fileExt, fileBuffer, {
19038
- pat
19039
- });
19040
- if (!remoteFileUpload.success) {
21997
+ const uploaded = await uploadBytesToRemote(ctx, session, relativeFilePath, fileBuffer, metadata, schema);
21998
+ if (!uploaded.success) {
19041
21999
  return {
19042
22000
  success: false,
19043
- errorMessage: `Could not upload remote file: '${ref}'. Error: ${remoteFileUpload.error}`
22001
+ errorMessage: uploaded.error
19044
22002
  };
19045
22003
  }
22004
+ const {
22005
+ ref
22006
+ } = uploaded;
19046
22007
  ctx.remoteFiles[ctx.sourcePath] = {
19047
22008
  ref,
19048
22009
  metadata
@@ -19050,9 +22011,9 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
19050
22011
  return {
19051
22012
  success: true,
19052
22013
  shouldApplyPatch: true,
19053
- publicProjectId,
19054
- remoteFileBuckets,
19055
- remoteFilesCounter,
22014
+ publicProjectId: session.publicProjectId,
22015
+ remoteFileBuckets: session.remoteFileBuckets,
22016
+ remoteFilesCounter: session.remoteFilesCounter,
19056
22017
  events: [{
19057
22018
  type: "remote-uploading",
19058
22019
  ref
@@ -19253,50 +22214,6 @@ async function handleUniqueFolderCheck(ctx) {
19253
22214
  success: true
19254
22215
  };
19255
22216
  }
19256
-
19257
- /**
19258
- * What is out of step between a gallery's entries and its directory.
19259
- *
19260
- * Two questions, and they treat a remote entry differently — which is the whole
19261
- * reason this is separate from the handler around it:
19262
- *
19263
- * - **Missing**: an entry with no bytes at its local path. Asked of LOCAL
19264
- * entries only. A remote entry's bytes live on the content host, and nothing
19265
- * puts a copy in the working tree: `saveOrUploadFiles` uploads the remote
19266
- * descriptors and copies only the local ones into the tree, so a remote entry
19267
- * added through the Studio (or over MCP) has no local file by design, and
19268
- * demanding one would mean committing remote bytes to git — which is what
19269
- * remote storage exists to avoid. Whether those bytes really are on the host
19270
- * is a different check, `image:check-remote`, which already runs for exactly
19271
- * these entries.
19272
- * - **Untracked**: a file in the directory that no entry claims. Asked of every
19273
- * entry, remote included, and that is why they are normalised to their local
19274
- * path: `val validate --fix` promotes a local file to a remote ref and leaves
19275
- * the file where it was, so a remote entry can perfectly well have one.
19276
- */
19277
- function checkGalleryFiles(input) {
19278
- const {
19279
- dir,
19280
- projectRoot,
19281
- fs
19282
- } = input;
19283
- const entries = input.entryKeys.map(galleryEntryOf);
19284
- const trackedFiles = new Set(entries.map(entry => entry.localPath));
19285
- const missingTrackedFiles = entries.filter(entry => !entry.remote && !fs.fileExists(path__namespace["default"].join(projectRoot, entry.localPath))).map(entry => entry.localPath);
19286
- const filesInDir = [];
19287
- try {
19288
- const found = fs.readDirectory(path__namespace["default"].join(projectRoot, dir), undefined, undefined, ["**/*"]);
19289
- for (const entry of found) {
19290
- filesInDir.push("/" + path__namespace["default"].relative(projectRoot, entry).split(path__namespace["default"].sep).join("/"));
19291
- }
19292
- } catch {
19293
- // directory doesn't exist — no untracked files possible
19294
- }
19295
- return {
19296
- missingTrackedFiles,
19297
- untrackedFiles: filesInDir.filter(f => !trackedFiles.has(f))
19298
- };
19299
- }
19300
22217
  async function handleCheckAllFiles(ctx) {
19301
22218
  const value = ctx.validationError.value;
19302
22219
  if (!value || typeof value.dir !== "string") {
@@ -19443,12 +22360,20 @@ const currentFixHandlers = {
19443
22360
  "image:add-metadata": handleFileMetadata,
19444
22361
  "file:check-metadata": handleFileMetadata,
19445
22362
  "file:add-metadata": handleFileMetadata,
22363
+ "video:add-metadata": handleVideoMetadata,
19446
22364
  "image:upload-remote": handleRemoteFileUpload,
19447
22365
  "file:upload-remote": handleRemoteFileUpload,
19448
22366
  "images:upload-remote": handleRemoteGalleryFileUpload,
19449
22367
  "files:upload-remote": handleRemoteGalleryFileUpload,
19450
22368
  "image:download-remote": handleRemoteFileDownload,
19451
22369
  "file:download-remote": handleRemoteFileDownload,
22370
+ "video:upload-remote": handleVideoUploadRemote,
22371
+ "video:download-remote": handleVideoDownloadRemote,
22372
+ "videos:add-metadata": handleVideosetMetadata,
22373
+ "videos:upload-remote": handleVideosetUploadRemote,
22374
+ "videos:check-remote": handleVideosetCheckRemote,
22375
+ "videos:check-unique-folder": handleUniqueFolderCheck,
22376
+ "videos:check-all-files": handleVideosetCheckAllFiles,
19452
22377
  "image:check-remote": handleRemoteFileCheck,
19453
22378
  "images:check-remote": handleRemoteFileCheck,
19454
22379
  "file:check-remote": handleRemoteFileCheck,
@@ -19644,20 +22569,15 @@ function createPrettierFormatter(prettier, options) {
19644
22569
  }
19645
22570
 
19646
22571
  /**
19647
- * NOTE: this is intentionally NOT `SharedValConfig` from `@valbuild/shared`.
19648
- * That schema requires `files.directory` to be exactly `/public/val`, whereas
19649
- * this one accepts any path beneath `/public`. Unifying them would change which
19650
- * configs are accepted, so they are kept separate on purpose.
22572
+ * NOTE: this is intentionally NOT `SharedValConfig` from `@valbuild/shared`,
22573
+ * which leaves `files` out: `files.remote` decides how the schemas are built,
22574
+ * so it is read where `val.config.ts` is, not shared with the client.
19651
22575
  */
19652
22576
  const ValConfigSchema = z__default["default"].object({
19653
22577
  project: z__default["default"].string().optional(),
19654
22578
  root: z__default["default"].string().optional(),
19655
22579
  files: z__default["default"].object({
19656
- directory: z__default["default"].string().refine(val => (val === "/public" || val.startsWith("/public/") && !val.endsWith("/")) &&
19657
- // Reject path traversal so the directory cannot escape /public
19658
- !val.split("/").some(segment => segment === "." || segment === ".."), {
19659
- message: "files.directory must start with '/public', must not end with '/' and must not contain '.' or '..' segments"
19660
- })
22580
+ remote: z__default["default"].boolean().optional()
19661
22581
  }).optional(),
19662
22582
  gitCommit: z__default["default"].string().optional(),
19663
22583
  gitBranch: z__default["default"].string().optional(),
@@ -20146,7 +23066,7 @@ async function replaySnapshot(snapshotDir) {
20146
23066
  const serverOps = new ValOpsFS(process.env.VAL_CONTENT_URL || core.DEFAULT_CONTENT_HOST, root, valModules,
20147
23067
  // The snapshot's own val.config, as evaluated by loadValModules - no need to
20148
23068
  // re-read it, and this way the replay uses exactly the config the snapshot
20149
- // carries (files.directory in particular).
23069
+ // carries.
20150
23070
  {
20151
23071
  config: valModules.config
20152
23072
  });
@@ -20229,6 +23149,7 @@ Object.defineProperty(exports, 'hasRemoteFileSchema', {
20229
23149
  enumerable: true,
20230
23150
  get: function () { return core.hasRemoteFileSchema; }
20231
23151
  });
23152
+ exports.APP_MODE_REQUIRES_REMOTE_FILES = APP_MODE_REQUIRES_REMOTE_FILES;
20232
23153
  exports.DEFAULT_LOGIN_EXPIRES_IN_SECONDS = DEFAULT_LOGIN_EXPIRES_IN_SECONDS;
20233
23154
  exports.DEFAULT_LOGIN_HOST = DEFAULT_LOGIN_HOST;
20234
23155
  exports.DEFAULT_LOGIN_POLL_INTERVAL_SECONDS = DEFAULT_LOGIN_POLL_INTERVAL_SECONDS;
@@ -20268,6 +23189,10 @@ exports.evalValConfigFile = evalValConfigFile;
20268
23189
  exports.extractFileMetadata = extractFileMetadata;
20269
23190
  exports.extractImageMetadata = extractImageMetadata;
20270
23191
  exports.extractJsonValuesEntry = extractJsonValuesEntry;
23192
+ exports.extractVideoMetadata = extractVideoMetadata;
23193
+ exports.extractVideoMetadataFromFile = extractVideoMetadataFromFile;
23194
+ exports.filesOfVideo = filesOfVideo;
23195
+ exports.filesOfVideosetEntry = filesOfVideosetEntry;
20271
23196
  exports.findAndEvalValConfigFile = findAndEvalValConfigFile;
20272
23197
  exports.findDefaultExport = findDefaultExport;
20273
23198
  exports.findJsonEntryFilePath = findJsonEntryFilePath;
@@ -20292,6 +23217,10 @@ exports.handleRemoteFileDownload = handleRemoteFileDownload;
20292
23217
  exports.handleRemoteFileUpload = handleRemoteFileUpload;
20293
23218
  exports.handleRemoteGalleryFileUpload = handleRemoteGalleryFileUpload;
20294
23219
  exports.handleUniqueFolderCheck = handleUniqueFolderCheck;
23220
+ exports.handleVideosetCheckAllFiles = handleVideosetCheckAllFiles;
23221
+ exports.handleVideosetCheckRemote = handleVideosetCheckRemote;
23222
+ exports.handleVideosetMetadata = handleVideosetMetadata;
23223
+ exports.handleVideosetUploadRemote = handleVideosetUploadRemote;
20295
23224
  exports.initHandlerOptions = initHandlerOptions;
20296
23225
  exports.isExternalResult = isExternalResult;
20297
23226
  exports.loadValModules = loadValModules;
@@ -20310,3 +23239,4 @@ exports.startValLogin = startValLogin;
20310
23239
  exports.uploadRemoteFile = uploadRemoteFile;
20311
23240
  exports.validateMetadata = validateMetadata;
20312
23241
  exports.verifyJwt = verifyJwt;
23242
+ exports.videosetEntryVideoSchema = videosetEntryVideoSchema;