@uploadfilm/sdk 0.0.0-stage → 0.1.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.
Files changed (218) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +509 -2
  3. package/dist/ai/embed.d.ts +58 -0
  4. package/dist/ai/fake.d.ts +41 -0
  5. package/dist/ai/http.d.ts +17 -0
  6. package/dist/ai/index.d.ts +27 -0
  7. package/dist/ai/languages.d.ts +2 -0
  8. package/dist/ai/ollama.d.ts +23 -0
  9. package/dist/ai/openaiCompatible.d.ts +54 -0
  10. package/dist/ai/passages.d.ts +28 -0
  11. package/dist/ai/transcribe.d.ts +84 -0
  12. package/dist/ai/types.d.ts +141 -0
  13. package/dist/ai/usage.d.ts +66 -0
  14. package/dist/ai/whisperJson.d.ts +15 -0
  15. package/dist/ai/workersAi.d.ts +56 -0
  16. package/dist/ai.js +1 -0
  17. package/dist/ai.mjs +1 -0
  18. package/dist/cards/files.d.ts +91 -0
  19. package/dist/cards/index.d.ts +15 -0
  20. package/dist/cards/layouts.d.ts +121 -0
  21. package/dist/cards/probe.d.ts +69 -0
  22. package/dist/cards/proxies.d.ts +70 -0
  23. package/dist/cards/select.d.ts +68 -0
  24. package/dist/cards/volumes.d.ts +170 -0
  25. package/dist/cards/xml.d.ts +80 -0
  26. package/dist/cards.js +1 -0
  27. package/dist/cards.mjs +1 -0
  28. package/dist/copy/checksums.d.ts +66 -0
  29. package/dist/copy/engine.d.ts +24 -0
  30. package/dist/copy/errors.d.ts +109 -0
  31. package/dist/copy/index.d.ts +15 -0
  32. package/dist/copy/steps.d.ts +28 -0
  33. package/dist/copy/sweep.d.ts +24 -0
  34. package/dist/copy/types.d.ts +336 -0
  35. package/dist/embed/player.js +2 -0
  36. package/dist/host/adapters.d.ts +107 -0
  37. package/dist/host/detect.d.ts +68 -0
  38. package/dist/host/encoders.d.ts +34 -0
  39. package/dist/host/environment.d.ts +53 -0
  40. package/dist/host/index.d.ts +20 -0
  41. package/dist/host/linux.d.ts +94 -0
  42. package/dist/host/mac.d.ts +47 -0
  43. package/dist/host/network.d.ts +54 -0
  44. package/dist/host/node.d.ts +13 -0
  45. package/dist/host/policy.d.ts +101 -0
  46. package/dist/host/tuner.d.ts +48 -0
  47. package/dist/host/types.d.ts +118 -0
  48. package/dist/host-node.js +1 -0
  49. package/dist/host-node.mjs +1 -0
  50. package/dist/host.js +1 -0
  51. package/dist/host.mjs +1 -0
  52. package/dist/images/index.d.ts +11 -0
  53. package/dist/images/settings.d.ts +43 -0
  54. package/dist/images/types.d.ts +83 -0
  55. package/dist/images/url.d.ts +65 -0
  56. package/dist/index.d.ts +16 -0
  57. package/dist/index.js +1 -0
  58. package/dist/index.mjs +1 -0
  59. package/dist/player/adapters/hlsjs.d.ts +28 -0
  60. package/dist/player/bandwidthMemory.d.ts +28 -0
  61. package/dist/player/captions/index.d.ts +55 -0
  62. package/dist/player/embed/code.d.ts +195 -0
  63. package/dist/player/embed/constants.d.ts +4 -0
  64. package/dist/player/embed/controller.d.ts +62 -0
  65. package/dist/player/embed/element.d.ts +32 -0
  66. package/dist/player/embed/frame.d.ts +65 -0
  67. package/dist/player/embed/global.d.ts +14 -0
  68. package/dist/player/embed/index.d.ts +15 -0
  69. package/dist/player/embed/loader.d.ts +1 -0
  70. package/dist/player/embed/oembed.d.ts +74 -0
  71. package/dist/player/embed/protocol.d.ts +64 -0
  72. package/dist/player/engine.d.ts +215 -0
  73. package/dist/player/index.d.ts +18 -0
  74. package/dist/player/start.d.ts +62 -0
  75. package/dist/player/store.d.ts +10 -0
  76. package/dist/player/storyboard/index.d.ts +161 -0
  77. package/dist/player/stream.d.ts +206 -0
  78. package/dist/player/tracks.d.ts +41 -0
  79. package/dist/player.js +1 -0
  80. package/dist/player.mjs +1 -0
  81. package/dist/proxies/args.d.ts +19 -0
  82. package/dist/proxies/budget.d.ts +57 -0
  83. package/dist/proxies/camera.d.ts +104 -0
  84. package/dist/proxies/formats.d.ts +36 -0
  85. package/dist/proxies/index.d.ts +18 -0
  86. package/dist/proxies/jobs.d.ts +98 -0
  87. package/dist/proxies/node.d.ts +32 -0
  88. package/dist/proxies/plan.d.ts +89 -0
  89. package/dist/proxies/probe.d.ts +39 -0
  90. package/dist/proxies/render.d.ts +104 -0
  91. package/dist/proxies/safety.d.ts +45 -0
  92. package/dist/proxies/types.d.ts +83 -0
  93. package/dist/proxies/upload.d.ts +14 -0
  94. package/dist/react/BigPlay.d.ts +26 -0
  95. package/dist/react/Player.d.ts +58 -0
  96. package/dist/react/embed/index.d.ts +45 -0
  97. package/dist/react/examples/CustomControls.d.ts +8 -0
  98. package/dist/react/images/Image.d.ts +16 -0
  99. package/dist/react/images/index.d.ts +4 -0
  100. package/dist/react/images/useImage.d.ts +47 -0
  101. package/dist/react/index.d.ts +17 -0
  102. package/dist/react/storyboard/index.d.ts +58 -0
  103. package/dist/react/theme.d.ts +37 -0
  104. package/dist/react/useAdapterErrors.d.ts +8 -0
  105. package/dist/react/usePlaybackStart.d.ts +18 -0
  106. package/dist/react/usePlayer.d.ts +28 -0
  107. package/dist/react/useReducedMotion.d.ts +2 -0
  108. package/dist/react/useTimedTrack.d.ts +22 -0
  109. package/dist/react.js +1 -0
  110. package/dist/react.mjs +1 -0
  111. package/dist/server/auth/apiKeys.d.ts +30 -0
  112. package/dist/server/auth/cache.d.ts +21 -0
  113. package/dist/server/auth/deviceTokens.d.ts +38 -0
  114. package/dist/server/auth/envelope.d.ts +15 -0
  115. package/dist/server/auth/grants.d.ts +76 -0
  116. package/dist/server/auth/index.d.ts +19 -0
  117. package/dist/server/auth/jwt.d.ts +65 -0
  118. package/dist/server/auth/keyring.d.ts +31 -0
  119. package/dist/server/auth/kv.d.ts +12 -0
  120. package/dist/server/auth/repository.d.ts +45 -0
  121. package/dist/server/auth/revocations.d.ts +21 -0
  122. package/dist/server/auth/scope.d.ts +4 -0
  123. package/dist/server/auth/serviceAuth.d.ts +24 -0
  124. package/dist/server/auth/signedUrls.d.ts +28 -0
  125. package/dist/server/embed/index.d.ts +36 -0
  126. package/dist/server/embed/lifecycle.d.ts +53 -0
  127. package/dist/server/embed/playerScript.d.ts +4 -0
  128. package/dist/server/images/index.d.ts +15 -0
  129. package/dist/server/images/job.d.ts +80 -0
  130. package/dist/server/images/layout.d.ts +24 -0
  131. package/dist/server/images/params.d.ts +90 -0
  132. package/dist/server/images/route.d.ts +101 -0
  133. package/dist/server/images/sign.d.ts +55 -0
  134. package/dist/server/index.d.ts +42 -0
  135. package/dist/server/media/client.d.ts +66 -0
  136. package/dist/server/media/frameCheck.d.ts +62 -0
  137. package/dist/server/media/index.d.ts +10 -0
  138. package/dist/server/media/protocol.d.ts +318 -0
  139. package/dist/server/media/storyboard.d.ts +144 -0
  140. package/dist/server/media/transcript.d.ts +143 -0
  141. package/dist/server/pipeline/index.d.ts +12 -0
  142. package/dist/server/pipeline/match.d.ts +10 -0
  143. package/dist/server/pipeline/pipeline.d.ts +182 -0
  144. package/dist/server/pipeline/queues.d.ts +108 -0
  145. package/dist/server/pipeline/sources.d.ts +54 -0
  146. package/dist/server/r2/client.d.ts +150 -0
  147. package/dist/server/r2/crc32.d.ts +24 -0
  148. package/dist/server/r2/encoding.d.ts +35 -0
  149. package/dist/server/r2/errors.d.ts +9 -0
  150. package/dist/server/r2/integrity.d.ts +25 -0
  151. package/dist/server/r2/parts.d.ts +46 -0
  152. package/dist/server/r2/sign.d.ts +47 -0
  153. package/dist/server/redis/index.d.ts +39 -0
  154. package/dist/server/state/memory.d.ts +18 -0
  155. package/dist/server/state/r2.d.ts +73 -0
  156. package/dist/server/state/types.d.ts +57 -0
  157. package/dist/server/storage/chunked.d.ts +21 -0
  158. package/dist/server/storage/index.d.ts +12 -0
  159. package/dist/server/storage/r2.d.ts +96 -0
  160. package/dist/server/storage/s3.d.ts +93 -0
  161. package/dist/server/testing/fake-r2.d.ts +390 -0
  162. package/dist/server/testing/index.d.ts +10 -0
  163. package/dist/server/testing/kv-contract.d.ts +14 -0
  164. package/dist/server/transfer/handler.d.ts +167 -0
  165. package/dist/server/transfer/keys.d.ts +45 -0
  166. package/dist/server/transfer/protocol.d.ts +141 -0
  167. package/dist/server/zip/client.d.ts +32 -0
  168. package/dist/server/zip/generations.d.ts +83 -0
  169. package/dist/server/zip/index.d.ts +12 -0
  170. package/dist/server/zip/planner.d.ts +94 -0
  171. package/dist/server/zip/sign.d.ts +22 -0
  172. package/dist/server-media.js +1 -0
  173. package/dist/server-media.mjs +1 -0
  174. package/dist/server-redis.js +1 -0
  175. package/dist/server-redis.mjs +1 -0
  176. package/dist/server-testing.js +1 -0
  177. package/dist/server-testing.mjs +1 -0
  178. package/dist/server.js +1 -0
  179. package/dist/server.mjs +1 -0
  180. package/dist/storage/browserFile.d.ts +19 -0
  181. package/dist/storage/index.d.ts +12 -0
  182. package/dist/storage/local.d.ts +9 -0
  183. package/dist/storage/presigned.d.ts +22 -0
  184. package/dist/sync/ffmpeg.d.ts +44 -0
  185. package/dist/sync/index.d.ts +17 -0
  186. package/dist/sync/match.d.ts +28 -0
  187. package/dist/sync/probe.d.ts +30 -0
  188. package/dist/sync/timecode.d.ts +50 -0
  189. package/dist/sync/transcript.d.ts +35 -0
  190. package/dist/sync/types.d.ts +172 -0
  191. package/dist/sync/waveform.d.ts +89 -0
  192. package/dist/sync.js +1 -0
  193. package/dist/sync.mjs +1 -0
  194. package/dist/transfer/claims.d.ts +41 -0
  195. package/dist/transfer/client.d.ts +256 -0
  196. package/dist/transfer/download.d.ts +192 -0
  197. package/dist/transfer/engine.d.ts +382 -0
  198. package/dist/transfer/errors.d.ts +50 -0
  199. package/dist/transfer/index.d.ts +39 -0
  200. package/dist/transfer/integrity.d.ts +93 -0
  201. package/dist/transfer/limits.d.ts +34 -0
  202. package/dist/transfer/node.d.ts +63 -0
  203. package/dist/transfer/pool.d.ts +83 -0
  204. package/dist/transfer/protocol.d.ts +167 -0
  205. package/dist/transfer/signer.d.ts +29 -0
  206. package/dist/transfer/storage.d.ts +110 -0
  207. package/dist/transfer/timing.d.ts +132 -0
  208. package/dist/transfer/transports/electronNet.d.ts +62 -0
  209. package/dist/transfer/transports/fetch.d.ts +15 -0
  210. package/dist/transfer/transports/retryAfter.d.ts +12 -0
  211. package/dist/transfer/transports/undici.d.ts +72 -0
  212. package/dist/transfer/tuner.d.ts +56 -0
  213. package/dist/zip/index.d.ts +13 -0
  214. package/dist/zip/layout.d.ts +129 -0
  215. package/dist/zip/names.d.ts +34 -0
  216. package/dist/zip/plan.d.ts +115 -0
  217. package/dist/zip/sw.d.ts +7 -0
  218. package/package.json +265 -4
@@ -0,0 +1,167 @@
1
+ import type { R2Client } from "../r2/client";
2
+ import type { TransferOp, TransferResult } from "./protocol";
3
+ /** Base64 of a 16-byte MD5: 22 chars + "==". */
4
+ export declare const MD5_B64: RegExp;
5
+ /** "ok" lets the write through; anything else refuses it (unknown answers too: fail closed). */
6
+ export type ReserveOutcome = "ok" | "quota" | "exists" | "deleted" | {
7
+ refuse: TransferResult;
8
+ };
9
+ /** What the dedupe hook found: a key in the caller's own scope, or one elsewhere it explicitly authorizes. */
10
+ export type DedupeSource = {
11
+ key: string;
12
+ etag: string;
13
+ crossScopeAuthorized?: true;
14
+ } | null;
15
+ /** One write about to be issued, as the grant hook sees it. */
16
+ export interface GrantEntry {
17
+ index: number;
18
+ op: string;
19
+ key: string;
20
+ /** How long what is being issued stays usable (URL TTL, or the server-side window for create/complete). */
21
+ ttlSeconds: number;
22
+ }
23
+ export interface CustomOp<Ctx> {
24
+ /**
25
+ * The key this op will write, for the grant hook (null: no grant). Keyless ops derive their key from the context
26
+ * and the op, never from the client.
27
+ */
28
+ grantKey?: (op: Record<string, unknown>, ctx: Ctx) => string | null;
29
+ /** TTL recorded with the grant. */
30
+ grantTtlSeconds?: number;
31
+ /** What a refused grant answers for this op. */
32
+ refused?: TransferResult;
33
+ run: (op: Record<string, unknown>, ctx: Ctx) => Promise<TransferResult> | TransferResult;
34
+ }
35
+ export interface SignHandlerOptions<Kind extends string, Ctx> {
36
+ /** Storage access (presign + control plane). Per call, so a product can pick a bucket per context. */
37
+ r2: R2Client | ((ctx: Ctx) => R2Client);
38
+ /** The key-layout guard for this context's scope: the key's kind, or null when it isn't one of the layouts. */
39
+ classify: (key: unknown, ctx: Ctx) => Kind | null;
40
+ /** Kinds written once and counted (UploadFilm: originals). Default: none. */
41
+ immutable?: (kind: Kind) => boolean;
42
+ limits?: {
43
+ /** Ops per call (default 64). */
44
+ maxOps?: number;
45
+ /** Parts per multipart upload (default 10,000). */
46
+ maxParts?: number;
47
+ /** Largest object (default 5 TiB, S3's). */
48
+ maxObjectSize?: number;
49
+ /** Presigned part/put URL lifetime, seconds (default 3600). */
50
+ presignTtlSeconds?: number;
51
+ /** Grant window recorded for server-side writes (create/complete), seconds (default 300). */
52
+ serverWriteTtlSeconds?: number;
53
+ /** Content-Type values are cut to this many characters (default 200). */
54
+ maxContentType?: number;
55
+ };
56
+ /** Product copy for the refusals clients show. */
57
+ messages?: {
58
+ quota?: string;
59
+ exists?: string;
60
+ deleted?: string;
61
+ busy?: string;
62
+ refused?: string;
63
+ internal?: string;
64
+ /** The 403 body's error when a key is outside the layouts. */
65
+ foreignKey?: (ctx: Ctx) => string;
66
+ };
67
+ hooks?: {
68
+ /** Whole-batch and per-op refusals before anything runs (per-op results are final for that op). */
69
+ guard?: (batch: {
70
+ ops: Record<string, unknown>[];
71
+ writes: boolean[];
72
+ custom: boolean[];
73
+ }, ctx: Ctx) => Promise<GuardOutcome> | GuardOutcome;
74
+ /** Record/re-check writes right before they are issued. Returns the indices it refuses (→ `messages.deleted`, or the custom op's `refused`). */
75
+ grant?: (entries: GrantEntry[], ctx: Ctx) => Promise<Iterable<number>> | Iterable<number>;
76
+ /**
77
+ * Per-request lifetime of the presigned part/put URLs, seconds (e.g. what's left of the caller's token, so a URL
78
+ * never outlives the credential it was issued to). Called once per batch; it applies to the URLs, their
79
+ * `expiresAt` and the grants' `ttlSeconds`. It can only lower `limits.presignTtlSeconds`, never raise it.
80
+ * undefined/null: the global limit. Anything that isn't a positive number fails closed to 1 s.
81
+ */
82
+ presignTtl?: (ctx: Ctx) => Promise<number | null | undefined> | number | null | undefined;
83
+ /**
84
+ * Charge an immutable write before it is issued. `uploadId` null for create (bound later), "put" for a single PUT.
85
+ * Only immutable kinds are reserved (see the module comment: "charge per key").
86
+ */
87
+ reserve?: (ctx: Ctx, w: {
88
+ key: string;
89
+ size: number;
90
+ kind: Kind;
91
+ uploadId: string | null;
92
+ }) => Promise<ReserveOutcome> | ReserveOutcome;
93
+ /** The multipart upload created for a reserved key. */
94
+ bindUpload?: (ctx: Ctx, key: string, uploadId: string) => Promise<void> | void;
95
+ /** An immutable object is stored at `size` bytes (complete / head / dedupe copy). */
96
+ confirm?: (ctx: Ctx, key: string, size: number) => Promise<void> | void;
97
+ /**
98
+ * A reserved multipart upload was aborted BY THIS CALL (storage removed it: an open upload, so one that never
99
+ * completed) and nothing else can use the key's reservation now: no other multipart
100
+ * upload of the key is open in storage (one may be completing against it, or complete later) and nothing is stored
101
+ * at the key (a complete that just landed and whose `confirm` hasn't run yet). Otherwise the handler doesn't call
102
+ * it, and the reservation stays for that upload (BL-S22: releasing it let another key take the quota while an older
103
+ * multipart of the same key completed, over quota); a product's reconcile frees reservations nothing ever used.
104
+ * Not called when storage answers the abort with NoSuchUpload: the upload was completed (its object may have been
105
+ * deleted since: storage can't tell), aborted before (a repeated abort), expired, or never was this key's (a made-up
106
+ * id); the reservation stays for the product's reconcile (UploadFilm: lib/crons.ts) or a new create of the key.
107
+ * Aborts of one upload repeated in a batch run once (the others answer the same). Still, keep it idempotent: delete
108
+ * only a row that is unconfirmed and bound to this uploadId.
109
+ * Never called for the uploadId "put" (a single PUT's reservation). Storage can't show an outstanding single-PUT URL:
110
+ * a product whose ledger keeps one reservation per key must not let a create re-bind a reservation made for a PUT
111
+ * (UploadFilm keeps such a row bound to "put"), or aborting that multipart would free quota the URL can still use.
112
+ */
113
+ release?: (ctx: Ctx, key: string, uploadId: string) => Promise<void> | void;
114
+ /**
115
+ * The bytes reserved for this multipart upload of an immutable kind (what `reserve` charged for it, bound by
116
+ * `bindUpload`), or null when there is no reservation for it. At `complete` the handler sums the sizes storage
117
+ * holds for the parts being completed (ListParts) and refuses, and aborts, an upload over its reservation (or over
118
+ * `maxObjectSize`): part URLs aren't length-bound, so without this a client could reserve 1 byte and store
119
+ * terabytes. Null refuses the complete (non-retryable `ReservationRefused`) without aborting. Without this hook
120
+ * only `maxObjectSize` is enforced at complete. The product's `reserve` must never shrink a key's reservation while
121
+ * one of its uploads may be completing (UploadFilm keeps the larger of the two), or a concurrent re-create could
122
+ * free quota between this check and the complete.
123
+ */
124
+ reservation?: (ctx: Ctx, key: string, uploadId: string) => Promise<number | null> | number | null;
125
+ /**
126
+ * Dedupe: the same content (by `sha256`, which the client sends with create/put) already stored at another key.
127
+ * Return that key and the ETag of the version whose sha256 was verified, to have the server copy exactly that
128
+ * version into place instead of an upload (`{ ok, deduped: true }`), or null.
129
+ * Called for immutable kinds only, after the size and Exists checks and the reservation.
130
+ *
131
+ * THIS HOOK IS AN AUTHORIZATION BOUNDARY. The client only claims a digest; the handler can't hash stored bytes.
132
+ * Return only sources whose sha256 your server computed or verified itself, that this caller may read. A key
133
+ * outside the caller's scope (classify(key, ctx) === null) is ignored unless returned with
134
+ * `crossScopeAuthorized: true`. The copy is pinned to the returned ETag (a source replaced since it was verified
135
+ * is not copied: the client uploads instead) and never overwrites the destination (R2 conditional copy): a race
136
+ * leaves the stored object alone and answers Exists.
137
+ */
138
+ dedupe?: (ctx: Ctx, w: {
139
+ key: string;
140
+ size: number;
141
+ kind: Kind;
142
+ contentType: string;
143
+ sha256: string;
144
+ }) => Promise<DedupeSource> | DedupeSource;
145
+ /** Storage/internal failures turned into generic results (default: console.error, as UploadFilm logs them). */
146
+ onError?: (e: unknown, retryable: boolean) => void;
147
+ };
148
+ /** The product's own keyless ops, by name. */
149
+ ops?: Record<string, CustomOp<Ctx>>;
150
+ }
151
+ export type GuardOutcome = {
152
+ refuse: {
153
+ status: number;
154
+ body: unknown;
155
+ };
156
+ } | {
157
+ refuse?: undefined;
158
+ results?: Map<number, TransferResult> | void;
159
+ } | void;
160
+ export interface HandlerAnswer {
161
+ status: number;
162
+ body: unknown;
163
+ }
164
+ export declare function createSignHandler<Kind extends string, Ctx>(opts: SignHandlerOptions<Kind, Ctx>): {
165
+ handle: (body: unknown, ctx: Ctx) => Promise<HandlerAnswer>;
166
+ run: (op: TransferOp, kind: Kind, expiresAt: string, ctx: Ctx, urlTtl?: number, capUntil?: number) => Promise<TransferResult>;
167
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The key-layout guard: every key a server signs or reads for a scope (a project, an account, a user…) must be one of
3
+ * the product's layouts under that scope's prefix. The product declares the layouts; this module refuses everything
4
+ * that isn't a plain, well-formed key first, so a layout never sees a traversal or an encoding trick:
5
+ *
6
+ * - not a string, longer than `maxLength` (S3: 1024 bytes of UTF-8; checked in bytes), empty;
7
+ * - outside the prefix;
8
+ * - a segment that is empty, "." or ".." (URL parsers collapse them: `p/a/../b` would be signed and served as `p/b`);
9
+ * - backslashes (URL parsers treat `\` as `/` in http(s) paths) and ASCII control characters;
10
+ * - not well-formed Unicode (lone surrogates: no UTF-8 encoding, the signer would throw);
11
+ * - with `strictUnicode` (default on): C1 controls, bidi overrides/isolates, zero-width and other invisible format
12
+ * characters, line/paragraph separators, and the non-characters U+FFFE/U+FFFF — characters that make a key display
13
+ * as another key (`clip<U+202E>vom.exe`), break logs, or vanish in copy-paste; and segments that percent-decode to
14
+ * "." or ".." (`%2e%2e`): harmless through the SDK's signer (it encodes `%`), a traversal for any code that puts a
15
+ * raw key into a URL.
16
+ *
17
+ * A layout gets the segments after the prefix and answers its kind, or null. UploadFilm's layouts live in its
18
+ * web/lib/layout.ts (`classifyKey`).
19
+ *
20
+ * A leaf module (no imports): UploadFilm's web/lib/layout.ts imports it by path and plain Node loaders load it, so it
21
+ * stays free of imports and of TypeScript-only runtime syntax.
22
+ */
23
+ export interface KeyGuardOptions {
24
+ /** Longest key, in UTF-8 bytes. Default 1024 (S3's limit). */
25
+ maxBytes?: number;
26
+ /** Longest key, in UTF-16 code units, checked first (cheap). Default `maxBytes`. */
27
+ maxLength?: number;
28
+ /** Refuse invisible / direction-changing / C1 characters too. Default true. */
29
+ strictUnicode?: boolean;
30
+ }
31
+ export type KeyLayout<K> = (segments: string[], key: string) => K | null;
32
+ /** The key's segments after `prefix`, or null when the key is not a plain, safe key under it (see above). */
33
+ export declare function keySegments(prefix: string, key: unknown, o?: KeyGuardOptions): string[] | null;
34
+ /**
35
+ * A classifier: `(prefix, key) → kind | null`. Layouts are tried in order; the first non-null kind wins.
36
+ *
37
+ * ```ts
38
+ * const classify = createKeyGuard([
39
+ * (s) => (s[0] === "orig" && s.length >= 2 ? "original" : null),
40
+ * (s) => (s[0] === "thumb" && s.length >= 2 && /\.jpe?g$/i.test(s[s.length - 1]) ? "thumb" : null),
41
+ * ]);
42
+ * classify(`p/${projectId}/`, key); // "original" | "thumb" | null
43
+ * ```
44
+ */
45
+ export declare function createKeyGuard<K>(layouts: KeyLayout<K> | KeyLayout<K>[], o?: KeyGuardOptions): (prefix: string, key: unknown) => K | null;
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The sign protocol between a client that sends bytes and the product's server that holds the storage credentials.
3
+ * The client never holds credentials: it asks the server to sign each operation, then sends bytes straight to storage
4
+ * with the presigned URL. The server never touches file bodies.
5
+ *
6
+ * POST <product route> `{ ops: TransferOp[] }` → `{ results: TransferResult[] }`, results positional. Every key must
7
+ * be one of the product's layouts for the scope (transfer/keys.ts), or the whole batch is refused (403).
8
+ * Products add their own keyless ops (UploadFilm: "manifest") through the handler's `ops` option.
9
+ *
10
+ * Types only: products re-export them (UploadFilm's shared/api.ts), and type-only re-exports cost nothing at runtime.
11
+ */
12
+ export type TransferOp =
13
+ /**
14
+ * Server performs CreateMultipartUpload and returns the uploadId. `size` lets the server enforce plans (immutable
15
+ * kinds must give it). `sha256` (hex, optional) lets a dedupe hook recognise content that is already stored.
16
+ */
17
+ {
18
+ op: "create";
19
+ key: string;
20
+ contentType: string;
21
+ size?: number;
22
+ counts?: boolean;
23
+ sha256?: string;
24
+ }
25
+ /**
26
+ * Presigned PUT for one part (body sent by the client). With `contentMd5` (base64 MD5 of the body) the URL signs
27
+ * Content-MD5, so storage rejects a body that changed in transit (BadDigest) instead of storing it.
28
+ */
29
+ | {
30
+ op: "part";
31
+ key: string;
32
+ uploadId: string;
33
+ partNumber: number;
34
+ contentMd5?: string;
35
+ }
36
+ /** Server performs CompleteMultipartUpload and returns the final size (HEAD). */
37
+ | {
38
+ op: "complete";
39
+ key: string;
40
+ uploadId: string;
41
+ parts: {
42
+ n: number;
43
+ etag: string;
44
+ }[];
45
+ }
46
+ /** Server aborts a multipart upload. */
47
+ | {
48
+ op: "abort";
49
+ key: string;
50
+ uploadId: string;
51
+ }
52
+ /** Presigned single PUT (small files, posters). `contentMd5` as for parts; `sha256` as for create. */
53
+ | {
54
+ op: "put";
55
+ key: string;
56
+ contentType: string;
57
+ contentMd5?: string;
58
+ size?: number;
59
+ counts?: boolean;
60
+ sha256?: string;
61
+ }
62
+ /** Server HEADs the key: size or null. */
63
+ | {
64
+ op: "head";
65
+ key: string;
66
+ }
67
+ /**
68
+ * Server lists the parts storage holds for this multipart upload (all pages): what a resumed upload checks its
69
+ * saved parts against. NoSuchUpload (not retryable) when the upload is gone.
70
+ */
71
+ | {
72
+ op: "listParts";
73
+ key: string;
74
+ uploadId: string;
75
+ }
76
+ /**
77
+ * Server lists the multipart uploads open on exactly this key (upload id, when it was initiated): a client that was
78
+ * killed between asking for a create and recording its upload id finds the orphan and aborts it (RL-10).
79
+ */
80
+ | {
81
+ op: "listUploads";
82
+ key: string;
83
+ };
84
+ export type TransferOpName = TransferOp["op"];
85
+ /** Ops that write (or lead to a write of) the key. */
86
+ export declare const WRITE_OP_NAMES: readonly TransferOpName[];
87
+ export type TransferResult = {
88
+ ok: true;
89
+ uploadId: string;
90
+ } | {
91
+ ok: true;
92
+ url: string;
93
+ headers: Record<string, string>;
94
+ expiresAt: string;
95
+ }
96
+ /** complete, head. `etag` is storage's ETag without quotes: MD5 hex for a single PUT, md5(part md5s)-N for multipart. */
97
+ | {
98
+ ok: true;
99
+ size: number | null;
100
+ etag: string | null;
101
+ }
102
+ /**
103
+ * create, put, when the server's dedupe hook found the same content already stored and copied it to the key
104
+ * server-side: nothing to upload. `etag`/`size` as for head. Only products that enable dedupe ever answer this.
105
+ */
106
+ | {
107
+ ok: true;
108
+ deduped: true;
109
+ size: number | null;
110
+ etag: string | null;
111
+ } | {
112
+ ok: true;
113
+ }
114
+ /** listParts. `etag`: storage's part ETag without quotes (the part's MD5 hex on R2). */
115
+ | {
116
+ ok: true;
117
+ parts: {
118
+ n: number;
119
+ etag: string;
120
+ size: number;
121
+ }[];
122
+ }
123
+ /** listUploads: the multipart uploads open on the key (`initiated`: ISO time, when storage reports it). */
124
+ | {
125
+ ok: true;
126
+ uploads: {
127
+ uploadId: string;
128
+ initiated?: string;
129
+ }[];
130
+ } | {
131
+ ok: false;
132
+ error: string;
133
+ code?: string;
134
+ retryable: boolean;
135
+ };
136
+ export interface TransferRequest<Op = TransferOp> {
137
+ ops: Op[];
138
+ }
139
+ export interface TransferResponse<Result = TransferResult> {
140
+ results: Result[];
141
+ }
@@ -0,0 +1,32 @@
1
+ import { type ZipDomains } from "./sign";
2
+ export interface ZipWorkerClientOptions {
3
+ /** The Worker's origin, e.g. https://zip.example.com (a trailing "/" is fine). */
4
+ url: () => string;
5
+ /** Shared with the Worker (≥ 32 characters). */
6
+ secret: () => string;
7
+ domains: ZipDomains;
8
+ /** Default: the global fetch. */
9
+ fetch?: typeof fetch;
10
+ /** Default: Date.now. */
11
+ now?: () => number;
12
+ }
13
+ export interface CrcAnswer {
14
+ status: number;
15
+ crc32?: string;
16
+ error?: string;
17
+ }
18
+ export interface ZipWorkerClient {
19
+ /** A signed link to archive `planId` of `shareId`, downloaded as `fileName`, valid until `exp` (Unix seconds). */
20
+ link(shareId: string, planId: string, fileName: string, exp: number): Promise<string>;
21
+ /**
22
+ * CRC-32 of [offset, offset+length) of an object, computed by the Worker next to storage, conditional on `etag`.
23
+ * The request is valid for 15 minutes. An answer for another length or without a CRC is a 502.
24
+ */
25
+ crc(key: string, etag: string, offset: number, length: number): Promise<CrcAnswer>;
26
+ }
27
+ export declare function createZipWorkerClient(o: ZipWorkerClientOptions): ZipWorkerClient;
28
+ /** The CRC-32 of a whole object from its ranges' CRCs, in order (8 lowercase hex). */
29
+ export declare const combineCrcChunks: (chunks: {
30
+ crc32: string;
31
+ length: number;
32
+ }[]) => string;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * A collection's zip generation: how a product withdraws archive links. Every plan records the generation it was built
3
+ * under (../../zip/plan.ts); the Worker serves it only while that is still the collection's current generation and
4
+ * its id isn't revoked. Withdrawing every outstanding link of a collection = bumping its generation (files left it,
5
+ * or it was revoked/deleted). Withdrawing one plan without touching the others = revoking its id.
6
+ *
7
+ * Why a plan built from older records can't survive a removal: the product reads the generation BEFORE it reads its
8
+ * records, and a removal bumps it AFTER the records are written. A plan that still lists a removed file was read from
9
+ * the records before that write, so its generation is older than the bump: refused, even if written again later.
10
+ * publish() also re-reads the generation after writing a plan, so a link isn't handed out for a dead plan.
11
+ *
12
+ * Storage is behind GenStore (compare-and-swap on the marker); tested with an in-memory store. Moved from UploadFilm's
13
+ * web/lib/zipGen.ts; the marker bytes and the order of reads and writes are unchanged.
14
+ */
15
+ import { type GenMarker, type ZipKeyLayout } from "../../zip/plan";
16
+ /** The marker's storage: a read with a version, and a conditional write. */
17
+ export interface GenStore {
18
+ get(key: string): Promise<{
19
+ text: string;
20
+ etag: string;
21
+ } | null>;
22
+ /** Conditional write: false when the condition failed (someone else wrote first). */
23
+ put(key: string, text: string, cond: {
24
+ ifMatch?: string;
25
+ ifNoneMatch?: boolean;
26
+ }): Promise<boolean>;
27
+ }
28
+ /** What the sweep reads. */
29
+ export interface SweepIo {
30
+ /** Keys of the collection's stored plans. */
31
+ listPlans(shareId: string): Promise<string[]>;
32
+ getText(key: string): Promise<string | null>;
33
+ del(key: string): Promise<unknown>;
34
+ /** Keys the collection still holds (any plan naming another key is stale), or null when the collection is gone. */
35
+ keys(shareId: string): Promise<Set<string> | null>;
36
+ }
37
+ export interface ZipGenerations {
38
+ read(shareId: string): Promise<GenMarker & {
39
+ etag: string | null;
40
+ }>;
41
+ /** Bump the generation (compare-and-swap, retried), adding `seen` removal ids. → the new generation. */
42
+ bump(shareId: string, seen?: string[], tries?: number): Promise<number>;
43
+ /**
44
+ * Withdraw single plans (their links stop; the collection's other links don't). Entries older than
45
+ * `revokedForMs` are dropped: by then no plan they name may still exist (see zipGenerations).
46
+ */
47
+ revoke(shareId: string, ids: string[], now?: number, tries?: number): Promise<void>;
48
+ /**
49
+ * Write a plan built under generation `gen`, then make sure no removal happened meanwhile: if the generation moved,
50
+ * the plan is deleted and the answer is false (ask again). The Worker would refuse it anyway; this just avoids
51
+ * handing out a dead link.
52
+ */
53
+ publish(io: {
54
+ put(): Promise<unknown>;
55
+ del(): Promise<unknown>;
56
+ }, shareId: string, gen: number): Promise<boolean>;
57
+ /**
58
+ * The sweep, for one collection. A plan whose generation is current but that lists a key the collection no longer
59
+ * holds is revoked BY ID: its links stop, the collection's other links don't. Older-generation plans are already
60
+ * refused and are only deleted. A collection that is gone gets a generation bump (every link stops).
61
+ */
62
+ sweep(io: SweepIo, shareId: string): Promise<{
63
+ plans: number;
64
+ withdrawn: number;
65
+ bumped: boolean;
66
+ }>;
67
+ }
68
+ export interface ZipGenerationOptions extends Pick<ZipKeyLayout, "genKey" | "entryPrefix"> {
69
+ /** A stored plan's key → its id. */
70
+ planIdOfKey(key: string): string;
71
+ /**
72
+ * How long a revocation is kept. It MUST outlive every plan it can name: longer than a plan can stay in storage after
73
+ * its last write (a lifecycle rule) AND than any link signed for it. A revocation dropped earlier revives the link.
74
+ * No default: it depends on the product's plan lifetime (e.g. plans expiring 30 days after their last write need
75
+ * revocations kept longer than 30 days, and longer than the longest link).
76
+ */
77
+ revokedForMs: number;
78
+ }
79
+ /**
80
+ * The generation protocol over `store`, with the product's key layout (`genKey` for the marker, `entryPrefix` for the
81
+ * keys a plan names), `planIdOfKey` and how long revocations are kept.
82
+ */
83
+ export declare function zipGenerations(store: GenStore, keys: ZipGenerationOptions): ZipGenerations;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Streaming ZIP, the site's side (Node or Workers): link and request signatures, planning (pinning, CRCs, limits),
3
+ * the generation protocol (withdrawing links) and the client for the zip Worker (sdks/zip-worker).
4
+ */
5
+ export { sign, verify, zipLinkPath } from "./sign";
6
+ export type { ZipDomains } from "./sign";
7
+ export { crcChunkFor, crcKey, crcRanges, encodeForWorker, MAX_CRC_RANGE, MAX_CRC_STEPS, planFor, planStillValid, } from "./planner";
8
+ export type { MissingCrc, PlanResult, Stored, ZipSource } from "./planner";
9
+ export { zipGenerations } from "./generations";
10
+ export type { GenStore, SweepIo, ZipGenerationOptions, ZipGenerations } from "./generations";
11
+ export { combineCrcChunks, createZipWorkerClient } from "./client";
12
+ export type { CrcAnswer, ZipWorkerClient, ZipWorkerClientOptions } from "./client";
@@ -0,0 +1,94 @@
1
+ /**
2
+ * From the files a product wants zipped + what storage holds now + CRCs it knows → a zip plan the Worker can serve
3
+ * (../../zip/plan.ts), or the list of objects whose CRC-32 still has to be computed (the Worker's POST /crc, a range
4
+ * at a time: crcRanges, combined with crc32CombineAll). Pure (no I/O).
5
+ *
6
+ * Pinning: every entry is pinned to the ETag storage reports NOW (from a listing), not to what the product's records
7
+ * claim. A CRC is used only if it belongs to that same ETag: the file's `verified.crc32` when `verified.etag` equals
8
+ * it, else one the product computed before for (key, etag) (crcKey).
9
+ *
10
+ * Moved from UploadFilm's web/lib/zipPlan.ts; plans, ids and ranges are unchanged.
11
+ */
12
+ import { type Plan } from "../../zip/plan";
13
+ /** One file the product wants in the archive, in archive order. */
14
+ export interface ZipSource {
15
+ /** Path inside the archive (zip/names.ts allocateNames makes safe ones). */
16
+ path: string;
17
+ /** Storage key. */
18
+ key: string;
19
+ /** ISO date: the entry's modification time. */
20
+ lastModified: string;
21
+ /** A checksum the product recorded for one version of the object: used only when its ETag is the stored one. */
22
+ verified?: {
23
+ etag: string;
24
+ crc32?: unknown;
25
+ } | null;
26
+ }
27
+ /** What a listing says about a key right now. */
28
+ export interface Stored {
29
+ etag: string;
30
+ size: number;
31
+ }
32
+ export interface MissingCrc {
33
+ key: string;
34
+ etag: string;
35
+ size: number;
36
+ }
37
+ /** The key of a computed CRC: one per object version. */
38
+ export declare const crcKey: (key: string, etag: string) => string;
39
+ /**
40
+ * skipped: listed but not in storage (deleted, or the listing raced a removal): left out.
41
+ * empty nothing to zip
42
+ * too-many over MAX_ENTRIES
43
+ * crc CRCs still missing (compute them, then ask again)
44
+ */
45
+ export type PlanResult = {
46
+ ok: true;
47
+ plan: Plan;
48
+ files: number;
49
+ bytes: number;
50
+ skipped: number;
51
+ } | {
52
+ ok: false;
53
+ reason: "crc";
54
+ missing: MissingCrc[];
55
+ files: number;
56
+ bytes: number;
57
+ skipped: number;
58
+ } | {
59
+ ok: false;
60
+ reason: "empty" | "too-many";
61
+ files: number;
62
+ bytes: number;
63
+ skipped: number;
64
+ };
65
+ /**
66
+ * The plan for collection `shareId` named `name` (the archive's file name) under generation `gen`. `stored`: key →
67
+ * what storage holds; `crcs`: crcKey(key, etag) → 8 lowercase hex.
68
+ */
69
+ export declare function planFor(shareId: string, name: string, files: ZipSource[], stored: Map<string, Stored>, crcs: Map<string, string>, gen?: number): PlanResult;
70
+ /** Most ranges one CRC backfill may use (an Inngest run allows 1,000 steps; a few more go to bookkeeping). */
71
+ export declare const MAX_CRC_STEPS = 900;
72
+ /** The Worker computes at most this much per request. */
73
+ export declare const MAX_CRC_RANGE: number;
74
+ /**
75
+ * Range size for a file: `base`, or bigger so a huge file still fits in MAX_CRC_STEPS (whole MiB); null when even
76
+ * MAX_CRC_RANGE pieces would be too many (> ~3.5 TiB: such a file stays without a zip CRC).
77
+ */
78
+ export declare function crcChunkFor(size: number, base: number): number | null;
79
+ /** The byte ranges a CRC backfill asks the Worker for: [0, size) in pieces of `chunk` (one empty range for an empty file). */
80
+ export declare function crcRanges(size: number, chunk: number): {
81
+ i: number;
82
+ off: number;
83
+ len: number;
84
+ }[];
85
+ /** The stored plan (keys under `keyPrefix`), or null when it would be over the Worker's limits (answer "too many"). */
86
+ export declare function encodeForWorker(plan: Plan, keyPrefix: string): Promise<{
87
+ text: string;
88
+ id: string;
89
+ } | null>;
90
+ /**
91
+ * Does a stored plan of `shareId` (keys under `keyPrefix`) only reference keys still in `keys`? A plan naming a
92
+ * removed file must be withdrawn. Unreadable → false.
93
+ */
94
+ export declare function planStillValid(text: string, shareId: string, keyPrefix: string, keys: Set<string>): boolean;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Signatures between a product's site and its zip Worker: HMAC-SHA256 over a domain tag and fields joined by "\n",
3
+ * base64url. Two requests are signed: an archive link (`/z/<share>/<planId>/<name>?e=&s=`) and a CRC range request
4
+ * (`POST /crc`). Each product picks its own domain tags (they separate these signatures from any other HMAC made with
5
+ * the same secret) and keeps them for as long as links signed with them must work.
6
+ *
7
+ * SELF-CONTAINED ON PURPOSE: no imports and only erasable TypeScript (plain Node, workerd and bundlers load it by
8
+ * path). WebCrypto only. Moved from UploadFilm's shared/zip/plan.ts; the signatures are unchanged.
9
+ */
10
+ /** The domain tags a product signs with: its own, never another product's (e.g. "<product>-zip-1", "<product>-crc-1"). */
11
+ export interface ZipDomains {
12
+ /** Archive links. */
13
+ link: string;
14
+ /** CRC range requests. */
15
+ crc: string;
16
+ }
17
+ /** HMAC-SHA256 over a domain tag and fields joined by "\n", base64url. A secret under 32 characters throws. */
18
+ export declare function sign(secret: string, domain: string, fields: (string | number)[]): Promise<string>;
19
+ /** Constant-time check (WebCrypto verify). Only the canonical base64url spelling of a signature is accepted. */
20
+ export declare function verify(secret: string, domain: string, fields: (string | number)[], sig: string): Promise<boolean>;
21
+ /** Path + query of a signed archive link, valid until `exp` (Unix seconds). Prefix it with the Worker's origin. */
22
+ export declare function zipLinkPath(secret: string, domain: string, shareId: string, planId: string, fileName: string, exp: number): Promise<string>;
@@ -0,0 +1 @@
1
+ "use strict";const t=[{short:360,kbps:700,peak:1e3},{short:720,kbps:2800,peak:4e3},{short:1080,kbps:5500,peak:8e3}];const e=["ladder","poster","storyboard","faststart","audio","transcript","frame-check"],r=["audio","transcript","frame-check"],s=t=>t.some(t=>r.includes(t)),o=t=>t.includes("audio")||t.includes("transcript");function n(t,e={}){return{version:t,audio:{kbps:24,chunkS:600,...e.audio},vad:{noiseDb:-40,minSilenceS:.6,edgeS:.3,...e.vad},transcript:{model:"@cf/openai/whisper-large-v3-turbo",...e.transcript},frameCheck:{gapFactor:1.5,jitter:.1,maxErrorLines:20,...e.frameCheck},...e.storyboard?{storyboard:{...e.storyboard}}:{}}}const a=n("steps/1"),i=(t,e)=>t.includes("storyboard")&&!!e?.storyboard,c="audio/audio.json",u="transcript.vtt",d="transcript.json",p="frame-check.json";const l=/^[a-z0-9]{1,8}$/;function h(t,e){if("master.m3u8"===t)return"playlist";const r=new RegExp(`^v(\\d{1,2})\\/(index\\.m3u8|init(?:_\\d{1,2})?\\.mp4|(?:${function(t){for(const e of t)if(!l.test(e))throw new Error(`bad segment name: ${e}`);return t.join("|")}(e)})-\\d{5,6}\\.m4s)$`).exec(t);return r?"index.m3u8"===r[2]?"playlist":r[2].startsWith("init")?"init":"segment":null}const f=4096,m=604800,y=t=>"number"==typeof t&&Number.isFinite(t)&&t>0&&t<=m;function x(t){return JSON.stringify({id:t.id,attempt:t.attempt,src:t.src,etag:t.etag,bytes:t.bytes,prefix:t.prefix,done:t.done,...void 0!==t.maxShort?{maxShort:t.maxShort}:{},...void 0!==t.steps?{steps:t.steps}:{},...void 0!==t.issuedAt?{issuedAt:t.issuedAt}:{},...void 0!==t.expectDurationS?{expectDurationS:t.expectDurationS}:{}})}const g=(t,e)=>t.ladder===e,b=t=>Math.round(1e3*t)/1e3;function S(t,e,r){let s=0;for(const o of r)s+=Math.max(0,Math.min(e,o.end)-Math.max(t,o.start));return s}function w(t,e,r,s){const o=e-t;if(o<=0)return r.some(e=>t>=e.start&&t<=e.end);const n=S(t,e,r);return n>0&&n>=.8*o&&o-n<=s}function v(t){const e=Math.max(0,Math.round(1e3*t)),r=Math.floor(e/36e5),s=Math.floor(e/6e4)%60,o=Math.floor(e/1e3)%60,n=(t,e=2)=>String(t).padStart(e,"0");return`${n(r)}:${n(s)}:${n(o)}.${n(e%1e3,3)}`}const A=t=>t.replace(/\r\n?/g,"\n").replace(/\n\s*\n/g,"\n").replace(/-->/g,"→").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").trim();const M=new TextEncoder;new TextDecoder;function E(t){const e="string"==typeof t?M.encode(t):t,r=new Uint8Array(e.length);return r.set(e),r}async function $(t,e,r){if(function(t){if("string"!=typeof t||t.length<32)throw new Error("secret missing or too short")}(t),"string"!=typeof e||e.includes("\n"))throw new Error("bad HMAC domain");return(t=>{let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e})(await async function(t,e){const r=await crypto.subtle.importKey("raw",E(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,E(e)))}(t,`${e}\n${r}`))}class k extends Error{reached;status;timedOut;constructor(t,e){super(t,void 0===e.cause?void 0:{cause:e.cause}),this.name="MediaJobError",this.reached=e.reached,this.timedOut=e.timedOut??!1,void 0!==e.status&&(this.status=e.status)}}function T(t,e={}){const r={version:t,intervalS:2,maxFrames:200,size:160,cols:5,rows:5,quality:60,minQuality:20,maxSheetBytes:1e5,maxBytes:1e6,...e};return N(r),r}const j=T("storyboard/1");function D(t,e,r){return"number"==typeof t&&Number.isInteger(t)&&t>=e&&t<=r}function N(t){const e=t=>{throw new Error(`storyboard settings: bad ${t}`)};"string"==typeof t.version&&t.version||e("version"),"number"==typeof t.intervalS&&t.intervalS>=.1&&t.intervalS<=3600||e("intervalS"),D(t.maxFrames,1,1e4)||e("maxFrames"),(!D(t.size,16,1024)||t.size%2)&&e("size"),D(t.cols,1,32)&&D(t.rows,1,32)||e("cols/rows"),(!D(t.quality,1,100)||!D(t.minQuality,1,100)||t.minQuality>t.quality)&&e("quality/minQuality"),D(t.maxSheetBytes,1e3,1e8)&&D(t.maxBytes,t.maxSheetBytes,1e9)||e("maxSheetBytes/maxBytes")}const _=t=>Math.max(2,2*Math.round(t/2));const F="storyboard",R="storyboard/storyboard.vtt",O="storyboard/storyboard.json",C=t=>`storyboard/sb-${String(t+1).padStart(3,"0")}.webp`;function I(t){return t===O?"storyboard-index":t===R?"storyboard-vtt":/^storyboard\/sb-\d{3,4}\.webp$/.test(t)?"storyboard":null}const B=(t,e)=>Math.ceil(e/(t.cols*t.rows));function U(t,e){const r=t.cols*t.rows,s=[];for(let o=0;o<e;o++){const n=o%r,a=H(o*t.interval),i=H((o+1)*t.interval),c=o===e-1?Math.max(i,H(t.seconds)):i;s.push({start:a,end:c,sheet:Math.floor(o/r),x:n%t.cols*t.width,y:Math.floor(n/t.cols)*t.height,w:t.width,h:t.height})}return s}function H(t){return Math.round(1e3*t)/1e3}function V(t){const e=Math.round(1e3*t),r=Math.floor(e/36e5),s=Math.floor(e/6e4)%60,o=Math.floor(e/1e3)%60,n=(t,e=2)=>String(t).padStart(e,"0");return`${n(r)}:${n(s)}:${n(o)}.${n(e%1e3,3)}`}function W(t){const e=t;return!!e&&"object"==typeof e&&"string"==typeof e.version&&[e.interval,e.width,e.height,e.seconds,e.bytes].every(t=>"number"==typeof t&&Number.isFinite(t)&&t>=0)&&e.interval>0&&D(e.cols,1,32)&&D(e.rows,1,32)&&D(e.count,1,1e5)&&Array.isArray(e.sheets)&&e.sheets.length===Math.ceil(e.count/(e.cols*e.rows))&&e.sheets.every(t=>"string"==typeof t&&"storyboard"===I(t))&&e.vtt===R}exports.AUDIO_INDEX=c,exports.DEFAULT_RUNGS=t,exports.DEFAULT_STEP_SETTINGS=a,exports.DEFAULT_STORYBOARD_SETTINGS=j,exports.EXPECT_HEADER="x-media-expect-duration",exports.EXTRA_STEPS=r,exports.FRAME_CHECK_FILE=p,exports.MAX_BODY=f,exports.MAX_EXPECT_DURATION_S=m,exports.MediaJobError=k,exports.RUNNER_OUTPUT_REVISION=2,exports.SDK_ENTRY="server/media",exports.SILENT_SHARE=.8,exports.STEPS=e,exports.STORYBOARD_DIR=F,exports.STORYBOARD_INDEX=O,exports.STORYBOARD_VTT=R,exports.TRANSCRIPT_JSON=d,exports.TRANSCRIPT_VTT=u,exports.VERSION_HEADER="x-media-version",exports.audioChunkName=t=>`audio/a-${String(t).padStart(3,"0")}.ogg`,exports.buildTranscript=function(t,e){const r=[];let s=0,o=t.language;for(const{chunk:n,result:a}of t.results){o??=a.transcription_info?.language;const i=n.end-n.start;for(const o of a.segments??[]){const a=String(o.text??"").trim();if(!a||!Number.isFinite(o.start)||!Number.isFinite(o.end))continue;const c=b(n.start+Math.max(0,Math.min(o.start,i))),u=b(n.start+Math.max(0,Math.min(Math.max(o.end,o.start),i)));if(w(c,u,t.silences,e.edgeS)){s++;continue}const d=(o.words??[]).filter(t=>t&&"string"==typeof t.word&&Number.isFinite(t.start)&&Number.isFinite(t.end)).map(t=>({word:t.word.trim(),start:b(n.start+Math.max(0,t.start)),end:b(n.start+Math.max(0,t.end))})).filter(e=>e.word&&!w(e.start,e.end,t.silences,0));r.push({start:c,end:Math.max(c,u),text:a,...d.length?{words:d}:{}})}}return r.sort((t,e)=>t.start-e.start),{format:1,model:t.model,...o?{language:o}:{},seconds:b(t.seconds),segments:r,text:r.map(t=>t.text).join(" "),dropped:s,silentChunks:t.silentChunks??0}},exports.checkStoryboardSettings=N,exports.chunkSilent=(t,e)=>t.end-t.start-S(t.start,t.end,e)<=.05,exports.completionFile=function(t){return t.includes("ladder")?"master.m3u8":t.includes("faststart")?"faststart.mp4":t.includes("storyboard")?"storyboard/storyboard.json":t.includes("poster")||!s(t)?"poster.jpg":o(t)?c:p},exports.contentTypeOf=t=>t.endsWith(".m3u8")?"application/vnd.apple.mpegurl":t.endsWith(".m4s")?"video/iso.segment":t.endsWith(".jpg")?"image/jpeg":t.endsWith(".webp")?"image/webp":t.endsWith(".json")?"application/json":t.endsWith(".ogg")?"audio/ogg":t.endsWith(".vtt")?"text/vtt; charset=utf-8":"video/mp4",exports.hasExtraSteps=s,exports.inSilence=w,exports.isStoryboardIndex=W,exports.jobBody=x,exports.jobVersion=(t,e,r=a)=>{const o="string"==typeof r?{version:r}:r;return s(e)||i(e,o)?`${t}+${o.version}`:t},exports.keyframeExpr=(t,e)=>`expr:gte(t,if(lt(n_forced,2),n_forced*${t},(n_forced-1)*${e}))`,exports.ladderFile=h,exports.ladderSettings=function(e,r={}){return{version:e,rungs:t,audioKbps:128,firstSegmentS:1,segmentS:4,keyframeS:2,segmentName:"seg",copyMaxGopS:4,copyMaxBps:12e6,preset:"veryfast",cappedPreset:"superfast",...r}},exports.mediaJobClient=function(t){const e=()=>"function"==typeof t.secret?t.secret():t.secret;return{sign:async(r,s)=>$(e(),(e=>"job"===e?t.jobDomain:t.doneDomain)(r),s),async request(r){if(void 0!==r.expectDurationS&&!y(r.expectDurationS))throw new Error(`media job: bad expectDurationS ${String(r.expectDurationS)}`);const s=x(t.issuedAt&&void 0===r.issuedAt?{...r,issuedAt:Math.floor((t.now??Date.now)()/1e3)}:r);if(s.length>f)throw new Error("media job: request too big");let o;try{o=await(t.fetch??fetch)(`${t.url.replace(/\/$/,"")}/jobs`,{method:"POST",body:s,headers:{"content-type":"application/json",[t.signatureHeader]:await $(e(),t.jobDomain,s)},signal:AbortSignal.timeout(t.timeoutMs??3e4)})}catch(t){const e="TimeoutError"===t?.name||"AbortError"===t?.name;throw new k(`media worker: ${e?"no answer in time":"unreachable"}: ${t?.message??String(t)}`,{reached:!1,timedOut:e,cause:t})}if(!o.ok)throw new k(`media worker: ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`,{reached:!0,status:o.status})},async readReport(r,s){if("string"!=typeof r||r.length>f||!function(t,e){if("string"!=typeof t||"string"!=typeof e||t.length!==e.length)return!1;let r=0;for(let s=0;s<t.length;s++)r|=t.charCodeAt(s)^e.charCodeAt(s);return 0===r}(s,await $(e(),t.doneDomain,r)))return{ok:!1,status:403,body:"bad signature"};let o;try{o=JSON.parse(r)}catch{return{ok:!1,status:400,body:"bad json"}}return o&&"object"==typeof o?{ok:!0,report:o}:{ok:!1,status:400,body:"bad report"}}}},exports.mediaStepFiles=function(t){return{audioIndex:`${t}audio/audio.json`,transcriptVtt:`${t}transcript.vtt`,transcriptJson:`${t}transcript.json`,frameCheck:`${t}frame-check.json`}},exports.outputFile=function(t,e,r){if(e.includes("ladder")){const e=h(t,r);if(e)return e}if(e.includes("poster")&&"poster.jpg"===t)return"poster";if(e.includes("storyboard")){if("storyboard/storyboard.json"===t)return"storyboard-index";if(/^storyboard\/sb-\d{3,4}\.(?:jpg|webp)$/.test(t)||"storyboard/storyboard.vtt"===t)return"storyboard"}if(e.includes("faststart")&&"faststart.mp4"===t)return"faststart";if(o(e)){if(t===c)return"audio-index";if(/^audio\/a-\d{3,4}\.ogg$/.test(t))return"audio"}if(e.includes("transcript")){if(t===u)return"transcript";if(t===d)return"transcript-json"}return e.includes("frame-check")&&t===p?"frame-check":null},exports.parseSteps=function(t,r=e){if(!Array.isArray(t)||!t.length||t.length>2*e.length)return null;for(const e of t)if("string"!=typeof e||!r.includes(e))return null;return e.filter(e=>t.includes(e))},exports.planStoryboard=function(t,e=j){const r=t.width>0?t.width:16,s=t.height>0?t.height:9,o=Number.isFinite(t.seconds)&&t.seconds>0?t.seconds:0,n=e.size/Math.max(r,s),a=Math.ceil(1e3*Math.max(e.intervalS,o/e.maxFrames))/1e3,i=o?Math.min(e.maxFrames,Math.max(1,Math.ceil(o/a-1e-9))):1;return{interval:a,maxFrames:e.maxFrames,expected:i,width:_(r*n),height:_(s*n),cols:e.cols,rows:e.rows,seconds:o}},exports.readAudioIndex=function(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||"object"!=typeof e)return null;const r=e,s=t=>"number"==typeof t&&Number.isFinite(t)&&t>=0;if(1!==r.format||!Array.isArray(r.chunks)||!Array.isArray(r.silences)||!s(r.seconds))return null;for(const t of r.chunks)if(!t||"string"!=typeof t.file||!/^audio\/a-\d{3,4}\.ogg$/.test(t.file)||!s(t.start)||!s(t.end)||t.end<t.start)return null;for(const t of r.silences)if(!t||!s(t.start)||!s(t.end)||t.end<t.start)return null;return r},exports.readFrameCheck=function(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||"object"!=typeof e)return null;const r=e;return 1===r.format&&"boolean"==typeof r.ok&&"number"==typeof r.frames&&Array.isArray(r.gaps)&&Array.isArray(r.decodeErrors)?r:null},exports.readTranscript=function(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||"object"!=typeof e)return null;const r=e;if(1!==r.format||"string"!=typeof r.model||!Array.isArray(r.segments))return null;for(const t of r.segments)if(!t||"number"!=typeof t.start||"number"!=typeof t.end||"string"!=typeof t.text)return null;return r},exports.refuseStale=function(t,e){return"done"===t.state&&!g(t,e)},exports.rungsFor=function(t,e,r,s){const o=t=>Math.max(2,2*Math.round(t/2));if(s&&Math.min(e,r)>s){const t=s/Math.min(e,r);e=o(e*t),r=o(r*t)}const n=Math.min(e,r),a=[];for(const s of t){if(s.short>=.9*n)break;const t=s.short/n;a.push({width:o(e*t),height:o(r*t),kbps:s.kbps,peak:s.peak,top:!1})}const i=[...t].reverse().find(t=>t.short<=1.1*n)??t[0];return a.push({width:o(e),height:o(r),kbps:i.kbps,peak:i.peak,top:!0}),a},exports.silentSeconds=S,exports.sourceHash=async function(t,e,r){const s=new Uint8Array(await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(`${t}#${e}${r?`#${r}`:""}`)));let o="";for(let t=0;t<s.length;t++)o+=s[t].toString(16).padStart(2,"0");return o},exports.stampMatches=g,exports.stepSettings=n,exports.storyboardCues=U,exports.storyboardDescriptor=function(t,e){/\/$/.test(t)||(t+="/");const r={vtt:t+R,index:t+O};if(!e)return r;if(!W(e))throw new Error("storyboard: not a storyboard index");return{...r,interval:e.interval,cols:e.cols,rows:e.rows,width:e.width,height:e.height,count:e.count,seconds:e.seconds,sheets:e.sheets.map(e=>t+e)}},exports.storyboardFile=I,exports.storyboardIndex=function(t,e,r,s){const o=B(t,e);return{version:r,interval:t.interval,cols:t.cols,rows:t.rows,width:t.width,height:t.height,count:e,seconds:H(t.seconds),sheets:Array.from({length:o},(t,e)=>C(e)),vtt:R,bytes:s}},exports.storyboardSettings=T,exports.storyboardSheetCount=B,exports.storyboardSheetName=C,exports.storyboardV2=i,exports.storyboardVtt=function(t,e){const r=["WEBVTT",""];for(const s of U(t,e))r.push(`${V(s.start)} --\x3e ${V(s.end)}`,`${C(s.sheet).slice(11)}#xywh=${s.x},${s.y},${s.w},${s.h}`,"");return r.join("\n")},exports.toWebVtt=function(t){const e=["WEBVTT",""];return t.segments.forEach((t,r)=>{const s=t.end>t.start?t.end:t.start+.5;e.push(String(r+1),`${v(t.start)} --\x3e ${v(s)}`,A(t.text),"")}),e.join("\n")},exports.validExpectDuration=y,exports.vttText=A,exports.vttTime=v,exports.wantsAudio=o;