@editframe/elements 0.18.19-beta.0 → 0.18.21-beta.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.
@@ -18,9 +18,9 @@ export declare const RenderInfo: z.ZodObject<{
18
18
  efImage: string[];
19
19
  }>;
20
20
  }, "strip", z.ZodTypeAny, {
21
+ durationMs: number;
21
22
  width: number;
22
23
  height: number;
23
- durationMs: number;
24
24
  fps: number;
25
25
  assets: {
26
26
  efMedia: Record<string, any>;
@@ -28,9 +28,9 @@ export declare const RenderInfo: z.ZodObject<{
28
28
  efImage: string[];
29
29
  };
30
30
  }, {
31
+ durationMs: number;
31
32
  width: number;
32
33
  height: number;
33
- durationMs: number;
34
34
  fps: number;
35
35
  assets: {
36
36
  efMedia: Record<string, any>;
@@ -2,9 +2,14 @@ import { LitElement } from 'lit';
2
2
  declare const TestContext_base: (new (...args: any[]) => import('./ContextMixin.js').ContextMixinInterface) & typeof LitElement;
3
3
  declare class TestContext extends TestContext_base {
4
4
  }
5
+ declare const TestContextElement_base: (new (...args: any[]) => import('./ContextMixin.js').ContextMixinInterface) & typeof LitElement;
6
+ declare class TestContextElement extends TestContextElement_base {
7
+ render(): import('lit-html').TemplateResult<1>;
8
+ }
5
9
  declare global {
6
10
  interface HTMLElementTagNameMap {
7
11
  "test-context": TestContext;
12
+ "test-context-reactivity": TestContextElement;
8
13
  }
9
14
  }
10
15
  export {};
@@ -24,14 +24,22 @@ function ContextMixin(superClass) {
24
24
  init.headers ||= {};
25
25
  Object.assign(init.headers, { "Content-Type": "application/json" });
26
26
  if (this.signingURL) {
27
- if (!this.#URLTokens[url]) this.#URLTokens[url] = fetch(this.signingURL, {
27
+ const now = Date.now();
28
+ const { cacheKey, signingPayload } = this.#getTokenCacheKey(url);
29
+ const tokenExpiration = this.#URLTokenExpirations[cacheKey] || 0;
30
+ if (!this.#URLTokens[cacheKey] || now >= tokenExpiration) this.#URLTokens[cacheKey] = fetch(this.signingURL, {
28
31
  method: "POST",
29
- body: JSON.stringify({ url })
32
+ body: JSON.stringify(signingPayload)
30
33
  }).then(async (response) => {
31
- if (response.ok) return (await response.json()).token;
34
+ if (response.ok) {
35
+ const tokenData = await response.json();
36
+ const token = tokenData.token;
37
+ this.#URLTokenExpirations[cacheKey] = this.#parseTokenExpiration(token);
38
+ return token;
39
+ }
32
40
  throw new Error(`Failed to sign URL: ${url}. SigningURL: ${this.signingURL} ${response.status} ${response.statusText}`);
33
41
  });
34
- const urlToken = await this.#URLTokens[url];
42
+ const urlToken = await this.#URLTokens[cacheKey];
35
43
  Object.assign(init.headers, { authorization: `Bearer ${urlToken}` });
36
44
  } else init.credentials = "include";
37
45
  return fetch(url, init);
@@ -51,7 +59,76 @@ function ContextMixin(superClass) {
51
59
  set apiHost(value) {
52
60
  this.#apiHost = value;
53
61
  }
62
+ get durationMs() {
63
+ return this.targetTimegroup?.durationMs ?? 0;
64
+ }
65
+ get endTimeMs() {
66
+ return this.targetTimegroup?.endTimeMs ?? 0;
67
+ }
54
68
  #URLTokens = {};
69
+ #URLTokenExpirations = {};
70
+ /**
71
+ * Generate a cache key for URL token based on signing strategy
72
+ *
73
+ * Uses unified prefix + parameter matching approach:
74
+ * - For transcode URLs: signs base "/api/v1/transcode" + params like {url: "source.mp4"}
75
+ * - For regular URLs: signs full URL with empty params {}
76
+ * - All validation uses prefix matching + exhaustive parameter matching
77
+ * - Multiple transcode segments with same source share one token (reduces round-trips)
78
+ */
79
+ #getTokenCacheKey(url) {
80
+ try {
81
+ const urlObj = new URL(url);
82
+ if (urlObj.pathname.includes("/api/v1/transcode/")) {
83
+ const urlParam = urlObj.searchParams.get("url");
84
+ if (urlParam) {
85
+ const basePath = `${urlObj.origin}/api/v1/transcode`;
86
+ const cacheKey = `${basePath}?url=${urlParam}`;
87
+ return {
88
+ cacheKey,
89
+ signingPayload: {
90
+ url: basePath,
91
+ params: { url: urlParam }
92
+ }
93
+ };
94
+ }
95
+ }
96
+ return {
97
+ cacheKey: url,
98
+ signingPayload: { url }
99
+ };
100
+ } catch {
101
+ return {
102
+ cacheKey: url,
103
+ signingPayload: { url }
104
+ };
105
+ }
106
+ }
107
+ /**
108
+ * Parse JWT token to extract safe expiration time (with buffer)
109
+ * @param token JWT token string
110
+ * @returns Safe expiration timestamp in milliseconds (actual expiry minus buffer), or 0 if parsing fails
111
+ */
112
+ #parseTokenExpiration(token) {
113
+ try {
114
+ const parts = token.split(".");
115
+ if (parts.length !== 3) return 0;
116
+ const payload = parts[1];
117
+ if (!payload) return 0;
118
+ const decoded = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
119
+ const parsed = JSON.parse(decoded);
120
+ const exp = parsed.exp;
121
+ const iat = parsed.iat;
122
+ if (!exp) return 0;
123
+ const lifetimeSeconds = iat ? exp - iat : 3600;
124
+ const tenPercentBufferMs = lifetimeSeconds * .1 * 1e3;
125
+ const fiveMinutesMs = 5 * 60 * 1e3;
126
+ const bufferMs = Math.min(fiveMinutesMs, tenPercentBufferMs);
127
+ return exp * 1e3 - bufferMs;
128
+ } catch {
129
+ return 0;
130
+ }
131
+ }
55
132
  #signingURL;
56
133
  /**
57
134
  * A URL that will be used to generated signed tokens for accessing media files from the
@@ -66,10 +143,20 @@ function ContextMixin(superClass) {
66
143
  #FPS = 30;
67
144
  #MS_PER_FRAME = 1e3 / this.#FPS;
68
145
  #timegroupObserver = new MutationObserver((mutations) => {
146
+ let shouldUpdate = false;
69
147
  for (const mutation of mutations) if (mutation.type === "childList") {
70
148
  const newTimegroup = this.querySelector("ef-timegroup");
71
- if (newTimegroup !== this.targetTimegroup) this.targetTimegroup = newTimegroup;
149
+ if (newTimegroup !== this.targetTimegroup) {
150
+ this.targetTimegroup = newTimegroup;
151
+ shouldUpdate = true;
152
+ } else if (mutation.target instanceof Element && (mutation.target.tagName === "EF-TIMEGROUP" || mutation.target.closest("ef-timegroup"))) shouldUpdate = true;
153
+ } else if (mutation.type === "attributes") {
154
+ if (mutation.attributeName === "duration" || mutation.attributeName === "mode" || mutation.target instanceof Element && (mutation.target.tagName === "EF-TIMEGROUP" || mutation.target.closest("ef-timegroup"))) shouldUpdate = true;
72
155
  }
156
+ if (shouldUpdate) queueMicrotask(() => {
157
+ this.requestUpdate();
158
+ if (this.targetTimegroup) this.targetTimegroup.requestUpdate();
159
+ });
73
160
  });
74
161
  connectedCallback() {
75
162
  super.connectedCallback();
@@ -85,6 +172,8 @@ function ContextMixin(superClass) {
85
172
  super.disconnectedCallback();
86
173
  this.#timegroupObserver.disconnect();
87
174
  this.stopPlayback();
175
+ this.#URLTokens = {};
176
+ this.#URLTokenExpirations = {};
88
177
  }
89
178
  update(changedProperties) {
90
179
  if (changedProperties.has("playing")) if (this.playing) this.startPlayback();
@@ -194,6 +283,8 @@ function ContextMixin(superClass) {
194
283
  })], ContextElement.prototype, "apiHost", null);
195
284
  _decorate([provide({ context: efContext })], ContextElement.prototype, "efContext", void 0);
196
285
  _decorate([provide({ context: targetTimegroupContext }), state()], ContextElement.prototype, "targetTimegroup", void 0);
286
+ _decorate([state()], ContextElement.prototype, "durationMs", null);
287
+ _decorate([state()], ContextElement.prototype, "endTimeMs", null);
197
288
  _decorate([provide({ context: fetchContext })], ContextElement.prototype, "fetch", void 0);
198
289
  _decorate([property({
199
290
  type: String,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@editframe/elements",
3
- "version": "0.18.19-beta.0",
3
+ "version": "0.18.21-beta.0",
4
4
  "description": "",
5
5
  "exports": {
6
6
  ".": {
@@ -27,7 +27,7 @@
27
27
  "license": "UNLICENSED",
28
28
  "dependencies": {
29
29
  "@bramus/style-observer": "^1.3.0",
30
- "@editframe/assets": "0.18.19-beta.0",
30
+ "@editframe/assets": "0.18.21-beta.0",
31
31
  "@lit/context": "^1.1.2",
32
32
  "@lit/task": "^1.0.1",
33
33
  "d3": "^7.9.0",
@@ -1,6 +1,6 @@
1
- import { LitElement } from "lit";
1
+ import { html, LitElement } from "lit";
2
2
  import { customElement } from "lit/decorators/custom-element.js";
3
- import { describe, expect, test, vi } from "vitest";
3
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
4
4
 
5
5
  import { ContextMixin } from "./ContextMixin.js";
6
6
 
@@ -10,9 +10,17 @@ import "../elements/EFTimegroup.js";
10
10
  @customElement("test-context")
11
11
  class TestContext extends ContextMixin(LitElement) {}
12
12
 
13
+ @customElement("test-context-reactivity")
14
+ class TestContextElement extends ContextMixin(LitElement) {
15
+ render() {
16
+ return html`<slot></slot>`;
17
+ }
18
+ }
19
+
13
20
  declare global {
14
21
  interface HTMLElementTagNameMap {
15
22
  "test-context": TestContext;
23
+ "test-context-reactivity": TestContextElement;
16
24
  }
17
25
  }
18
26
 
@@ -21,6 +29,482 @@ describe("ContextMixin", () => {
21
29
  expect(ContextMixin).toBeDefined();
22
30
  });
23
31
 
32
+ describe("Token age checking", () => {
33
+ let element: TestContext & { fetch: typeof fetch };
34
+ let mockFetch: any;
35
+ let originalFetch: any;
36
+
37
+ // Helper to create a JWT token with specific expiration time
38
+ const createJWTToken = (
39
+ expirationMs: number,
40
+ issuedAtMs?: number,
41
+ ): string => {
42
+ const iat = issuedAtMs
43
+ ? Math.floor(issuedAtMs / 1000)
44
+ : Math.floor(Date.now() / 1000);
45
+ const header = btoa(JSON.stringify({ typ: "JWT", alg: "HS256" }));
46
+ const payload = btoa(
47
+ JSON.stringify({
48
+ type: "url",
49
+ url: "test-url",
50
+ exp: Math.floor(expirationMs / 1000), // JWT exp is in seconds
51
+ iat: iat,
52
+ }),
53
+ );
54
+ const signature = "mock-signature";
55
+ return `${header}.${payload}.${signature}`;
56
+ };
57
+
58
+ beforeEach(() => {
59
+ originalFetch = window.fetch;
60
+ mockFetch = vi.fn();
61
+ window.fetch = mockFetch;
62
+
63
+ element = document.createElement("test-context") as TestContext & {
64
+ fetch: typeof fetch;
65
+ };
66
+ element.signingURL = "https://test.com/api/v1/url-token";
67
+ document.body.appendChild(element);
68
+
69
+ vi.useFakeTimers();
70
+ });
71
+
72
+ afterEach(() => {
73
+ if (element.parentNode) {
74
+ document.body.removeChild(element);
75
+ }
76
+ window.fetch = originalFetch;
77
+ vi.useRealTimers();
78
+ });
79
+
80
+ test("should fetch new token when none exists", async () => {
81
+ const futureTime = Date.now() + 60 * 60 * 1000; // 1 hour from now
82
+ const token = createJWTToken(futureTime);
83
+
84
+ mockFetch.mockResolvedValueOnce({
85
+ ok: true,
86
+ json: () => Promise.resolve({ token }),
87
+ });
88
+
89
+ mockFetch.mockResolvedValueOnce({
90
+ ok: true,
91
+ text: () => Promise.resolve("success"),
92
+ });
93
+
94
+ await element.fetch("https://example.com/media.mp4");
95
+
96
+ expect(mockFetch).toHaveBeenCalledWith(
97
+ "https://test.com/api/v1/url-token",
98
+ {
99
+ method: "POST",
100
+ body: JSON.stringify({ url: "https://example.com/media.mp4" }),
101
+ },
102
+ );
103
+
104
+ expect(mockFetch).toHaveBeenCalledWith("https://example.com/media.mp4", {
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ authorization: `Bearer ${token}`,
108
+ },
109
+ });
110
+ }, 1000);
111
+
112
+ test("should reuse cached token when fresh", async () => {
113
+ const futureTime = Date.now() + 60 * 60 * 1000; // 1 hour from now
114
+ const token = createJWTToken(futureTime);
115
+
116
+ mockFetch.mockResolvedValueOnce({
117
+ ok: true,
118
+ json: () => Promise.resolve({ token }),
119
+ });
120
+
121
+ mockFetch.mockResolvedValueOnce({
122
+ ok: true,
123
+ text: () => Promise.resolve("success1"),
124
+ });
125
+
126
+ await element.fetch("https://example.com/media.mp4");
127
+
128
+ // Advance time by 30 minutes (token still valid for 30 more minutes)
129
+ vi.advanceTimersByTime(30 * 60 * 1000);
130
+
131
+ mockFetch.mockResolvedValueOnce({
132
+ ok: true,
133
+ text: () => Promise.resolve("success2"),
134
+ });
135
+
136
+ await element.fetch("https://example.com/media.mp4");
137
+
138
+ // Should only call signing URL once
139
+ expect(mockFetch).toHaveBeenCalledTimes(3); // 1 signing + 2 media requests
140
+ }, 1000);
141
+
142
+ test("should fetch new token when cached token is expired", async () => {
143
+ const now = Date.now();
144
+ const issuedAt = now;
145
+ const expiresAt = now + 30 * 60 * 1000; // 30 minutes from now
146
+
147
+ // For a 30-minute token: 10% = 3 minutes buffer (smaller than 5 minutes)
148
+ // Token will be considered expired at 27 minutes
149
+ const token1 = createJWTToken(expiresAt, issuedAt);
150
+
151
+ mockFetch.mockResolvedValueOnce({
152
+ ok: true,
153
+ json: () => Promise.resolve({ token: token1 }),
154
+ });
155
+
156
+ mockFetch.mockResolvedValueOnce({
157
+ ok: true,
158
+ text: () => Promise.resolve("success1"),
159
+ });
160
+
161
+ await element.fetch("https://example.com/media.mp4");
162
+
163
+ // Advance time by 28 minutes (past the 27-minute buffer threshold)
164
+ vi.advanceTimersByTime(28 * 60 * 1000);
165
+
166
+ const newExpiry = Date.now() + 60 * 60 * 1000; // 1 hour from current time
167
+ const token2 = createJWTToken(newExpiry);
168
+
169
+ mockFetch.mockResolvedValueOnce({
170
+ ok: true,
171
+ json: () => Promise.resolve({ token: token2 }),
172
+ });
173
+
174
+ mockFetch.mockResolvedValueOnce({
175
+ ok: true,
176
+ text: () => Promise.resolve("success2"),
177
+ });
178
+
179
+ await element.fetch("https://example.com/media.mp4");
180
+
181
+ // Should call signing URL twice
182
+ expect(mockFetch).toHaveBeenCalledTimes(4); // 2 signing + 2 media requests
183
+
184
+ expect(mockFetch).toHaveBeenCalledWith(
185
+ "https://test.com/api/v1/url-token",
186
+ {
187
+ method: "POST",
188
+ body: JSON.stringify({ url: "https://example.com/media.mp4" }),
189
+ },
190
+ );
191
+
192
+ expect(mockFetch).toHaveBeenCalledWith("https://example.com/media.mp4", {
193
+ headers: {
194
+ "Content-Type": "application/json",
195
+ authorization: `Bearer ${token2}`,
196
+ },
197
+ });
198
+ }, 1000);
199
+
200
+ test("should handle different URLs with separate token expiry", async () => {
201
+ const url1 = "https://example.com/media1.mp4";
202
+ const url2 = "https://example.com/media2.mp4";
203
+
204
+ const startTime = Date.now();
205
+
206
+ // URL1 gets a 30-minute token (10% buffer = 3 min, so expires at 27 min)
207
+ const url1IssuedAt = startTime;
208
+ const url1ExpiresAt = startTime + 30 * 60 * 1000; // 30 minutes
209
+ const token1 = createJWTToken(url1ExpiresAt, url1IssuedAt);
210
+
211
+ mockFetch.mockResolvedValueOnce({
212
+ ok: true,
213
+ json: () => Promise.resolve({ token: token1 }),
214
+ });
215
+ mockFetch.mockResolvedValueOnce({
216
+ ok: true,
217
+ text: () => Promise.resolve("success1"),
218
+ });
219
+
220
+ await element.fetch(url1);
221
+
222
+ // Advance time by 15 minutes
223
+ vi.advanceTimersByTime(15 * 60 * 1000);
224
+
225
+ // URL2 gets a 60-minute token (5 min buffer is smaller than 10% = 6 min, so expires at 55 min)
226
+ const url2IssuedAt = Date.now();
227
+ const url2ExpiresAt = url2IssuedAt + 60 * 60 * 1000; // 60 minutes from current time
228
+ const token2 = createJWTToken(url2ExpiresAt, url2IssuedAt);
229
+
230
+ mockFetch.mockResolvedValueOnce({
231
+ ok: true,
232
+ json: () => Promise.resolve({ token: token2 }),
233
+ });
234
+ mockFetch.mockResolvedValueOnce({
235
+ ok: true,
236
+ text: () => Promise.resolve("success2"),
237
+ });
238
+
239
+ await element.fetch(url2);
240
+
241
+ // Advance time by another 15 minutes (total 30 min from start)
242
+ // URL1 token: 30 min from start, past its 27-min threshold → expired
243
+ // URL2 token: 15 min from its creation, well within its 55-min threshold → still valid
244
+ vi.advanceTimersByTime(15 * 60 * 1000);
245
+
246
+ // Request URL1 again (should get new token - expired)
247
+ const url1NewExpiry = Date.now() + 60 * 60 * 1000;
248
+ const token3 = createJWTToken(url1NewExpiry);
249
+
250
+ mockFetch.mockResolvedValueOnce({
251
+ ok: true,
252
+ json: () => Promise.resolve({ token: token3 }),
253
+ });
254
+ mockFetch.mockResolvedValueOnce({
255
+ ok: true,
256
+ text: () => Promise.resolve("success3"),
257
+ });
258
+
259
+ await element.fetch(url1);
260
+
261
+ // Request URL2 again (should reuse token - still valid)
262
+ mockFetch.mockResolvedValueOnce({
263
+ ok: true,
264
+ text: () => Promise.resolve("success4"),
265
+ });
266
+
267
+ await element.fetch(url2);
268
+
269
+ expect(mockFetch).toHaveBeenCalledTimes(7); // 3 signing + 4 media requests (URL2 reused token)
270
+ }, 1000);
271
+
272
+ test("should clear token cache on component disconnect", async () => {
273
+ const futureTime = Date.now() + 60 * 60 * 1000; // 1 hour from now
274
+ const token1 = createJWTToken(futureTime);
275
+
276
+ mockFetch.mockResolvedValueOnce({
277
+ ok: true,
278
+ json: () => Promise.resolve({ token: token1 }),
279
+ });
280
+
281
+ mockFetch.mockResolvedValueOnce({
282
+ ok: true,
283
+ text: () => Promise.resolve("success"),
284
+ });
285
+
286
+ await element.fetch("https://example.com/media.mp4");
287
+
288
+ if (element.parentNode) {
289
+ document.body.removeChild(element);
290
+ }
291
+
292
+ // Create new element and add back to DOM
293
+ element = document.createElement("test-context") as TestContext & {
294
+ fetch: typeof fetch;
295
+ };
296
+ element.signingURL = "https://test.com/api/v1/url-token";
297
+ document.body.appendChild(element);
298
+
299
+ const token2 = createJWTToken(futureTime);
300
+
301
+ mockFetch.mockResolvedValueOnce({
302
+ ok: true,
303
+ json: () => Promise.resolve({ token: token2 }),
304
+ });
305
+
306
+ mockFetch.mockResolvedValueOnce({
307
+ ok: true,
308
+ text: () => Promise.resolve("success2"),
309
+ });
310
+
311
+ await element.fetch("https://example.com/media.mp4");
312
+
313
+ expect(mockFetch).toHaveBeenCalledTimes(4); // 2 signing + 2 media requests
314
+ }, 1000);
315
+
316
+ test("should use single token for multiple transcode segments with same source URL", async () => {
317
+ const futureTime = Date.now() + 60 * 60 * 1000;
318
+ const token = createJWTToken(futureTime);
319
+
320
+ const sourceUrl = "https://example.com/source-video.mp4";
321
+ const segment1 = `https://editframe.dev/api/v1/transcode/video-1080p/1.mp4?url=${encodeURIComponent(sourceUrl)}`;
322
+ const segment2 = `https://editframe.dev/api/v1/transcode/video-1080p/2.mp4?url=${encodeURIComponent(sourceUrl)}`;
323
+ const segment3 = `https://editframe.dev/api/v1/transcode/audio-44100/1.m4a?url=${encodeURIComponent(sourceUrl)}`;
324
+
325
+ // Should only sign once for the base URL + params combination
326
+ mockFetch.mockResolvedValueOnce({
327
+ ok: true,
328
+ json: () => Promise.resolve({ token }),
329
+ });
330
+
331
+ // Mock all segment requests
332
+ mockFetch.mockResolvedValueOnce({
333
+ ok: true,
334
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(1024)),
335
+ });
336
+ mockFetch.mockResolvedValueOnce({
337
+ ok: true,
338
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(1024)),
339
+ });
340
+ mockFetch.mockResolvedValueOnce({
341
+ ok: true,
342
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(1024)),
343
+ });
344
+
345
+ // Fetch multiple segments
346
+ await element.fetch(segment1);
347
+ await element.fetch(segment2);
348
+ await element.fetch(segment3);
349
+
350
+ // Should only call signing URL once + 3 segment requests
351
+ expect(mockFetch).toHaveBeenCalledTimes(4);
352
+
353
+ // Verify the signing request used base URL + params format
354
+ expect(mockFetch).toHaveBeenCalledWith(
355
+ "https://test.com/api/v1/url-token",
356
+ {
357
+ method: "POST",
358
+ body: JSON.stringify({
359
+ url: "https://editframe.dev/api/v1/transcode",
360
+ params: { url: sourceUrl },
361
+ }),
362
+ },
363
+ );
364
+
365
+ // All segment requests should use the same token
366
+ expect(mockFetch).toHaveBeenCalledWith(segment1, {
367
+ headers: {
368
+ "Content-Type": "application/json",
369
+ authorization: `Bearer ${token}`,
370
+ },
371
+ });
372
+ expect(mockFetch).toHaveBeenCalledWith(segment2, {
373
+ headers: {
374
+ "Content-Type": "application/json",
375
+ authorization: `Bearer ${token}`,
376
+ },
377
+ });
378
+ expect(mockFetch).toHaveBeenCalledWith(segment3, {
379
+ headers: {
380
+ "Content-Type": "application/json",
381
+ authorization: `Bearer ${token}`,
382
+ },
383
+ });
384
+ }, 1000);
385
+
386
+ test("should use different tokens for transcode segments with different source URLs", async () => {
387
+ const futureTime = Date.now() + 60 * 60 * 1000;
388
+ const token1 = createJWTToken(futureTime);
389
+ const token2 = createJWTToken(futureTime);
390
+
391
+ const sourceUrl1 = "https://example.com/video1.mp4";
392
+ const sourceUrl2 = "https://example.com/video2.mp4";
393
+
394
+ const segment1A = `https://editframe.dev/api/v1/transcode/video-1080p/1.mp4?url=${encodeURIComponent(sourceUrl1)}`;
395
+ const segment1B = `https://editframe.dev/api/v1/transcode/video-1080p/2.mp4?url=${encodeURIComponent(sourceUrl1)}`;
396
+ const segment2A = `https://editframe.dev/api/v1/transcode/video-720p/1.mp4?url=${encodeURIComponent(sourceUrl2)}`;
397
+
398
+ // First source URL token request
399
+ mockFetch.mockResolvedValueOnce({
400
+ ok: true,
401
+ json: () => Promise.resolve({ token: token1 }),
402
+ });
403
+
404
+ mockFetch.mockResolvedValueOnce({
405
+ ok: true,
406
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(1024)),
407
+ });
408
+ mockFetch.mockResolvedValueOnce({
409
+ ok: true,
410
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(1024)),
411
+ });
412
+
413
+ // Fetch segments for first source
414
+ await element.fetch(segment1A);
415
+ await element.fetch(segment1B);
416
+
417
+ // Second source URL token request
418
+ mockFetch.mockResolvedValueOnce({
419
+ ok: true,
420
+ json: () => Promise.resolve({ token: token2 }),
421
+ });
422
+
423
+ mockFetch.mockResolvedValueOnce({
424
+ ok: true,
425
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(1024)),
426
+ });
427
+
428
+ // Fetch segment for second source
429
+ await element.fetch(segment2A);
430
+
431
+ // Should call signing URL twice + 3 segment requests
432
+ expect(mockFetch).toHaveBeenCalledTimes(5);
433
+
434
+ // Verify separate signing requests
435
+ expect(mockFetch).toHaveBeenCalledWith(
436
+ "https://test.com/api/v1/url-token",
437
+ {
438
+ method: "POST",
439
+ body: JSON.stringify({
440
+ url: "https://editframe.dev/api/v1/transcode",
441
+ params: { url: sourceUrl1 },
442
+ }),
443
+ },
444
+ );
445
+ expect(mockFetch).toHaveBeenCalledWith(
446
+ "https://test.com/api/v1/url-token",
447
+ {
448
+ method: "POST",
449
+ body: JSON.stringify({
450
+ url: "https://editframe.dev/api/v1/transcode",
451
+ params: { url: sourceUrl2 },
452
+ }),
453
+ },
454
+ );
455
+ }, 1000);
456
+
457
+ test("should still sign individual URLs for non-transcode endpoints", async () => {
458
+ const futureTime = Date.now() + 60 * 60 * 1000;
459
+ const token1 = createJWTToken(futureTime);
460
+ const token2 = createJWTToken(futureTime);
461
+
462
+ const regularUrl1 = "https://example.com/api/v1/media/123";
463
+ const regularUrl2 = "https://example.com/api/v1/assets/456";
464
+
465
+ // First URL signing
466
+ mockFetch.mockResolvedValueOnce({
467
+ ok: true,
468
+ json: () => Promise.resolve({ token: token1 }),
469
+ });
470
+ mockFetch.mockResolvedValueOnce({
471
+ ok: true,
472
+ text: () => Promise.resolve("success1"),
473
+ });
474
+
475
+ // Second URL signing
476
+ mockFetch.mockResolvedValueOnce({
477
+ ok: true,
478
+ json: () => Promise.resolve({ token: token2 }),
479
+ });
480
+ mockFetch.mockResolvedValueOnce({
481
+ ok: true,
482
+ text: () => Promise.resolve("success2"),
483
+ });
484
+
485
+ await element.fetch(regularUrl1);
486
+ await element.fetch(regularUrl2);
487
+
488
+ expect(mockFetch).toHaveBeenCalledTimes(4); // 2 signing + 2 requests
489
+
490
+ // Should sign each URL individually (existing behavior)
491
+ expect(mockFetch).toHaveBeenCalledWith(
492
+ "https://test.com/api/v1/url-token",
493
+ {
494
+ method: "POST",
495
+ body: JSON.stringify({ url: regularUrl1 }),
496
+ },
497
+ );
498
+ expect(mockFetch).toHaveBeenCalledWith(
499
+ "https://test.com/api/v1/url-token",
500
+ {
501
+ method: "POST",
502
+ body: JSON.stringify({ url: regularUrl2 }),
503
+ },
504
+ );
505
+ }, 1000);
506
+ });
507
+
24
508
  describe("Playback", () => {
25
509
  test("should start playback", () => {
26
510
  const element = document.createElement("test-context");
@@ -73,4 +557,87 @@ describe("ContextMixin", () => {
73
557
  const event = await timeupdatePromise;
74
558
  expect(event.detail.currentTimeMs).toBe(1000);
75
559
  });
560
+
561
+ describe("Reactivity", () => {
562
+ test("should update durationMs when child tree changes", async () => {
563
+ const element = document.createElement("test-context-reactivity");
564
+ document.body.appendChild(element);
565
+
566
+ // Wait for initial render
567
+ await element.updateComplete;
568
+
569
+ // Create a timegroup with initial duration
570
+ const timegroup = document.createElement("ef-timegroup");
571
+ timegroup.mode = "contain";
572
+
573
+ const child = document.createElement("ef-timegroup");
574
+ child.mode = "fixed";
575
+ child.duration = "5s";
576
+ timegroup.appendChild(child);
577
+
578
+ element.appendChild(timegroup);
579
+
580
+ // Wait for updates
581
+ await element.updateComplete;
582
+ await timegroup.updateComplete;
583
+
584
+ // Initially, the timegroup should have 5s duration
585
+ expect(element.targetTimegroup?.durationMs).toBe(5000);
586
+
587
+ // Now change the child duration
588
+ child.duration = "10s";
589
+
590
+ // Wait for updates
591
+ await element.updateComplete;
592
+ await timegroup.updateComplete;
593
+
594
+ // The targetTimegroup should now have 10s duration
595
+ expect(element.targetTimegroup?.durationMs).toBe(10000);
596
+
597
+ document.body.removeChild(element);
598
+ });
599
+
600
+ test("should update when media elements are added/removed", async () => {
601
+ const element = document.createElement("test-context-reactivity");
602
+ document.body.appendChild(element);
603
+
604
+ await element.updateComplete;
605
+
606
+ // Create initial timegroup with 5s duration
607
+ const timegroup = document.createElement("ef-timegroup");
608
+ timegroup.mode = "contain";
609
+
610
+ const child = document.createElement("ef-timegroup");
611
+ child.mode = "fixed";
612
+ child.duration = "5s";
613
+ timegroup.appendChild(child);
614
+
615
+ element.appendChild(timegroup);
616
+
617
+ await element.updateComplete;
618
+ await timegroup.updateComplete;
619
+
620
+ // Initially duration should be 5s
621
+ expect(element.targetTimegroup?.durationMs).toBe(5000);
622
+
623
+ // Add a new child with longer duration
624
+ const newChild = document.createElement("ef-timegroup");
625
+ newChild.mode = "fixed";
626
+ newChild.duration = "15s";
627
+ timegroup.appendChild(newChild);
628
+
629
+ // Wait for updates
630
+ await element.updateComplete;
631
+ await timegroup.updateComplete;
632
+ await newChild.updateComplete;
633
+
634
+ // Wait for next animation frame to ensure temporal cache is cleared
635
+ await new Promise((resolve) => requestAnimationFrame(resolve));
636
+
637
+ // Duration should now be 15s (the max of all children)
638
+ expect(element.targetTimegroup?.durationMs).toBe(15000);
639
+
640
+ document.body.removeChild(element);
641
+ });
642
+ });
76
643
  });
@@ -71,6 +71,17 @@ export function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {
71
71
  @state()
72
72
  targetTimegroup: EFTimegroup | null = null;
73
73
 
74
+ // Add reactive properties that depend on the targetTimegroup
75
+ @state()
76
+ get durationMs(): number {
77
+ return this.targetTimegroup?.durationMs ?? 0;
78
+ }
79
+
80
+ @state()
81
+ get endTimeMs(): number {
82
+ return this.targetTimegroup?.endTimeMs ?? 0;
83
+ }
84
+
74
85
  @provide({ context: fetchContext })
75
86
  fetch = async (url: string, init: RequestInit = {}) => {
76
87
  init.headers ||= {};
@@ -79,13 +90,23 @@ export function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {
79
90
  });
80
91
 
81
92
  if (this.signingURL) {
82
- if (!this.#URLTokens[url]) {
83
- this.#URLTokens[url] = fetch(this.signingURL, {
93
+ const now = Date.now();
94
+ const { cacheKey, signingPayload } = this.#getTokenCacheKey(url);
95
+ const tokenExpiration = this.#URLTokenExpirations[cacheKey] || 0;
96
+
97
+ // Check if we need to fetch a new token (no token exists or token is expired)
98
+ if (!this.#URLTokens[cacheKey] || now >= tokenExpiration) {
99
+ this.#URLTokens[cacheKey] = fetch(this.signingURL, {
84
100
  method: "POST",
85
- body: JSON.stringify({ url }),
101
+ body: JSON.stringify(signingPayload),
86
102
  }).then(async (response) => {
87
103
  if (response.ok) {
88
- return (await response.json()).token;
104
+ const tokenData = await response.json();
105
+ const token = tokenData.token;
106
+ // Parse and store the token's actual expiration time
107
+ this.#URLTokenExpirations[cacheKey] =
108
+ this.#parseTokenExpiration(token);
109
+ return token;
89
110
  }
90
111
  throw new Error(
91
112
  `Failed to sign URL: ${url}. SigningURL: ${this.signingURL} ${response.status} ${response.statusText}`,
@@ -93,7 +114,7 @@ export function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {
93
114
  });
94
115
  }
95
116
 
96
- const urlToken = await this.#URLTokens[url];
117
+ const urlToken = await this.#URLTokens[cacheKey];
97
118
 
98
119
  Object.assign(init.headers, {
99
120
  authorization: `Bearer ${urlToken}`,
@@ -106,6 +127,89 @@ export function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {
106
127
  };
107
128
 
108
129
  #URLTokens: Record<string, Promise<string>> = {};
130
+ #URLTokenExpirations: Record<string, number> = {};
131
+
132
+ /**
133
+ * Generate a cache key for URL token based on signing strategy
134
+ *
135
+ * Uses unified prefix + parameter matching approach:
136
+ * - For transcode URLs: signs base "/api/v1/transcode" + params like {url: "source.mp4"}
137
+ * - For regular URLs: signs full URL with empty params {}
138
+ * - All validation uses prefix matching + exhaustive parameter matching
139
+ * - Multiple transcode segments with same source share one token (reduces round-trips)
140
+ */
141
+ #getTokenCacheKey(url: string): {
142
+ cacheKey: string;
143
+ signingPayload: { url: string; params?: Record<string, string> };
144
+ } {
145
+ try {
146
+ const urlObj = new URL(url);
147
+
148
+ // Check if this is a transcode URL pattern
149
+ if (urlObj.pathname.includes("/api/v1/transcode/")) {
150
+ const urlParam = urlObj.searchParams.get("url");
151
+ if (urlParam) {
152
+ // For transcode URLs, sign the base path + url parameter
153
+ const basePath = `${urlObj.origin}/api/v1/transcode`;
154
+ const cacheKey = `${basePath}?url=${urlParam}`;
155
+ return {
156
+ cacheKey,
157
+ signingPayload: { url: basePath, params: { url: urlParam } },
158
+ };
159
+ }
160
+ }
161
+
162
+ // For non-transcode URLs, use full URL (existing behavior)
163
+ return {
164
+ cacheKey: url,
165
+ signingPayload: { url },
166
+ };
167
+ } catch {
168
+ // If URL parsing fails, fall back to full URL
169
+ return {
170
+ cacheKey: url,
171
+ signingPayload: { url },
172
+ };
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Parse JWT token to extract safe expiration time (with buffer)
178
+ * @param token JWT token string
179
+ * @returns Safe expiration timestamp in milliseconds (actual expiry minus buffer), or 0 if parsing fails
180
+ */
181
+ #parseTokenExpiration(token: string): number {
182
+ try {
183
+ // JWT has 3 parts separated by dots: header.payload.signature
184
+ const parts = token.split(".");
185
+ if (parts.length !== 3) return 0;
186
+
187
+ // Decode the payload (second part)
188
+ const payload = parts[1];
189
+ if (!payload) return 0;
190
+
191
+ const decoded = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
192
+ const parsed = JSON.parse(decoded);
193
+
194
+ // Extract timestamps (in seconds)
195
+ const exp = parsed.exp;
196
+ const iat = parsed.iat;
197
+ if (!exp) return 0;
198
+
199
+ // Calculate token lifetime and buffer
200
+ const lifetimeSeconds = iat ? exp - iat : 3600; // Default to 1 hour if no iat
201
+ const tenPercentBufferMs = lifetimeSeconds * 0.1 * 1000; // 10% of lifetime in ms
202
+ const fiveMinutesMs = 5 * 60 * 1000; // 5 minutes in ms
203
+
204
+ // Use whichever buffer is smaller (more conservative)
205
+ const bufferMs = Math.min(fiveMinutesMs, tenPercentBufferMs);
206
+
207
+ // Return expiration time minus buffer
208
+ return exp * 1000 - bufferMs;
209
+ } catch {
210
+ return 0;
211
+ }
212
+ }
109
213
 
110
214
  #signingURL?: string;
111
215
  /**
@@ -138,14 +242,47 @@ export function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {
138
242
  #MS_PER_FRAME = 1000 / this.#FPS;
139
243
 
140
244
  #timegroupObserver = new MutationObserver((mutations) => {
245
+ let shouldUpdate = false;
246
+
141
247
  for (const mutation of mutations) {
142
248
  if (mutation.type === "childList") {
143
249
  const newTimegroup = this.querySelector("ef-timegroup");
144
250
  if (newTimegroup !== this.targetTimegroup) {
145
251
  this.targetTimegroup = newTimegroup;
252
+ shouldUpdate = true;
253
+ } else if (
254
+ mutation.target instanceof Element &&
255
+ (mutation.target.tagName === "EF-TIMEGROUP" ||
256
+ mutation.target.closest("ef-timegroup"))
257
+ ) {
258
+ // Handle childList changes within existing timegroups
259
+ shouldUpdate = true;
260
+ }
261
+ } else if (mutation.type === "attributes") {
262
+ // Watch for attribute changes that might affect duration
263
+ if (
264
+ mutation.attributeName === "duration" ||
265
+ mutation.attributeName === "mode" ||
266
+ (mutation.target instanceof Element &&
267
+ (mutation.target.tagName === "EF-TIMEGROUP" ||
268
+ mutation.target.closest("ef-timegroup")))
269
+ ) {
270
+ shouldUpdate = true;
146
271
  }
147
272
  }
148
273
  }
274
+
275
+ if (shouldUpdate) {
276
+ // Trigger an update to ensure reactive properties recalculate
277
+ // Use a microtask to ensure DOM updates are complete
278
+ queueMicrotask(() => {
279
+ this.requestUpdate();
280
+ // Also ensure the targetTimegroup updates its computed properties
281
+ if (this.targetTimegroup) {
282
+ this.targetTimegroup.requestUpdate();
283
+ }
284
+ });
285
+ }
149
286
  });
150
287
 
151
288
  connectedCallback(): void {
@@ -169,6 +306,9 @@ export function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {
169
306
  super.disconnectedCallback();
170
307
  this.#timegroupObserver.disconnect();
171
308
  this.stopPlayback();
309
+ // Clear token cache on disconnect to prevent stale tokens
310
+ this.#URLTokens = {};
311
+ this.#URLTokenExpirations = {};
172
312
  }
173
313
 
174
314
  update(changedProperties: Map<string | number | symbol, unknown>) {