@threenative/runtime-native 0.2.0 → 0.3.1

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.
@@ -16,12 +16,41 @@ import {
16
16
  } from 'node:fs';
17
17
  import { tmpdir } from 'node:os';
18
18
  import { dirname, join, resolve } from 'node:path';
19
- import { pathToFileURL } from 'node:url';
19
+ import { fileURLToPath, pathToFileURL } from 'node:url';
20
+
21
+ import { assertNativeAssetsDecodable, deriveDesktopWebpSupport } from './asset-preflight.mjs';
22
+ import { installPrebuilt } from './install-prebuilt.mjs';
23
+
24
+ const runtimeRoot = resolve(fileURLToPath(new URL('..', import.meta.url)));
25
+
26
+ /**
27
+ * Resolve the desktop runtime binary a consumer build compiles against.
28
+ *
29
+ * A published install ships no compiled runtime until the postinstall hook fetches one, so a
30
+ * missing `--runtime` installs from the release manifest rather than failing with a bare
31
+ * "missing file". `THREENATIVE_RUNTIME_SOURCE` remains the decoder-preflight source only: it
32
+ * never selects or substitutes the runtime binary, and no code path here reads a checkout as
33
+ * the runtime. `options.runtimeSource` is an explicit test seam for the preflight directory.
34
+ */
35
+ export async function resolveDesktopRuntime(explicit, options = {}) {
36
+ if (explicit) {
37
+ if (!existsSync(explicit)) throw new Error(`Missing prebuilt runtime for '${process.platform}-${process.arch}': ${explicit}`);
38
+ return explicit;
39
+ }
40
+ const sourceOverride = options.runtimeSource ?? process.env.THREENATIVE_RUNTIME_SOURCE;
41
+ if (sourceOverride) {
42
+ throw new Error(
43
+ `Desktop source-checkout preflight is set (THREENATIVE_RUNTIME_SOURCE=${sourceOverride}) but no --runtime was provided. ` +
44
+ 'Pass the checkout-built --runtime explicitly for a maintainer build; consumer builds unset the override and install from the release manifest.',
45
+ );
46
+ }
47
+ return installPrebuilt({ ...options.install, reuse: true });
48
+ }
20
49
 
21
50
  export const DEFAULT_DESKTOP_CONFIG = {
22
51
  app: { id: 'com.threenative.game', name: 'ThreeNative', version: '0.1.0', build: 1 },
23
- display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false },
24
- window: { title: 'ThreeNative', width: 1280, height: 720, resizable: true },
52
+ display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false, maxFps: 60 },
53
+ window: { title: 'ThreeNative', width: 1280, height: 720, maximized: false, resizable: true },
25
54
  };
26
55
 
27
56
  function readConfig(configPath) {
@@ -38,12 +67,15 @@ export function parseArgs(args) {
38
67
  for (let index = 0; index < args.length; index += 2) {
39
68
  const flag = args[index];
40
69
  const value = args[index + 1];
41
- if (!['--assets', '--bundle', '--config', '--output', '--runtime'].includes(flag) || !value) {
42
- throw new Error('Usage: package-desktop.mjs --bundle FILE --runtime FILE --output FILE [--assets DIR] [--config FILE]');
70
+ if (!['--assets', '--bundle', '--config', '--output', '--runtime', '--ui'].includes(flag) || !value) {
71
+ throw new Error('Usage: package-desktop.mjs --bundle FILE --output FILE [--runtime FILE] [--assets DIR] [--ui DIR] [--config FILE]');
43
72
  }
44
73
  options[flag.slice(2)] = resolve(value);
45
74
  }
46
- for (const required of ['bundle', 'output', 'runtime']) {
75
+ // `--runtime` is optional: a consumer build with no `--runtime` installs the verified
76
+ // prebuilt from the release manifest via resolveDesktopRuntime. A maintainer build passes
77
+ // the checkout-built binary explicitly.
78
+ for (const required of ['bundle', 'output']) {
47
79
  if (!options[required]) throw new Error(`Missing --${required}.`);
48
80
  }
49
81
  return options;
@@ -54,9 +86,23 @@ export function packageDesktop(options) {
54
86
  if (!['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'win32-x64'].includes(key)) {
55
87
  throw new Error(`Unsupported desktop platform '${key}'.`);
56
88
  }
57
- for (const [label, file] of [['native bundle', options.bundle], ['prebuilt runtime', options.runtime]]) {
58
- if (!existsSync(file)) throw new Error(`Missing ${label} for '${key}': ${file}`);
89
+ if (!options.bundle || !existsSync(options.bundle)) {
90
+ throw new Error(`Missing native bundle for '${key}': ${options.bundle ?? '(not provided)'}`);
91
+ }
92
+ // An explicit `--runtime` keeps the original sync body: the preflight failure the
93
+ // decoder tests assert stays a sync throw. Only the missing-runtime install is async.
94
+ if (options.runtime) {
95
+ if (!existsSync(options.runtime)) {
96
+ throw new Error(`Missing prebuilt runtime for '${key}': ${options.runtime}`);
97
+ }
98
+ return compileDesktopArtifact(options, options.runtime);
59
99
  }
100
+ return resolveDesktopRuntime(undefined, { runtimeSource: options.runtimeSource, install: options.install }).then((runtime) =>
101
+ compileDesktopArtifact(options, runtime),
102
+ );
103
+ }
104
+
105
+ function compileDesktopArtifact(options, runtime) {
60
106
  const output = process.platform === 'win32' && !options.output.endsWith('.exe')
61
107
  ? `${options.output}.exe`
62
108
  : options.output;
@@ -68,6 +114,17 @@ export function packageDesktop(options) {
68
114
  options.assets,
69
115
  staging,
70
116
  options.config === undefined ? undefined : readConfig(options.config),
117
+ process.env.THREENATIVE_RUNTIME_SOURCE ?? runtimeRoot,
118
+ );
119
+ // The UI bundle sits beside the executable rather than inside it. Desktop compiles to one
120
+ // file, but the overlay's web view reads its page from a real path — that is what gives it a
121
+ // real origin, the way `WebViewAssetLoader` does on Android, and it is the difference between
122
+ // `fetch` behaving as it does on web and not. A game with the native UI renderer ships neither
123
+ // the directory nor an overlay.
124
+ stageDesktopUi(
125
+ options.ui,
126
+ options.config === undefined ? 'native' : readConfig(options.config).ui?.renderer ?? 'native',
127
+ join(dirname(output), 'ui'),
71
128
  );
72
129
  const args = [
73
130
  'compile',
@@ -79,7 +136,7 @@ export function packageDesktop(options) {
79
136
  '--out',
80
137
  output,
81
138
  ];
82
- const result = spawnSync(options.runtime, args, { encoding: 'utf8', stdio: 'inherit' });
139
+ const result = spawnSync(runtime, args, { encoding: 'utf8', stdio: 'inherit' });
83
140
  if (result.error) throw result.error;
84
141
  if (result.status !== 0)
85
142
  throw new Error(`Runtime packager exited with code ${result.status ?? 'unknown'}.`);
@@ -91,12 +148,60 @@ export function packageDesktop(options) {
91
148
  return output;
92
149
  }
93
150
 
94
- export function stageDesktopFiles(bundle, assets, staging, config = undefined) {
151
+ /**
152
+ * Stage the built UI bundle beside the desktop executable.
153
+ *
154
+ * Fails closed both ways, for the same reasons the Android packager does: a `web` game with no
155
+ * built UI would install, launch and show nothing over a working game, and a `native` game must
156
+ * ship no bundle at all.
157
+ */
158
+ export function stageDesktopUi(ui, renderer, destination) {
159
+ rmSync(destination, { force: true, recursive: true });
160
+ if (renderer !== 'web') {
161
+ if (ui) {
162
+ throw new Error(
163
+ `TN_UI_BUNDLE_UNEXPECTED: a UI bundle was staged for a game whose ui.renderer is '${renderer}'. ` +
164
+ 'The native renderer ships no web view; remove the bundle or set ui.renderer to "web".',
165
+ );
166
+ }
167
+ return [];
168
+ }
169
+ if (!ui || !existsSync(ui)) {
170
+ throw new Error(
171
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "web" but no built UI was found at ${ui ?? '(not provided)'}. ` +
172
+ 'Build the UI before packaging, or set ui.renderer to "native".',
173
+ );
174
+ }
175
+ if (!statSync(ui).isDirectory()) throw new Error(`TN_UI_BUNDLE_MISSING: not a directory: ${ui}`);
176
+ if (!existsSync(join(ui, 'index.html'))) {
177
+ throw new Error(
178
+ `TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`,
179
+ );
180
+ }
181
+ mkdirSync(destination, { recursive: true });
182
+ cpSync(ui, destination, { recursive: true });
183
+ return readdirSync(destination);
184
+ }
185
+
186
+ export function stageDesktopFiles(
187
+ bundle,
188
+ assets,
189
+ staging,
190
+ config = undefined,
191
+ runtimeSource = runtimeRoot,
192
+ ) {
95
193
  mkdirSync(staging, { recursive: true });
96
194
  if (assets && existsSync(assets)) {
97
195
  if (!statSync(assets).isDirectory()) {
98
196
  throw new Error(`Desktop assets path is not a directory: ${assets}`);
99
197
  }
198
+ // Desktop ran no preflight at all, so an asset the runtime cannot decode reached the same
199
+ // rejected `decodeAudioData` that black-screened an APK — with the packager having already
200
+ // read the bytes on its way past. Same gate, desktop's own derived capabilities.
201
+ assertNativeAssetsDecodable(assets, {
202
+ target: 'desktop',
203
+ capabilities: { webp: deriveDesktopWebpSupport(runtimeSource) },
204
+ });
100
205
  for (const entry of readdirSync(assets)) {
101
206
  if (entry === '.threenative') {
102
207
  throw new Error('TN_NATIVE_ASSET_RESERVED_PATH: public/.threenative is reserved.');
@@ -108,14 +213,29 @@ export function stageDesktopFiles(bundle, assets, staging, config = undefined) {
108
213
  mkdirSync(dirname(entry), { recursive: true });
109
214
  copyFileSync(bundle, entry);
110
215
  if (config !== undefined) {
111
- writeFileSync(join(staging, '.threenative', 'config.json'), `${JSON.stringify(config, null, 2)}\n`);
216
+ const icon = config.app?.icon ?? config.app?.icons?.android?.foreground;
217
+ const packaged = { ...config, app: { ...(config.app ?? {}) } };
218
+ // Flattened deliberately. The embedded config is read by a small scanner in the C++ host, and
219
+ // `renderer` already exists at the top level as the WebGPU preference — a nested lookup for a
220
+ // second `renderer` would find the wrong one. Anything but "web" is the native renderer.
221
+ packaged.uiRenderer = config.ui?.renderer === 'web' ? 'web' : 'native';
222
+ packaged.maxFps = config.display?.maxFps ?? 60;
223
+ if (icon !== undefined) {
224
+ if (!existsSync(icon) || !statSync(icon).isFile()) {
225
+ throw new Error(`TN_CONFIG_BRAND_DESKTOP_MISSING: app icon does not exist: ${icon}`);
226
+ }
227
+ const stagedIcon = join(staging, '.threenative', 'app-icon.png');
228
+ copyFileSync(icon, stagedIcon);
229
+ packaged.app.icon = '.threenative/app-icon.png';
230
+ }
231
+ writeFileSync(join(staging, '.threenative', 'config.json'), `${JSON.stringify(packaged, null, 2)}\n`);
112
232
  }
113
233
  return entry;
114
234
  }
115
235
 
116
236
  if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
117
237
  try {
118
- packageDesktop(parseArgs(process.argv.slice(2)));
238
+ await packageDesktop(parseArgs(process.argv.slice(2)));
119
239
  } catch (error) {
120
240
  console.error(error instanceof Error ? error.message : String(error));
121
241
  process.exitCode = 1;
@@ -17,14 +17,17 @@ import { tmpdir } from 'node:os';
17
17
  import { basename, dirname, join, posix, resolve } from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import { spawnSync } from 'node:child_process';
20
+ import { assertNativeAssetsDecodable, deriveIosWebpSupport } from './asset-preflight.mjs';
20
21
  import { downloadReleaseArtifact } from './install-prebuilt.mjs';
22
+ import { PNG } from 'pngjs';
21
23
 
22
24
  export const NATIVE_ORIENTATIONS = ['landscape', 'portrait', 'sensor'];
23
25
  export const DEFAULT_IOS_CONFIG = {
24
26
  app: { id: 'com.threenative.game', name: 'ThreeNative', version: '0.1.13', build: 1 },
25
- display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false },
26
- window: { title: 'ThreeNative', width: 1280, height: 720, resizable: true },
27
+ display: { orientation: 'landscape', fullscreen: true, keepScreenOn: false, maxFps: 60 },
28
+ window: { title: 'ThreeNative', width: 1280, height: 720, maximized: false, resizable: true },
27
29
  };
30
+ const BINARY_PLIST_MAGIC = Buffer.from('bplist00', 'ascii');
28
31
  const IOS_ORIENTATIONS = {
29
32
  landscape: ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'],
30
33
  portrait: ['UIInterfaceOrientationPortrait'],
@@ -41,6 +44,7 @@ function configValue(value, orientation) {
41
44
  const app = source.app && typeof source.app === 'object' ? source.app : {};
42
45
  const display = source.display && typeof source.display === 'object' ? source.display : {};
43
46
  const window = source.window && typeof source.window === 'object' ? source.window : {};
47
+ const bootSplash = source.bootSplash && typeof source.bootSplash === 'object' ? source.bootSplash : {};
44
48
  return {
45
49
  app: { ...DEFAULT_IOS_CONFIG.app, ...app },
46
50
  display: {
@@ -49,6 +53,7 @@ function configValue(value, orientation) {
49
53
  orientation: orientation ?? display.orientation ?? DEFAULT_IOS_CONFIG.display.orientation,
50
54
  },
51
55
  window: { ...DEFAULT_IOS_CONFIG.window, ...window },
56
+ ...(source.bootSplash === undefined ? {} : { bootSplash: { ...bootSplash } }),
52
57
  };
53
58
  }
54
59
 
@@ -61,6 +66,31 @@ function readConfig(configPath) {
61
66
  }
62
67
  }
63
68
 
69
+ function convertBinaryInfoPlist(path) {
70
+ const result = spawnSync('plutil', ['-convert', 'xml1', '-o', '-', path], {
71
+ encoding: 'utf8',
72
+ });
73
+ if (result.error) {
74
+ throw new Error(
75
+ `TN_IOS_INFO_PLIST_CONVERT_FAILED: plutil could not convert ${path}: ${result.error.message}`,
76
+ );
77
+ }
78
+ if (result.status !== 0 || !result.stdout?.includes('<plist')) {
79
+ throw new Error(
80
+ `TN_IOS_INFO_PLIST_CONVERT_FAILED: plutil exited with code ${result.status ?? 'unknown'} for ${path}: ${result.stderr || 'no XML output'}`,
81
+ );
82
+ }
83
+ return result.stdout;
84
+ }
85
+
86
+ function readIosInfoPlist(path, convertInfoPlist = convertBinaryInfoPlist) {
87
+ const source = readFileSync(path);
88
+ if (!source.subarray(0, BINARY_PLIST_MAGIC.length).equals(BINARY_PLIST_MAGIC)) {
89
+ return { format: 'xml', source: source.toString('utf8') };
90
+ }
91
+ return { format: 'binary', source: convertInfoPlist(path, source) };
92
+ }
93
+
64
94
  function xmlEscape(value) {
65
95
  return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;');
66
96
  }
@@ -69,21 +99,35 @@ function plistKey(source, key, value) {
69
99
  const rendered = ` <key>${key}</key>\n <string>${xmlEscape(value)}</string>`;
70
100
  const pattern = new RegExp(`\\s*<key>${key}</key>\\s*<(?:string|true|false)>[\\s\\S]*?</(?:string|true|false)>`, 'u');
71
101
  if (pattern.test(source)) return source.replace(pattern, `\n${rendered}`);
72
- return source.replace(/\s*<\/dict>/u, `\n${rendered}\n</dict>`);
102
+ return source.replace(/\s*<\/dict>\s*<\/plist>/u, `\n${rendered}\n</dict>\n</plist>`);
73
103
  }
74
104
 
75
105
  function plistBoolean(source, key, value) {
76
106
  const rendered = ` <key>${key}</key>\n <${value ? 'true' : 'false'}/>`;
77
107
  const pattern = new RegExp(`\\s*<key>${key}</key>\\s*<(?:true|false)\\s*/?>`, 'u');
78
108
  if (pattern.test(source)) return source.replace(pattern, `\n${rendered}`);
79
- return source.replace(/\s*<\/dict>/u, `\n${rendered}\n</dict>`);
109
+ return source.replace(/\s*<\/dict>\s*<\/plist>/u, `\n${rendered}\n</dict>\n</plist>`);
80
110
  }
81
111
 
82
112
  function plistInteger(source, key, value) {
83
113
  const rendered = ` <key>${key}</key>\n <integer>${value}</integer>`;
84
114
  const pattern = new RegExp(`\\s*<key>${key}</key>\\s*<integer>[\\s\\S]*?</integer>`, 'u');
85
115
  if (pattern.test(source)) return source.replace(pattern, `\n${rendered}`);
86
- return source.replace(/\s*<\/dict>/u, `\n${rendered}\n</dict>`);
116
+ return source.replace(/\s*<\/dict>\s*<\/plist>/u, `\n${rendered}\n</dict>\n</plist>`);
117
+ }
118
+
119
+ function plistLaunchScreen(source, config) {
120
+ const image = config.bootSplash?.image === undefined ? undefined : 'LaunchImage';
121
+ const inner = [
122
+ ' <key>UIColorName</key>',
123
+ ' <string>TNLaunchBackground</string>',
124
+ ...(image === undefined ? [] : [' <key>UIImageName</key>', ` <string>${image}</string>`]),
125
+ ].join('\n');
126
+ const rendered = ` <key>UILaunchScreen</key>\n <dict>\n${inner}\n </dict>`;
127
+ const pattern = /\s*<key>UILaunchScreen<\/key>\s*<dict>[\s\S]*?<\/dict>/u;
128
+ return pattern.test(source)
129
+ ? source.replace(pattern, `\n${rendered}`)
130
+ : source.replace(/\s*<\/dict>\s*<\/plist>/u, `\n${rendered}\n</dict>\n</plist>`);
87
131
  }
88
132
 
89
133
  function orientationValue(value = 'landscape') {
@@ -111,12 +155,15 @@ export function renderIosInfoPlist(source, orientation = 'landscape') {
111
155
  rendered = plistKey(rendered, 'CFBundleVersion', config.app.build);
112
156
  rendered = plistBoolean(rendered, 'TNFullscreen', config.display.fullscreen);
113
157
  rendered = plistBoolean(rendered, 'TNKeepScreenOn', config.display.keepScreenOn);
158
+ rendered = plistInteger(rendered, 'TNMaxFps', config.display.maxFps);
114
159
  rendered = plistKey(rendered, 'TNWindowTitle', config.window.title);
115
160
  rendered = plistInteger(rendered, 'TNWindowWidth', config.window.width);
116
161
  rendered = plistInteger(rendered, 'TNWindowHeight', config.window.height);
117
162
  rendered = plistBoolean(rendered, 'TNWindowResizable', config.window.resizable);
118
- if (config.app.icon !== undefined) rendered = plistKey(rendered, 'CFBundleIconName', 'AppIcon');
119
- return rendered;
163
+ if (config.app.icon !== undefined || config.app.icons?.ios !== undefined) {
164
+ rendered = plistKey(rendered, 'CFBundleIconName', 'AppIcon');
165
+ }
166
+ return plistLaunchScreen(rendered, config);
120
167
  }
121
168
 
122
169
  function argumentAfter(args, flag) {
@@ -159,15 +206,17 @@ function findApp(directory) {
159
206
  return undefined;
160
207
  }
161
208
 
162
- function compileIosIcon(catalog, output) {
163
- const result = spawnSync(
209
+ export function compileIosAssets(catalog, output, includeAppIcon = false, execute = spawnSync) {
210
+ const iconArguments = includeAppIcon ? ['--app-icon', 'AppIcon'] : [];
211
+ const result = execute(
164
212
  'xcrun',
165
213
  [
166
214
  'actool',
167
215
  '--compile',
168
216
  output,
169
- '--app-icon',
170
- 'AppIcon',
217
+ ...iconArguments,
218
+ '--output-partial-info-plist',
219
+ '/dev/null',
171
220
  '--platform',
172
221
  'iphonesimulator',
173
222
  '--minimum-deployment-target',
@@ -192,10 +241,72 @@ function compileIosIcon(catalog, output) {
192
241
  }
193
242
  }
194
243
 
195
- function stageIosIcon(output, icon, compileIcon = compileIosIcon) {
244
+ function compileIosIcon(catalog, output) {
245
+ return compileIosAssets(catalog, output, true);
246
+ }
247
+
248
+ function assertIosIconSource(icon, label) {
249
+ let image;
250
+ try {
251
+ image = PNG.sync.read(readFileSync(icon));
252
+ } catch (error) {
253
+ throw new Error(
254
+ `TN_CONFIG_ICON_INVALID: ${label} is not a valid PNG file: ${icon} (${error instanceof Error ? error.message : String(error)})`,
255
+ );
256
+ }
257
+ if (image.width !== 1024 || image.height !== 1024) {
258
+ throw new Error(
259
+ `TN_CONFIG_ICON_DIMENSIONS_INVALID: ${label} must be 1024x1024 for iOS AppIcon metadata; received ${image.width}x${image.height}: ${icon}`,
260
+ );
261
+ }
262
+ }
263
+
264
+ function colorComponents(value) {
265
+ const hex = /^#([0-9a-f]{6})$/iu.exec(value ?? '')?.[1] ?? '000000';
266
+ return {
267
+ blue: hex.slice(4, 6),
268
+ green: hex.slice(2, 4),
269
+ red: hex.slice(0, 2),
270
+ };
271
+ }
272
+
273
+ function writeLaunchColor(catalog, value) {
274
+ const colorset = join(catalog, 'LaunchBackground.colorset');
275
+ mkdirSync(colorset, { recursive: true });
276
+ const components = colorComponents(value);
277
+ writeFileSync(
278
+ join(colorset, 'Contents.json'),
279
+ `${JSON.stringify(
280
+ {
281
+ colors: [
282
+ {
283
+ color: {
284
+ 'color-space': 'srgb',
285
+ components: { alpha: '1.000', ...components },
286
+ },
287
+ idiom: 'universal',
288
+ },
289
+ ],
290
+ info: { author: 'xcode', version: 1 },
291
+ },
292
+ null,
293
+ 2,
294
+ )}\n`,
295
+ );
296
+ }
297
+
298
+ function writeAssetCatalogContents(catalog) {
299
+ writeFileSync(
300
+ join(catalog, 'Contents.json'),
301
+ `${JSON.stringify({ info: { author: 'xcode', version: 1 } }, null, 2)}\n`,
302
+ );
303
+ }
304
+
305
+ function stageIosIcon(output, icon, compileIcon = compileIosIcon, options = {}) {
196
306
  if (!existsSync(icon) || !statSync(icon).isFile()) {
197
307
  throw new Error(`TN_CONFIG_ICON_MISSING: app.icon does not exist: ${icon}`);
198
308
  }
309
+ assertIosIconSource(icon, 'app.icon');
199
310
  const temporary = mkdtempSync(join(tmpdir(), 'threenative-ios-icon-'));
200
311
  try {
201
312
  const catalog = join(temporary, 'Assets.xcassets');
@@ -203,20 +314,41 @@ function stageIosIcon(output, icon, compileIcon = compileIosIcon) {
203
314
  const compiled = join(temporary, 'compiled');
204
315
  mkdirSync(appIcon, { recursive: true });
205
316
  mkdirSync(compiled, { recursive: true });
317
+ writeAssetCatalogContents(catalog);
206
318
  copyFileSync(icon, join(appIcon, 'AppIcon-1024.png'));
319
+ const appearances = options.variants ?? {};
320
+ const images = [
321
+ {
322
+ filename: 'AppIcon-1024.png',
323
+ idiom: 'universal',
324
+ platform: 'ios',
325
+ scale: '1x',
326
+ size: '1024x1024',
327
+ },
328
+ ];
329
+ for (const [appearance, source] of [['dark', appearances.dark], ['tinted', appearances.tinted]]) {
330
+ if (source === undefined) continue;
331
+ if (!existsSync(source) || !statSync(source).isFile()) {
332
+ throw new Error(`TN_CONFIG_BRAND_IOS_${appearance.toUpperCase()}_MISSING: ${source}`);
333
+ }
334
+ assertIosIconSource(source, `app.icons.ios.${appearance}`);
335
+ const filename = `AppIcon-1024-${appearance}.png`;
336
+ copyFileSync(source, join(appIcon, filename));
337
+ images.push({
338
+ appearances: [{ appearance: 'luminosity', value: appearance }],
339
+ filename,
340
+ idiom: 'universal',
341
+ platform: 'ios',
342
+ scale: '1x',
343
+ size: '1024x1024',
344
+ });
345
+ }
346
+ writeLaunchColor(catalog, options.backgroundColor ?? '#000000');
207
347
  writeFileSync(
208
348
  join(appIcon, 'Contents.json'),
209
349
  `${JSON.stringify(
210
350
  {
211
- images: [
212
- {
213
- idiom: 'universal',
214
- platform: 'ios',
215
- size: '1024x1024',
216
- scale: '1x',
217
- filename: 'AppIcon-1024.png',
218
- },
219
- ],
351
+ images,
220
352
  info: { author: 'xcode', version: 1 },
221
353
  },
222
354
  null,
@@ -235,14 +367,74 @@ function stageIosIcon(output, icon, compileIcon = compileIosIcon) {
235
367
  }
236
368
  }
237
369
 
370
+ function stageIosLaunchAssets(output, backgroundColor, compileAssets = compileIosAssets) {
371
+ const temporary = mkdtempSync(join(tmpdir(), 'threenative-ios-launch-'));
372
+ try {
373
+ const catalog = join(temporary, 'Assets.xcassets');
374
+ const compiled = join(temporary, 'compiled');
375
+ mkdirSync(compiled, { recursive: true });
376
+ mkdirSync(catalog, { recursive: true });
377
+ writeAssetCatalogContents(catalog);
378
+ writeLaunchColor(catalog, backgroundColor);
379
+ compileAssets(catalog, compiled);
380
+ const assetsCar = join(compiled, 'Assets.car');
381
+ if (!existsSync(assetsCar) || !statSync(assetsCar).isFile() || statSync(assetsCar).size === 0) {
382
+ throw new Error('TN_IOS_LAUNCH_COMPILE_FAILED: actool did not produce a usable Assets.car.');
383
+ }
384
+ copyFileSync(assetsCar, join(output, 'Assets.car'));
385
+ } finally {
386
+ rmSync(temporary, { force: true, recursive: true });
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Stage the built UI bundle into the app bundle, where `WKURLSchemeHandler` serves it.
392
+ *
393
+ * Same two refusals as Android and desktop, because the same two mistakes are possible: a `web`
394
+ * game with no built UI would launch and show nothing over a working game, and a `native` game must
395
+ * carry no bundle at all.
396
+ *
397
+ * **The iOS host that would read this has never run.** See `ios/ui_overlay_ios.mm`.
398
+ */
399
+ export function stageIosUi(ui, renderer, destination) {
400
+ rmSync(destination, { force: true, recursive: true });
401
+ if (renderer !== 'web') {
402
+ if (ui) {
403
+ throw new Error(
404
+ `TN_UI_BUNDLE_UNEXPECTED: a UI bundle was staged for a game whose ui.renderer is '${renderer}'. ` +
405
+ 'The native renderer ships no web view; remove the bundle or set ui.renderer to "web".',
406
+ );
407
+ }
408
+ return [];
409
+ }
410
+ if (!ui || !existsSync(ui)) {
411
+ throw new Error(
412
+ `TN_UI_BUNDLE_MISSING: ui.renderer is "web" but no built UI was found at ${ui ?? '(not provided)'}. ` +
413
+ 'Build the UI before packaging, or set ui.renderer to "native".',
414
+ );
415
+ }
416
+ if (!statSync(ui).isDirectory()) throw new Error(`TN_UI_BUNDLE_MISSING: not a directory: ${ui}`);
417
+ if (!existsSync(join(ui, 'index.html'))) {
418
+ throw new Error(
419
+ `TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`,
420
+ );
421
+ }
422
+ mkdirSync(destination, { recursive: true });
423
+ cpSync(ui, destination, { recursive: true });
424
+ return listFiles(destination);
425
+ }
426
+
238
427
  export function stageIosSimulatorApp({
239
428
  assets,
240
429
  bundle,
430
+ ui = undefined,
241
431
  output,
242
432
  templateApp,
243
433
  orientation = undefined,
244
434
  config = undefined,
245
435
  compileIcon = compileIosIcon,
436
+ compileAssets = compileIosAssets,
437
+ convertInfoPlist = convertBinaryInfoPlist,
246
438
  }) {
247
439
  const declared = configValue(config, orientation);
248
440
  const declaredOrientation = orientationValue(declared.display.orientation);
@@ -264,14 +456,42 @@ export function stageIosSimulatorApp({
264
456
  const game = join(output, 'game');
265
457
  rmSync(game, { force: true, recursive: true });
266
458
  mkdirSync(game, { recursive: true });
459
+ stageIosUi(ui, declared.ui?.renderer === 'web' ? 'web' : 'native', join(output, 'ui'));
267
460
  const plist = join(output, 'Info.plist');
268
- writeFileSync(plist, renderIosInfoPlist(readFileSync(plist, 'utf8'), declared));
269
- if (declared.app.icon !== undefined) stageIosIcon(output, declared.app.icon, compileIcon);
461
+ const infoPlist = readIosInfoPlist(plist, convertInfoPlist);
462
+ writeFileSync(plist, renderIosInfoPlist(infoPlist.source, declared));
463
+ const iosVariants = declared.app.icons?.ios ?? {};
464
+ const icon = declared.app.icon ?? iosVariants.dark ?? iosVariants.tinted;
465
+ if (icon !== undefined) {
466
+ stageIosIcon(output, icon, compileIcon, {
467
+ backgroundColor: declared.bootSplash?.backgroundColor,
468
+ variants: iosVariants,
469
+ });
470
+ } else if (declared.bootSplash !== undefined) {
471
+ stageIosLaunchAssets(
472
+ output,
473
+ declared.bootSplash.backgroundColor ?? '#000000',
474
+ compileAssets,
475
+ );
476
+ }
477
+ if (declared.bootSplash?.image !== undefined) {
478
+ if (!existsSync(declared.bootSplash.image) || !statSync(declared.bootSplash.image).isFile()) {
479
+ throw new Error(`TN_CONFIG_BRAND_SPLASH_MISSING: ${declared.bootSplash.image}`);
480
+ }
481
+ copyFileSync(declared.bootSplash.image, join(output, 'LaunchImage.png'));
482
+ }
270
483
  let assetFiles = [];
271
484
  if (assets && existsSync(assets)) {
272
485
  if (!statSync(assets).isDirectory()) {
273
486
  throw new Error(`iOS assets path is not a directory: ${assets}`);
274
487
  }
488
+ // iOS ran no preflight at all. Its capability set is not Android's: `CMakeLists.txt` excludes
489
+ // IOS from every libwebp branch, so a WebP texture that packages for Android must still be
490
+ // refused here, while the audio answer is the same on every native target.
491
+ assertNativeAssetsDecodable(assets, {
492
+ target: 'ios',
493
+ capabilities: { webp: deriveIosWebpSupport() },
494
+ });
275
495
  assetFiles = listFiles(assets);
276
496
  for (const file of assetFiles) {
277
497
  const staged = join(game, file);
@@ -283,13 +503,16 @@ export function stageIosSimulatorApp({
283
503
  assets: assetFiles.map((path) => ({ path, sha256: checksum(join(game, path)) })),
284
504
  bundleSha256: checksum(bundle),
285
505
  host: 'ios-simulator-arm64',
506
+ infoPlistFormat: infoPlist.format,
286
507
  orientation: declaredOrientation,
287
508
  appId: declared.app.id,
288
509
  appName: declared.app.name,
289
510
  version: declared.app.version,
290
511
  build: declared.app.build,
291
- ...(declared.app.icon === undefined ? {} : { icon: declared.app.icon }),
292
- ...(declared.app.icon === undefined ? {} : { iconArtifact: 'Assets.car' }),
512
+ ...(icon === undefined ? {} : { icon }),
513
+ ...(icon === undefined ? {} : { iconArtifact: 'Assets.car' }),
514
+ ...(declared.bootSplash?.image === undefined ? {} : { launchImage: 'LaunchImage.png' }),
515
+ launchBackground: declared.bootSplash?.backgroundColor ?? '#000000',
293
516
  output,
294
517
  outputBundleSha256: checksum(join(output, 'native-smoke.js')),
295
518
  };
@@ -355,6 +578,7 @@ export async function packageIosSimulator(options) {
355
578
  export function parseIosPackageArgs(args) {
356
579
  return {
357
580
  assets: args.includes('--assets') ? valueAfter(args, '--assets') : undefined,
581
+ ui: args.includes('--ui') ? valueAfter(args, '--ui') : undefined,
358
582
  bundle: valueAfter(args, '--bundle'),
359
583
  output: valueAfter(args, '--output'),
360
584
  config: args.includes('--config') ? valueAfter(args, '--config') : undefined,