@simba-dev/react-native-media-player 2.0.1 → 2.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 (34) hide show
  1. package/README.md +317 -560
  2. package/android/src/main/cpp/main.cpp +117 -17
  3. package/android/src/main/java/com/simba/player/PipManager.kt +13 -0
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +177 -6
  5. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  6. package/package.json +11 -2
  7. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  8. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  9. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  10. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  11. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  12. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewRegistryTest.kt +0 -120
  13. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  14. package/scripts/override_react_methods.js +0 -184
  15. package/scripts/override_react_methods.py +0 -150
  16. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -163
  17. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  18. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  19. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  20. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  21. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  22. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  23. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  24. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  25. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  26. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  27. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  28. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  29. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  30. package/src/types/__tests__/config.test.ts +0 -188
  31. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  32. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  33. package/src/types/__tests__/player.test.tsx +0 -1365
  34. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -1,184 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * V16.0.6 patch release (D-032 / B-010 proper fix):
4
- * MpvBridgeModule.kt must extend NativeMpvPlayerSpec. Every @ReactMethod-
5
- * annotated function is an override of the spec's abstract method, so we add
6
- * `@Override` (Kotlin annotation) on its own line and the `override` keyword
7
- * on the `fun` line.
8
- *
9
- * We also normalize a handful of signature mismatches:
10
- * - dumpObservedProperties(): Int → Double (spec returns double)
11
- * - openPlayer(..., title: String?, ...): Promise
12
- * → title: String (spec is non-null)
13
- * - enterPip(chapterTitle: String? = null, progressPct: String? = null)
14
- * → enterPip(chapterTitle: String, progressPct: String)
15
- * (spec is non-null, no defaults; defaults are dropped — the only
16
- * internal callers were JS via @ReactMethod)
17
- *
18
- * Methods NOT in the spec (addListener / removeListeners / startNotification
19
- * / updateNotification / stopNotification / initialize lifecycle / the
20
- * IMpvConfigProvider & IMpvNativePtrProvider & IPipModeChangeEmitter
21
- * implementations) are left untouched so they keep their RN-bridge / private
22
- * implementor semantics.
23
- *
24
- * The toggleMute() stub is added in a separate pass — the spec declares
25
- * `abstract void toggleMute();` but MpvBridgeModule.kt 1.5.5 doesn't have
26
- * the Kotlin override, so extending NativeMpvPlayerSpec would otherwise
27
- * fail to compile with the dreaded
28
- * "Class 'MpvBridgeModule' is not abstract and does not override abstract
29
- * member 'public abstract void toggleMute()'".
30
- */
31
- "use strict";
32
-
33
- const fs = require("fs");
34
- const path = require("path");
35
-
36
- const SRC_PATH = path.resolve(
37
- "X:/Development/SIMBA/react-native-media-player/android/src/main/java/" +
38
- "com/simba/player/mpv/MpvBridgeModule.kt"
39
- );
40
-
41
- // @ReactMethod-annotated methods on MpvBridgeModule that are NOT in the
42
- // NativeMpvPlayerSpec — we must NOT add `override` to them.
43
- const NON_SPEC_REACT_METHODS = new Set([
44
- "addListener", // RN NativeEventEmitter requirement
45
- "removeListeners", // RN NativeEventEmitter requirement
46
- "startNotification", // lib-private notification flow
47
- "updateNotification",// lib-private notification flow
48
- "stopNotification", // lib-private notification flow
49
- ]);
50
-
51
- // Exact signature normalizations to apply BEFORE the @Override pass so
52
- // capture groups line up with existing line breaks.
53
- const SIGNATURE_NORMALIZATIONS = [
54
- // 1. dumpObservedProperties(): Int -> Double (spec returns double)
55
- {
56
- name: "dumpObservedProperties-return-type",
57
- pattern: /( @ReactMethod\(isBlockingSynchronousMethod = true\)\r?\n fun dumpObservedProperties)\(\): Int \{/,
58
- replacement: "$1(): Double {",
59
- },
60
- // 2. openPlayer title: String? -> String
61
- {
62
- name: "openPlayer-title-type",
63
- pattern: /( fun openPlayer\(\r?\n uri: String,\r?\n) title: String\?,\r?\n/,
64
- replacement: "$1 title: String,\r\n",
65
- },
66
- // 2b. openPlayer body — title?.takeIf { ... } -> title.takeIf { ... }
67
- {
68
- name: "openPlayer-body-takeif",
69
- pattern: / val resolvedTitle = title\?\.takeIf \{ it\.isNotBlank\(\) \} \?: uri/,
70
- replacement: " val resolvedTitle = title.takeIf { it.isNotBlank() } ?: uri",
71
- },
72
- // 3. enterPip — v1.9.3: THE NORMALIZATION IS GONE.
73
- //
74
- // It used to rewrite
75
- // fun enterPip(chapterTitle: String? = null, progressPct: String? = null)
76
- // into
77
- // fun enterPip(chapterTitle: String, progressPct: String)
78
- // on the stated grounds that "the spec is non-null, no defaults".
79
- //
80
- // That was the cause of a hard crash, not a compatibility fix.
81
- // TurboModule enforces the KOTLIN arity, and the TypeScript contract
82
- // has always declared both params optional, so `enterPip()` from JS
83
- // was rejected before it reached the method body:
84
- //
85
- // Exception in HostFunction: TurboModule method "enterPip"
86
- // called with 0 arguments (expected argument count: 2)
87
- //
88
- // The nullability is now KEPT (that is what codegen produces from
89
- // `MpvPlayerModule.ts`), which makes both zero-arg and two-arg calls
90
- // legal. This rule used to throw if it matched zero times, so it
91
- // could not simply be left in place: re-running this script would
92
- // have failed the build with a confusing "did not match exactly once"
93
- // rather than silently reverting the fix. Kept here as an
94
- // assertion instead, so a re-run PROVES the signature is still the
95
- // fixed one and fails loudly if someone reintroduces the bug.
96
- {
97
- name: "enterPip-signature-guard",
98
- pattern: / override fun enterPip\(chapterTitle: String\?, progressPct: String\?\) \{/,
99
- replacement: " override fun enterPip(chapterTitle: String?, progressPct: String?) {",
100
- },
101
- ];
102
-
103
- const REACT_METHOD_LINE = /^( )(@ReactMethod(?:\([^)]*\))?)\s*$/;
104
- const FUN_LINE = /^( )fun ([A-Za-z_][A-Za-z0-9_]*)(\(.*)$/;
105
-
106
- function applySignatureNormalizations(src) {
107
- for (const norm of SIGNATURE_NORMALIZATIONS) {
108
- // Count non-overlapping matches via the `g` + `exec` loop (reliable even
109
- // when the regex has capture groups — `String.prototype.split` would
110
- // inflate its count by the number of captures).
111
- const re = new RegExp(norm.pattern.source, "g");
112
- let count = 0;
113
- let m;
114
- while ((m = re.exec(src)) !== null) {
115
- count++;
116
- // Guard against zero-length matches to avoid infinite loop in pathological cases.
117
- if (m[0].length === 0) re.lastIndex++;
118
- }
119
- if (count !== 1) {
120
- throw new Error(
121
- `signature normalization '${norm.name}' did not match exactly once (matched ${count} times)`
122
- );
123
- }
124
- // Now apply the actual replacement (preserve the original flags / backref semantics).
125
- const reNoG = new RegExp(norm.pattern.source, norm.pattern.flags);
126
- src = src.replace(reNoG, norm.replacement);
127
- console.log(` [signature] ${norm.name}: matched ${count}x`);
128
- }
129
- return src;
130
- }
131
-
132
- function addOverrideAnnoAndKeyword(src) {
133
- const lines = src.split(/\r?\n/);
134
- const out = [];
135
- let i = 0;
136
- while (i < lines.length) {
137
- const line = lines[i];
138
- const mAnno = line.match(REACT_METHOD_LINE);
139
- if (mAnno && i + 1 < lines.length) {
140
- const nextLine = lines[i + 1];
141
- const mFun = nextLine.match(FUN_LINE);
142
- if (mFun) {
143
- const name = mFun[2];
144
- if (NON_SPEC_REACT_METHODS.has(name)) {
145
- out.push(line);
146
- out.push(nextLine);
147
- i += 2;
148
- continue;
149
- }
150
- const indent = mAnno[1];
151
- out.push(line);
152
- out.push(`${indent}@Override`);
153
- out.push(`${indent}override fun ${name}${mFun[3]}`);
154
- i += 2;
155
- continue;
156
- }
157
- }
158
- out.push(line);
159
- i += 1;
160
- }
161
- return out.join("\n");
162
- }
163
-
164
- function main() {
165
- let src = fs.readFileSync(SRC_PATH, { encoding: "utf-8" });
166
- // Normalize CRLF -> LF for consistent regex matching. We write LF-only
167
- // back to keep diffs clean (the rest of the file uses LF exclusively
168
- // when checked out via git; the actual byte stream from the edit tool
169
- // happens to also be LF).
170
- src = src.replace(/\r\n/g, "\n");
171
- src = applySignatureNormalizations(src);
172
- src = addOverrideAnnoAndKeyword(src);
173
- fs.writeFileSync(SRC_PATH, src, { encoding: "utf-8" });
174
-
175
- const overrideCount = (src.match(/^ @Override$/mg) || []).length;
176
- const reactMethodCount = (src.match(/^ @ReactMethod/gm) || []).length;
177
- console.log(`Total @ReactMethod blocks: ${reactMethodCount}`);
178
- console.log(`Added @Override annotations: ${overrideCount}`);
179
- console.log(
180
- `Expected: ~${reactMethodCount - NON_SPEC_REACT_METHODS.size} @Override on spec overrides`
181
- );
182
- }
183
-
184
- main();
@@ -1,150 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- V16.0.6 patch release (D-032 / B-010 proper fix):
4
- MpvBridgeModule.kt must extend NativeMpvPlayerSpec. Every @ReactMethod-
5
- annotated function is an override of the spec's abstract method, so we add
6
- `@Override` (Kotlin annotation) on its own line and the `override` keyword
7
- on the `fun` line.
8
-
9
- We also normalize a handful of signature mismatches:
10
- - dumpObservedProperties(): Int → Double (spec returns `double`)
11
- - openPlayer(..., title: String?, ...): Promise
12
- → title: String (spec is non-null)
13
- - enterPip(chapterTitle: String? = null, progressPct: String? = null)
14
- → enterPip(chapterTitle: String, progressPct: String)
15
- (spec is non-null, no defaults; defaults are dropped — the only
16
- internal callers were JS via @ReactMethod)
17
-
18
- Methods NOT in the spec (addListener / removeListeners / startNotification
19
- / updateNotification / stopNotification / initialize lifecycle / the
20
- IMpvConfigProvider & IMpvNativePtrProvider & IPipModeChangeEmitter
21
- implementations) are left untouched so they keep their RN-bridge / private
22
- implementor semantics.
23
-
24
- The toggleMute() stub is added in a separate pass — the spec declares
25
- `abstract void toggleMute();` but MpvBridgeModule.kt 1.5.5 doesn't have
26
- the Kotlin override, so extending NativeMpvPlayerSpec would otherwise
27
- fail to compile with the dreaded
28
- "Class 'MpvBridgeModule' is not abstract and does not override abstract
29
- member 'public abstract void toggleMute()'".
30
- """
31
- import io
32
- import re
33
- import sys
34
-
35
- SRC_PATH = (
36
- "X:/Development/SIMBA/react-native-media-player/android/src/main/java/"
37
- "com/simba/player/mpv/MpvBridgeModule.kt"
38
- )
39
-
40
- # Methods on MpvBridgeModule that have @ReactMethod but are NOT in the
41
- # NativeMpvPlayerSpec (we shouldn't add `override` to them — adding
42
- # `override` would be a Kotlin compiler error since the spec doesn't
43
- # declare them as abstract overrides, and they aren't overrides of
44
- # ReactContextBaseJavaModule either; they're just additional @ReactMethod
45
- # surfaces RN will register).
46
- NON_SPEC_REACT_METHODS = {
47
- "addListener", # RN NativeEventEmitter requirement (line ~1179)
48
- "removeListeners", # RN NativeEventEmitter requirement (line ~1185)
49
- "startNotification", # lib-private notification flow (line ~1508)
50
- "updateNotification",# lib-private notification flow (line ~1541)
51
- "stopNotification", # lib-private notification flow (line ~1570)
52
- }
53
-
54
- # Methods whose signatures must be normalized to match the spec.
55
- # Format: method_name -> (new_return_annotation_or_None, regex_pattern, replacement)
56
- SIGNATURE_NORMALIZATIONS = [
57
- # 1. dumpObservedProperties(): Int -> Double (spec returns double)
58
- (
59
- "dumpObservedProperties",
60
- r"( @ReactMethod\(isBlockingSynchronousMethod = true\)\n)"
61
- r"( fun dumpObservedProperties)\(\): Int \{",
62
- r"\1\2(): Double {",
63
- ),
64
- # 2. openPlayer title: String? -> String
65
- (
66
- "openPlayer",
67
- r"( fun openPlayer\(\n uri: String,\n)"
68
- r" title: String\?,\n",
69
- r"\1 title: String,\n",
70
- ),
71
- # 2b. openPlayer body — title?.takeIf { ... } -> title.takeIf { ... }
72
- (
73
- "openPlayer-body",
74
- r" val resolvedTitle = title\?\.takeIf \{ it\.isNotBlank\(\) \} \?: uri",
75
- " val resolvedTitle = title.takeIf { it.isNotBlank() } ?: uri",
76
- ),
77
- # 3. enterPip: drop nullable types + defaults
78
- (
79
- "enterPip",
80
- r" fun enterPip\(chapterTitle: String\? = null, progressPct: String\? = null\) \{",
81
- " fun enterPip(chapterTitle: String, progressPct: String) {",
82
- ),
83
- ]
84
-
85
-
86
- def main() -> int:
87
- with open(SRC_PATH, "r", encoding="utf-8") as f:
88
- src = f.read()
89
-
90
- # Step 1 — apply signature normalizations BEFORE adding @Override so the
91
- # capture groups line up cleanly with the existing lines.
92
- for name, pattern, replacement in SIGNATURE_NORMALIZATIONS:
93
- new_src, n = re.subn(pattern, replacement, src, count=1)
94
- if n != 1:
95
- print(f"ERROR: signature normalization '{name}' did not match exactly once (matched {n} times)", file=sys.stderr)
96
- return 2
97
- print(f" [signature] {name}: matched {n}x")
98
- src = new_src
99
-
100
- # Step 2 — convert each @ReactMethod fun <name>... block to add
101
- # `@Override` annotation and `override` keyword. We do this line by
102
- # line so the regex pattern is unambiguous.
103
- lines = io.StringIO(src).readlines()
104
- out: list[str] = []
105
- i = 0
106
- while i < len(lines):
107
- line = lines[i]
108
- # Match `@ReactMethod` (with optional params) on its own indented line,
109
- # followed by an indented `fun <ident>(...) ... {` line.
110
- m_anno = re.match(r"^( )(@ReactMethod(?:\([^)]*\))?)\s*$", line)
111
- if m_anno and i + 1 < len(lines):
112
- next_line = lines[i + 1]
113
- m_fun = re.match(
114
- r"^( )fun (?P<name>[A-Za-z_][A-Za-z0-9_]*)(?P<rest>\(.*)$",
115
- next_line,
116
- )
117
- if m_fun:
118
- name = m_fun.group("name")
119
- if name in NON_SPEC_REACT_METHODS:
120
- out.append(line)
121
- out.append(next_line)
122
- i += 2
123
- continue
124
- indent = m_anno.group(1)
125
- # Add @Override on its own line. Use the same indent.
126
- out.append(line) # @ReactMethod(...)
127
- out.append(f"{indent}@Override\n") # @Override
128
- out.append(f"{indent}override fun {name}{m_fun.group('rest')}\n") # override fun ...
129
- i += 2
130
- continue
131
- out.append(line)
132
- i += 1
133
-
134
- new_src = "".join(out)
135
-
136
- # Write back
137
- with open(SRC_PATH, "w", encoding="utf-8") as f:
138
- f.write(new_src)
139
-
140
- # Quick sanity: count the @Override we added
141
- override_count = new_src.count(" @Override\n")
142
- react_method_count = len(re.findall(r"^ @ReactMethod", new_src, flags=re.MULTILINE))
143
- print(f"Total @ReactMethod blocks: {react_method_count}")
144
- print(f"Added @Override annotations: {override_count}")
145
- print(f"Expected: ~{react_method_count - len(NON_SPEC_REACT_METHODS)} @Override on spec overrides")
146
- return 0
147
-
148
-
149
- if __name__ == "__main__":
150
- sys.exit(main())
@@ -1,163 +0,0 @@
1
- /**
2
- * Unit tests for `src/bridge/MpvPlayerModule.ts`.
3
- *
4
- * Spec §Phase 34 doesn't have an explicit bullet for bridge tests,
5
- * but they're foundational — every hook/component ultimately routes
6
- * through `getMpvPlayerModule()` so we need to verify the typed
7
- * wrapper's contract.
8
- *
9
- * Test surface:
10
- * - `getMpvPlayerModule()` returns the underlying module when
11
- * `NativeModules.MpvPlayerModule` is defined
12
- * - The returned object exposes every documented method (typed
13
- * `MpvPlayerModuleBridge` interface)
14
- * - Each method delegates to the same name on the underlying
15
- * NativeModule
16
- *
17
- * What we DON'T test:
18
- * - The "no native module" path returns null. We can't easily
19
- * unmock the global mock in jest.setup.ts; the production code
20
- * path is `const native = NativeModules.MpvPlayerModule; return
21
- * native === undefined ? null : native;` — a pure lookup that
22
- * needs no test beyond its existence.
23
- */
24
-
25
- // The MpvPlayerModule bridge mock is installed globally in
26
- // `jest.setup.ts` (it extends the @react-native/jest-preset's own
27
- // `NativeModules` mock rather than overriding it). Every test file
28
- // in this module shares the same `NativeModules.MpvPlayerModule`
29
- // instance, so `mockClear()` in beforeEach is the way to reset
30
- // call counts between tests.
31
-
32
- import { NativeModules } from 'react-native';
33
- import {
34
- getMpvPlayerModule,
35
- type MpvPlayerModuleBridge,
36
- } from '../MpvPlayerModule';
37
-
38
- describe('getMpvPlayerModule', () => {
39
- beforeEach(() => {
40
- // The global mock is shared across all test files in this
41
- // module — clear call history between tests so .toHaveBeenCalledTimes
42
- // assertions are deterministic.
43
- for (const key of Object.keys(NativeModules.MpvPlayerModule)) {
44
- const fn = (NativeModules.MpvPlayerModule as Record<string, jest.Mock>)[key];
45
- if (typeof fn?.mockClear === 'function') {
46
- fn.mockClear();
47
- }
48
- }
49
- });
50
-
51
- it('returns a non-null typed bridge when NativeModules.MpvPlayerModule exists', () => {
52
- const bridge = getMpvPlayerModule();
53
- expect(bridge).not.toBeNull();
54
- expect(bridge).toBeDefined();
55
- });
56
-
57
- it('returns the underlying NativeModule reference (same instance)', () => {
58
- // The wrapper is a transparent pass-through — consumers can rely
59
- // on reference equality with `NativeModules.MpvPlayerModule` if
60
- // they need to. Phase 24 design.
61
- const bridge = getMpvPlayerModule();
62
- expect(bridge).toBe(NativeModules.MpvPlayerModule);
63
- });
64
-
65
- it('exposes every documented method on the typed bridge interface', () => {
66
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
67
- const expectedMethods = [
68
- 'play',
69
- 'pause',
70
- 'seekAbsolute',
71
- 'seekForward',
72
- 'seekBackward',
73
- 'playlistNext',
74
- 'playlistPrev',
75
- ];
76
- for (const method of expectedMethods) {
77
- expect(typeof bridge[method as keyof MpvPlayerModuleBridge]).toBe(
78
- 'function',
79
- );
80
- }
81
- });
82
-
83
- it('each method is callable and returns a thenable (Promise)', async () => {
84
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
85
- // All methods are documented as `Promise<void>`. We don't
86
- // exhaustively call them — just smoke-test the most common ones.
87
- await expect(bridge.play()).resolves.toBeUndefined();
88
- await expect(bridge.pause()).resolves.toBeUndefined();
89
- await expect(bridge.seekAbsolute(42)).resolves.toBeUndefined();
90
- await expect(bridge.seekForward(10)).resolves.toBeUndefined();
91
- await expect(bridge.seekBackward(10)).resolves.toBeUndefined();
92
- });
93
-
94
- it('play() forwards arguments through to the native module', async () => {
95
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
96
- (NativeModules.MpvPlayerModule.play as jest.Mock).mockClear();
97
- await bridge.play();
98
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalledTimes(1);
99
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalledWith();
100
- });
101
-
102
- it('seekAbsolute(seconds) forwards the position argument', async () => {
103
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
104
- (NativeModules.MpvPlayerModule.seekAbsolute as jest.Mock).mockClear();
105
- await bridge.seekAbsolute(123.456);
106
- expect(NativeModules.MpvPlayerModule.seekAbsolute).toHaveBeenCalledWith(
107
- 123.456,
108
- );
109
- });
110
-
111
- // ── The mock must not invent a surface ──────────────────────────────────
112
- //
113
- // This mock stands in for the NATIVE module. In jest there is never a
114
- // picture view — a picture view is a native View that only React
115
- // Native's ViewManager can create — so the honest answer to "is a surface
116
- // mounted?" is `false`, and every surface mutator must refuse.
117
- //
118
- // The mock used to answer `true` for all four. The native implementation
119
- // could only ever answer `false`, so the suite was green exactly where
120
- // the product was broken, and the defect it hid was real: a deep-linked
121
- // video never played, because `commands.openPlayer(...)` refused it.
122
- //
123
- // A mock that returns the happy answer for a method that can only fail
124
- // does not test the method — it erases the defect.
125
- describe('the installed native mock does not invent a surface', () => {
126
- it('answers false to isSurfaceMounted', () => {
127
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
128
- expect(bridge.isSurfaceMounted()).toBe(false);
129
- });
130
-
131
- it('has every surface mutator refuse', async () => {
132
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
133
- await expect(bridge.setVideoBounds(0, 0, 10, 10)).resolves.toBe(false);
134
- await expect(bridge.fillVideoBounds()).resolves.toBe(false);
135
- await expect(bridge.setSurfaceVisible(true)).resolves.toBe(false);
136
- });
137
-
138
- it('agrees with the module own NOOP fallback on every surface call', async () => {
139
- // The NOOP fallback is the module's own answer for "there is no
140
- // native module at all" — and it is the same environment jest
141
- // simulates. The installed mock must not disagree with it: a mock
142
- // that says `true` where the fallback says `false` is the same
143
- // defect wearing a different hat.
144
- //
145
- // The fallback is reached by removing the native module, exactly as
146
- // `player.test.tsx` does; it is put back afterwards so the shared
147
- // global mock is intact for the next test.
148
- const native = NativeModules.MpvPlayerModule;
149
- (NativeModules as {MpvPlayerModule?: unknown}).MpvPlayerModule =
150
- undefined;
151
- try {
152
- const noop = getMpvPlayerModule();
153
- expect(noop.isSurfaceMounted()).toBe(false);
154
- await expect(noop.setVideoBounds(0, 0, 10, 10)).resolves.toBe(false);
155
- await expect(noop.fillVideoBounds()).resolves.toBe(false);
156
- await expect(noop.setSurfaceVisible(true)).resolves.toBe(false);
157
- } finally {
158
- (NativeModules as {MpvPlayerModule?: unknown}).MpvPlayerModule =
159
- native;
160
- }
161
- });
162
- });
163
- });
@@ -1,138 +0,0 @@
1
- /**
2
- * Tests for the Phase 39 debug-mode API.
3
- *
4
- * Spec §39 — Logging & debug mode.
5
- *
6
- * Covers:
7
- * - `setDebugLogging(true/false)` toggles verbose logging
8
- * - `dumpObservedProperties()` returns the count
9
- * - The module-scoped `_debugLoggingEnabled` flag gates `dlog`
10
- * - `__DEV__` conditional behaviour (only logs in debug builds)
11
- * - The no-op fallback in jest (no native module) doesn't throw
12
- */
13
-
14
- import {
15
- getMpvPlayerModule,
16
- setDebugLogging,
17
- dumpObservedProperties,
18
- dlog,
19
- } from '../MpvPlayerModule';
20
-
21
- describe('Phase 39 — debug mode API', () => {
22
- beforeEach(() => {
23
- // Reset debug flag between tests
24
- setDebugLogging(false);
25
- });
26
-
27
- afterAll(() => {
28
- setDebugLogging(false);
29
- });
30
-
31
- it('setDebugLogging(true) toggles the module-scoped flag', () => {
32
- const result = setDebugLogging(true);
33
- expect(result).toBe(true);
34
- });
35
-
36
- it('setDebugLogging(false) toggles back off', () => {
37
- setDebugLogging(true);
38
- const result = setDebugLogging(false);
39
- expect(result).toBe(false);
40
- });
41
-
42
- it('setDebugLogging is idempotent', () => {
43
- setDebugLogging(true);
44
- setDebugLogging(true);
45
- const result = setDebugLogging(false);
46
- expect(result).toBe(false);
47
- });
48
-
49
- it('setDebugLogging forwards to the bridge (via getMpvPlayerModule)', () => {
50
- const bridge = getMpvPlayerModule();
51
- // The bridge exposes setDebugLogging as a function (when the
52
- // mock provides it; see jest.setup.ts)
53
- const bridgeAny = bridge as unknown as Record<string, unknown>;
54
- if (typeof bridgeAny.setDebugLogging === 'function') {
55
- // Live bridge: verify the typed wrapper exposes it
56
- expect(typeof bridge.setDebugLogging).toBe('function');
57
- }
58
- // setDebugLogging must not throw regardless of whether the
59
- // underlying bridge method exists (it catches + logs via dlog)
60
- expect(() => setDebugLogging(true)).not.toThrow();
61
- });
62
-
63
- it('dumpObservedProperties returns a number', () => {
64
- const count = dumpObservedProperties();
65
- expect(typeof count).toBe('number');
66
- expect(count).toBeGreaterThanOrEqual(0);
67
- });
68
-
69
- it('dlog is a no-op when debug logging is off', () => {
70
- setDebugLogging(false);
71
- const originalLog = console.log;
72
- let logCalls = 0;
73
- console.log = () => {
74
- logCalls++;
75
- };
76
- try {
77
- dlog('test message');
78
- expect(logCalls).toBe(0);
79
- } finally {
80
- console.log = originalLog;
81
- }
82
- });
83
-
84
- it('dlog is a no-op when __DEV__ is false (even if flag is true)', () => {
85
- // The `IS_DEV` flag is set at module load time based on
86
- // `typeof __DEV__`. In jest test runs, `__DEV__` is typically
87
- // undefined or false. Verify dlog respects this by NOT calling
88
- // console.log even when the user-facing flag is true.
89
- //
90
- // Note: this test is robust to both `__DEV__ === true` (debug
91
- // build) and `__DEV__ === undefined/false` (release) — it only
92
- // verifies that the count doesn't INCREASE from before to
93
- // after.
94
- setDebugLogging(true);
95
- const originalLog = console.log;
96
- let logCallsBefore = 0;
97
- console.log = () => {
98
- logCallsBefore++;
99
- };
100
- // The act of setting the flag may itself log via getMpvPlayerModule.
101
- // To get a stable measurement, we set a known count first.
102
- console.log = originalLog;
103
- logCallsBefore = 0;
104
- console.log = () => {
105
- logCallsBefore++;
106
- };
107
- // Trigger 5 dlog calls
108
- dlog('1');
109
- dlog('2');
110
- dlog('3');
111
- dlog('4');
112
- dlog('5');
113
- const calls = logCallsBefore;
114
- console.log = originalLog;
115
- // In jest, __DEV__ is typically false (the production build path),
116
- // so all 5 dlog calls should be no-ops. If __DEV__ is true (debug
117
- // build), all 5 would log — also acceptable.
118
- expect(calls === 0 || calls === 5).toBe(true);
119
- });
120
-
121
- it('no-op fallback setDebugLogging does not throw', () => {
122
- // When the native module is absent (jest), setDebugLogging
123
- // must not throw even though the no-op fallback is used.
124
- expect(() => setDebugLogging(true)).not.toThrow();
125
- expect(() => setDebugLogging(false)).not.toThrow();
126
- });
127
-
128
- it('no-op fallback dumpObservedProperties returns 0', () => {
129
- // When the native module is absent, dumpObservedProperties
130
- // returns 0 (the no-op fallback's default return value).
131
- // Note: this only holds if the test runs without the mock
132
- // native module — in our setup, the jest.setup.ts installs a
133
- // mock, so dumpObservedProperties delegates to it. Either way,
134
- // the function returns a non-negative number.
135
- const count = dumpObservedProperties();
136
- expect(count).toBeGreaterThanOrEqual(0);
137
- });
138
- });