@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,150 @@
1
+ import { type Query } from "./encoding";
2
+ export interface R2Config {
3
+ /** `https://<account>.r2.cloudflarestorage.com` (trailing slash ignored). */
4
+ endpoint: string;
5
+ /** Bucket name, optionally followed by a key prefix: `bucket` or `bucket/prefix`. */
6
+ bucket: string;
7
+ accessKeyId: string;
8
+ secretAccessKey: string;
9
+ /** Default "auto" (R2). */
10
+ region?: string;
11
+ /** Default globalThis.fetch. Next.js: pass one that adds `cache: "no-store"`. */
12
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
13
+ /** Clock for signing (tests). */
14
+ now?: () => Date;
15
+ /** base64 MD5 (DeleteObjects needs Content-MD5). Default: WebCrypto MD5 (Workers), else node:crypto. */
16
+ md5Base64?: (bytes: Uint8Array) => Promise<string>;
17
+ /** Wait between putObject retries (tests). */
18
+ sleep?: (ms: number) => Promise<void>;
19
+ }
20
+ export interface PresignPutOptions {
21
+ expiresIn?: number;
22
+ query?: Query;
23
+ contentType?: string;
24
+ contentMd5?: string;
25
+ contentLength?: number;
26
+ ifNoneMatch?: boolean;
27
+ }
28
+ export interface PresignGetOptions {
29
+ expiresIn?: number;
30
+ /** Content-Disposition: attachment with this file name (the browser saves instead of playing). */
31
+ download?: string;
32
+ /** Content-Disposition: inline with this file name (previews). */
33
+ inline?: string;
34
+ /** Forced response Content-Type. */
35
+ contentType?: string;
36
+ }
37
+ export interface SignedFetchOptions {
38
+ headers?: Record<string, string>;
39
+ body?: Uint8Array | string;
40
+ query?: Query;
41
+ /** A request on the bucket itself (e.g. ListMultipartUploads); the key must be "". */
42
+ bucketLevel?: boolean;
43
+ /** Passed to fetch (only when given). */
44
+ signal?: AbortSignal;
45
+ }
46
+ export interface CopyObjectOptions {
47
+ /** The destination must be empty (R2 conditional copy; a multipart copy completes with If-None-Match: *). */
48
+ ifNoneMatch?: boolean;
49
+ /** The source must still be this version (x-amz-copy-source-if-match). */
50
+ sourceEtag?: string;
51
+ /**
52
+ * Stop by this time (epoch ms, Date.now()): e.g. the platform's function limit minus a margin. A multipart copy
53
+ * (over 5 GiB, 1 GiB UploadPartCopy calls in sequence) doesn't start a part it can't expect to finish in time (the
54
+ * slowest part so far is the estimate), cuts the one in flight at the deadline, aborts the multipart it started and
55
+ * throws R2Error "DeadlineExceeded" (retryable: run it where it has the time, e.g. a background job). Nothing is
56
+ * left open and there is no partial state to resume. A single CopyObject (≤ 5 GiB) is cut the same way; storage
57
+ * may still finish it, which is harmless (the same bytes) and, with `ifNoneMatch`, never an overwrite.
58
+ */
59
+ deadline?: number;
60
+ /** The same as `deadline`, driven by the caller (e.g. the request's own signal). */
61
+ signal?: AbortSignal;
62
+ }
63
+ export declare function checkError200(text: string, what: string): string;
64
+ /** S3's limits, the ones presigning and copies rely on. */
65
+ export declare const PRESIGN_MAX_SECONDS = 604800;
66
+ /** One CopyObject handles up to 5 GiB; above that the copy is multipart (UploadPartCopy) in 1 GiB parts. */
67
+ export declare const COPY_SINGLE_MAX: number;
68
+ export declare const COPY_PART: number;
69
+ export type R2Client = ReturnType<typeof createR2Client>;
70
+ export declare function createR2Client(config: R2Config): {
71
+ bucket: string;
72
+ signedFetch: (method: string, key: string, { headers, body, query, bucketLevel, signal }?: SignedFetchOptions) => Promise<Response>;
73
+ createMultipart: (key: string, contentType: string, { signal }?: {
74
+ signal?: AbortSignal;
75
+ }) => Promise<string>;
76
+ completeMultipart: (key: string, uploadId: string, parts: {
77
+ n: number;
78
+ etag: string;
79
+ }[], { ifNoneMatch, signal }?: {
80
+ ifNoneMatch?: boolean;
81
+ signal?: AbortSignal;
82
+ }) => Promise<void>;
83
+ abortMultipart: (key: string, uploadId: string, { signal }?: {
84
+ signal?: AbortSignal;
85
+ }) => Promise<boolean>;
86
+ listParts: (key: string, uploadId: string) => Promise<{
87
+ n: number;
88
+ etag: string;
89
+ size: number;
90
+ }[]>;
91
+ headInfo: (key: string) => Promise<{
92
+ size: number | null;
93
+ etag: string | null;
94
+ }>;
95
+ headObject: (key: string) => Promise<{
96
+ etag: string;
97
+ meta: Record<string, string>;
98
+ } | null>;
99
+ headMeta: (key: string) => Promise<{
100
+ size: number;
101
+ etag: string;
102
+ meta: Record<string, string>;
103
+ } | null>;
104
+ putJson: (key: string, body: string, { ifMatch, ifNoneMatch, meta }?: {
105
+ ifMatch?: string;
106
+ ifNoneMatch?: boolean;
107
+ meta?: Record<string, string>;
108
+ }) => Promise<string>;
109
+ putObject: (key: string, body: string | Uint8Array, { contentType, contentEncoding, meta, ifNoneMatch, }?: {
110
+ contentType?: string;
111
+ contentEncoding?: string;
112
+ meta?: Record<string, string>;
113
+ ifNoneMatch?: boolean;
114
+ }) => Promise<string | null>;
115
+ listObjects: (prefix: string) => Promise<Map<string, {
116
+ etag: string;
117
+ size: number;
118
+ }>>;
119
+ listKeys: (prefix: string) => Promise<{
120
+ key: string;
121
+ lastModified: number;
122
+ }[]>;
123
+ listMultipartUploads: (prefix: string) => Promise<{
124
+ key: string;
125
+ uploadId: string;
126
+ initiatedAt?: string;
127
+ }[]>;
128
+ deleteObjects: (keys: string[]) => Promise<{
129
+ key: string;
130
+ code: string;
131
+ }[]>;
132
+ deleteObject: (key: string) => Promise<undefined>;
133
+ copyObject: (src: string, dst: string, size: number, contentType: string, { ifNoneMatch, sourceEtag, deadline, signal }?: CopyObjectOptions) => Promise<void>;
134
+ getText: (key: string) => Promise<{
135
+ text: string;
136
+ etag: string;
137
+ } | null>;
138
+ getBytes: (key: string, maxBytes: number) => Promise<Uint8Array | null>;
139
+ getJson: <T>(key: string) => Promise<T | null>;
140
+ presignPut: (key: string, { expiresIn, query, contentType, contentMd5, contentLength, ifNoneMatch }?: PresignPutOptions) => Promise<string>;
141
+ presignGet: (key: string, { expiresIn, download, inline, contentType }?: PresignGetOptions) => Promise<string>;
142
+ };
143
+ /**
144
+ * `bucket` or `bucket/prefix/…`: an R2/S3 bucket name, then prefix segments of unreserved characters only. The bucket
145
+ * part of a path is not percent-encoded (it never was), so anything else could address another bucket or prefix
146
+ * (`bkt/a/../../other`, `bkt/a%2Fb`, `bkt/a+b`): refused when the client is created.
147
+ */
148
+ export declare function assertBucket(bucket: string): void;
149
+ /** RFC 6266: a plain ASCII fallback plus the UTF-8 name. */
150
+ export declare function contentDisposition(type: "attachment" | "inline", name: string): string;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * CRC-32 (the ZIP / zlib / PNG one) combination: crc32(A ‖ B) from crc32(A), crc32(B) and B's length.
3
+ *
4
+ * Computing CRCs is NOT done here: callers use zlib's own (`zlib.crc32` in Node ≥ 22.2 and in workerd's
5
+ * node:zlib). Only combining is, because no maintained package exposes zlib's crc32_combine (UploadFilm's
6
+ * PHASE2-PLAN.md, DESIGN). This is a direct port of zlib 1.3's crc32_combine64 (multmodp / x2nmodp in
7
+ * crc32.c), tested against zlib.crc32 of the concatenation (__tests__/crc32.property.test.ts here, and UploadFilm's
8
+ * worker/zip/test/crc32.test.ts).
9
+ *
10
+ * A leaf module (no imports): UploadFilm's shared/zip/crc32.ts re-exports it by file path, and plain Node loads it
11
+ * that way (worker/zip's tests), so it must stay free of imports and of TypeScript-only runtime syntax.
12
+ *
13
+ * Lengths are plain numbers (exact up to 2^53 bytes); CRCs are unsigned 32-bit numbers.
14
+ */
15
+ /** crc32 of A followed by B, given crc32(A), crc32(B) and B's length in bytes. */
16
+ export declare function crc32Combine(crcA: number, crcB: number, lenB: number): number;
17
+ /** Combine pieces in order: [{ crc, len }, …] → crc32 of their concatenation. */
18
+ export declare function crc32CombineAll(pieces: {
19
+ crc: number;
20
+ len: number;
21
+ }[]): number;
22
+ /** 8 lowercase hex digits, the form the manifest and plans store. */
23
+ export declare const crcHex: (c: number) => string;
24
+ export declare const parseCrcHex: (s: unknown) => number | null;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * How keys and queries become the path and query string an S3-compatible store (R2) signs and serves.
3
+ *
4
+ * The encodings are the ones UploadFilm's hand-written signer used (web/lib/r2.ts before aws4fetch), so presigned URLs
5
+ * stay string-identical: RFC 3986 percent-encoding per key segment ("/" kept), query keys sorted, every key and value
6
+ * RFC 3986-encoded.
7
+ */
8
+ /** RFC 3986 percent-encoding: encodeURIComponent plus the five characters it leaves alone (`!'()*`). */
9
+ export declare const uriEncode: (s: string) => string;
10
+ export type Query = Record<string, string | number>;
11
+ /** `k=v&…`, keys sorted, keys and values RFC 3986-encoded (empty values kept: `uploads=`). */
12
+ export declare const canonicalQueryString: (query: Query) => string;
13
+ /** The object's path in the bucket, each key segment RFC 3986-encoded: what the URL carries and SigV4 signs. */
14
+ export declare const objectPath: (bucket: string, key: string) => string;
15
+ /** Thrown before anything is signed for a key that must never be signed (see `assertSignableKey`). */
16
+ export declare class UnsignableKeyError extends Error {
17
+ readonly key: string;
18
+ constructor(message: string, key: string);
19
+ }
20
+ /**
21
+ * Refuse keys that can't be signed safely:
22
+ * - empty or absolute (`/x`): the original rule;
23
+ * - a `.` or `..` segment: URL parsers (fetch, aws4fetch's `new URL`) collapse them, so a request signed for
24
+ * `p/a/../b` would be sent and verified as `p/b`, another object (a path-traversal hole once signing goes through
25
+ * a URL object; the hand-written signer only produced a request R2 refused);
26
+ * - not well-formed UTF-16 (a lone surrogate): it has no UTF-8 encoding (encodeURIComponent throws URIError).
27
+ */
28
+ export declare function assertSignableKey(key: string): void;
29
+ /** String.prototype.isWellFormed (ES2024), with a fallback for runtimes without it. */
30
+ export declare function isWellFormed(s: string): boolean;
31
+ /** S3 XML text: the five predefined entities. */
32
+ export declare const xmlEscape: (s: string) => string;
33
+ export declare const xmlUnescape: (x: string) => string;
34
+ /** ETags compare as the bare value: no quotes, no weak marker (`W/"abc"` → `abc`). */
35
+ export declare const bareEtag: (e: string | null | undefined) => string;
@@ -0,0 +1,9 @@
1
+ /** An R2 (S3) failure with the S3 error code, so callers can tell "retry" from "give up". */
2
+ export declare class R2Error extends Error {
3
+ status: number;
4
+ code?: string;
5
+ constructor(message: string, status: number, code?: string);
6
+ get retryable(): boolean;
7
+ }
8
+ /** The body as text when the response is OK; otherwise an R2Error with S3's <Code> and <Message>. */
9
+ export declare function expectOk(res: Response, what: string): Promise<string>;
@@ -0,0 +1,25 @@
1
+ /** MD5 of bytes (WebCrypto MD5 on Workers, node:crypto on Node). */
2
+ export declare function md5(bytes: Uint8Array): Promise<Uint8Array>;
3
+ export declare const toHex: (b: Uint8Array) => string;
4
+ export declare const toBase64: (b: Uint8Array) => string;
5
+ /** The ETag storage gives a multipart object made of parts with these ETags (MD5 hex, quotes allowed). */
6
+ export declare function multipartEtag(partEtags: string[]): Promise<string>;
7
+ /** Content-MD5 (base64) → the ETag R2 will answer for that body (MD5 hex). */
8
+ export declare const etagOfContentMd5: (b64: string) => string;
9
+ export type Verdict = {
10
+ ok: true;
11
+ } | {
12
+ ok: false;
13
+ reason: "missing" | "size" | "etag" | "weak-etag";
14
+ };
15
+ /**
16
+ * Does what storage reports match what was sent? `expected.etag`: the single-PUT MD5 hex or the multipart composite.
17
+ * A weak ETag (`W/…`, HEAD without identity on a text-like object) is not proof: "weak-etag", ask again with identity.
18
+ */
19
+ export declare function verifyStored(stored: {
20
+ size: number | null;
21
+ etag: string | null;
22
+ }, expected: {
23
+ size: number;
24
+ etag: string;
25
+ }): Verdict;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Multipart arithmetic under S3/R2's rules: how to cut an object into parts, where each part sits, and whether a
3
+ * completion's part list will be accepted.
4
+ *
5
+ * S3 limits: at most 10,000 parts, every part but the last at least 5 MiB, at most 5 GiB per part, at most 5 TiB per
6
+ * object. R2 adds one: every part but the last has the SAME size (else CompleteMultipartUpload fails InvalidPart).
7
+ */
8
+ export declare const MIB: number;
9
+ export declare const S3_MIN_PART: number;
10
+ export declare const S3_MAX_PART: number;
11
+ export declare const S3_MAX_PARTS = 10000;
12
+ export declare const S3_MAX_OBJECT: number;
13
+ export interface PartPlanOptions {
14
+ /** Smallest part to use (≥ 5 MiB). Default 16 MiB (UploadFilm's). */
15
+ minPart?: number;
16
+ /** At most this many parts (≤ 10,000). Default 9,500 (UploadFilm's, headroom under S3's 10,000). */
17
+ maxParts?: number;
18
+ /** Part sizes are multiples of this. Default 1 MiB. */
19
+ align?: number;
20
+ }
21
+ /**
22
+ * The part size for an object of `size` bytes: the smallest multiple of `align`, at least `minPart`, that fits the
23
+ * object in `maxParts` parts. UploadFilm's app/src/main/engine.ts partSizeFor is this with the defaults.
24
+ * Throws RangeError for sizes S3 can't store in one object.
25
+ */
26
+ export declare function partSizeFor(size: number, { minPart, maxParts, align }?: PartPlanOptions): number;
27
+ /** How many parts `size` bytes make at `partSize` (0 bytes → 1 empty part: a multipart object always has one). */
28
+ export declare const partCount: (size: number, partSize: number) => number;
29
+ /** Byte range of part `n` (1-based): [start, end) and its length. */
30
+ export declare function partRange(n: number, partSize: number, size: number): {
31
+ start: number;
32
+ end: number;
33
+ length: number;
34
+ };
35
+ export type CompletionProblem = "NoParts" | "TooManyParts" | "InvalidPartOrder" | "InvalidPart" | "EntityTooSmall" | "EntityTooLarge";
36
+ /**
37
+ * Would storage accept CompleteMultipartUpload with these parts (sizes as storage holds them)? null = yes, else the
38
+ * S3 error code R2 answers, in R2's order: duplicate numbers → InvalidPartOrder (before any size check); a non-final
39
+ * part under 5 MiB → EntityTooSmall;
40
+ * unequal non-final parts (R2), a number out of 1..10,000 or a size that isn't a non-negative integer → InvalidPart;
41
+ * a part over 5 GiB or an object over 5 TiB → EntityTooLarge.
42
+ */
43
+ export declare function checkCompletion(parts: {
44
+ n: number;
45
+ size: number;
46
+ }[]): CompletionProblem | null;
@@ -0,0 +1,47 @@
1
+ import { type Query } from "./encoding";
2
+ export interface SigningCredentials {
3
+ accessKeyId: string;
4
+ secretAccessKey: string;
5
+ /** R2: "auto". */
6
+ region?: string;
7
+ /** R2 / S3: "s3". */
8
+ service?: string;
9
+ }
10
+ /** `YYYYMMDDTHHMMSSZ`, the SigV4 timestamp. */
11
+ export declare const amzDate: (d: Date) => string;
12
+ /** Thrown when a header that would be signed has a value SigV4/HTTP can't carry unchanged. */
13
+ export declare class UnsignableHeaderError extends Error {
14
+ readonly header: string;
15
+ constructor(header: string);
16
+ }
17
+ /**
18
+ * A signed header must reach storage byte for byte: printable ASCII, no leading/trailing space, no runs of spaces
19
+ * (SigV4 collapses them, HTTP stacks may not), no control characters (fetch refuses them).
20
+ */
21
+ export declare function assertHeaderValue(name: string, value: string): void;
22
+ /** SHA-256 hex of the payload (WebCrypto). */
23
+ export declare function sha256Hex(body: Uint8Array | string | undefined): Promise<string>;
24
+ export interface SignedRequest {
25
+ url: string;
26
+ method: string;
27
+ /** Authorization, X-Amz-Date, X-Amz-Content-Sha256 (the body's SHA-256) and every header given, all signed. */
28
+ headers: Record<string, string>;
29
+ body?: Uint8Array;
30
+ }
31
+ /**
32
+ * A header-signed request (the control plane: multipart create/complete/abort, HEAD, GET, PUT, list, delete).
33
+ * `origin` is the endpoint (`https://<account>.r2.cloudflarestorage.com`), `canonicalPath` the encoded path
34
+ * (`/bucket/key…` or `/bucket`).
35
+ */
36
+ export declare function signRequest(creds: SigningCredentials, method: string, origin: string, canonicalPath: string, { headers, body, query, now, }?: {
37
+ headers?: Record<string, string>;
38
+ body?: Uint8Array | string;
39
+ query?: Query;
40
+ now?: Date;
41
+ }): Promise<SignedRequest>;
42
+ /**
43
+ * A presigned URL (`UNSIGNED-PAYLOAD`): `${origin}${canonical path}?${canonical query}&X-Amz-Signature=…`.
44
+ * `query` carries the request's own parameters and `X-Amz-Expires`; every header in `headers` is signed and must be
45
+ * sent verbatim by whoever uses the URL.
46
+ */
47
+ export declare function presignUrl(creds: SigningCredentials, method: string, origin: string, canonicalPath: string, query: Query, headers: Record<string, string>, now?: Date): Promise<string>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `@uploadfilm/sdk/server/redis`: the KeyValueStore (server/state) over a product's own Redis client: ioredis (or any
3
+ * client with ioredis's call shapes) or @upstash/redis (REST, Workers-friendly). Both are optional peer dependencies:
4
+ * this module never imports them, it only calls the client it is given.
5
+ *
6
+ * Upstash: create the client with `automaticDeserialization: false`. With the default, @upstash/redis JSON-parses every
7
+ * reply ("123" comes back as the number 123, '{"a": 1}' as an object), so stored strings would not come back byte for
8
+ * byte; the adapter refuses such a client instead of corrupting values.
9
+ *
10
+ * `incr` and `compareAndSet` run as Lua scripts (EVAL), so they are atomic across processes.
11
+ */
12
+ import { type AtomicKeyValueStore } from "@uploadfilm/sdk/server";
13
+ export declare const SDK_ENTRY: "server/redis";
14
+ /** The ioredis calls the adapter makes. */
15
+ export interface IoRedisLike {
16
+ get(key: string): Promise<string | null>;
17
+ set(key: string, value: string, ...args: (string | number)[]): Promise<string | null>;
18
+ del(...keys: string[]): Promise<number>;
19
+ pttl(key: string): Promise<number>;
20
+ eval(script: string, numKeys: number, ...keysAndArgs: (string | number)[]): Promise<unknown>;
21
+ }
22
+ /** The @upstash/redis calls the adapter makes. */
23
+ export interface UpstashLike {
24
+ get(key: string): Promise<unknown>;
25
+ set(key: string, value: string, opts?: {
26
+ px?: number;
27
+ nx?: boolean;
28
+ }): Promise<unknown>;
29
+ del(...keys: string[]): Promise<number>;
30
+ pttl(key: string): Promise<number>;
31
+ eval(script: string, keys: string[], args: string[]): Promise<unknown>;
32
+ }
33
+ export interface RedisStoreOptions {
34
+ /** Prepended to every key (default ""). */
35
+ prefix?: string;
36
+ /** Which client shape; detected when omitted (ioredis has defineCommand, @upstash/redis has exec + opts). */
37
+ kind?: "ioredis" | "upstash";
38
+ }
39
+ export declare function createRedisStore(client: IoRedisLike | UpstashLike, o?: RedisStoreOptions): AtomicKeyValueStore;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The in-memory KeyValueStore: one process (a dev server, a test, a single long-lived Worker isolate as a best-effort
3
+ * cache). Expired keys are dropped lazily on access and by a sweep every `sweepEvery` writes, so the map can't grow
4
+ * without bound from keys nobody reads again. `maxKeys` (optional) caps it: the oldest-written keys go first.
5
+ */
6
+ import { type AtomicKeyValueStore } from "./types";
7
+ export interface MemoryStoreOptions {
8
+ /** Clock in ms (tests). Default Date.now. */
9
+ now?: () => number;
10
+ /** Sweep expired keys every this many writes (default 1000). */
11
+ sweepEvery?: number;
12
+ /** Most keys kept (default unbounded). */
13
+ maxKeys?: number;
14
+ }
15
+ export declare function createMemoryStore(o?: MemoryStoreOptions): AtomicKeyValueStore & {
16
+ size(): number;
17
+ clear(): void;
18
+ };
@@ -0,0 +1,73 @@
1
+ /**
2
+ * A KeyValueStore kept in an R2 (or any S3-compatible) bucket, for products that keep their state as objects in their
3
+ * own bucket instead of Redis (ClipMe: no database, no Redis). One object per key; atomic operations are optimistic:
4
+ * read the object and its ETag, write only if the ETag is still that one (If-Match), or only if there is no object
5
+ * (If-None-Match: *); on a lost race, read again and retry.
6
+ *
7
+ * Two ways to reach the bucket:
8
+ * createR2Store(r2ClientBackend(createR2Client({ endpoint, bucket, accessKeyId, secretAccessKey }))) // S3 API: Node, Vercel, Workers
9
+ * createR2Store(r2BindingBackend(env.BUCKET)) // a Workers R2 binding
10
+ *
11
+ * R2 has no expiry: a TTL is written next to the value, and a key past it is gone for every operation. The first
12
+ * operation that finds it expired replaces it with a tombstone (a conditional write), so a write still in flight from
13
+ * before the expiry, conditional on the old ETag, can't bring the old value back after someone saw the key missing.
14
+ * Sweep old objects with a bucket lifecycle rule on the prefix if keys aren't reused.
15
+ *
16
+ * Lost replies (REALITY-CHECK RC-S1, the pattern that lost first downloads in production): a conditional write can land
17
+ * and its answer be lost (the connection drops, or a transport retry of the same PUT gets 412). Every conditional write
18
+ * carries a token only that call knows (`t`); when its answer is a refusal or an error, the object is read back, and if
19
+ * it holds this call's token the write landed and the call answers as such (a `set ifAbsent` that wrote the key never
20
+ * reads as "taken").
21
+ *
22
+ * Costs: every get is one read; a set is one write (two operations with ifAbsent); incr and compareAndSet are a read and
23
+ * a write, more under contention. Fine for job records, locks and caches; not for a hot counter.
24
+ */
25
+ import type { R2Client } from "../r2/client";
26
+ import { type AtomicKeyValueStore } from "./types";
27
+ /** What the store needs from a bucket. `put` → false when its condition failed (nothing written). */
28
+ export interface R2KvBackend {
29
+ get(key: string): Promise<{
30
+ body: string;
31
+ etag: string;
32
+ } | null>;
33
+ put(key: string, body: string, condition?: {
34
+ ifMatch: string;
35
+ } | {
36
+ ifAbsent: true;
37
+ }): Promise<boolean>;
38
+ delete(key: string): Promise<void>;
39
+ }
40
+ /** The S3 API, through the SDK's R2 client (header-signed requests; the key prefix of `bucket/prefix` applies). */
41
+ export declare function r2ClientBackend(client: Pick<R2Client, "signedFetch">): R2KvBackend;
42
+ /** The calls made on a Workers R2 binding (R2Bucket). */
43
+ export interface R2BindingLike {
44
+ get(key: string): Promise<{
45
+ etag: string;
46
+ text(): Promise<string>;
47
+ } | null>;
48
+ put(key: string, value: string, options?: {
49
+ onlyIf?: unknown;
50
+ httpMetadata?: {
51
+ contentType?: string;
52
+ };
53
+ }): Promise<unknown | null>;
54
+ delete(key: string): Promise<void>;
55
+ }
56
+ /** A Workers R2 binding: conditional puts with `onlyIf` (a failed condition answers null). */
57
+ export declare function r2BindingBackend(bucket: R2BindingLike): R2KvBackend;
58
+ export interface R2StoreOptions {
59
+ /** Prepended to every object key (keep the store's objects under one prefix). Default "kv/". */
60
+ prefix?: string;
61
+ /** Clock in ms (tests). Default Date.now. */
62
+ now?: () => number;
63
+ /** Tries of an atomic operation that keeps losing races before it throws (default 100). */
64
+ maxAttempts?: number;
65
+ /** Wait before try n (n ≥ 1) of a lost race. Default: random up to min(5 n, 100) ms. */
66
+ backoff?: (attempt: number) => Promise<void>;
67
+ }
68
+ /**
69
+ * Keys are opaque strings ("a/../b", "日本", "*" are all fine): each is percent-encoded into one path segment, dots
70
+ * included, so no key can name another prefix or a "." / ".." segment.
71
+ */
72
+ export declare const r2KeyOf: (prefix: string, key: string) => string;
73
+ export declare function createR2Store(backend: R2KvBackend, o?: R2StoreOptions): AtomicKeyValueStore;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Pluggable state. Wherever the SDK caches or keeps state (token caches, revocation lists, upload sessions, dedupe
3
+ * indexes, rate windows…) it takes a KeyValueStore the product injects: the in-memory one (state/memory.ts) for a
4
+ * single process and tests, or the Redis adapter (`@uploadfilm/sdk/server/redis`) over the product's own ioredis or
5
+ * Upstash client. The SDK owns no tables and needs no database; records a product wants in its own DB reach it
6
+ * through hooks.
7
+ *
8
+ * Semantics (both adapters pass the same contract tests, state/__tests__/contract.ts):
9
+ * - values are strings, returned byte for byte as stored (no JSON coercion);
10
+ * - `ttlMs` is a positive integer; a key past its TTL is gone for every operation;
11
+ * - a plain `set` (no ttlMs) leaves the key without expiry, as Redis SET does;
12
+ * - `incr` and `compareAndSet` are atomic across concurrent callers (on Redis: across processes).
13
+ */
14
+ /**
15
+ * A TTL: `{ ttlMs }` or `{ ttlSeconds }` (positive integers; not both), or a bare number of SECONDS — the auth kit's
16
+ * convention (server/auth/kv.ts), so these stores fit its KeyValueStore exactly and a TTL is never silently dropped.
17
+ */
18
+ export type Ttl = number | {
19
+ ttlMs?: number;
20
+ ttlSeconds?: number;
21
+ };
22
+ export interface SetOptions {
23
+ /** Expire after this many milliseconds (positive integer). */
24
+ ttlMs?: number;
25
+ /** Expire after this many seconds (positive integer). The auth kit's unit. */
26
+ ttlSeconds?: number;
27
+ /** Only set when the key is missing. */
28
+ ifAbsent?: boolean;
29
+ }
30
+ export interface KeyValueStore {
31
+ get(key: string): Promise<string | null>;
32
+ /** → false when `ifAbsent` was set and the key exists (nothing written), true otherwise. */
33
+ set(key: string, value: string, options?: SetOptions): Promise<boolean>;
34
+ /** Remove the key (missing is fine). Resolves to nothing, like the auth kit's KeyValueStore it must fit. */
35
+ del(key: string): Promise<void>;
36
+ /** Remaining milliseconds: null when the key is missing, Infinity when it has no expiry. */
37
+ ttl?(key: string): Promise<number | null>;
38
+ /**
39
+ * Atomic add to an integer counter (missing = 0). `ttlMs` applies only when this call creates the key, so a
40
+ * window counter expires when its window does. Throws when the value isn't an integer.
41
+ */
42
+ incr?(key: string, by?: number, ttl?: Ttl): Promise<number>;
43
+ /** Atomic: write `value` only when the current value is `expected` (null = only when missing). */
44
+ compareAndSet?(key: string, expected: string | null, value: string, ttl?: Ttl): Promise<boolean>;
45
+ }
46
+ /** A KeyValueStore with every optional atomic op. */
47
+ export type AtomicKeyValueStore = Required<KeyValueStore>;
48
+ export declare class StateError extends Error {
49
+ constructor(message: string);
50
+ }
51
+ export declare function checkTtl(ttlMs: number | undefined): void;
52
+ /** A Ttl (or SetOptions) → milliseconds, validated; undefined = no expiry. */
53
+ export declare function ttlMsOf(t: Ttl | SetOptions | undefined): number | undefined;
54
+ export declare function checkBy(by: number): void;
55
+ export declare function checkValue(value: unknown): asserts value is string;
56
+ /** Every key under `prefix` (keep products' and the SDK's keys apart in a shared Redis). */
57
+ export declare function namespaced<S extends KeyValueStore>(store: S, prefix: string): S;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * S3's `aws-chunked` body framing with a trailing CRC-32 (`STREAMING-UNSIGNED-PAYLOAD-TRAILER`), computed while the
3
+ * bytes pass. This is S3's wire format for a streamed upload whose checksum is known only at the end (AWS:
4
+ * "Uploading objects with trailing checksums"); no maintained library offers it without the AWS SDK.
5
+ *
6
+ * Why not a checksum header: it must be known before the body, so the part would be read twice or buffered. With the
7
+ * trailer, S3 checks the CRC of every part on arrival and stores it, and the multipart upload's FULL_OBJECT CRC-32 is
8
+ * combined from them. A bucket with Object Lock accepts it (it requires Content-MD5 or an x-amz-checksum).
9
+ *
10
+ * The body is re-framed into fixed CHUNK-sized aws-chunks, so the encoded length is known before the first byte
11
+ * (S3 needs Content-Length). Memory: one chunk being filled. Errors (never a short part) unless exactly `size`
12
+ * bytes pass.
13
+ */
14
+ import { type CopyHasher } from "../../copy/checksums";
15
+ /** aws-chunk payload size (S3: ≥ 8 KiB except the last). */
16
+ export declare const CHUNK: number;
17
+ export declare const TRAILER = "x-amz-checksum-crc32";
18
+ /** Bytes on the wire for a `size`-byte payload. */
19
+ export declare function encodedLength(size: number): number;
20
+ /** Raw bytes in, aws-chunked bytes out; `onCrc` gets the payload's CRC-32 once it all passed. */
21
+ export declare function awsChunked(size: number, hasher: Pick<CopyHasher, "crc32">, onCrc?: (crc: number) => void): TransformStream<Uint8Array, Uint8Array>;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Server-only storage modules for `copy()`: `r2(binding | config | client)` and `s3({ bucket, region, storageClass,
3
+ * lock, credentials })`, both signed with aws4fetch (never the AWS S3 SDK), with the copy engine and its errors, so a
4
+ * Worker imports one entry (`@uploadfilm/sdk/server`). Not exported from the root entry: storage credentials never
5
+ * reach the Mac app or a browser.
6
+ */
7
+ export { r2 } from "./r2";
8
+ export type { R2Module, R2ModuleOptions, R2BucketLike, R2ObjectLike, R2ObjectBodyLike, R2MultipartUploadLike, } from "./r2";
9
+ export { s3, S3_STORAGE_CLASSES, ARCHIVE_CLASSES, WORKER_MAX_REQUEST, WORKER_MAX_PART, payloadFor, inWorker } from "./s3";
10
+ export type { S3Module, S3Options, S3Credentials, S3Lock } from "./s3";
11
+ export { awsChunked, encodedLength, CHUNK as AWS_CHUNK } from "./chunked";
12
+ export * from "../../copy";