crt-ship 0.1.0: CLI, Claude Code skills and templates for shipping mobile games to Google Play and the App Store

This commit is contained in:
CRTkafa 2026-10-10 12:29:20 +00:00
commit ecb3dc3dc3
64 changed files with 4509 additions and 0 deletions

23
cli/shots/browser.ts Normal file
View file

@ -0,0 +1,23 @@
// Playwright is not a dependency of crt-ship: it is resolved from the project (or the crt-ship folder), so a project
// that never renders screenshots never downloads a browser. Launch order: Playwright's own Chromium, then an installed
// Google Chrome (channel "chrome"), so `bunx playwright install chromium` is optional when Chrome is there.
import { join } from 'node:path';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function chromium(root: string): Promise<any> {
for (const base of [root, join(import.meta.dir, '../..')]) {
try {
const p = Bun.resolveSync('playwright', base);
return (await import(p)).chromium;
} catch { /* next */ }
}
throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function launch(root: string, opts: Record<string, unknown>): Promise<any> {
const c = await chromium(root);
try { return await c.launch(opts); } catch (e) {
try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; }
}
}

53
cli/shots/capture.ts Normal file
View file

@ -0,0 +1,53 @@
// Raw frames from a running build of your game (headless Chromium, mobile viewport, touch, device scale).
// crt-ship shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet]
// Each entry of shots.capture.shots: { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }.
// URL = baseUrl + path + (? or &) + query, with "{lang}" replaced. Frames go to <shots.frames>/<lang>/<device>/<name>.png.
// The frame is the screen BELOW the status bar (the template draws one), so the viewport is phone.w x phone.h.
// Tip: give your game URL switches for screenshots (fixed seed, no ads, no tutorial, freeze at a moment).
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { launch } from './browser';
import { DEFAULT_PHONE, DEFAULT_TABLET } from './lib';
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const shots = need(config.shots, 'shots');
const cap = need(shots.capture, 'shots.capture');
const a = ctx.args;
const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id);
const only = a.list('only');
const devices = a.get('device') ? [a.get('device') as 'phone' | 'tablet'] : (['phone', 'tablet'] as const);
const dims = { phone: { ...DEFAULT_PHONE, ...shots.phone }, tablet: { ...DEFAULT_TABLET, ...shots.tablet } };
const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] });
let failed = 0;
try {
for (const lang of langs) for (const device of devices) for (const [name, s] of Object.entries(cap.shots)) {
if (only.length && !only.includes(name)) continue;
const want = s.device ?? 'phone';
if (want !== 'both' && want !== device) continue;
const d = dims[device];
const out = resolve(join(shots.frames, lang, device));
mkdirSync(out, { recursive: true });
const q = (cap.query ?? '').replaceAll('{lang}', lang);
const url = cap.baseUrl.replace(/\/$/, '') + s.path.replaceAll('{lang}', lang) + (q ? (s.path.includes('?') ? '&' : '?') + q : '');
const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: lang });
const page = await c.newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 });
if (s.waitFor) await page.waitForFunction(s.waitFor, null, { timeout: 120000, polling: 50 });
for (const js of s.eval ?? []) await page.evaluate(js);
await page.waitForTimeout(s.delayMs ?? 1000);
await page.screenshot({ path: join(out, `${name}.png`) });
log('shots', `${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`);
} catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); }
await c.close();
}
} finally { await browser.close(); }
if (failed) throw new Error(`${failed} captures failed`);
done('shots', 'capture done');
}

63
cli/shots/feature.html Normal file
View file

@ -0,0 +1,63 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/fonts/fonts.css">
<!-- Play feature graphic, 1024 x 500: logo (or the app name) on the left, a tilted phone with one frame on the right.
feature.html?lang=<id>. Rendered by `crt-ship shots render`. Keep text out of it: Play overlays its own UI. -->
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 1024px; height: 500px; overflow: hidden; background: #000; }
#c { position: relative; width: 1024px; height: 500px; overflow: hidden; isolation: isolate; background: var(--bg); }
.rays { position: absolute; left: 360px; top: 250px; width: 1700px; height: 1700px; transform: translate(-50%, -50%) rotate(8deg); z-index: -4;
opacity: .55; background: repeating-conic-gradient(rgba(255,255,255,.22) 0deg 7deg, rgba(255,255,255,0) 7deg 18deg);
-webkit-mask-image: radial-gradient(closest-side, #000 0%, rgba(0,0,0,.6) 30%, transparent 75%); }
.glow { position: absolute; left: 360px; top: 250px; width: 900px; height: 700px; transform: translate(-50%, -50%); z-index: -3;
background: radial-gradient(closest-side, var(--glow), transparent); }
.vign { position: absolute; inset: 0; z-index: -2; background: radial-gradient(90% 90% at 45% 50%, transparent 60%, rgba(0,0,0,.28) 100%); }
.logo { position: absolute; left: 360px; top: 252px; width: 600px; transform: translate(-50%, -50%) rotate(-3deg); z-index: 5;
filter: drop-shadow(0 14px 22px rgba(0,0,0,.4)); }
.name { position: absolute; left: 360px; top: 250px; transform: translate(-50%, -50%) rotate(-3deg); z-index: 5; width: 640px; text-align: center;
font-family: var(--tf); font-size: 104px; line-height: .95; color: #fff; -webkit-text-stroke: 9px var(--ink); paint-order: stroke fill;
filter: drop-shadow(0 8px 0 var(--ink)) drop-shadow(0 14px 22px rgba(0,0,0,.35)); }
.tel { position: absolute; left: 748px; top: 36px; width: 232px; aspect-ratio: var(--ar); transform: rotate(7deg); z-index: 3;
border-radius: 40px; padding: 6px;
background: linear-gradient(140deg, #f4f4f6 0%, #9da0a8 8%, #3c3e44 20%, #1a1b1f 50%, #3c3e44 82%, #c8cad0 100%);
box-shadow: inset 0 0 0 1px rgba(255,255,255,.6), inset 0 0 0 3px #101114, 0 20px 50px var(--shadow); }
.screen { position: relative; width: 100%; height: 100%; overflow: hidden; border-radius: 34px; background: #000; }
.screen img { position: absolute; left: 0; bottom: 0; width: 100%; height: var(--appH); object-fit: cover; object-position: top; }
.screen .bar { position: absolute; left: 0; right: 0; top: 0; height: var(--barH); background: #0b0b10 center top / 100% 60000% no-repeat; }
.island { position: absolute; top: 6px; left: 50%; transform: translateX(-50%); width: 30%; height: 20px; background: #000; border-radius: 99px; }
.spark { position: absolute; width: var(--s); height: var(--s); transform: translate(-50%, -50%); background: #fff; z-index: -1;
clip-path: polygon(50% 0, 58% 42%, 100% 50%, 58% 58%, 50% 100%, 42% 58%, 0 50%, 42% 42%); opacity: var(--o); filter: drop-shadow(0 0 6px #fff); }
</style>
</head>
<body>
<div id="c">
<div class="glow"></div><div class="rays"></div><div class="vign"></div>
<div class="tel"><div class="screen"><div class="bar" id="bar"></div><img id="f"><div class="island"></div></div></div>
</div>
<script type="module">
const lang = new URLSearchParams(location.search).get('lang');
const job = await (await fetch(`/job.json?lang=${encodeURIComponent(lang)}&feature=1`)).json();
const P = job.palette, R = document.documentElement.style, dev = job.phone;
R.setProperty('--bg', `linear-gradient(160deg, ${P.bg[0]} 0%, ${P.bg[1]} 50%, ${P.bg[2]} 100%)`);
R.setProperty('--glow', P.glow); R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow);
R.setProperty('--tf', `'${job.fonts.title}', sans-serif`);
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);
const c = document.getElementById('c');
const src = `/frames/${encodeURIComponent(lang)}/phone/${encodeURIComponent(job.frame)}`;
document.getElementById('f').src = src;
document.getElementById('bar').style.backgroundImage = `url('${src}')`;
c.insertAdjacentHTML('beforeend', job.logo ? '<img class="logo" src="/logo">' : `<div class="name">${String(job.appName).replace(/</g, '&lt;')}</div>`);
let seed = 7; const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296);
for (let i = 0; i < 22; i++)
c.insertAdjacentHTML('beforeend', `<i class="spark" style="left:${rnd() * 1024}px;top:${rnd() * 500}px;--s:${8 + rnd() * 18}px;--o:${.5 + rnd() * .5}"></i>`);
await document.fonts.ready;
await Promise.all([...document.images].map(i => i.decode().catch(() => {})));
document.body.dataset.ready = '1';
</script>
</body>
</html>

61
cli/shots/fonts.ts Normal file
View file

@ -0,0 +1,61 @@
// Downloads the fonts the screenshot template needs, subset by Google Fonts (css2 `text=`) to exactly the characters
// your copy uses, so even CJK stays small: title + body family for Latin text, plus one Noto family per non-Latin
// script found in the copy (CJK, Arabic, Hebrew, Devanagari, Thai, Cyrillic / Greek).
// crt-ship shots fonts (re-run after editing the copy)
// Out: <project>/.crt-ship/fonts/*.woff2 + fonts.css. All of these fonts are SIL Open Font License 1.1.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { type CopyFile, copyText, scriptFont } from './lib';
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join('') + '·';
async function fetchSubset(family: string, chars: string, variable: boolean): Promise<ArrayBuffer> {
const fam = encodeURIComponent(family) + (variable ? ':wght@100..900' : '');
let res = await fetch(`https://fonts.googleapis.com/css2?family=${fam}&text=${encodeURIComponent(chars)}&display=block`, { headers: { 'user-agent': UA } });
if (!res.ok && variable) return fetchSubset(family, chars, false);
if (!res.ok) throw new Error(`${family}: ${res.status} ${await res.text()}`);
const src = /url\((https:[^)]+)\)/.exec(await res.text())?.[1];
if (!src) throw new Error(`${family}: no font url`);
res = await fetch(src, { headers: { 'user-agent': UA } });
return res.arrayBuffer();
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const shots = need(config.shots, 'shots');
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
const dir = join(root, '.crt-ship', 'fonts');
mkdirSync(dir, { recursive: true });
const title = shots.fonts?.title ?? 'Lilita One', body = shots.fonts?.body ?? 'Montserrat';
const latin = new Set(ASCII);
const scripts = new Map<string, { family: string; chars: Set<string> }>();
for (const [lang, c] of Object.entries(copy)) {
const text = copyText(lang, c);
const s = scriptFont(lang, text);
if (!s) { for (const ch of text) latin.add(ch); continue; }
const cur = scripts.get(s.slug) ?? { family: s.family, chars: new Set(ASCII) };
for (const ch of text) cur.chars.add(ch);
scripts.set(s.slug, cur);
}
for (const ch of config.app.name) latin.add(ch);
const latinChars = [...latin].sort().join('');
let css = '/* Generated by crt-ship shots fonts (Google Fonts, SIL Open Font License 1.1), subset to the copy. */\n';
const jobs: [string, string, string, boolean][] = [[title, 'title', latinChars, false], [body, 'body', latinChars, true],
...[...scripts.entries()].map(([slug, s]) => [s.family, slug, [...s.chars].sort().join(''), true] as [string, string, string, boolean])];
for (const [family, slug, chars, variable] of jobs) {
const bin = await fetchSubset(family, chars, variable);
const file = `${slug}.woff2`;
writeFileSync(join(dir, file), Buffer.from(bin));
const face = slug === 'title' ? title : slug === 'body' ? body : `Store ${slug}`;
css += `@font-face { font-family: '${face}'; font-weight: 100 900; src: url(${file}) format('woff2'); }\n`;
log('shots', `${file.padEnd(18)} ${family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...chars].length} chars`);
}
writeFileSync(join(dir, 'fonts.css'), css);
done('shots', 'fonts done');
}

34
cli/shots/jpeg.ts Normal file
View file

@ -0,0 +1,34 @@
// JPEG copies of the Play renders (play, tab7, tab10, feature): about 4x smaller, so `play images` uploads much faster.
// The App Store screenshots stay PNG.
// crt-ship shots jpeg [--q 92] [--lang en,tr]
import { existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import type { Ctx } from '../lib/ctx';
import { done, log } from '../lib/log';
/** ffmpeg's mjpeg -q:v (2 best .. 31 worst) for a 0-100 quality. */
export const ffmpegQ = (q: number): number => Math.max(2, Math.min(31, Math.round(2 + (100 - q) * 0.29)));
export async function run(ctx: Ctx): Promise<void> {
const { config, resolve } = ctx.loaded;
const src = resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders');
const q = ctx.args.num('q', 92);
const langs = ctx.args.list('lang').length ? ctx.args.list('lang') : config.languages.map(l => l.id);
const sips = spawnSync('sh', ['-c', 'command -v sips']).status === 0;
let n = 0;
for (const lang of langs) for (const sub of ['play', 'tab7', 'tab10', 'feature']) {
const dir = join(src, lang, sub);
if (!existsSync(dir)) continue;
for (const f of readdirSync(dir).filter(f => f.endsWith('.png'))) {
const inp = join(dir, f), out = inp.replace(/\.png$/, '.jpg');
const r = sips
? spawnSync('sips', ['-s', 'format', 'jpeg', '-s', 'formatOptions', String(q), inp, '--out', out])
: spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', inp, '-q:v', String(ffmpegQ(q)), out]);
if (r.status !== 0) throw new Error(`jpeg failed for ${inp}`);
n++;
}
log('shots', `${lang}/${sub}: jpeg q${q}`);
}
done('shots', `${n} JPEG copies`);
}

76
cli/shots/lib.ts Normal file
View file

@ -0,0 +1,76 @@
// Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data.
import type { Palette, ShotsConfig } from '../lib/config';
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), play = Play phone 9:16,
* tab7 / tab10 = Play 7" / 10" tablets (tablet frames), feature = Play feature graphic. */
export const SIZES: Record<string, { w: number; h: number; device?: 'tablet'; feature?: true }> = {
ios69: { w: 1320, h: 2868 },
ios65: { w: 1284, h: 2778 },
play: { w: 1080, h: 1920 },
tab7: { w: 1080, h: 1920, device: 'tablet' },
tab10: { w: 1440, h: 2560, device: 'tablet' },
feature: { w: 1024, h: 500, feature: true },
};
export const PALETTES: Record<string, Palette> = {
fire: { bg: ['#ff3d2e', '#ff7a1a', '#ffc43a'], glow: 'rgba(255,240,150,.95)', ink: '#6e1300', shadow: 'rgba(120,10,0,.45)' },
violet: { bg: ['#2b1676', '#6a2fe0', '#ff5fb8'], glow: 'rgba(255,170,240,.75)', ink: '#22095e', shadow: 'rgba(30,0,80,.55)' },
blast: { bg: ['#ff2d55', '#ff6a2a', '#ffb02e'], glow: 'rgba(255,236,140,.9)', ink: '#6a0a1e', shadow: 'rgba(110,0,30,.45)' },
green: { bg: ['#0fa35c', '#3cc96a', '#ff6f91'], glow: 'rgba(230,255,170,.85)', ink: '#0a4a2a', shadow: 'rgba(0,60,30,.45)' },
night: { bg: ['#14105a', '#4a2bd6', '#11b8ff'], glow: 'rgba(140,230,255,.85)', ink: '#170d55', shadow: 'rgba(10,0,70,.55)' },
sky: { bg: ['#0a6fe0', '#21a8ff', '#7be3ff'], glow: 'rgba(255,255,255,.85)', ink: '#06336e', shadow: 'rgba(0,40,100,.45)' },
gold: { bg: ['#ff8a00', '#ffb300', '#ffe14a'], glow: 'rgba(255,255,220,.95)', ink: '#6b2c00', shadow: 'rgba(120,50,0,.4)' },
candy: { bg: ['#d01f7a', '#ff4f8b', '#ff9f43'], glow: 'rgba(255,220,180,.9)', ink: '#5e0636', shadow: 'rgba(90,0,50,.45)' },
};
export const palette = (p: string | Palette | undefined): Palette => {
if (!p) return PALETTES.fire!;
if (typeof p !== 'string') return p;
const hit = PALETTES[p];
if (!hit) throw new Error(`unknown palette "${p}" (${Object.keys(PALETTES).join(', ')}) or pass { bg, glow, ink, shadow }`);
return hit;
};
export interface SceneCopy { eyebrow?: string; title: [string, string]; sub?: string; badges?: [string, string?][] }
export type CopyFile = Record<string, Record<string, SceneCopy>>;
/** Noto family + slug for the first non-Latin script found in a language's text, or null for Latin-only text. */
export function scriptFont(lang: string, text: string): { family: string; slug: string } | null {
if (/\p{Script=Hangul}/u.test(text)) return { family: 'Noto Sans KR', slug: 'kr' };
if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) return { family: 'Noto Sans JP', slug: 'jp' };
if (/\p{Script=Han}/u.test(text)) return /Hant|TW|HK/.test(lang) ? { family: 'Noto Sans TC', slug: 'tc' } : { family: 'Noto Sans SC', slug: 'sc' };
if (/\p{Script=Arabic}/u.test(text)) return { family: 'Noto Sans Arabic', slug: 'arabic' };
if (/\p{Script=Hebrew}/u.test(text)) return { family: 'Noto Sans Hebrew', slug: 'hebrew' };
if (/\p{Script=Devanagari}/u.test(text)) return { family: 'Noto Sans Devanagari', slug: 'devanagari' };
if (/\p{Script=Bengali}/u.test(text)) return { family: 'Noto Sans Bengali', slug: 'bengali' };
if (/\p{Script=Thai}/u.test(text)) return { family: 'Noto Sans Thai', slug: 'thai' };
if (/[\p{Script=Cyrillic}\p{Script=Greek}]/u.test(text)) return { family: 'Noto Sans', slug: 'cyrgreek' };
return null;
}
/** Every string of a language's copy (for font subsetting and script detection), upper-cased eyebrows included. */
export function copyText(lang: string, c: Record<string, SceneCopy> | undefined): string {
if (!c) return '';
return Object.values(c).flatMap(s => [s.eyebrow ?? '', (s.eyebrow ?? '').toLocaleUpperCase(lang), ...s.title, s.sub ?? '',
...(s.badges ?? []).flat().filter((x): x is string => !!x)]).join('');
}
/** Problems with the copy file for the configured scenes and languages. */
export function validateCopy(copy: CopyFile, shots: ShotsConfig, langs: string[]): string[] {
const e: string[] = [];
for (const lang of langs) {
const c = copy[lang];
if (!c) { e.push(`${lang}: no copy`); continue; }
for (const s of shots.scenes) {
const sc = c[s.id];
if (!sc) { e.push(`${lang} scene ${s.id}: missing`); continue; }
if (!Array.isArray(sc.title) || sc.title.length !== 2) e.push(`${lang} scene ${s.id}: title must be [line1, line2]`);
const slots = s.badges?.length ?? 0;
if ((sc.badges?.length ?? 0) > slots) e.push(`${lang} scene ${s.id}: ${sc.badges!.length} badges but the scene has ${slots} slots`);
}
}
return e;
}
export const DEFAULT_PHONE = { w: 440, h: 902, dpr: 3, bar: 54 };
export const DEFAULT_TABLET = { w: 800, h: 1240, dpr: 2, bar: 40 };

129
cli/shots/render.ts Normal file
View file

@ -0,0 +1,129 @@
// Store screenshots + Play feature graphic at exact pixel sizes, from raw game frames and per-language copy.
// crt-ship shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--no-sheet] [--port 8792]
// Out: <shots.out>/<lang>/<size>/NN.png (24-bit RGB: Play rejects alpha / palette PNGs), <lang>/feature/1024x500.png,
// and <lang>/sheet.png (contact sheet of every size, for a quick review). Needs playwright + ffmpeg.
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { join, relative } from 'node:path';
import { spawnSync } from 'node:child_process';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { launch } from './browser';
import { type CopyFile, DEFAULT_PHONE, DEFAULT_TABLET, SIZES, copyText, palette, scriptFont, validateCopy } from './lib';
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' };
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const shots = need(config.shots, 'shots');
const a = ctx.args;
const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id);
const sizes = a.list('size').length ? a.list('size') : Object.keys(SIZES);
const sceneIds = a.list('scenes').length ? a.list('scenes') : shots.scenes.map(s => s.id);
for (const s of sizes) if (!SIZES[s]) throw new Error(`unknown size ${s} (${Object.keys(SIZES).join(', ')})`);
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
const problems = validateCopy(copy, shots, langs);
if (problems.length) throw new Error('shots copy:\n ' + problems.join('\n '));
const framesDir = resolve(shots.frames), outDir = resolve(shots.out);
const fontsDir = join(root, '.crt-ship', 'fonts');
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .crt-ship/fonts/fonts.css: run `crt-ship shots fonts` first (falling back to system fonts)');
const phone = { ...DEFAULT_PHONE, ...shots.phone }, tablet = { ...DEFAULT_TABLET, ...shots.tablet };
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
const fonts = { title: shots.fonts?.title ?? 'Lilita One', body: shots.fonts?.body ?? 'Montserrat' };
const tpl = import.meta.dir;
const server = Bun.serve({
port: a.num('port', 8792), hostname: '127.0.0.1',
async fetch(req) {
const url = new URL(req.url);
const p = decodeURIComponent(url.pathname);
if (p === '/job.json') {
const lang = url.searchParams.get('lang') ?? '';
const text = copyText(lang, copy[lang]);
const script = scriptFont(lang, text);
const base = { phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name,
fonts: { ...fonts, script: script ? `Store ${script.slug}` : null } };
if (url.searchParams.has('feature'))
return Response.json({ ...base, frame: shots.feature?.frame ?? shots.scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? shots.scenes[0]!.palette) });
const sid = url.searchParams.get('s') ?? '';
const scene = shots.scenes.find(s => s.id === sid)!;
const number = shots.scenes.filter(s => !s.hero).indexOf(scene) + 1;
return Response.json({ ...base, scene, number, palette: palette(scene.palette), copy: copy[lang]?.[sid] ?? {} });
}
let file = '';
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7));
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
else if (/^\/(template|feature)\.html$/.test(p)) file = join(tpl, p.slice(1));
if (!file || file.includes('..')) return new Response('no', { status: 404 });
const f = Bun.file(file);
if (!(await f.exists())) return new Response('missing ' + p, { status: 404 });
return new Response(f, { headers: { 'content-type': TYPES[file.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream' } });
},
});
const base = `http://127.0.0.1:${server.port}`;
const browser = await launch(root, { headless: true });
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); });
let warnings = 0;
async function shoot(url: string, w: number, h: number, out: string): Promise<void> {
errs.length = 0;
mkdirSync(join(out, '..'), { recursive: true });
await page.setViewportSize({ width: w, height: h });
await page.goto(url, { waitUntil: 'load' });
await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: 30000 });
await page.waitForTimeout(200);
const tmp = out + '.tmp.png';
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]);
rmSync(tmp, { force: true });
if (r.status !== 0) throw new Error('ffmpeg: ' + r.stderr);
if (errs.length) warnings++;
log('shots', `${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`);
}
try {
for (const lang of langs) {
const rows: { size: string; files: string[] }[] = [];
for (const size of sizes) {
const s = SIZES[size]!;
if (s.feature) {
const f = join(outDir, lang, 'feature', '1024x500.png');
await shoot(`${base}/feature.html?lang=${encodeURIComponent(lang)}`, s.w, s.h, f);
rows.push({ size, files: [f] });
continue;
}
const files: string[] = [];
for (const [i, id] of sceneIds.entries()) {
const f = join(outDir, lang, size, `${String(i + 1).padStart(2, '0')}.png`);
await shoot(`${base}/template.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}`, s.w, s.h, f);
files.push(f);
}
rows.push({ size, files });
}
if (!a.has('no-sheet') && rows.length) {
const H0 = 900, gap = 24;
let y = gap, W = 0, imgs = '';
for (const row of rows) {
const d = SIZES[row.size]!, h = d.feature ? H0 / 2 : H0, w = Math.round(h * d.w / d.h);
row.files.forEach((f, i) => { imgs += `<img src="/out/${relative(outDir, f)}" style="position:absolute;left:${gap + i * (w + gap)}px;top:${y}px;width:${w}px;height:${h}px;border-radius:14px">`; });
W = Math.max(W, gap + row.files.length * (w + gap)); y += h + gap;
}
const sheet = join(outDir, lang, '.sheet.html');
await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${W}px;height:${y}px;position:relative">${imgs}
<script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`);
await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(outDir, lang, 'sheet.png'));
rmSync(sheet, { force: true });
}
}
} finally {
await browser.close();
server.stop(true);
}
done('shots', `render done${warnings ? `, ${warnings} with warnings (missing frames or fonts?)` : ''}`);
}

231
cli/shots/template.html Normal file
View file

@ -0,0 +1,231 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/fonts/fonts.css">
<!--
Store screenshot template (rendered by `crt-ship shots render`, served by its local server).
template.html?s=<scene id>&w=<px>&h=<px>&lang=<id>[&device=tablet]
/job.json gives the scene (palette, frames, badge slots), the words for this language and the font families.
Layout: everything is in u = W / 100; the text block is measured first, then the phone fills the room below it.
-->
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { overflow: hidden; background: #000; }
body { font-family: var(--bf); -webkit-font-smoothing: antialiased; color: #fff; }
#c { position: relative; overflow: hidden; width: var(--W); height: var(--H); isolation: isolate; background: var(--bg); }
/* background: sunburst, glow, vignette, sparkles */
.rays { position: absolute; left: 50%; top: var(--rayY); width: calc(var(--u) * 260); height: calc(var(--u) * 260);
transform: translate(-50%, -50%) rotate(var(--rayRot, 0deg)); z-index: -4; opacity: .55;
background: repeating-conic-gradient(from 0deg, rgba(255,255,255,.20) 0deg 7deg, rgba(255,255,255,0) 7deg 18deg);
-webkit-mask-image: radial-gradient(closest-side, #000 0%, rgba(0,0,0,.65) 35%, transparent 80%); }
.glow { position: absolute; left: 50%; top: var(--rayY); width: calc(var(--u) * 150); height: calc(var(--u) * 150); z-index: -3;
transform: translate(-50%, -50%); background: radial-gradient(closest-side, var(--glow) 0%, transparent 100%); opacity: .9; }
.vign { position: absolute; inset: 0; z-index: -2; pointer-events: none;
background: radial-gradient(120% 70% at 50% 45%, transparent 55%, rgba(0,0,0,.28) 100%); }
.spark { position: absolute; z-index: -1; width: var(--s); height: var(--s); transform: translate(-50%, -50%) rotate(var(--r));
background: #fff; opacity: var(--o);
clip-path: polygon(50% 0, 58% 42%, 100% 50%, 58% 58%, 50% 100%, 42% 58%, 0 50%, 42% 42%);
filter: drop-shadow(0 0 calc(var(--u) * .8) rgba(255,255,255,.9)); }
.dot { position: absolute; z-index: -1; width: var(--s); height: var(--s); border-radius: 50%; transform: translate(-50%, -50%);
background: radial-gradient(circle, rgba(255,255,255,.55), rgba(255,255,255,0) 70%); }
/* text block */
.top { position: absolute; left: 0; right: 0; top: calc(var(--u) * var(--top)); text-align: center; z-index: 6;
padding: 0 calc(var(--u) * 5); display: flex; flex-direction: column; align-items: center; }
.eyebrow { display: inline-flex; align-items: center; gap: calc(var(--u) * 1.6); margin-bottom: calc(var(--u) * 3);
padding: calc(var(--u) * 1.15) calc(var(--u) * 3) calc(var(--u) * 1.15) calc(var(--u) * 1.3); border-radius: 999px;
background: rgba(0,0,0,.26); box-shadow: inset 0 0 0 calc(var(--u) * .25) rgba(255,255,255,.28);
font-size: calc(var(--u) * 2.75); font-weight: 800; letter-spacing: var(--kls, .2em); text-transform: uppercase; line-height: 1.15; }
.eyebrow b { display: grid; place-items: center; width: calc(var(--u) * 5); height: calc(var(--u) * 5); border-radius: 50%;
background: linear-gradient(180deg, #fff3a8, #ffc31f 55%, #ff9500); color: #5a2300; font-weight: 900; letter-spacing: 0;
font-size: calc(var(--u) * 2.5); box-shadow: 0 calc(var(--u) * .35) 0 rgba(0,0,0,.25); }
h1 { font-family: var(--tf); font-weight: var(--tw); line-height: var(--lh); letter-spacing: var(--ls, .005em);
font-size: calc(var(--u) * var(--fs)); color: #fff;
-webkit-text-stroke: calc(var(--u) * var(--fs) * var(--sk, .085)) var(--ink); paint-order: stroke fill;
filter: drop-shadow(0 calc(var(--u) * .9) 0 var(--ink)) drop-shadow(0 calc(var(--u) * 1.6) calc(var(--u) * 2.2) rgba(0,0,0,.3)); }
h1 span { display: block; width: max-content; margin: 0 auto; white-space: nowrap; }
h1 span + span { color: #ffd23a; font-size: .86em; margin-top: .06em; }
p.sub { margin-top: calc(var(--u) * 2.6); max-width: calc(var(--u) * 80); font-size: calc(var(--u) * var(--sub));
line-height: 1.32; font-weight: 700; color: #fff; text-wrap: balance;
text-shadow: 0 calc(var(--u) * .3) calc(var(--u) * 1) rgba(0,0,0,.35); }
.logo { width: calc(var(--u) * 86); max-height: calc(var(--u) * 36); object-fit: contain; margin: calc(var(--u) * -1) 0 calc(var(--u) * 1);
filter: drop-shadow(0 calc(var(--u) * 1.5) calc(var(--u) * 2.5) rgba(0,0,0,.35)); }
/* phone */
.tel { position: absolute; z-index: 3; width: var(--pw); aspect-ratio: var(--ar); left: var(--px); top: var(--py);
transform: translateX(-50%) rotate(var(--pr, 0deg)); transform-origin: 50% 40%;
border-radius: calc(var(--pw) * .16); padding: calc(var(--pw) * .024);
background: linear-gradient(140deg, #f4f4f6 0%, #9da0a8 8%, #3c3e44 20%, #1a1b1f 50%, #3c3e44 82%, #c8cad0 100%);
box-shadow: inset 0 0 0 calc(var(--pw) * .004) rgba(255,255,255,.6), inset 0 0 0 calc(var(--pw) * .011) #101114,
0 calc(var(--u) * 3) calc(var(--u) * 6) rgba(0,0,0,.35), 0 calc(var(--u) * 6) calc(var(--u) * 14) var(--shadow); }
.tel.back { z-index: 2; filter: saturate(.9) brightness(.9); }
.screen { position: relative; width: 100%; height: 100%; overflow: hidden; background: #000; border-radius: calc(var(--pw) * .137); }
.screen img.app { position: absolute; left: 0; bottom: 0; width: 100%; height: var(--appH); object-fit: cover; object-position: top; }
.screen::after { content: ""; position: absolute; inset: 0; z-index: 4; pointer-events: none;
background: linear-gradient(115deg, rgba(255,255,255,.12) 0%, rgba(255,255,255,.03) 24%, transparent 40%); }
/* status bar: the frame's top pixel row stretched, so it matches the game's own top colour */
.bar { position: absolute; top: 0; left: 0; right: 0; height: var(--barH); display: flex; align-items: center;
justify-content: space-between; padding: 0 8.5% 0 11.5%; font-family: -apple-system, 'SF Pro Text', sans-serif;
font-weight: 600; font-size: calc(var(--pw) * .041); z-index: 2; background: #0b0b10 center top / 100% 60000% no-repeat; }
.bar svg { height: calc(var(--pw) * .03); width: auto; margin-left: calc(var(--pw) * .012); }
.island { position: absolute; top: calc(var(--pw) * .025); left: 50%; transform: translateX(-50%); width: 30%; height: calc(var(--pw) * .082);
background: #000; border-radius: 999px; z-index: 3; }
.tablet .tel { border-radius: calc(var(--pw) * .065); padding: calc(var(--pw) * .02); }
.tablet .screen { border-radius: calc(var(--pw) * .048); }
.tablet .bar { padding: 0 5%; font-size: calc(var(--pw) * .024); }
.tablet .bar svg { height: calc(var(--pw) * .018); }
.tablet .island { width: calc(var(--pw) * .016); height: calc(var(--pw) * .016); top: calc(var(--pw) * .007); }
/* badges */
.badge { position: absolute; z-index: 9; display: flex; align-items: center; gap: calc(var(--u) * 2.2);
padding: calc(var(--u) * 1.7) calc(var(--u) * 3.6) calc(var(--u) * 1.7) calc(var(--u) * 1.7); border-radius: calc(var(--u) * 4);
background: linear-gradient(180deg, #ffffff 0%, #fff6e2 55%, #ffe3b0 100%);
box-shadow: inset 0 calc(var(--u) * -.7) 0 rgba(180,90,0,.18), 0 0 0 calc(var(--u) * .55) var(--ink),
0 calc(var(--u) * 1.1) 0 calc(var(--u) * .55) var(--ink), 0 calc(var(--u) * 3) calc(var(--u) * 5) rgba(0,0,0,.35);
transform: rotate(var(--br, 0deg)); color: var(--ink); white-space: nowrap; }
.badge .icon { flex: none; width: calc(var(--u) * 9); height: calc(var(--u) * 9); border-radius: calc(var(--u) * 2.6);
display: grid; place-items: center; background: var(--ic, linear-gradient(180deg, #ffd84d, #ff8a00));
box-shadow: inset 0 calc(var(--u) * .5) 0 rgba(255,255,255,.45), inset 0 calc(var(--u) * -.6) 0 rgba(0,0,0,.2); }
.badge .icon svg { width: 62%; height: 62%; overflow: visible; }
.badge b { display: block; font-family: var(--tf); font-weight: var(--tw); font-size: calc(var(--u) * 4.7); line-height: 1.02; }
.badge small { display: block; font-size: calc(var(--u) * 2.35); font-weight: 700; opacity: .72; margin-top: calc(var(--u) * .5); }
.badge.hot { background: linear-gradient(180deg, #fff27a 0%, #ffc21a 45%, #ff8a00 100%); padding: calc(var(--u) * 2) calc(var(--u) * 4.2); }
.badge.hot b { color: #fff; font-size: calc(var(--u) * 5.6); -webkit-text-stroke: calc(var(--u) * .5) #7a2c00; paint-order: stroke fill;
text-shadow: 0 calc(var(--u) * .5) 0 #7a2c00; }
.badge .stars { display: flex; gap: calc(var(--u) * .4); margin-right: calc(var(--u) * .6); }
.badge .stars svg { width: calc(var(--u) * 6.4); height: calc(var(--u) * 6.4); }
.badge .stars svg:nth-child(2) { transform: translateY(calc(var(--u) * -1)) scale(1.15); }
</style>
</head>
<body>
<div id="c"></div>
<script type="module">
const q = new URLSearchParams(location.search);
const W = +q.get('w'), H = +q.get('h'), LANG = q.get('lang'), SID = q.get('s');
const tablet = q.get('device') === 'tablet';
const job = await (await fetch(`/job.json?lang=${encodeURIComponent(LANG)}&s=${encodeURIComponent(SID)}`)).json();
const S = job.scene, C = job.copy, P = job.palette;
const u = W / 100, Hu = H / u;
const dev = tablet ? job.tablet : job.phone; // { w, h, bar } in CSS px of the raw frame
const FR = `/frames/${encodeURIComponent(LANG)}/${tablet ? 'tablet' : 'phone'}/`;
document.documentElement.lang = LANG;
const RTL = !!job.rtl;
const R = document.documentElement.style;
R.setProperty('--W', W + 'px'); R.setProperty('--H', H + 'px'); R.setProperty('--u', u + 'px');
R.setProperty('--ink', P.ink); R.setProperty('--glow', P.glow); R.setProperty('--shadow', P.shadow);
R.setProperty('--bg', `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 48%, ${P.bg[2]} 100%)`);
// A script the title font lacks (CJK, Arabic, Cyrillic, ...): the whole line switches to the Noto subset so a word
// never mixes two typefaces.
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
R.setProperty('--tf', X ? `'${X}', '${T}', sans-serif` : `'${T}', sans-serif`);
R.setProperty('--bf', X ? `'${X}', '${B}', sans-serif` : `'${B}', sans-serif`);
R.setProperty('--tw', X ? 900 : job.fonts.titleWeight ?? 400);
const CJK = /^(ja|ko|zh)/.test(LANG);
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.28 : CJK ? 1.12 : .98);
if (X) { R.setProperty('--ls', '0'); R.setProperty('--kls', '0'); }
if (CJK) R.setProperty('--sk', '.06');
if (LANG.startsWith('ja')) document.documentElement.style.wordBreak = 'auto-phrase';
if (LANG.startsWith('ko')) document.documentElement.style.wordBreak = 'keep-all';
if (tablet) document.body.classList.add('tablet');
const tall = Hu > 200; // iOS 6.9" / 6.5" vs 16:9
R.setProperty('--top', tall ? 9 : 5.5);
R.setProperty('--fs', S.hero ? (tall ? 10.5 : 8.6) : (tall ? 12 : 9.8));
R.setProperty('--sub', tall ? 3.75 : 3.3);
const AR = dev.w / (dev.h + dev.bar);
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);
const I = {
clock: '<svg viewBox="0 0 24 24"><circle cx="12" cy="13" r="8.5" fill="#fff" stroke="#5a2300" stroke-width="2"/><path d="M12 8v5l3.5 2.2" stroke="#5a2300" stroke-width="2.4" fill="none" stroke-linecap="round"/><rect x="9" y="1.5" width="6" height="3" rx="1.2" fill="#5a2300"/></svg>',
bolt: '<svg viewBox="0 0 24 24"><path d="M13.5 1.5 4 14h6.5L9.5 22.5 20 9.5h-6.8z" fill="#fff" stroke="#5a2300" stroke-width="1.8" stroke-linejoin="round"/></svg>',
burst: '<svg viewBox="0 0 24 24"><path d="M12 1l2.3 6 6.2-2-3.4 5.6 5.4 3.4-6.4.9.9 6.5L12 17l-5 4.4.9-6.5-6.4-.9 5.4-3.4L3.5 5l6.2 2z" fill="#fff" stroke="#5a2300" stroke-width="1.6" stroke-linejoin="round"/></svg>',
cube: '<svg viewBox="0 0 24 24"><path d="M12 2 21 7v10l-9 5-9-5V7z" fill="#fff" stroke="#0a4a2a" stroke-width="1.8" stroke-linejoin="round"/><path d="M3 7l9 5 9-5M12 12v10" stroke="#0a4a2a" stroke-width="1.8" fill="none"/></svg>',
map: '<svg viewBox="0 0 24 24"><path d="M3 6l6-2.5 6 2.5 6-2.5v14.5L15 20.5 9 18l-6 2.5z" fill="#fff" stroke="#06336e" stroke-width="1.8" stroke-linejoin="round"/><path d="M9 3.5V18M15 6v14.5" stroke="#06336e" stroke-width="1.8"/></svg>',
star: '<svg viewBox="0 0 24 24"><path d="M12 1.8l3 6.4 7 .9-5.1 4.8 1.3 6.9L12 17.4l-6.2 3.4 1.3-6.9L2 9.1l7-.9z" fill="url(#sg)" stroke="#6b2c00" stroke-width="1.6" stroke-linejoin="round"/><defs><linearGradient id="sg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff59a"/><stop offset=".55" stop-color="#ffcc1a"/><stop offset="1" stop-color="#ff9000"/></linearGradient></defs></svg>',
grid: '<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="3" fill="#fff" stroke="#5e0636" stroke-width="1.8"/><path d="M3 9h18M3 15h18M9 3v18M15 3v18" stroke="#5e0636" stroke-width="1.5"/></svg>',
gift: '<svg viewBox="0 0 24 24"><rect x="3" y="9" width="18" height="12" rx="2" fill="#fff" stroke="#5e0636" stroke-width="1.8"/><rect x="2" y="6" width="20" height="4" rx="1.5" fill="#fff" stroke="#5e0636" stroke-width="1.8"/><path d="M12 6v15M12 6C10 2 6 3 7.5 6M12 6c2-4 6-3 4.5 0" stroke="#5e0636" stroke-width="1.8" fill="none"/></svg>',
offline: '<svg viewBox="0 0 24 24"><path d="M2.5 9a14 14 0 0 1 19 0M6 12.5a9 9 0 0 1 12 0M9.4 16a4 4 0 0 1 5.2 0" stroke="#fff" stroke-width="2.4" fill="none" stroke-linecap="round"/><circle cx="12" cy="19.3" r="1.6" fill="#fff"/><path d="M3 3l18 18" stroke="#6e1300" stroke-width="4.4" stroke-linecap="round"/><path d="M3 3l18 18" stroke="#fff" stroke-width="2.2" stroke-linecap="round"/></svg>',
flag: '<svg viewBox="0 0 24 24"><path d="M5 22V3" stroke="#6e1300" stroke-width="2.4" stroke-linecap="round"/><path d="M5 3.5h13l-3 4 3 4H5z" fill="#fff" stroke="#6e1300" stroke-width="1.8" stroke-linejoin="round"/></svg>',
trophy: '<svg viewBox="0 0 24 24"><path d="M7 3h10v5a5 5 0 0 1-10 0z" fill="#fff" stroke="#6b2c00" stroke-width="1.8" stroke-linejoin="round"/><path d="M7 5H3.5a3.5 3.5 0 0 0 4 4M17 5h3.5a3.5 3.5 0 0 1-4 4M12 13v4M8 21h8l-1-4H9z" stroke="#6b2c00" stroke-width="1.8" fill="#fff" stroke-linejoin="round"/></svg>',
heart: '<svg viewBox="0 0 24 24"><path d="M12 21s-8.5-5.3-8.5-11.2A4.8 4.8 0 0 1 12 6.6a4.8 4.8 0 0 1 8.5 3.2C20.5 15.7 12 21 12 21z" fill="#fff" stroke="#5e0636" stroke-width="1.8" stroke-linejoin="round"/></svg>',
};
const ICON_BG = {
gold: 'linear-gradient(180deg,#ffe05a,#ff8a00)', green: 'linear-gradient(180deg,#8ff06a,#16a34a)',
blue: 'linear-gradient(180deg,#7fe0ff,#1f7aff)', violet: 'linear-gradient(180deg,#c49bff,#6a2fe0)',
pink: 'linear-gradient(180deg,#ffa3c8,#e8306f)', red: 'linear-gradient(180deg,#ff8a6a,#e4251b)',
};
// seeded rng: every render of a scene is identical
let seed = 0; for (const ch of SID + JSON.stringify(P.bg)) seed = (seed * 31 + ch.charCodeAt(0)) >>> 0;
const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296);
const c = document.getElementById('c');
// RTL: keep number runs ("72 / 80") left-to-right inside right-to-left text
const esc = s => { const t = String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;');
return RTL ? t.replace(/\d+(?:\s*\/\s*\d+)?/g, m => '⁦' + m + '⁩') : t; };
let top = '';
if (S.hero && job.logo) top += `<img class="logo" src="/logo">`;
else if (!S.hero && C.eyebrow) top += `<div class="eyebrow"><b>${String(job.number).padStart(2, '0')}</b>${esc(C.eyebrow)}</div>`;
top += `<h1><span>${esc(C.title?.[0])}</span><span>${esc(C.title?.[1])}</span></h1>`;
if (!S.hero && C.sub) top += `<p class="sub">${esc(C.sub)}</p>`;
c.innerHTML = `<div class="glow"></div><div class="rays"></div><div class="vign"></div><div class="top"${RTL ? ' dir="rtl"' : ''}>${top}</div>`;
await document.fonts.ready;
await Promise.all([...document.images].map(i => i.decode().catch(() => {})));
for (const sp of c.querySelectorAll('h1 span')) { // shrink a line that would overflow (long words)
const max = W - 10 * u, wd = sp.getBoundingClientRect().width;
let f = 1; while (wd * f > max && f > .55) f -= .02;
if (f < 1) sp.style.fontSize = `calc(${getComputedStyle(sp).fontSize} * ${f.toFixed(2)})`;
}
const textBottom = c.querySelector('.top').getBoundingClientRect().bottom / u;
const frames = S.frames.map(f => ({ x: 0, dy: 0, scale: 1, rotate: 0, ...f }));
const front = frames[0];
const pTop = textBottom + (S.hero ? 4 : 5.5);
const room = Hu - pTop + (S.over ?? 7);
const pw = Math.min(tablet ? 82 : 78, Math.max(56, room * AR)) * front.scale;
const ph = pw / AR;
R.setProperty('--rayY', (pTop + ph * .3) * u + 'px');
R.setProperty('--rayRot', (rnd() * 20) + 'deg');
const BAR = `<span>9:41</span><span style="display:flex;align-items:center">
<svg viewBox="0 0 18 12"><g fill="#fff"><rect x="0" y="8" width="3" height="4" rx=".8"/><rect x="5" y="5.5" width="3" height="6.5" rx=".8"/><rect x="10" y="3" width="3" height="9" rx=".8"/><rect x="15" y="0" width="3" height="12" rx=".8"/></g></svg>
<svg viewBox="0 0 16 12"><path fill="#fff" d="M8 2.2c2.3 0 4.4.9 6 2.4l1.3-1.3A10.3 10.3 0 0 0 8 .4C5.2.4 2.6 1.5.7 3.3L2 4.6a8.5 8.5 0 0 1 6-2.4zm0 3.6c1.3 0 2.5.5 3.4 1.3l1.3-1.3A6.6 6.6 0 0 0 8 4c-1.8 0-3.4.7-4.7 1.8l1.3 1.3C5.5 6.3 6.7 5.8 8 5.8zm0 3.6c.4 0 .8.2 1.1.4L8 11.6 6.9 9.8c.3-.2.7-.4 1.1-.4z"/></svg>
<svg viewBox="0 0 27 13"><rect x=".5" y=".5" width="23" height="12" rx="3.5" fill="none" stroke="rgba(255,255,255,.45)"/><rect x="2" y="2" width="20" height="9" rx="2.2" fill="#fff"/><path d="M25 4.5v4c.8-.3 1.4-1.1 1.4-2s-.6-1.7-1.4-2z" fill="rgba(255,255,255,.45)"/></svg></span>`;
let html = '';
for (let i = 0; i < 26; i++) {
const x = rnd() * 100, y = textBottom + rnd() * (Hu - textBottom);
if (i % 2) html += `<i class="spark" style="left:${x * u}px;top:${y * u}px;--s:${(1.6 + rnd() * 3.2) * u}px;--r:${rnd() * 45}deg;--o:${.55 + rnd() * .45}"></i>`;
else html += `<i class="dot" style="left:${x * u}px;top:${y * u}px;--s:${(3 + rnd() * 9) * u}px"></i>`;
}
for (let i = 0; i < 8; i++) {
const x = i % 2 ? 1 + rnd() * 6 : 93 + rnd() * 6, y = 2 + rnd() * (textBottom - 4);
html += `<i class="spark" style="left:${x * u}px;top:${y * u}px;--s:${(1.2 + rnd() * 2) * u}px;--r:0deg;--o:${.4 + rnd() * .4}"></i>`;
}
const phone = (f, cls) => {
const w = pw / front.scale * f.scale, src = FR + encodeURIComponent(f.src);
return `<div class="tel ${cls}" style="--pw:${w * u}px;--px:${(50 + f.x) * u}px;--py:${(pTop + f.dy) * u}px;--pr:${f.rotate}deg"><div class="screen">
<div class="bar" style="background-image:url('${src}')">${BAR}</div><div class="island"></div><img class="app" src="${src}"></div></div>`;
};
for (const f of frames.slice(1)) html += phone(f, 'back');
html += phone(front, 'front');
(S.badges ?? []).forEach((b, i) => {
const [big, small] = (C.badges ?? [])[i] ?? [''];
if (!big) return;
const ic = b.stars ? `<span class="stars">${I.star}${I.star}${I.star}</span>`
: b.hot ? '' : `<span class="icon" style="--ic:${ICON_BG[b.iconBg] ?? b.iconBg ?? ICON_BG.gold}">${I[b.icon] ?? I.star}</span>`;
const pos = b.side === 'l' ? `left:${4 * u}px` : `right:${4 * u}px`;
html += `<div class="badge${b.hot ? ' hot' : ''}"${RTL ? ' dir="rtl"' : ''} style="${pos};top:${Math.min(pTop + ph * b.y, Hu - 18) * u}px;--br:${b.rot || 0}deg">${ic}
<div${RTL ? ' dir="rtl"' : ''}><b>${esc(big)}</b>${small ? `<small>${esc(small)}</small>` : ''}</div></div>`;
});
c.insertAdjacentHTML('beforeend', html);
await Promise.all([...document.images].map(i => i.decode().catch(() => {})));
document.body.dataset.ready = '1';
</script>
</body>
</html>