codeplay-common 4.11.12 → 4.11.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.
Files changed (33) hide show
  1. package/CHANGELOG.md +114 -101
  2. package/LICENSE +21 -21
  3. package/README.md +274 -229
  4. package/RELEASE_NOTES.md +110 -97
  5. package/files/buildCodeplay/add-splash-screen.js +256 -255
  6. package/files/buildCodeplay/apk-store-builder.js +97 -97
  7. package/files/buildCodeplay/codeplayBeforeBuild.js +98 -52
  8. package/files/buildCodeplay/fix-onesignal-plugin.js +96 -96
  9. package/files/buildCodeplay/fix-optimize-builld/android-r8-rules.cjs +31 -31
  10. package/files/buildCodeplay/fix-optimize-builld/ffmpeg-jni-rules.cjs +28 -28
  11. package/files/buildCodeplay/fix-optimize-builld/fix-optimize-build.gradle +9 -9
  12. package/files/buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs +30 -30
  13. package/files/buildCodeplay/ios-emi-admob-modification.js +24 -24
  14. package/files/buildCodeplay/manifestModification.js +38 -38
  15. package/files/buildCodeplay/release-sync.config.json +4 -4
  16. package/files/buildCodeplay/setSplashAnimation.js +228 -226
  17. package/files/buildCodeplay/splash-setup.cjs +88 -0
  18. package/files/buildCodeplay/splashxml/codeplay_splashScreen.xml +1 -1
  19. package/files/buildCodeplay/sync-admob-nextgen.js +219 -219
  20. package/files/buildCodeplay/versions.json +27 -27
  21. package/files/finalrelease +1263 -1263
  22. package/files/generate-ai-promo-video.js +23 -23
  23. package/files/ionic.config.json +6 -6
  24. package/files/scripts-common/run-codeplay-sync-after.js +21 -21
  25. package/files/scripts-common/screenshot/background-decorations.js +120 -120
  26. package/files/scripts-common/screenshot/frame-samples.js +117 -117
  27. package/files/scripts-common/setup-baseline-profile.js +291 -291
  28. package/files/take-screen-video.js +644 -644
  29. package/package.json +28 -27
  30. package/runtime/splash-ready.mjs +52 -0
  31. package/scripts/splash-setup.test.cjs +142 -0
  32. package/scripts/sync-files.js +114 -113
  33. package/scripts/uninstall.js +2 -2
package/package.json CHANGED
@@ -1,27 +1,28 @@
1
- {
2
- "name": "codeplay-common",
3
- "version": "4.11.12",
4
- "description": "Common build scripts and files",
5
- "scripts": {
6
- "postinstall": "node scripts/sync-files.js",
7
- "preinstall": "node scripts/uninstall.js"
8
- },
9
- "dependencies": {
10
- "adm-zip": "^0.6.1",
11
- "plist": "^3.1.0"
12
- },
13
- "repository": {
14
- "type": "git",
15
- "url": "https://github.com/merbin2012/codeplay-common.git"
16
- },
17
- "author": "Codeplay Technologies",
18
- "license": "MIT",
19
- "files": [
20
- "files/",
21
- "scripts/",
22
- "README.md",
23
- "CHANGELOG.md",
24
- "RELEASE_NOTES.md",
25
- "LICENSE"
26
- ]
27
- }
1
+ {
2
+ "name": "codeplay-common",
3
+ "version": "4.11.15",
4
+ "description": "Common build scripts and files",
5
+ "scripts": {
6
+ "postinstall": "node scripts/sync-files.js",
7
+ "preinstall": "node scripts/uninstall.js"
8
+ },
9
+ "dependencies": {
10
+ "adm-zip": "^0.6.1",
11
+ "plist": "^3.1.0"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/merbin2012/codeplay-common.git"
16
+ },
17
+ "author": "Codeplay Technologies",
18
+ "license": "MIT",
19
+ "files": [
20
+ "files/",
21
+ "scripts/",
22
+ "README.md",
23
+ "CHANGELOG.md",
24
+ "RELEASE_NOTES.md",
25
+ "LICENSE",
26
+ "runtime/"
27
+ ]
28
+ }
@@ -0,0 +1,52 @@
1
+ // Framework7 and Capacitor stay owned by the consuming app; no extra dependency.
2
+ const registrations = new WeakMap();
3
+
4
+ export function hideSplashWhenReady({ f7, hide, imageSelector = '[data-splash-ready], .t-film-art img', timeout = 8000 }) {
5
+ if (!f7 || typeof f7.on !== 'function' || typeof f7.off !== 'function' || typeof hide !== 'function') {
6
+ throw new TypeError('Splash readiness requires Framework7 and a hide callback.');
7
+ }
8
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 60000) throw new TypeError('Invalid splash readiness timeout.');
9
+ if (typeof imageSelector !== 'string') throw new TypeError('Invalid splash image selector.');
10
+ if (registrations.has(f7)) return registrations.get(f7);
11
+ let finished = false;
12
+ let preparing = false;
13
+ let image;
14
+ const detachImage = () => {
15
+ image?.removeEventListener('load', onImageReady);
16
+ image?.removeEventListener('error', onImageReady);
17
+ };
18
+ const finish = () => {
19
+ if (finished) return;
20
+ finished = true;
21
+ clearTimeout(fallback);
22
+ f7.off('pageAfterIn', onPageReady);
23
+ detachImage();
24
+ // Plugin availability differs by platform; failed native hiding must not
25
+ // create an unhandled rejection. The native launch timeout is the backup.
26
+ try { Promise.resolve(hide()).catch(() => {}); } catch {}
27
+ };
28
+ const onImageReady = () => {
29
+ if (finished) return;
30
+ detachImage();
31
+ if (image.naturalWidth > 0 && typeof image.decode === 'function') {
32
+ Promise.resolve().then(() => image.decode()).catch(() => {}).then(finish);
33
+ } else finish();
34
+ };
35
+ const onPageReady = page => {
36
+ if (finished || preparing || !page?.el?.closest('.view-main')) return;
37
+ preparing = true;
38
+ try { image = imageSelector ? page.el.querySelector(imageSelector) : null; } catch { finish(); return; }
39
+ if (!image) finish();
40
+ else if (image.complete) onImageReady();
41
+ else {
42
+ image.addEventListener('load', onImageReady, { once: true });
43
+ image.addEventListener('error', onImageReady, { once: true });
44
+ }
45
+ };
46
+ const fallback = setTimeout(finish, timeout);
47
+ registrations.set(f7, finish);
48
+ f7.on('pageAfterIn', onPageReady);
49
+ const currentPage = f7.views?.main?.router?.currentPageEl;
50
+ if (currentPage) onPageReady({ el: currentPage });
51
+ return finish;
52
+ }
@@ -0,0 +1,142 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { execFileSync } = require('child_process');
6
+ const { readSplashOptions, migrateSplashTheme, migrateReadinessSource, syncSplashSetup } = require('../files/buildCodeplay/splash-setup.cjs');
7
+
8
+ function fixture(t) {
9
+ const base = path.resolve(process.env.CODEPLAY_TEST_ROOT || path.join(__dirname, '../agent-temp'));
10
+ fs.mkdirSync(base, { recursive: true });
11
+ const root = fs.mkdtempSync(path.join(base, 'splash-'));
12
+ t.after(() => {
13
+ if (path.dirname(path.resolve(root)) !== base) throw new Error('Unsafe fixture cleanup');
14
+ fs.rmSync(root, { recursive: true, force: true });
15
+ });
16
+ return root;
17
+ }
18
+ const legacy = `var capacitorApp = {
19
+ handleSplashscreen: function () {
20
+ if (!window.Capacitor) return;
21
+ setTimeout(() => { if (window.Capacitor.Plugins?.SplashScreen) window.Capacitor.Plugins.SplashScreen.hide(); }, 2000);
22
+ },
23
+ };`;
24
+ const options = readSplashOptions({ plugins: { CodeplaySplashScreen: { migrateLegacyReadiness: true } } });
25
+
26
+ test('duration defaults to1000 and preserves explicit0;invalid values fail', () => {
27
+ assert.equal(readSplashOptions({}).duration, 1000);
28
+ assert.equal(readSplashOptions({ plugins: { CodeplaySplashScreen: { exitAnimationDuration: 0 } } }).duration, 0);
29
+ for (const duration of [-1, '0', 1.5, 10001]) assert.throws(() => readSplashOptions({ plugins: { CodeplaySplashScreen: { exitAnimationDuration: duration } } }));
30
+ });
31
+ test('repair known legacy theme,idempotently preserve app-specific themes', () => {
32
+ const before = '<item name="postSplashScreenTheme">@style/Theme.AppCompat.NoActionBar</item>';
33
+ const after = migrateSplashTheme(before);
34
+ assert.ok(after.includes('Theme.AppCompat.DayNight.NoActionBar'));
35
+ assert.equal(migrateSplashTheme(after), after);
36
+ assert.equal(migrateSplashTheme(before.replace('Theme.AppCompat.NoActionBar', 'MyCustomTheme')), before.replace('Theme.AppCompat.NoActionBar', 'MyCustomTheme'));
37
+ });
38
+ test('legacy handler migration requires opt-in,is idempotent,and preserves custom handlers', () => {
39
+ assert.equal(migrateReadinessSource(legacy, readSplashOptions({})).source, legacy);
40
+ const migrated = migrateReadinessSource(legacy, options);
41
+ assert.equal(migrated.status, 'managed');
42
+ assert.equal(migrateReadinessSource(migrated.source, options).source, migrated.source);
43
+ const custom = migrated.source.replace(' if (!window.Capacitor)', ' customStartup();\n if (!window.Capacitor)');
44
+ assert.equal(migrateReadinessSource(custom, options).source, custom);
45
+ const customAfter = migrated.source.replace(' });', ' });\n customStartup();');
46
+ assert.equal(migrateReadinessSource(customAfter, options).source, customAfter);
47
+ });
48
+ test('migration keeps legacy native-disabled config and custom theme intact', t => {
49
+ const root = fixture(t);
50
+ fs.mkdirSync(path.join(root, 'src/js'), { recursive: true });
51
+ fs.mkdirSync(path.join(root, 'buildCodeplay/splashxml'), { recursive: true });
52
+ fs.writeFileSync(path.join(root, 'src/js/capacitor-app.js'), legacy);
53
+ fs.writeFileSync(path.join(root, 'buildCodeplay/splashxml/codeplay_splashScreen.xml'), '<item name="postSplashScreenTheme">@style/Custom</item>');
54
+ fs.writeFileSync(path.join(root, 'capacitor.config.json'), JSON.stringify({ plugins: { SplashScreen: { launchShowDuration: 0 }, CodeplaySplashScreen: { migrateLegacyReadiness: true } } }));
55
+ const log = [];
56
+ syncSplashSetup(root, { log: value => log.push(value) });
57
+ assert.equal(fs.readFileSync(path.join(root, 'src/js/capacitor-app.js'), 'utf8'), legacy);
58
+ assert.ok(log.some(value => value.includes('native fallback')));
59
+ });
60
+ test('generator emits0ms without changing launchShowDuration', t => {
61
+ const root = fixture(t);
62
+ const java = path.join(root, 'android/app/src/main/java/example/app/MainActivity.java');
63
+ fs.mkdirSync(path.dirname(java), { recursive: true });
64
+ fs.writeFileSync(java, 'package example.app;');
65
+ const config = { appId: 'example.app', plugins: { SplashScreen: { launchShowDuration: 8000 }, CodeplaySplashScreen: { exitAnimationDuration: 0 } } };
66
+ fs.writeFileSync(path.join(root, 'capacitor.config.json'), JSON.stringify(config));
67
+ execFileSync(process.execPath, [path.resolve(__dirname, '../files/buildCodeplay/setSplashAnimation.js')], { cwd: root, stdio: 'pipe' });
68
+ assert.ok(fs.readFileSync(java, 'utf8').includes('.setDuration(0)'));
69
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, 'capacitor.config.json'))), config);
70
+ });
71
+ test('complete migration requires fallback and plugin dependency;repeat preparation is stable', t => {
72
+ const root = fixture(t);
73
+ fs.mkdirSync(path.join(root, 'src/js'), { recursive: true });
74
+ const app = path.join(root, 'src/js/capacitor-app.js');
75
+ fs.writeFileSync(app, legacy);
76
+ const config = { plugins: { SplashScreen: { launchShowDuration: 8000, launchAutoHide: true }, CodeplaySplashScreen: { migrateLegacyReadiness: true } } };
77
+ fs.writeFileSync(path.join(root, 'capacitor.config.json'), JSON.stringify(config));
78
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ dependencies: {} }));
79
+ syncSplashSetup(root, { log() {} });
80
+ assert.equal(fs.readFileSync(app, 'utf8'), legacy);
81
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ dependencies: { '@capacitor/splash-screen': '^8.0.0' } }));
82
+ syncSplashSetup(root, { log() {} });
83
+ const result = fs.readFileSync(app, 'utf8');
84
+ assert.ok(result.includes('return hideSplashWhenReady('));
85
+ syncSplashSetup(root, { log() {} });
86
+ assert.equal(fs.readFileSync(app, 'utf8'), result);
87
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, 'capacitor.config.json'))), config);
88
+ });
89
+
90
+ function framework(image, cached = false) {
91
+ const handlers = new Map();
92
+ const page = { closest: () => true, querySelector: () => image };
93
+ return { page, handlers, f7: { on: (name, fn) => handlers.set(name, fn), off: name => handlers.delete(name), views: { main: { router: { currentPageEl: cached ? page : null } } } } };
94
+ }
95
+ test('wait for main-page image decode,hide once,and detach listeners', async () => {
96
+ const { hideSplashWhenReady } = await import('../runtime/splash-ready.mjs');
97
+ let decoded, count = 0;
98
+ const listeners = new Map();
99
+ const image = { complete: false, naturalWidth: 100, decode: () => new Promise(resolve => { decoded = resolve; }), addEventListener: (name, fn) => listeners.set(name, fn), removeEventListener: name => listeners.delete(name) };
100
+ const { f7, handlers, page } = framework(image);
101
+ const finish = hideSplashWhenReady({ f7, hide: () => { count++; } });
102
+ handlers.get('pageAfterIn')({ el: { closest: () => false } });
103
+ assert.equal(count, 0);
104
+ handlers.get('pageAfterIn')({ el: page });
105
+ listeners.get('load')();
106
+ await Promise.resolve();
107
+ assert.equal(count, 0);
108
+ decoded();
109
+ await new Promise(resolve => setImmediate(resolve));
110
+ finish();
111
+ assert.equal(count, 1);
112
+ assert.equal(handlers.size, 0);
113
+ assert.equal(listeners.size, 0);
114
+ });
115
+ test('cached page without hero hides immediately and repeated setup is safe', async () => {
116
+ const { hideSplashWhenReady } = await import('../runtime/splash-ready.mjs');
117
+ const { f7 } = framework(null, true);
118
+ let count = 0;
119
+ hideSplashWhenReady({ f7, hide: () => { count++; } });
120
+ hideSplashWhenReady({ f7, hide: () => { count++; } });
121
+ assert.equal(count, 1);
122
+ });
123
+ test('broken image and failed decode release splash', async () => {
124
+ const { hideSplashWhenReady } = await import('../runtime/splash-ready.mjs');
125
+ for (const naturalWidth of [0, 100]) {
126
+ let count = 0;
127
+ const image = { complete: true, naturalWidth, decode: () => Promise.reject(new Error('decode failed')), removeEventListener() {} };
128
+ const { f7 } = framework(image, true);
129
+ hideSplashWhenReady({ f7, hide: () => { count++; } });
130
+ await new Promise(resolve => setImmediate(resolve));
131
+ assert.equal(count, 1);
132
+ }
133
+ });
134
+ test('timeout releases stuck page and consumes native plugin rejection', async () => {
135
+ const { hideSplashWhenReady } = await import('../runtime/splash-ready.mjs');
136
+ const { f7, handlers } = framework(null);
137
+ let count = 0;
138
+ hideSplashWhenReady({ f7, timeout: 10, hide: () => { count++; return Promise.reject(new Error('native unavailable')); } });
139
+ await new Promise(resolve => setTimeout(resolve, 30));
140
+ assert.equal(count, 1);
141
+ assert.equal(handlers.size, 0);
142
+ });
@@ -1,113 +1,114 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { updateBuildScripts, removeVersionedBuildScripts } = require('../files/buildCodeplay/project-scripts.cjs');
4
- const { syncAndroidR8Rules } = require('../files/buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs');
5
-
6
- function migrateAppScripts(projectRoot) {
7
- const root = path.resolve(projectRoot);
8
- const source = path.resolve(root, 'scripts');
9
- const destination = path.resolve(root, 'scripts-common');
10
- if (path.dirname(source) !== root || path.dirname(destination) !== root) throw new Error('Invalid app scripts path.');
11
- if (!fs.existsSync(source)) return;
12
- // Preflight the entire tree before moving anything. Never overwrite a
13
- // different existing file or follow a linked directory.
14
- function check(from, to) {
15
- if (fs.lstatSync(from).isSymbolicLink() || (fs.existsSync(to) && fs.lstatSync(to).isSymbolicLink())) throw new Error('Cannot migrate linked script paths.');
16
- if (!fs.existsSync(to)) return;
17
- if (fs.statSync(from).isDirectory() && fs.statSync(to).isDirectory()) {
18
- for (const name of fs.readdirSync(from)) check(path.join(from, name), path.join(to, name));
19
- } else if (!fs.statSync(from).isFile() || !fs.statSync(to).isFile() || !fs.readFileSync(from).equals(fs.readFileSync(to))) {
20
- throw new Error(`Scripts folder conflict; both files preserved: ${to}`);
21
- }
22
- }
23
- function move(from, to) {
24
- if (!fs.existsSync(to)) { fs.renameSync(from, to); return; }
25
- if (fs.statSync(from).isDirectory()) {
26
- for (const name of fs.readdirSync(from)) move(path.join(from, name), path.join(to, name));
27
- fs.rmdirSync(from);
28
- } else fs.unlinkSync(from); // Identical existing file, verified above.
29
- }
30
- check(source, destination);
31
- move(source, destination);
32
- }
33
-
34
- function migrateAppConfigurator(projectRoot) {
35
- const filePath = path.join(projectRoot, 'scripts-common', 'configure-codeplay-common.js');
36
- if (!fs.existsSync(filePath)) return;
37
- const original = fs.readFileSync(filePath, 'utf8');
38
- let updated = original;
39
- // Preserve app-specific configuration; extend only the known legacy lookups.
40
- for (const [variable, script] of [
41
- ['buildFile', 'codeplayBeforeBuild.js'],
42
- ['packageIdFile', 'packageidBaseModification.js'],
43
- ]) {
44
- updated = updated.replace(
45
- `const ${variable} = fs.readdirSync(buildDir)`,
46
- `const ${variable} = fs.existsSync(path.join(buildDir, '${script}'))\n` +
47
- ` ? '${script}'\n` +
48
- ` : fs.readdirSync(buildDir)`
49
- );
50
- }
51
- updated = updated.replace(
52
- "packageJson.scripts['capacitor:sync:after'] = 'node scripts/run-codeplay-sync-after.js';",
53
- "packageJson.scripts['capacitor:sync:after'] = 'node scripts-common/run-codeplay-sync-after.js';"
54
- );
55
- if (updated !== original) fs.writeFileSync(filePath, updated, 'utf8');
56
- }
57
-
58
- function findProjectRoot() {
59
- // npm may execute a file: dependency's lifecycle in its source directory.
60
- // INIT_CWD identifies the app that invoked npm in that case.
61
- for (const candidate of [process.env.INIT_CWD, path.join(__dirname, '../../..')]) {
62
- if (!candidate) continue;
63
- const root = path.resolve(candidate);
64
- const file = path.join(root, 'package.json');
65
- if (!fs.existsSync(file)) continue;
66
- if (JSON.parse(fs.readFileSync(file, 'utf8')).name !== 'codeplay-common' && fs.existsSync(path.join(root, 'capacitor.config.json'))) return root;
67
- }
68
- return null;
69
- }
70
-
71
- function install(options = {}) {
72
- const resolved = options.projectRoot || findProjectRoot();
73
- if (!resolved) {
74
- console.log('codeplay-common: no consuming Capacitor app found; skipping source-package setup.');
75
- return null;
76
- }
77
- const projectRoot = path.resolve(resolved);
78
- const commonFiles = path.resolve(__dirname, '../files');
79
- const packagePath = path.join(projectRoot, 'package.json');
80
- if (!fs.existsSync(packagePath)) throw new Error('Consuming application package.json was not found.');
81
- const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
82
- const scripts = updateBuildScripts(pkg.scripts || {});
83
- migrateAppScripts(projectRoot);
84
- // Copy the common templates into each application for local testing.
85
- const buildSource = path.join(commonFiles, 'buildCodeplay');
86
- const buildTarget = path.join(projectRoot, 'buildCodeplay');
87
- fs.mkdirSync(buildTarget, { recursive: true });
88
- for (const name of fs.readdirSync(buildSource)) {
89
- const target = path.join(buildTarget, name);
90
- if ((name === 'release-sync.config.json' || name === 'splashxml') && fs.existsSync(target)) continue;
91
- fs.cpSync(path.join(buildSource, name), target, { recursive: true });
92
- }
93
- fs.copyFileSync(path.join(commonFiles, 'finalrelease'), path.join(projectRoot, 'finalrelease'));
94
- if (options.copyAssets !== false) {
95
- for (const name of fs.readdirSync(commonFiles)) {
96
- if (name === 'buildCodeplay' || name === 'scripts-screenshot') continue;
97
- fs.cpSync(path.join(commonFiles, name), path.join(projectRoot, name), { recursive: true });
98
- }
99
- }
100
- migrateAppConfigurator(projectRoot);
101
- syncAndroidR8Rules(projectRoot, { installGradleHook: true });
102
- pkg.scripts = scripts;
103
- fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2) + '\n');
104
- // Cleanup happens only after replacement assets and package commands exist.
105
- removeVersionedBuildScripts(projectRoot);
106
- console.log('codeplay-common: unversioned build scripts copied to app buildCodeplay; app-owned settings preserved.');
107
- // Coupled IAP/AdMob/Home migrations run together during before-build.
108
- return pkg;
109
- }
110
- module.exports = { install, findProjectRoot, migrateAppScripts, migrateAppConfigurator };
111
- if (require.main === module) {
112
- try { install(); } catch (error) { console.error(error.message); process.exitCode = 1; }
113
- }
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { updateBuildScripts, removeVersionedBuildScripts } = require('../files/buildCodeplay/project-scripts.cjs');
4
+ const { syncAndroidR8Rules } = require('../files/buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs');
5
+
6
+ function migrateAppScripts(projectRoot) {
7
+ const root = path.resolve(projectRoot);
8
+ const source = path.resolve(root, 'scripts');
9
+ const destination = path.resolve(root, 'scripts-common');
10
+ if (path.dirname(source) !== root || path.dirname(destination) !== root) throw new Error('Invalid app scripts path.');
11
+ if (!fs.existsSync(source)) return;
12
+ // Preflight the entire tree before moving anything. Never overwrite a
13
+ // different existing file or follow a linked directory.
14
+ function check(from, to) {
15
+ if (fs.lstatSync(from).isSymbolicLink() || (fs.existsSync(to) && fs.lstatSync(to).isSymbolicLink())) throw new Error('Cannot migrate linked script paths.');
16
+ if (!fs.existsSync(to)) return;
17
+ if (fs.statSync(from).isDirectory() && fs.statSync(to).isDirectory()) {
18
+ for (const name of fs.readdirSync(from)) check(path.join(from, name), path.join(to, name));
19
+ } else if (!fs.statSync(from).isFile() || !fs.statSync(to).isFile() || !fs.readFileSync(from).equals(fs.readFileSync(to))) {
20
+ throw new Error(`Scripts folder conflict; both files preserved: ${to}`);
21
+ }
22
+ }
23
+ function move(from, to) {
24
+ if (!fs.existsSync(to)) { fs.renameSync(from, to); return; }
25
+ if (fs.statSync(from).isDirectory()) {
26
+ for (const name of fs.readdirSync(from)) move(path.join(from, name), path.join(to, name));
27
+ fs.rmdirSync(from);
28
+ } else fs.unlinkSync(from); // Identical existing file, verified above.
29
+ }
30
+ check(source, destination);
31
+ move(source, destination);
32
+ }
33
+
34
+ function migrateAppConfigurator(projectRoot) {
35
+ const filePath = path.join(projectRoot, 'scripts-common', 'configure-codeplay-common.js');
36
+ if (!fs.existsSync(filePath)) return;
37
+ const original = fs.readFileSync(filePath, 'utf8');
38
+ let updated = original;
39
+ // Preserve app-specific configuration; extend only the known legacy lookups.
40
+ for (const [variable, script] of [
41
+ ['buildFile', 'codeplayBeforeBuild.js'],
42
+ ['packageIdFile', 'packageidBaseModification.js'],
43
+ ]) {
44
+ updated = updated.replace(
45
+ `const ${variable} = fs.readdirSync(buildDir)`,
46
+ `const ${variable} = fs.existsSync(path.join(buildDir, '${script}'))\n` +
47
+ ` ? '${script}'\n` +
48
+ ` : fs.readdirSync(buildDir)`
49
+ );
50
+ }
51
+ updated = updated.replace(
52
+ "packageJson.scripts['capacitor:sync:after'] = 'node scripts/run-codeplay-sync-after.js';",
53
+ "packageJson.scripts['capacitor:sync:after'] = 'node scripts-common/run-codeplay-sync-after.js';"
54
+ );
55
+ if (updated !== original) fs.writeFileSync(filePath, updated, 'utf8');
56
+ }
57
+
58
+ function findProjectRoot() {
59
+ // npm may execute a file: dependency's lifecycle in its source directory.
60
+ // INIT_CWD identifies the app that invoked npm in that case.
61
+ for (const candidate of [process.env.INIT_CWD, path.join(__dirname, '../../..')]) {
62
+ if (!candidate) continue;
63
+ const root = path.resolve(candidate);
64
+ const file = path.join(root, 'package.json');
65
+ if (!fs.existsSync(file)) continue;
66
+ if (JSON.parse(fs.readFileSync(file, 'utf8')).name !== 'codeplay-common' && fs.existsSync(path.join(root, 'capacitor.config.json'))) return root;
67
+ }
68
+ return null;
69
+ }
70
+
71
+ function install(options = {}) {
72
+ const resolved = options.projectRoot || findProjectRoot();
73
+ if (!resolved) {
74
+ console.log('codeplay-common: no consuming Capacitor app found; skipping source-package setup.');
75
+ return null;
76
+ }
77
+ const projectRoot = path.resolve(resolved);
78
+ const commonFiles = path.resolve(__dirname, '../files');
79
+ const packagePath = path.join(projectRoot, 'package.json');
80
+ if (!fs.existsSync(packagePath)) throw new Error('Consuming application package.json was not found.');
81
+ const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
82
+ const scripts = updateBuildScripts(pkg.scripts || {});
83
+ migrateAppScripts(projectRoot);
84
+ // Copy the common templates into each application for local testing.
85
+ const buildSource = path.join(commonFiles, 'buildCodeplay');
86
+ const buildTarget = path.join(projectRoot, 'buildCodeplay');
87
+ fs.mkdirSync(buildTarget, { recursive: true });
88
+ for (const name of fs.readdirSync(buildSource)) {
89
+ const target = path.join(buildTarget, name);
90
+ if ((name === 'release-sync.config.json' || name === 'splashxml') && fs.existsSync(target)) continue;
91
+ fs.cpSync(path.join(buildSource, name), target, { recursive: true });
92
+ }
93
+ fs.copyFileSync(path.join(commonFiles, 'finalrelease'), path.join(projectRoot, 'finalrelease'));
94
+ if (options.copyAssets !== false) {
95
+ for (const name of fs.readdirSync(commonFiles)) {
96
+ if (name === 'buildCodeplay' || name === 'scripts-screenshot') continue;
97
+ fs.cpSync(path.join(commonFiles, name), path.join(projectRoot, name), { recursive: true });
98
+ }
99
+ }
100
+ require('../files/buildCodeplay/splash-setup.cjs').syncSplashSetup(projectRoot);
101
+ migrateAppConfigurator(projectRoot);
102
+ syncAndroidR8Rules(projectRoot, { installGradleHook: true });
103
+ pkg.scripts = scripts;
104
+ fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2) + '\n');
105
+ // Cleanup happens only after replacement assets and package commands exist.
106
+ removeVersionedBuildScripts(projectRoot);
107
+ console.log('codeplay-common: unversioned build scripts copied to app buildCodeplay; app-owned settings preserved.');
108
+ // Coupled IAP/AdMob/Home migrations run together during before-build.
109
+ return pkg;
110
+ }
111
+ module.exports = { install, findProjectRoot, migrateAppScripts, migrateAppConfigurator };
112
+ if (require.main === module) {
113
+ try { install(); } catch (error) { console.error(error.message); process.exitCode = 1; }
114
+ }
@@ -1,3 +1,3 @@
1
- // Preserve working app files during preinstall. Postinstall migrates commands
2
- // first, then removes only recognized copied build scripts.
1
+ // Preserve working app files during preinstall. Postinstall migrates commands
2
+ // first, then removes only recognized copied build scripts.
3
3
  console.log('codeplay-common: preserving app files until installation completes.');