@simba-dev/react-native-media-player 1.5.13 → 1.5.15

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.5.13",
3
+ "version": "1.5.15",
4
4
  "description": "React Native video/audio player powered by libmpv — Picture-in-Picture, MediaSession, custom RN UI. **V16.0.8 patch release** (2026-09-14) — D-033 16 KB page-size alignment: add_link_options(\"-Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384\") in CMakeLists.txt + ndkVersion r27+ so libsimbaplayer_mpv.so's LOAD segments are aligned to 16 KB (Android 14+ 16 KB page-size requirement). Without this, libsimbaplayer_mpv.so shows \"LOAD segment not aligned\" in the Android App Compatibility dialog and Android refuses to load it — which cascades to \"Unknown error\" for libmpv.so, libc++_shared.so, libav*.so (all transitively loaded via libsimbaplayer_mpv.so's NEEDED list), and the app boots to a white screen. v1.5.7 pre-load attempt was insufficient because the libs themselves weren't loading at all. See CHANGELOG.md for details.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -8,6 +8,7 @@
8
8
  "files": [
9
9
  "src/",
10
10
  "!src/README.example.tsx",
11
+ "scripts/",
11
12
  "android/",
12
13
  "android/build.gradle",
13
14
  "android/consumer-rules.pro",
@@ -54,6 +55,7 @@
54
55
  "test": "jest",
55
56
  "test:watch": "jest --watch",
56
57
  "test:coverage": "jest --coverage",
58
+ "postinstall": "node ./scripts/download-native.js",
57
59
  "prepack": "npm run typecheck && npm run test"
58
60
  },
59
61
  "peerDependencies": {
@@ -0,0 +1,379 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * download-native.js
4
+ *
5
+ * Postinstall hook for @simba-dev/react-native-media-player. Downloads the
6
+ * prebuilt native libraries (libmpv, libav*, libc++_shared, libplayer, etc.)
7
+ * from the matching GitHub release and extracts them into
8
+ * `android/src/main/jniLibs/` so the consumer's Gradle build can find them
9
+ * via CMakeLists.txt's `jniLibs/<abi>/libmpv.so` lookup.
10
+ *
11
+ * Why this exists (vs committing binaries to git):
12
+ * - Git history stays small (~152 MB of .so files would otherwise live
13
+ * in every clone forever).
14
+ * - This is the industry-standard pattern for React Native libraries
15
+ * shipping prebuilt native binaries — see `llama.rn` for the
16
+ * canonical implementation: https://github.com/mybigday/llama.rn
17
+ * - Binaries are versioned via GitHub Release assets (immutable, tied
18
+ * to the npm version) and SHA-256 verified before extraction.
19
+ *
20
+ * Idempotency:
21
+ * - If `android/src/main/jniLibs/<abi>/libmpv.so` already exists, the
22
+ * script exits 0 immediately (no network call). Re-running `npm
23
+ * install` is safe.
24
+ *
25
+ * Skipping:
26
+ * - Set `SKIP_DOWNLOAD_NATIVE=1` to bypass the download. Useful for CI
27
+ * builds that mount the binaries differently, or for tests.
28
+ *
29
+ * Failure modes (with actionable error messages):
30
+ * - No matching GitHub Release for the version → fail with the URL the
31
+ * user should check, and a hint that this is expected for unreleased
32
+ * versions.
33
+ * - Asset not in the release → fail naming the expected asset filename.
34
+ * - SHA-256 mismatch → fail with both expected and actual hash; refuse
35
+ * to extract (supply-chain protection).
36
+ * - Network failure → fail with the underlying error.
37
+ *
38
+ * Trust friction:
39
+ * - pnpm strict mode: consumers must add the lib to `pnpm.onlyBuiltDependencies`.
40
+ * - Bun: must add to `trustedDependencies` in package.json.
41
+ * - npm/yarn classic: no extra config needed.
42
+ * - All of this is documented in README.md under "Install".
43
+ */
44
+
45
+ 'use strict';
46
+
47
+ const https = require('https');
48
+ const crypto = require('crypto');
49
+ const fs = require('fs');
50
+ const path = require('path');
51
+ const { execFileSync } = require('child_process');
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // Configuration
55
+ // ---------------------------------------------------------------------------
56
+
57
+ const REPO_OWNER = 'pavalep';
58
+ const REPO_NAME = 'react-native-media-player';
59
+ // The asset basename uploaded by the release workflow (and the one-off
60
+ // manual upload for v1.5.14). Keep this in sync with release.yml.
61
+ const ASSET_BASENAME = 'jniLibs.tar.gz';
62
+ const SHA_SUFFIX = '.sha256';
63
+
64
+ // Expected minimum content: the consumer's CMakeLists.txt checks for
65
+ // `jniLibs/<abi>/libmpv.so` for every ABI we publish. If any of these
66
+ // is missing, the consumer's Gradle build will fail at configureCMake.
67
+ const REQUIRED_ABIS = ['arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'];
68
+ const REQUIRED_PROBE = 'libmpv.so';
69
+
70
+ // Allow override via env var (useful for fork consumers or air-gapped
71
+ // networks proxying through their own release server). Default: GitHub.
72
+ const RELEASE_BASE = process.env.RNMP_RELEASE_BASE
73
+ || `https://github.com/${REPO_OWNER}/${REPO_NAME}`;
74
+
75
+ const SKIP_DOWNLOAD = process.env.SKIP_DOWNLOAD_NATIVE === '1';
76
+ const DEBUG = process.env.RNMP_DOWNLOAD_DEBUG === '1';
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Helpers
80
+ // ---------------------------------------------------------------------------
81
+
82
+ function log(msg) {
83
+ process.stderr.write(`[download-native] ${msg}\n`);
84
+ }
85
+
86
+ function debug(msg) {
87
+ if (DEBUG) log(`DEBUG: ${msg}`);
88
+ }
89
+
90
+ function fail(msg, details) {
91
+ process.stderr.write(`[download-native] ERROR: ${msg}\n`);
92
+ if (details) process.stderr.write(`${details}\n`);
93
+ process.exit(1);
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // Step 1: Resolve package version
98
+ // ---------------------------------------------------------------------------
99
+
100
+ const libRoot = path.resolve(__dirname, '..');
101
+ const pkgPath = path.join(libRoot, 'package.json');
102
+ if (!fs.existsSync(pkgPath)) {
103
+ fail(`Cannot find package.json at ${pkgPath}. ` +
104
+ 'download-native.js must be invoked from inside the lib install tree.');
105
+ }
106
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
107
+ const version = pkg.version;
108
+ const tag = `v${version}`;
109
+ debug(`lib version=${version}, tag=${tag}`);
110
+ debug(`RELEASE_BASE=${RELEASE_BASE}`);
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Step 2: Idempotency check — if binaries are already present, skip.
114
+ // ---------------------------------------------------------------------------
115
+
116
+ const jniLibsRoot = path.join(libRoot, 'android', 'src', 'main', 'jniLibs');
117
+ const probeFile = path.join(jniLibsRoot, REQUIRED_ABIS[0], REQUIRED_PROBE);
118
+ if (fs.existsSync(probeFile)) {
119
+ debug(`Probe ${probeFile} exists; binaries already present. Skipping download.`);
120
+ process.exit(0);
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // Step 3: Skip if SKIP_DOWNLOAD_NATIVE=1
125
+ // ---------------------------------------------------------------------------
126
+
127
+ if (SKIP_DOWNLOAD) {
128
+ log(`SKIP_DOWNLOAD_NATIVE=1 set; skipping native download. ` +
129
+ `Make sure android/src/main/jniLibs/ is populated by another mechanism ` +
130
+ `(e.g. a CI mount).`);
131
+ process.exit(0);
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Step 4: HTTP helpers — streaming GET with redirect support
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * Performs an HTTPS GET, follows up to 5 redirects, and streams the
140
+ * response body into the writable `dest` (file path or Writable stream).
141
+ * Resolves with { statusCode, headers } on success; rejects on network
142
+ * error or non-2xx final status.
143
+ */
144
+ function httpsGetStream(url, dest, redirectsLeft = 5) {
145
+ return new Promise((resolve, reject) => {
146
+ const req = https.get(url, (res) => {
147
+ // Handle redirects — GitHub Releases redirect download URLs to
148
+ // S3-backed object storage.
149
+ if ([301, 302, 303, 307, 308].includes(res.statusCode)) {
150
+ res.resume(); // drain
151
+ const next = res.headers.location;
152
+ if (!next) return reject(new Error(`Redirect from ${url} with no Location header`));
153
+ if (redirectsLeft <= 0) return reject(new Error(`Too many redirects starting from ${url}`));
154
+ return resolve(httpsGetStream(next, dest, redirectsLeft - 1));
155
+ }
156
+ if (res.statusCode !== 200) {
157
+ res.resume();
158
+ return reject(new Error(`HTTP ${res.statusCode} for ${url}`));
159
+ }
160
+ const out = typeof dest === 'string'
161
+ ? fs.createWriteStream(dest)
162
+ : dest;
163
+ out.on('error', reject);
164
+ res.on('error', reject);
165
+ res.pipe(out);
166
+ out.on('finish', () => {
167
+ if (typeof dest === 'string') out.close(() => resolve({ statusCode: 200, headers: res.headers }));
168
+ else resolve({ statusCode: 200, headers: res.headers });
169
+ });
170
+ });
171
+ req.on('error', reject);
172
+ req.setTimeout(60_000, () => {
173
+ req.destroy(new Error(`Request timed out after 60s: ${url}`));
174
+ });
175
+ });
176
+ }
177
+
178
+ /**
179
+ * Performs an HTTPS GET and resolves with the response body as a string.
180
+ * Used for small JSON / sha256 responses (GitHub API + companion .sha256
181
+ * file). Rejects on non-2xx.
182
+ */
183
+ function httpsGetText(url, redirectsLeft = 5) {
184
+ return new Promise((resolve, reject) => {
185
+ const req = https.get(url, (res) => {
186
+ if ([301, 302, 303, 307, 308].includes(res.statusCode)) {
187
+ res.resume();
188
+ const next = res.headers.location;
189
+ if (!next) return reject(new Error(`Redirect from ${url} with no Location header`));
190
+ if (redirectsLeft <= 0) return reject(new Error(`Too many redirects starting from ${url}`));
191
+ return resolve(httpsGetText(next, redirectsLeft - 1));
192
+ }
193
+ if (res.statusCode !== 200) {
194
+ res.resume();
195
+ return reject(new Error(`HTTP ${res.statusCode} for ${url}`));
196
+ }
197
+ let body = '';
198
+ res.setEncoding('utf8');
199
+ res.on('data', (chunk) => { body += chunk; });
200
+ res.on('end', () => resolve(body));
201
+ res.on('error', reject);
202
+ });
203
+ req.on('error', reject);
204
+ req.setTimeout(30_000, () => {
205
+ req.destroy(new Error(`Request timed out after 30s: ${url}`));
206
+ });
207
+ });
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Step 5: Locate the GitHub release for the package version
212
+ // ---------------------------------------------------------------------------
213
+
214
+ async function findRelease() {
215
+ // GitHub's release-by-tag API: GET /repos/{owner}/{repo}/releases/tags/{tag}
216
+ const apiUrl = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/releases/tags/${tag}`;
217
+ debug(`Looking up release via ${apiUrl}`);
218
+ let body;
219
+ try {
220
+ body = await httpsGetText(apiUrl);
221
+ } catch (e) {
222
+ // Improve the most common failure: 404 = release not found yet.
223
+ if (/HTTP 404/.test(e.message)) {
224
+ fail(
225
+ `GitHub release ${tag} does not exist yet.\n` +
226
+ `This means the release was either never published, OR was published but the\n` +
227
+ `tag/asset is on a different repo (fork, mirror). Check:\n` +
228
+ ` - ${RELEASE_BASE}/releases/tag/${tag}\n\n` +
229
+ `If you're consuming from a fork or private mirror, set RNMP_RELEASE_BASE to\n` +
230
+ `the base URL of your mirror (e.g. https://your-mirror.example.com/owner/repo).`
231
+ );
232
+ }
233
+ if (/HTTP 403/.test(e.message)) {
234
+ fail(
235
+ `GitHub API returned 403 (rate limit or auth required) for ${apiUrl}.\n` +
236
+ `Unauthenticated requests are limited to 60/hour per IP. If this is happening\n` +
237
+ `during CI, either:\n` +
238
+ ` - Wait a few minutes and retry.\n` +
239
+ ` - Use an authenticated request via the GH_TOKEN env var (NOT implemented yet).\n` +
240
+ ` - Pre-stage the binaries via a different mechanism (mount, cache, manual\n` +
241
+ ` copy) and set SKIP_DOWNLOAD_NATIVE=1.\n\n` +
242
+ `Underlying error: ${e.message}`
243
+ );
244
+ }
245
+ throw e;
246
+ }
247
+ let release;
248
+ try {
249
+ release = JSON.parse(body);
250
+ } catch (e) {
251
+ fail(`Failed to parse GitHub API response for tag ${tag}. ` +
252
+ `This usually means the response was an error page (e.g. rate limit). ` +
253
+ `Response starts with: ${body.slice(0, 200)}`);
254
+ }
255
+ const assets = (release.assets || []).map((a) => a.name);
256
+ debug(`Release ${tag} has ${assets.length} assets: ${assets.join(', ')}`);
257
+ const expectedAsset = ASSET_BASENAME;
258
+ if (!assets.includes(expectedAsset)) {
259
+ fail(
260
+ `GitHub release ${tag} does not contain the expected asset "${expectedAsset}".\n` +
261
+ `Assets found: ${assets.length ? assets.join(', ') : '(none)'}\n\n` +
262
+ `This usually means one of:\n` +
263
+ ` (a) The release was published before the postinstall pattern was added (pre-v1.5.14).\n` +
264
+ ` The fix is to upgrade to a version that has the postinstall + matching asset\n` +
265
+ ` (check ${RELEASE_BASE}/releases/tag/${tag}).\n` +
266
+ ` (b) The release.yml workflow's upload step failed silently. Check the latest release\n` +
267
+ ` workflow run at https://github.com/${REPO_OWNER}/${REPO_NAME}/actions/workflows/release.yml.\n` +
268
+ ` (c) You're installing from a fork or local checkout that doesn't have a GitHub Release\n` +
269
+ ` for this version. Set RNMP_RELEASE_BASE to your fork's release URL.`
270
+ );
271
+ }
272
+ const asset = release.assets.find((a) => a.name === expectedAsset);
273
+ return asset.browser_download_url;
274
+ }
275
+
276
+ // ---------------------------------------------------------------------------
277
+ // Step 6: Download + verify + extract
278
+ // ---------------------------------------------------------------------------
279
+
280
+ async function downloadAndExtract() {
281
+ log(`Downloading native libraries for @simba-dev/react-native-media-player@${version}...`);
282
+ const downloadUrl = await findRelease();
283
+
284
+ const tmpDir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'rnmp-native-'));
285
+ const tarPath = path.join(tmpDir, ASSET_BASENAME);
286
+ const shaPath = path.join(tmpDir, ASSET_BASENAME + SHA_SUFFIX);
287
+
288
+ try {
289
+ // 1) Download the tarball
290
+ debug(`Downloading ${downloadUrl} -> ${tarPath}`);
291
+ await httpsGetStream(downloadUrl, tarPath);
292
+ const tarSize = fs.statSync(tarPath).size;
293
+ log(`Downloaded ${(tarSize / 1024 / 1024).toFixed(1)} MB tarball.`);
294
+
295
+ // 2) Download the companion .sha256 file from the same release.
296
+ // GitHub's asset URLs are deterministic — we can swap the filename
297
+ // in the URL. If that fails (e.g. CDN doesn't expose it), fall
298
+ // back to the GitHub API's `digest` field on the asset object.
299
+ const shaUrl = downloadUrl.replace(/\/[^/]+$/, `/${ASSET_BASENAME}${SHA_SUFFIX}`);
300
+ debug(`Downloading ${shaUrl} -> ${shaPath}`);
301
+ let expectedSha;
302
+ try {
303
+ const shaText = await httpsGetText(shaUrl);
304
+ // sha256sum format: "<hash> " or just "<hash>"
305
+ const match = shaText.trim().match(/^([a-f0-9]{64})/);
306
+ if (!match) {
307
+ fail(`Could not parse SHA-256 from companion file. ` +
308
+ `Expected a 64-char hex hash at the start of the line, got: ${shaText.slice(0, 200)}`);
309
+ }
310
+ expectedSha = match[1];
311
+ } catch (e) {
312
+ fail(
313
+ `Failed to download SHA-256 file from ${shaUrl}.\n` +
314
+ `Underlying error: ${e.message}\n\n` +
315
+ `This means we cannot verify the tarball's integrity. Refusing to extract. ` +
316
+ `Either:\n` +
317
+ ` - Ensure the release was created with both ${ASSET_BASENAME} and ` +
318
+ `${ASSET_BASENAME}${SHA_SUFFIX} assets.\n` +
319
+ ` - Or set SKIP_DOWNLOAD_NATIVE=1 and provision the binaries yourself.`
320
+ );
321
+ }
322
+
323
+ // 3) Verify SHA-256
324
+ const actualSha = crypto.createHash('sha256')
325
+ .update(fs.readFileSync(tarPath))
326
+ .digest('hex');
327
+ debug(`expected=${expectedSha} actual=${actualSha}`);
328
+ if (actualSha !== expectedSha) {
329
+ fail(
330
+ `SHA-256 mismatch on downloaded tarball — refusing to extract.\n` +
331
+ ` expected: ${expectedSha}\n` +
332
+ ` actual: ${actualSha}\n\n` +
333
+ `This indicates the tarball was corrupted in transit OR a malicious actor ` +
334
+ `is serving a tampered asset. Do NOT extract. Re-run npm install, or ` +
335
+ `verify the release's published asset hashes at ` +
336
+ `${RELEASE_BASE}/releases/tag/${tag}.`
337
+ );
338
+ }
339
+ log('SHA-256 verified.');
340
+
341
+ // 4) Extract into android/src/main/jniLibs/
342
+ // Make sure the parent dir exists; tar -xz handles nested paths.
343
+ fs.mkdirSync(jniLibsRoot, { recursive: true });
344
+
345
+ // Use the system `tar` to avoid pulling in a tar lib dependency.
346
+ // Cross-platform: macOS/Linux ship `tar` by default; on Windows,
347
+ // Node 20+ includes bsdtar, and Git for Windows also provides it.
348
+ // We invoke via the lib's root so the tarball's relative paths land
349
+ // in the right place (it was created from the lib root with paths
350
+ // like `android/src/main/jniLibs/<abi>/libmpv.so`).
351
+ log(`Extracting into ${jniLibsRoot}...`);
352
+ execFileSync('tar', ['-xzf', tarPath], { cwd: libRoot, stdio: 'inherit' });
353
+
354
+ // 5) Sanity check: probe every required ABI for libmpv.so.
355
+ const missing = REQUIRED_ABIS.filter(
356
+ (abi) => !fs.existsSync(path.join(jniLibsRoot, abi, REQUIRED_PROBE))
357
+ );
358
+ if (missing.length > 0) {
359
+ fail(
360
+ `Extraction completed but required probe file(s) are missing:\n` +
361
+ missing.map((abi) => ` - android/src/main/jniLibs/${abi}/${REQUIRED_PROBE}`).join('\n') +
362
+ `\n\nThe tarball may be corrupt or incomplete. Re-run, or check the release's ` +
363
+ `published assets at ${RELEASE_BASE}/releases/tag/${tag}.`
364
+ );
365
+ }
366
+ log(`Native libraries installed (${REQUIRED_ABIS.length} ABIs verified).`);
367
+ } finally {
368
+ // Clean up temp dir regardless of success/failure.
369
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (_) { /* best effort */ }
370
+ }
371
+ }
372
+
373
+ // ---------------------------------------------------------------------------
374
+ // Entry point
375
+ // ---------------------------------------------------------------------------
376
+
377
+ downloadAndExtract().catch((err) => {
378
+ fail(err.message || String(err));
379
+ });
@@ -0,0 +1,161 @@
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: drop nullable types + defaults
73
+ {
74
+ name: "enterPip-signature",
75
+ pattern: / fun enterPip\(chapterTitle: String\? = null, progressPct: String\? = null\) \{/,
76
+ replacement: " fun enterPip(chapterTitle: String, progressPct: String) {",
77
+ },
78
+ ];
79
+
80
+ const REACT_METHOD_LINE = /^( )(@ReactMethod(?:\([^)]*\))?)\s*$/;
81
+ const FUN_LINE = /^( )fun ([A-Za-z_][A-Za-z0-9_]*)(\(.*)$/;
82
+
83
+ function applySignatureNormalizations(src) {
84
+ for (const norm of SIGNATURE_NORMALIZATIONS) {
85
+ // Count non-overlapping matches via the `g` + `exec` loop (reliable even
86
+ // when the regex has capture groups — `String.prototype.split` would
87
+ // inflate its count by the number of captures).
88
+ const re = new RegExp(norm.pattern.source, "g");
89
+ let count = 0;
90
+ let m;
91
+ while ((m = re.exec(src)) !== null) {
92
+ count++;
93
+ // Guard against zero-length matches to avoid infinite loop in pathological cases.
94
+ if (m[0].length === 0) re.lastIndex++;
95
+ }
96
+ if (count !== 1) {
97
+ throw new Error(
98
+ `signature normalization '${norm.name}' did not match exactly once (matched ${count} times)`
99
+ );
100
+ }
101
+ // Now apply the actual replacement (preserve the original flags / backref semantics).
102
+ const reNoG = new RegExp(norm.pattern.source, norm.pattern.flags);
103
+ src = src.replace(reNoG, norm.replacement);
104
+ console.log(` [signature] ${norm.name}: matched ${count}x`);
105
+ }
106
+ return src;
107
+ }
108
+
109
+ function addOverrideAnnoAndKeyword(src) {
110
+ const lines = src.split(/\r?\n/);
111
+ const out = [];
112
+ let i = 0;
113
+ while (i < lines.length) {
114
+ const line = lines[i];
115
+ const mAnno = line.match(REACT_METHOD_LINE);
116
+ if (mAnno && i + 1 < lines.length) {
117
+ const nextLine = lines[i + 1];
118
+ const mFun = nextLine.match(FUN_LINE);
119
+ if (mFun) {
120
+ const name = mFun[2];
121
+ if (NON_SPEC_REACT_METHODS.has(name)) {
122
+ out.push(line);
123
+ out.push(nextLine);
124
+ i += 2;
125
+ continue;
126
+ }
127
+ const indent = mAnno[1];
128
+ out.push(line);
129
+ out.push(`${indent}@Override`);
130
+ out.push(`${indent}override fun ${name}${mFun[3]}`);
131
+ i += 2;
132
+ continue;
133
+ }
134
+ }
135
+ out.push(line);
136
+ i += 1;
137
+ }
138
+ return out.join("\n");
139
+ }
140
+
141
+ function main() {
142
+ let src = fs.readFileSync(SRC_PATH, { encoding: "utf-8" });
143
+ // Normalize CRLF -> LF for consistent regex matching. We write LF-only
144
+ // back to keep diffs clean (the rest of the file uses LF exclusively
145
+ // when checked out via git; the actual byte stream from the edit tool
146
+ // happens to also be LF).
147
+ src = src.replace(/\r\n/g, "\n");
148
+ src = applySignatureNormalizations(src);
149
+ src = addOverrideAnnoAndKeyword(src);
150
+ fs.writeFileSync(SRC_PATH, src, { encoding: "utf-8" });
151
+
152
+ const overrideCount = (src.match(/^ @Override$/mg) || []).length;
153
+ const reactMethodCount = (src.match(/^ @ReactMethod/gm) || []).length;
154
+ console.log(`Total @ReactMethod blocks: ${reactMethodCount}`);
155
+ console.log(`Added @Override annotations: ${overrideCount}`);
156
+ console.log(
157
+ `Expected: ~${reactMethodCount - NON_SPEC_REACT_METHODS.size} @Override on spec overrides`
158
+ );
159
+ }
160
+
161
+ main();
@@ -0,0 +1,150 @@
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())