@condorinst/mobile-bridge 0.19.2 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +100 -42
- package/CHANGELOG.md +106 -0
- package/README.md +64 -14
- package/contract/bridge-contract.json +70 -25
- package/dist/cli.cjs +436 -5
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +433 -3
- package/dist/cli.js.map +1 -1
- package/dist/dev-harness.global.js +2110 -0
- package/dist/dev.cjs +1662 -0
- package/dist/dev.cjs.map +1 -0
- package/dist/dev.d.cts +683 -0
- package/dist/dev.d.ts +683 -0
- package/dist/dev.js +1611 -0
- package/dist/dev.js.map +1 -0
- package/dist/index.cjs +96 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +265 -19
- package/dist/index.d.ts +265 -19
- package/dist/index.js +94 -3
- package/dist/index.js.map +1 -1
- package/docs/agent-guide.md +83 -25
- package/docs/bridge-contract.md +154 -25
- package/docs/client-guide.md +39 -28
- package/docs/device-testing.md +84 -0
- package/docs/pilot-onboarding.md +26 -12
- package/docs/troubleshooting.md +83 -18
- package/examples/minimal-home/AGENTS.md +9 -6
- package/examples/minimal-home/README.md +10 -5
- package/examples/minimal-home/build.mjs +2 -1
- package/examples/minimal-home/index.html +2 -0
- package/examples/minimal-home/package.json +3 -2
- package/examples/minimal-home/src/main.ts +151 -73
- package/llms-full.txt +2041 -0
- package/llms.txt +15 -13
- package/package.json +9 -3
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/cli-core.ts"],"sourcesContent":["/**\n * cli.ts — `bin` entry for `condor-mobile-bridge`.\n *\n * Thin: parse argv, dispatch to the subcommand, print a report and pick an\n * exit code. Every testable decision lives in `cli-core.ts`.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { buildBundle, parseArgs, USAGE, type ValidationResult, validateBundle } from './cli-core';\n\nfunction runBuild(htmlPath: string, outPath: string, maxBytes: number): void {\n const result = buildBundle(htmlPath, maxBytes);\n\n const resolvedOut = resolve(outPath);\n mkdirSync(dirname(resolvedOut), { recursive: true });\n writeFileSync(resolvedOut, result.zipBytes);\n\n const kb = (Buffer.byteLength(result.html) / 1024).toFixed(1);\n console.log(`Built ${outPath}`);\n console.log(` entry: index.html (${kb} KB self-contained)`);\n console.log(` bundleSize (zip): ${result.size} bytes`);\n console.log(` bundleHash (zip): ${result.hash}`);\n\n if (result.overLimit) {\n const limitMb = (maxBytes / (1024 * 1024)).toFixed(1);\n console.warn(\n `\\n⚠️ WARNING: the .zip (${result.size} bytes) exceeds the ${limitMb} MB limit — ` +\n 'the app will REJECT this bundle (falls back to the default screen). Reduce inline assets/media.',\n );\n }\n\n console.log('\\nNext: npx condor-mobile-bridge validate -i ' + outPath + ' --strict');\n}\n\nfunction reportValidation(input: string, result: ValidationResult, strict: boolean): number {\n console.log(`Validating ${input}`);\n if (result.entry) console.log(` entry: ${result.entry}`);\n if (result.size !== null) console.log(` bundleSize (zip): ${result.size} bytes`);\n if (result.hash !== null) console.log(` bundleHash (zip): ${result.hash}`);\n\n const errors = result.findings.filter((f) => f.severity === 'error');\n const warnings = result.findings.filter((f) => f.severity === 'warning');\n\n if (result.findings.length === 0) {\n console.log('\\n✅ No findings. This bundle conforms to the Canvas contract.');\n return 0;\n }\n\n console.log('');\n for (const f of result.findings) {\n const badge = f.severity === 'error' ? '❌ ERROR ' : '⚠️ WARNING';\n console.log(`${badge} [${f.rule}] ${f.message}`);\n }\n\n console.log(\n `\\n${errors.length} error(s), ${warnings.length} warning(s).` +\n (result.size === null\n ? '\\nNote: validating an HTML file skips the size and hash gates. Validate the .zip before delivery.'\n : ''),\n );\n\n if (errors.length > 0) {\n console.log('Errors are gates the Canvas app itself applies — it would reject this bundle.');\n return 1;\n }\n if (warnings.length > 0 && strict) {\n console.log('Warnings are failures under --strict.');\n return 1;\n }\n console.log(\n 'Warnings are not app-level rejections, but they fail silently on a real device. Re-run with --strict to gate on them.',\n );\n return 0;\n}\n\nfunction main(): void {\n const args = parseArgs(process.argv.slice(2));\n\n if (args.help || !args.htmlPath) {\n console.log(USAGE);\n process.exit(args.help ? 0 : 1);\n }\n\n if (args.command === 'validate') {\n const result = validateBundle(args.htmlPath, args.maxBytes);\n process.exit(reportValidation(args.htmlPath, result, args.strict));\n }\n\n runBuild(args.htmlPath, args.outPath, args.maxBytes);\n}\n\nmain();\n","/**\n * cli-core.ts — the pure, testable core of the `condor-mobile-bridge` CLI.\n *\n * `build` takes a client's `dist/index.html`, inlines JavaScript into\n * `<script>`, CSS into `<style>` (resolving `url()` into `data:` URIs),\n * converts local media into `data:` URIs, and packs the result into a `.zip`\n * holding a single `index.html` at the root. It does not touch the output\n * filesystem — `cli.ts` writes the `.zip`.\n *\n * `validate` checks a bundle against the gates the app applies on download,\n * plus a lint for the APIs the sandbox and the CSP block at runtime.\n *\n * Why self-contained: the app renders through `iframe.srcdoc` with a `null`\n * origin and no base URL, which can only resolve inline content and `data:`\n * URIs.\n *\n * **Known limitation.** The post-build inliner assumes a single-chunk `dist`:\n * one JS file, one CSS file, assets. A build with code splitting, or ES module\n * imports between chunks, breaks under `srcdoc` — the client must build\n * single-file (Vite: `vite-plugin-singlefile`; CRA: no splitting).\n */\nimport { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { dirname, extname, resolve } from 'node:path';\nimport { strToU8, unzipSync, zipSync } from 'fflate';\nimport { type HTMLElement, parse } from 'node-html-parser';\n\n/** Maximum `.zip` size. Mirrors `WhitelabelBundleLimits.maxZipBytes` in the app. */\nexport const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;\n\n/** Fixed mtime (>= 1980, the ZIP format floor) so the SHA-256 is reproducible. */\nconst FIXED_MTIME = new Date('2000-01-01T00:00:00Z');\n\n/** Extension → MIME map, for building `data:` URIs of embedded media. */\nexport const MIME_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.eot': 'application/vnd.ms-fontobject',\n '.mp3': 'audio/mpeg',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.json': 'application/json',\n};\n\n/** Refs that must NOT be inlined: external absolute, protocol-relative, already-inline `data:`. */\nfunction isExternalOrInline(url: string): boolean {\n return /^(https?:)?\\/\\//i.test(url) || /^data:/i.test(url) || /^(mailto:|tel:|#)/i.test(url);\n}\n\n/** Strips query and hash from a local ref (`main.js?v=abc#x` → `main.js`). */\nfunction stripQueryHash(url: string): string {\n return url.split(/[?#]/)[0] ?? url;\n}\n\n/**\n * Resolves a local ref to an absolute filesystem path.\n *\n * `htmlRoot` is the site root (the directory of `index.html`); `resourceDir` is\n * the directory of the resource holding the ref — for `url()` inside CSS, that\n * is the directory of the `.css`. A ref starting with `/` is relative to the\n * site root.\n */\nfunction resolveLocal(htmlRoot: string, resourceDir: string, url: string): string {\n const clean = stripQueryHash(url);\n return clean.startsWith('/') ? resolve(htmlRoot, `.${clean}`) : resolve(resourceDir, clean);\n}\n\n/** Reads a local file and returns a base64 `data:` URI. */\nexport function toDataUri(filePath: string): string {\n const bytes = readFileSync(filePath);\n const mime = MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n return `data:${mime};base64,${bytes.toString('base64')}`;\n}\n\n/**\n * Resolves `url(...)` inside a CSS block, replacing local refs with `data:`\n * URIs. `cssDir` is the directory of the CSS file, or of the HTML for an inline\n * `<style>`.\n */\nexport function inlineCssUrls(css: string, htmlRoot: string, cssDir: string): string {\n return css.replace(/url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)/gi, (match, _quote, rawUrl: string) => {\n if (isExternalOrInline(rawUrl)) return match;\n const filePath = resolveLocal(htmlRoot, cssDir, rawUrl);\n return `url(${toDataUri(filePath)})`;\n });\n}\n\n/** Inlines `<script src=\"local\">` into `<script>…</script>`, escaping `</script>`. */\nfunction inlineScripts(root: HTMLElement, htmlRoot: string): void {\n for (const el of root.querySelectorAll('script[src]')) {\n const src = el.getAttribute('src');\n if (!src || isExternalOrInline(src)) continue;\n const js = readFileSync(resolveLocal(htmlRoot, htmlRoot, src), 'utf-8').replace(\n /<\\/script>/gi,\n '<\\\\/script>',\n );\n el.removeAttribute('src');\n // `textContent`, never `set_content`: the latter PARSES what it receives\n // as HTML. Every bundle carries markup inside JS strings, and the parser\n // rewrites it — `<stop … />` becomes `<stop …></stop>`, a comparison like\n // `a<T` is read as an opening tag, and the matching close is emitted at the\n // end of the script. The JS comes out syntactically broken, the zip is\n // produced without error, and the app aborts the Home with \"native bridges\n // reachable from the iframe\" — because the client never got far enough to\n // answer the verify-sandbox probe.\n el.textContent = js;\n }\n}\n\n/** Inlines `<link rel=\"stylesheet\" href=\"local\">` into `<style>…</style>`, resolving `url()`. */\nfunction inlineStylesheets(root: HTMLElement, htmlRoot: string): void {\n for (const el of root.querySelectorAll('link[rel=\"stylesheet\"]')) {\n const href = el.getAttribute('href');\n if (!href || isExternalOrInline(href)) continue;\n const cssPath = resolveLocal(htmlRoot, htmlRoot, href);\n const css = inlineCssUrls(readFileSync(cssPath, 'utf-8'), htmlRoot, dirname(cssPath));\n el.replaceWith(...parse(`<style>${css}</style>`).childNodes);\n }\n}\n\n/** Resolves `url()` in `<style>` blocks already present in the HTML. */\nfunction inlineExistingStyleBlocks(root: HTMLElement, htmlRoot: string): void {\n for (const el of root.querySelectorAll('style')) {\n const css = el.innerHTML;\n if (!css.includes('url(')) continue;\n el.set_content(inlineCssUrls(css, htmlRoot, htmlRoot));\n }\n}\n\n/** Converts local media referenced by attribute (`src`/`href`) into `data:` URIs. */\nfunction inlineMediaAttributes(root: HTMLElement, htmlRoot: string): void {\n const targets: Array<[selector: string, attr: string]> = [\n ['img[src]', 'src'],\n ['source[src]', 'src'],\n ['audio[src]', 'src'],\n ['video[src]', 'src'],\n ['link[rel=\"icon\"]', 'href'],\n ['link[rel=\"shortcut icon\"]', 'href'],\n ['link[rel=\"apple-touch-icon\"]', 'href'],\n ['link[rel=\"preload\"]', 'href'],\n ];\n for (const [selector, attr] of targets) {\n for (const el of root.querySelectorAll(selector)) {\n const ref = el.getAttribute(attr);\n if (!ref || isExternalOrInline(ref)) continue;\n el.setAttribute(attr, toDataUri(resolveLocal(htmlRoot, htmlRoot, ref)));\n }\n }\n}\n\n/**\n * Reads the input HTML and returns the consolidated, self-contained document:\n * JS and CSS inline, media as `data:` URIs. Writes nothing to disk.\n */\nexport function inlineHtml(htmlPath: string): string {\n const htmlRoot = dirname(resolve(htmlPath));\n const root = parse(readFileSync(htmlPath, 'utf-8'), {\n comment: true,\n voidTag: { closingSlash: true },\n });\n inlineScripts(root, htmlRoot);\n inlineStylesheets(root, htmlRoot);\n inlineExistingStyleBlocks(root, htmlRoot);\n inlineMediaAttributes(root, htmlRoot);\n return root.toString();\n}\n\nexport interface BundleResult {\n /** The consolidated, self-contained HTML. */\n html: string;\n /** Bytes of the `.zip`, whose single entry is `index.html` at the root. */\n zipBytes: Uint8Array;\n /** Size of the `.zip` in bytes. */\n size: number;\n /** SHA-256 of the `.zip` bytes, as `sha256-<hex>`. Matches what the app computes. */\n hash: string;\n /** `true` when `size` exceeds `maxBytes`. */\n overLimit: boolean;\n}\n\n/**\n * Builds the bundle from the input `index.html`: inlines, zips it with\n * `index.html` at the root and a fixed mtime for a deterministic hash, and\n * computes size and SHA-256. Pure — writing the `.zip` is the caller's job.\n */\nexport function buildBundle(htmlPath: string, maxBytes: number = DEFAULT_MAX_BYTES): BundleResult {\n const html = inlineHtml(htmlPath);\n const zipBytes = zipSync({ 'index.html': [strToU8(html), { mtime: FIXED_MTIME }] }, { level: 6 });\n const size = zipBytes.length;\n const hash = `sha256-${createHash('sha256').update(zipBytes).digest('hex')}`;\n return { html, zipBytes, size, hash, overLimit: size > maxBytes };\n}\n\n// ---------------------------------------------------------------------------\n// validate — conformance checks for a client bundle\n// ---------------------------------------------------------------------------\n\n/**\n * Severity of a validation finding.\n *\n * `error` mirrors a guard the Canvas app itself applies when it downloads the\n * bundle: the app REJECTS the artifact and keeps the previous cache or falls\n * back to the default screen. `warning` marks something the app accepts but\n * the runtime blocks — the CSP or the `sandbox` attribute makes the call fail\n * on the device, where it is much harder to diagnose.\n */\nexport type ValidationSeverity = 'error' | 'warning';\n\n/** A single conformance finding. `rule` is a stable machine-readable id. */\nexport interface ValidationFinding {\n severity: ValidationSeverity;\n rule: string;\n message: string;\n}\n\n/** Outcome of validating a bundle (`.zip`) or a pre-build `index.html`. */\nexport interface ValidationResult {\n /** `false` when at least one `error` finding was produced. */\n ok: boolean;\n /** Entry document the app would render, or `null` when none was found. */\n entry: string | null;\n /** Size of the `.zip` in bytes; `null` when validating a bare HTML file. */\n size: number | null;\n /** `sha256-<hex>` of the `.zip`; `null` when validating a bare HTML file. */\n hash: string | null;\n findings: ValidationFinding[];\n}\n\n/**\n * APIs that are unreachable inside the Canvas client iframe.\n *\n * The client runs in `<iframe sandbox=\"allow-scripts\">` rendered from\n * `srcdoc`, so its origin is `null`, and it inherits the shell CSP\n * (`script-src 'self' 'unsafe-inline'`, `connect-src 'self'`, no\n * `'unsafe-eval'`). Every entry here fails silently or throws at runtime on a\n * real device — the bundle still installs, which is exactly what makes these\n * expensive to find later.\n *\n * Detection is textual and therefore best-effort: minified code that renames\n * `window.open` to `t.open` is invisible to it. Absence of findings is not a\n * proof of conformance.\n */\nexport const BLOCKED_API_RULES: ReadonlyArray<{\n rule: string;\n pattern: RegExp;\n message: string;\n}> = [\n {\n rule: 'web-storage',\n pattern: /\\b(?:localStorage|sessionStorage)\\b/,\n message:\n 'Web Storage throws SecurityError: the client iframe has a null origin. Keep state in memory — it is lost when the WebView reloads.',\n },\n {\n rule: 'indexed-db',\n pattern: /\\bindexedDB\\b/,\n message: 'IndexedDB is unavailable on a null origin. Keep state in memory.',\n },\n {\n rule: 'cookies',\n pattern: /document\\s*\\.\\s*cookie/,\n message: 'Cookies cannot be written from a null origin; the assignment is a no-op.',\n },\n {\n rule: 'dynamic-eval',\n pattern: /\\beval\\s*\\(|new\\s+Function\\s*\\(/,\n message:\n \"The shell CSP has no 'unsafe-eval'; eval() and new Function() are blocked. Build without eval-based sourcemaps.\",\n },\n {\n rule: 'service-worker',\n pattern: /serviceWorker/,\n message: 'Service workers cannot be registered from a null origin.',\n },\n {\n rule: 'send-beacon',\n pattern: /sendBeacon/,\n message:\n 'navigator.sendBeacon is neutralized by the shell before your bundle runs (pen test PT-10). The call returns without sending.',\n },\n {\n rule: 'popups',\n pattern: /window\\s*\\.\\s*open\\s*\\(/,\n message: 'The sandbox has no allow-popups; window.open() returns null.',\n },\n {\n rule: 'top-navigation',\n pattern: /window\\s*\\.\\s*top\\b/,\n message:\n 'The sandbox has no allow-top-navigation; reading or navigating window.top throws SecurityError.',\n },\n {\n rule: 'external-network',\n pattern: /\\bfetch\\s*\\(|\\bXMLHttpRequest\\b|\\bWebSocket\\s*\\(/,\n message:\n \"connect-src 'self' on a null origin blocks every network call. Request data through the bridge instead (e.g. BridgeClient.fetchSensorLog).\",\n },\n];\n\n/** Runs the blocked-API lint over a client document. */\nexport function lintClientHtml(html: string): ValidationFinding[] {\n const findings: ValidationFinding[] = [];\n for (const { rule, pattern, message } of BLOCKED_API_RULES) {\n if (pattern.test(html)) findings.push({ severity: 'warning', rule, message });\n }\n return findings;\n}\n\n/**\n * Checks that a document carries no reference the `srcdoc` render cannot\n * resolve. Mirrors `_isSelfContained` in the app's\n * `whitelabel_bundle_service.dart`: a `<script src>` or a stylesheet `<link>`\n * pointing anywhere but a `data:` URI makes the app reject the bundle.\n * Relative images are NOT rejected by the app (cosmetic degradation only), so\n * they surface here as warnings.\n */\nexport function checkSelfContained(html: string): ValidationFinding[] {\n const findings: ValidationFinding[] = [];\n const root = parse(html, { comment: true, voidTag: { closingSlash: true } });\n\n for (const el of root.querySelectorAll('script[src]')) {\n const src = el.getAttribute('src') ?? '';\n if (/^data:/i.test(src)) continue;\n findings.push({\n severity: 'error',\n rule: 'not-self-contained',\n message: `<script src=\"${src}\"> — the app rejects bundles with external scripts. Inline it (npx condor-mobile-bridge build does this for you).`,\n });\n }\n\n for (const el of root.querySelectorAll('link[rel=\"stylesheet\"]')) {\n const href = el.getAttribute('href') ?? '';\n if (/^data:/i.test(href)) continue;\n findings.push({\n severity: 'error',\n rule: 'not-self-contained',\n message: `<link rel=\"stylesheet\" href=\"${href}\"> — the app rejects bundles with external stylesheets. Inline it as <style>.`,\n });\n }\n\n for (const el of root.querySelectorAll('img[src]')) {\n const src = el.getAttribute('src') ?? '';\n if (/^data:/i.test(src) || isExternalOrInline(src)) continue;\n findings.push({\n severity: 'warning',\n rule: 'relative-asset',\n message: `<img src=\"${src}\"> is relative and will not resolve inside srcdoc. Embed it as a data: URI.`,\n });\n }\n\n return findings;\n}\n\n/** Sorts findings so every error is reported before any warning. */\nfunction errorsFirst(findings: ValidationFinding[]): ValidationFinding[] {\n return [...findings].sort((a, b) =>\n a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1,\n );\n}\n\n/**\n * Validates a built `.zip` — the artifact actually delivered to Condor.\n * Applies the same three hard gates the app applies on download: a single\n * `index.html` at the root, self-contained, and within the size limit.\n */\nexport function validateZipBytes(\n zipBytes: Uint8Array,\n maxBytes: number = DEFAULT_MAX_BYTES,\n): ValidationResult {\n const findings: ValidationFinding[] = [];\n const size = zipBytes.length;\n const hash = `sha256-${createHash('sha256').update(zipBytes).digest('hex')}`;\n\n if (size > maxBytes) {\n findings.push({\n severity: 'error',\n rule: 'too-large',\n message: `The .zip is ${size} bytes, over the ${maxBytes}-byte limit. The app rejects it and falls back to the default screen.`,\n });\n }\n\n let entries: Record<string, Uint8Array>;\n try {\n entries = unzipSync(zipBytes);\n } catch (err) {\n findings.push({\n severity: 'error',\n rule: 'unreadable-zip',\n message: `Could not read the .zip: ${err instanceof Error ? err.message : String(err)}`,\n });\n return { ok: false, entry: null, size, hash, findings: errorsFirst(findings) };\n }\n\n const names = Object.keys(entries).filter((n) => !n.endsWith('/'));\n let entry: string | null = null;\n\n if (names.includes('index.html')) {\n entry = 'index.html';\n } else {\n const firstHtml = names.find((n) => n.toLowerCase().endsWith('.html'));\n if (firstHtml) {\n entry = firstHtml;\n findings.push({\n severity: 'warning',\n rule: 'entry-fallback',\n message: `No index.html at the root; the app would fall back to \"${firstHtml}\". Name the entry index.html and put it at the root.`,\n });\n } else {\n findings.push({\n severity: 'error',\n rule: 'entry-missing',\n message: 'The .zip carries no .html document. The app cannot render this bundle.',\n });\n }\n }\n\n if (entry) {\n const html = Buffer.from(entries[entry] as Uint8Array).toString('utf-8');\n findings.push(...checkSelfContained(html), ...lintClientHtml(html));\n }\n\n const ok = !findings.some((f) => f.severity === 'error');\n return { ok, entry, size, hash, findings: errorsFirst(findings) };\n}\n\n/**\n * Validates an input path. A `.zip` is checked as the delivered artifact; any\n * other path is treated as a pre-build `index.html` and gets the document\n * checks only — there is no size or hash to report yet.\n */\nexport function validateBundle(\n inputPath: string,\n maxBytes: number = DEFAULT_MAX_BYTES,\n): ValidationResult {\n if (extname(inputPath).toLowerCase() === '.zip') {\n return validateZipBytes(readFileSync(inputPath), maxBytes);\n }\n const html = readFileSync(inputPath, 'utf-8');\n const findings = [...checkSelfContained(html), ...lintClientHtml(html)];\n return {\n ok: !findings.some((f) => f.severity === 'error'),\n entry: inputPath,\n size: null,\n hash: null,\n findings: errorsFirst(findings),\n };\n}\n\nexport type CliCommand = 'build' | 'validate';\n\nexport interface CliArgs {\n /** Subcommand. Defaults to `build` so pre-0.19 invocations keep working. */\n command: CliCommand;\n htmlPath: string;\n outPath: string;\n maxBytes: number;\n /** `validate` only: treat warnings as failures (exit code 1). */\n strict: boolean;\n help: boolean;\n}\n\nconst DEFAULT_OUT = 'dist/whitelabel-bundle.zip';\n\n/**\n * Minimal argv parse (no deps): `--html/-i`, `--out/-o`, `--max-bytes`,\n * `--strict`, `--help/-h`, plus the `build` and `validate` subcommands.\n */\nexport function parseArgs(argv: string[]): CliArgs {\n const args: CliArgs = {\n command: 'build',\n htmlPath: '',\n outPath: DEFAULT_OUT,\n maxBytes: DEFAULT_MAX_BYTES,\n strict: false,\n help: false,\n };\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n switch (token) {\n case '--help':\n case '-h':\n args.help = true;\n break;\n case '--html':\n case '-i':\n case '--input':\n args.htmlPath = argv[++i] ?? '';\n break;\n case '--out':\n case '-o':\n args.outPath = argv[++i] ?? DEFAULT_OUT;\n break;\n case '--max-bytes':\n args.maxBytes = Number.parseInt(argv[++i] ?? '', 10) || DEFAULT_MAX_BYTES;\n break;\n case '--strict':\n args.strict = true;\n break;\n case 'build':\n args.command = 'build';\n break;\n case 'validate':\n args.command = 'validate';\n break;\n default:\n // First positional becomes the input (ergonomics: `build dist/index.html`).\n if (token && !token.startsWith('-') && !args.htmlPath) args.htmlPath = token;\n }\n }\n return args;\n}\n\nexport const USAGE = `condor-mobile-bridge — tooling for Condor Canvas client bundles.\n\nUsage:\n npx condor-mobile-bridge build -i <html> [-o <zip>]\n npx condor-mobile-bridge validate -i <zip|html> [--strict]\n\nCommands:\n build Inline a dist/index.html into a self-contained .zip.\n validate Check a bundle against every rule the Canvas app enforces, plus\n the APIs the sandbox and the CSP block at runtime.\n\nOptions:\n -i, --html <path> Input. build: dist/index.html. validate: .zip or .html. Required.\n -o, --out <path> build only: output .zip (default: ${DEFAULT_OUT}).\n --max-bytes <n> Size limit in bytes (default: ${DEFAULT_MAX_BYTES} = 2 MB).\n --strict validate only: exit 1 on warnings too, not just errors.\n -h, --help Show this help.`;\n"],"mappings":";;;;AAMA,IAAAA,kBAAyC;AACzC,IAAAC,oBAAiC;;;ACcjC,yBAA2B;AAC3B,qBAA6B;AAC7B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uCAAuC;AACnD,WAAO;AAAA,EACT;AACA,UAAQ;AAAA,IACN;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,OAAa;AACpB,QAAM,OAAO,UAAU,QAAQ,KAAK,MAAM,CAAC,CAAC;AAE5C,MAAI,KAAK,QAAQ,CAAC,KAAK,UAAU;AAC/B,YAAQ,IAAI,KAAK;AACjB,YAAQ,KAAK,KAAK,OAAO,IAAI,CAAC;AAAA,EAChC;AAEA,MAAI,KAAK,YAAY,YAAY;AAC/B,UAAM,SAAS,eAAe,KAAK,UAAU,KAAK,QAAQ;AAC1D,YAAQ,KAAK,iBAAiB,KAAK,UAAU,QAAQ,KAAK,MAAM,CAAC;AAAA,EACnE;AAEA,WAAS,KAAK,UAAU,KAAK,SAAS,KAAK,QAAQ;AACrD;AAEA,KAAK;","names":["import_node_fs","import_node_path"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/cli-core.ts","../src/cli-dev.ts","../src/keys.ts","../src/dev/policy.ts","../src/dev/fixtures.ts","../src/dev/scenarios.ts"],"sourcesContent":["/**\n * cli.ts — `bin` entry for `condor-mobile-bridge`.\n *\n * Thin: parse argv, dispatch to the subcommand, print a report and pick an\n * exit code. Every testable decision lives in `cli-core.ts`.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { buildBundle, parseArgs, USAGE, type ValidationResult, validateBundle } from './cli-core';\nimport { startDevServer } from './cli-dev';\n\nfunction runDev(input: string, scenario: string, port: number, nativeVersion?: string): void {\n const server = startDevServer({ input, scenario, port, nativeVersion });\n server.on('listening', () => {\n const native = nativeVersion === undefined ? '' : `&nativeVersion=${nativeVersion}`;\n console.log(\n `Condor Canvas dev harness: http://localhost:${port}/?scenario=${scenario}${native}`,\n );\n console.log(` bundle: ${input} (re-read on every reload)`);\n console.log(' sandbox, shell policy and CSP: same as the app');\n console.log(' scenarios: default, cold-start, no-devices, shared-serial, offline');\n console.log(' OS back button: the \"◀ OS back\" button at the top');\n console.log('\\nA bundle is ready for a device only when it handles every scenario.');\n });\n server.on('error', (err) => {\n console.error(`dev: ${err.message}`);\n process.exit(1);\n });\n}\n\nfunction runBuild(htmlPath: string, outPath: string, maxBytes: number): void {\n const result = buildBundle(htmlPath, maxBytes);\n\n const resolvedOut = resolve(outPath);\n mkdirSync(dirname(resolvedOut), { recursive: true });\n writeFileSync(resolvedOut, result.zipBytes);\n\n const kb = (Buffer.byteLength(result.html) / 1024).toFixed(1);\n console.log(`Built ${outPath}`);\n console.log(` entry: index.html (${kb} KB self-contained)`);\n console.log(` bundleSize (zip): ${result.size} bytes`);\n console.log(` bundleHash (zip): ${result.hash}`);\n\n if (result.overLimit) {\n const limitMb = (maxBytes / (1024 * 1024)).toFixed(1);\n console.warn(\n `\\n⚠️ WARNING: the .zip (${result.size} bytes) exceeds the ${limitMb} MB limit — ` +\n 'the app will REJECT this bundle (falls back to the default screen). Reduce inline assets/media.',\n );\n }\n\n console.log('\\nNext: npx condor-mobile-bridge validate -i ' + outPath + ' --strict');\n}\n\nfunction reportValidation(input: string, result: ValidationResult, strict: boolean): number {\n console.log(`Validating ${input}`);\n if (result.entry) console.log(` entry: ${result.entry}`);\n if (result.size !== null) console.log(` bundleSize (zip): ${result.size} bytes`);\n if (result.hash !== null) console.log(` bundleHash (zip): ${result.hash}`);\n\n const errors = result.findings.filter((f) => f.severity === 'error');\n const warnings = result.findings.filter((f) => f.severity === 'warning');\n\n if (result.findings.length === 0) {\n console.log('\\n✅ No findings. This bundle conforms to the Canvas contract.');\n return 0;\n }\n\n console.log('');\n for (const f of result.findings) {\n const badge = f.severity === 'error' ? '❌ ERROR ' : '⚠️ WARNING';\n console.log(`${badge} [${f.rule}] ${f.message}`);\n }\n\n console.log(\n `\\n${errors.length} error(s), ${warnings.length} warning(s).` +\n (result.size === null\n ? '\\nNote: validating an HTML file skips the size and hash gates. Validate the .zip before delivery.'\n : ''),\n );\n\n if (errors.length > 0) {\n console.log('Errors are gates the Canvas app itself applies — it would reject this bundle.');\n return 1;\n }\n if (warnings.length > 0 && strict) {\n console.log('Warnings are failures under --strict.');\n return 1;\n }\n console.log(\n 'Warnings are not app-level rejections, but they fail silently on a real device. Re-run with --strict to gate on them.',\n );\n return 0;\n}\n\nfunction main(): void {\n const args = parseArgs(process.argv.slice(2));\n\n if (args.help || !args.htmlPath) {\n console.log(USAGE);\n process.exit(args.help ? 0 : 1);\n }\n\n if (args.command === 'dev') {\n try {\n runDev(args.htmlPath, args.scenario, args.port, args.nativeVersion);\n } catch (err) {\n console.error(`dev: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n return;\n }\n\n if (args.command === 'validate') {\n const result = validateBundle(args.htmlPath, args.maxBytes);\n process.exit(reportValidation(args.htmlPath, result, args.strict));\n }\n\n runBuild(args.htmlPath, args.outPath, args.maxBytes);\n}\n\nmain();\n","/**\n * cli-core.ts — the pure, testable core of the `condor-mobile-bridge` CLI.\n *\n * `build` takes a client's `dist/index.html`, inlines JavaScript into\n * `<script>`, CSS into `<style>` (resolving `url()` into `data:` URIs),\n * converts local media into `data:` URIs, and packs the result into a `.zip`\n * holding a single `index.html` at the root. It does not touch the output\n * filesystem — `cli.ts` writes the `.zip`.\n *\n * `validate` checks a bundle against the gates the app applies on download,\n * plus a lint for the APIs the sandbox and the CSP block at runtime.\n *\n * Why self-contained: the app renders through `iframe.srcdoc` with a `null`\n * origin and no base URL, which can only resolve inline content and `data:`\n * URIs.\n *\n * **Known limitation.** The post-build inliner assumes a single-chunk `dist`:\n * one JS file, one CSS file, assets. A build with code splitting, or ES module\n * imports between chunks, breaks under `srcdoc` — the client must build\n * single-file (Vite: `vite-plugin-singlefile`; CRA: no splitting).\n */\nimport { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { dirname, extname, resolve } from 'node:path';\nimport { strToU8, unzipSync, zipSync } from 'fflate';\nimport { type HTMLElement, parse } from 'node-html-parser';\n\n/** Maximum `.zip` size. Mirrors `WhitelabelBundleLimits.maxZipBytes` in the app. */\nexport const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;\n\n/** Fixed mtime (>= 1980, the ZIP format floor) so the SHA-256 is reproducible. */\nconst FIXED_MTIME = new Date('2000-01-01T00:00:00Z');\n\n/** Extension → MIME map, for building `data:` URIs of embedded media. */\nexport const MIME_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.bmp': 'image/bmp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.eot': 'application/vnd.ms-fontobject',\n '.mp3': 'audio/mpeg',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.json': 'application/json',\n};\n\n/** Refs that must NOT be inlined: external absolute, protocol-relative, already-inline `data:`. */\nfunction isExternalOrInline(url: string): boolean {\n return /^(https?:)?\\/\\//i.test(url) || /^data:/i.test(url) || /^(mailto:|tel:|#)/i.test(url);\n}\n\n/** Strips query and hash from a local ref (`main.js?v=abc#x` → `main.js`). */\nfunction stripQueryHash(url: string): string {\n return url.split(/[?#]/)[0] ?? url;\n}\n\n/**\n * Resolves a local ref to an absolute filesystem path.\n *\n * `htmlRoot` is the site root (the directory of `index.html`); `resourceDir` is\n * the directory of the resource holding the ref — for `url()` inside CSS, that\n * is the directory of the `.css`. A ref starting with `/` is relative to the\n * site root.\n */\nfunction resolveLocal(htmlRoot: string, resourceDir: string, url: string): string {\n const clean = stripQueryHash(url);\n return clean.startsWith('/') ? resolve(htmlRoot, `.${clean}`) : resolve(resourceDir, clean);\n}\n\n/** Reads a local file and returns a base64 `data:` URI. */\nexport function toDataUri(filePath: string): string {\n const bytes = readFileSync(filePath);\n const mime = MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n return `data:${mime};base64,${bytes.toString('base64')}`;\n}\n\n/**\n * Resolves `url(...)` inside a CSS block, replacing local refs with `data:`\n * URIs. `cssDir` is the directory of the CSS file, or of the HTML for an inline\n * `<style>`.\n */\nexport function inlineCssUrls(css: string, htmlRoot: string, cssDir: string): string {\n return css.replace(/url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)/gi, (match, _quote, rawUrl: string) => {\n if (isExternalOrInline(rawUrl)) return match;\n const filePath = resolveLocal(htmlRoot, cssDir, rawUrl);\n return `url(${toDataUri(filePath)})`;\n });\n}\n\n/** Inlines `<script src=\"local\">` into `<script>…</script>`, escaping `</script>`. */\nfunction inlineScripts(root: HTMLElement, htmlRoot: string): void {\n for (const el of root.querySelectorAll('script[src]')) {\n const src = el.getAttribute('src');\n if (!src || isExternalOrInline(src)) continue;\n const js = readFileSync(resolveLocal(htmlRoot, htmlRoot, src), 'utf-8').replace(\n /<\\/script>/gi,\n '<\\\\/script>',\n );\n el.removeAttribute('src');\n // `textContent`, never `set_content`: the latter PARSES what it receives\n // as HTML. Every bundle carries markup inside JS strings, and the parser\n // rewrites it — `<stop … />` becomes `<stop …></stop>`, a comparison like\n // `a<T` is read as an opening tag, and the matching close is emitted at the\n // end of the script. The JS comes out syntactically broken, the zip is\n // produced without error, and the app aborts the Home with \"native bridges\n // reachable from the iframe\" — because the client never got far enough to\n // answer the verify-sandbox probe.\n el.textContent = js;\n }\n}\n\n/** Inlines `<link rel=\"stylesheet\" href=\"local\">` into `<style>…</style>`, resolving `url()`. */\nfunction inlineStylesheets(root: HTMLElement, htmlRoot: string): void {\n for (const el of root.querySelectorAll('link[rel=\"stylesheet\"]')) {\n const href = el.getAttribute('href');\n if (!href || isExternalOrInline(href)) continue;\n const cssPath = resolveLocal(htmlRoot, htmlRoot, href);\n const css = inlineCssUrls(readFileSync(cssPath, 'utf-8'), htmlRoot, dirname(cssPath));\n el.replaceWith(...parse(`<style>${css}</style>`).childNodes);\n }\n}\n\n/** Resolves `url()` in `<style>` blocks already present in the HTML. */\nfunction inlineExistingStyleBlocks(root: HTMLElement, htmlRoot: string): void {\n for (const el of root.querySelectorAll('style')) {\n const css = el.innerHTML;\n if (!css.includes('url(')) continue;\n el.set_content(inlineCssUrls(css, htmlRoot, htmlRoot));\n }\n}\n\n/** Converts local media referenced by attribute (`src`/`href`) into `data:` URIs. */\nfunction inlineMediaAttributes(root: HTMLElement, htmlRoot: string): void {\n const targets: Array<[selector: string, attr: string]> = [\n ['img[src]', 'src'],\n ['source[src]', 'src'],\n ['audio[src]', 'src'],\n ['video[src]', 'src'],\n ['link[rel=\"icon\"]', 'href'],\n ['link[rel=\"shortcut icon\"]', 'href'],\n ['link[rel=\"apple-touch-icon\"]', 'href'],\n ['link[rel=\"preload\"]', 'href'],\n ];\n for (const [selector, attr] of targets) {\n for (const el of root.querySelectorAll(selector)) {\n const ref = el.getAttribute(attr);\n if (!ref || isExternalOrInline(ref)) continue;\n el.setAttribute(attr, toDataUri(resolveLocal(htmlRoot, htmlRoot, ref)));\n }\n }\n}\n\n/**\n * Reads the input HTML and returns the consolidated, self-contained document:\n * JS and CSS inline, media as `data:` URIs. Writes nothing to disk.\n */\nexport function inlineHtml(htmlPath: string): string {\n const htmlRoot = dirname(resolve(htmlPath));\n const root = parse(readFileSync(htmlPath, 'utf-8'), {\n comment: true,\n voidTag: { closingSlash: true },\n });\n inlineScripts(root, htmlRoot);\n inlineStylesheets(root, htmlRoot);\n inlineExistingStyleBlocks(root, htmlRoot);\n inlineMediaAttributes(root, htmlRoot);\n return root.toString();\n}\n\nexport interface BundleResult {\n /** The consolidated, self-contained HTML. */\n html: string;\n /** Bytes of the `.zip`, whose single entry is `index.html` at the root. */\n zipBytes: Uint8Array;\n /** Size of the `.zip` in bytes. */\n size: number;\n /** SHA-256 of the `.zip` bytes, as `sha256-<hex>`. Matches what the app computes. */\n hash: string;\n /** `true` when `size` exceeds `maxBytes`. */\n overLimit: boolean;\n}\n\n/**\n * Builds the bundle from the input `index.html`: inlines, zips it with\n * `index.html` at the root and a fixed mtime for a deterministic hash, and\n * computes size and SHA-256. Pure — writing the `.zip` is the caller's job.\n */\nexport function buildBundle(htmlPath: string, maxBytes: number = DEFAULT_MAX_BYTES): BundleResult {\n const html = inlineHtml(htmlPath);\n const zipBytes = zipSync({ 'index.html': [strToU8(html), { mtime: FIXED_MTIME }] }, { level: 6 });\n const size = zipBytes.length;\n const hash = `sha256-${createHash('sha256').update(zipBytes).digest('hex')}`;\n return { html, zipBytes, size, hash, overLimit: size > maxBytes };\n}\n\n// ---------------------------------------------------------------------------\n// validate — conformance checks for a client bundle\n// ---------------------------------------------------------------------------\n\n/**\n * Severity of a validation finding.\n *\n * `error` mirrors a guard the Canvas app itself applies when it downloads the\n * bundle: the app REJECTS the artifact and keeps the previous cache or falls\n * back to the default screen. `warning` marks something the app accepts but\n * the runtime blocks — the CSP or the `sandbox` attribute makes the call fail\n * on the device, where it is much harder to diagnose.\n */\nexport type ValidationSeverity = 'error' | 'warning';\n\n/** A single conformance finding. `rule` is a stable machine-readable id. */\nexport interface ValidationFinding {\n severity: ValidationSeverity;\n rule: string;\n message: string;\n}\n\n/** Outcome of validating a bundle (`.zip`) or a pre-build `index.html`. */\nexport interface ValidationResult {\n /** `false` when at least one `error` finding was produced. */\n ok: boolean;\n /** Entry document the app would render, or `null` when none was found. */\n entry: string | null;\n /** Size of the `.zip` in bytes; `null` when validating a bare HTML file. */\n size: number | null;\n /** `sha256-<hex>` of the `.zip`; `null` when validating a bare HTML file. */\n hash: string | null;\n findings: ValidationFinding[];\n}\n\n/**\n * APIs that are unreachable inside the Canvas client iframe.\n *\n * The client runs in `<iframe sandbox=\"allow-scripts\">` rendered from\n * `srcdoc`, so its origin is `null`, and it inherits the shell CSP\n * (`script-src 'self' 'unsafe-inline'`, `connect-src 'self'`, no\n * `'unsafe-eval'`). Every entry here fails silently or throws at runtime on a\n * real device — the bundle still installs, which is exactly what makes these\n * expensive to find later.\n *\n * Detection is textual and therefore best-effort: minified code that renames\n * `window.open` to `t.open` is invisible to it. Absence of findings is not a\n * proof of conformance.\n */\nexport const BLOCKED_API_RULES: ReadonlyArray<{\n rule: string;\n pattern: RegExp;\n message: string;\n}> = [\n {\n rule: 'web-storage',\n pattern: /\\b(?:localStorage|sessionStorage)\\b/,\n message:\n 'Web Storage throws SecurityError: the client iframe has a null origin. Keep state in memory — it is lost when the WebView reloads.',\n },\n {\n rule: 'indexed-db',\n pattern: /\\bindexedDB\\b/,\n message: 'IndexedDB is unavailable on a null origin. Keep state in memory.',\n },\n {\n rule: 'cookies',\n pattern: /document\\s*\\.\\s*cookie/,\n message: 'Cookies cannot be written from a null origin; the assignment is a no-op.',\n },\n {\n rule: 'dynamic-eval',\n pattern: /\\beval\\s*\\(|new\\s+Function\\s*\\(/,\n message:\n \"The shell CSP has no 'unsafe-eval'; eval() and new Function() are blocked. Build without eval-based sourcemaps.\",\n },\n {\n rule: 'service-worker',\n pattern: /serviceWorker/,\n message: 'Service workers cannot be registered from a null origin.',\n },\n {\n rule: 'send-beacon',\n pattern: /sendBeacon/,\n message:\n 'navigator.sendBeacon is neutralized by the shell before your bundle runs (pen test PT-10). The call returns without sending.',\n },\n {\n rule: 'popups',\n pattern: /window\\s*\\.\\s*open\\s*\\(/,\n message: 'The sandbox has no allow-popups; window.open() returns null.',\n },\n {\n rule: 'top-navigation',\n pattern: /window\\s*\\.\\s*top\\b/,\n message:\n 'The sandbox has no allow-top-navigation; reading or navigating window.top throws SecurityError.',\n },\n {\n rule: 'external-network',\n pattern: /\\bfetch\\s*\\(|\\bXMLHttpRequest\\b|\\bWebSocket\\s*\\(/,\n message:\n \"connect-src 'self' on a null origin blocks every network call. Request data through the bridge instead (e.g. BridgeClient.fetchSensorLog).\",\n },\n];\n\n/**\n * Marker the dev harness (`@condorinst/mobile-bridge/dev`) leaves in any code\n * that bundles it. Kept in sync with `DEV_HARNESS_MARKER` in `src/dev/harness.ts`.\n */\nexport const DEV_HARNESS_MARKER = '__condorDevHarness__';\n\n/** Runs the blocked-API lint over a client document. */\nexport function lintClientHtml(html: string): ValidationFinding[] {\n const findings: ValidationFinding[] = [];\n if (html.includes(DEV_HARNESS_MARKER)) {\n findings.push({\n severity: 'error',\n rule: 'dev-harness-bundled',\n message:\n 'The bundle contains the development harness (@condorinst/mobile-bridge/dev). It belongs in the page that hosts the bundle during development, never in the bundle: remove the import.',\n });\n }\n for (const { rule, pattern, message } of BLOCKED_API_RULES) {\n if (pattern.test(html)) findings.push({ severity: 'warning', rule, message });\n }\n return findings;\n}\n\n/**\n * Checks that a document carries no reference the `srcdoc` render cannot\n * resolve. Mirrors `_isSelfContained` in the app's\n * `whitelabel_bundle_service.dart`: a `<script src>` or a stylesheet `<link>`\n * pointing anywhere but a `data:` URI makes the app reject the bundle.\n * Relative images are NOT rejected by the app (cosmetic degradation only), so\n * they surface here as warnings.\n */\nexport function checkSelfContained(html: string): ValidationFinding[] {\n const findings: ValidationFinding[] = [];\n const root = parse(html, { comment: true, voidTag: { closingSlash: true } });\n\n for (const el of root.querySelectorAll('script[src]')) {\n const src = el.getAttribute('src') ?? '';\n if (/^data:/i.test(src)) continue;\n findings.push({\n severity: 'error',\n rule: 'not-self-contained',\n message: `<script src=\"${src}\"> — the app rejects bundles with external scripts. Inline it (npx condor-mobile-bridge build does this for you).`,\n });\n }\n\n for (const el of root.querySelectorAll('link[rel=\"stylesheet\"]')) {\n const href = el.getAttribute('href') ?? '';\n if (/^data:/i.test(href)) continue;\n findings.push({\n severity: 'error',\n rule: 'not-self-contained',\n message: `<link rel=\"stylesheet\" href=\"${href}\"> — the app rejects bundles with external stylesheets. Inline it as <style>.`,\n });\n }\n\n for (const el of root.querySelectorAll('img[src]')) {\n const src = el.getAttribute('src') ?? '';\n if (/^data:/i.test(src) || isExternalOrInline(src)) continue;\n findings.push({\n severity: 'warning',\n rule: 'relative-asset',\n message: `<img src=\"${src}\"> is relative and will not resolve inside srcdoc. Embed it as a data: URI.`,\n });\n }\n\n return findings;\n}\n\n/** Sorts findings so every error is reported before any warning. */\nfunction errorsFirst(findings: ValidationFinding[]): ValidationFinding[] {\n return [...findings].sort((a, b) =>\n a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1,\n );\n}\n\n/**\n * Validates a built `.zip` — the artifact actually delivered to Condor.\n * Applies the same three hard gates the app applies on download: a single\n * `index.html` at the root, self-contained, and within the size limit.\n */\nexport function validateZipBytes(\n zipBytes: Uint8Array,\n maxBytes: number = DEFAULT_MAX_BYTES,\n): ValidationResult {\n const findings: ValidationFinding[] = [];\n const size = zipBytes.length;\n const hash = `sha256-${createHash('sha256').update(zipBytes).digest('hex')}`;\n\n if (size > maxBytes) {\n findings.push({\n severity: 'error',\n rule: 'too-large',\n message: `The .zip is ${size} bytes, over the ${maxBytes}-byte limit. The app rejects it and falls back to the default screen.`,\n });\n }\n\n let entries: Record<string, Uint8Array>;\n try {\n entries = unzipSync(zipBytes);\n } catch (err) {\n findings.push({\n severity: 'error',\n rule: 'unreadable-zip',\n message: `Could not read the .zip: ${err instanceof Error ? err.message : String(err)}`,\n });\n return { ok: false, entry: null, size, hash, findings: errorsFirst(findings) };\n }\n\n const names = Object.keys(entries).filter((n) => !n.endsWith('/'));\n let entry: string | null = null;\n\n if (names.includes('index.html')) {\n entry = 'index.html';\n } else {\n const firstHtml = names.find((n) => n.toLowerCase().endsWith('.html'));\n if (firstHtml) {\n entry = firstHtml;\n findings.push({\n severity: 'warning',\n rule: 'entry-fallback',\n message: `No index.html at the root; the app would fall back to \"${firstHtml}\". Name the entry index.html and put it at the root.`,\n });\n } else {\n findings.push({\n severity: 'error',\n rule: 'entry-missing',\n message: 'The .zip carries no .html document. The app cannot render this bundle.',\n });\n }\n }\n\n if (entry) {\n const html = Buffer.from(entries[entry] as Uint8Array).toString('utf-8');\n findings.push(...checkSelfContained(html), ...lintClientHtml(html));\n }\n\n const ok = !findings.some((f) => f.severity === 'error');\n return { ok, entry, size, hash, findings: errorsFirst(findings) };\n}\n\n/**\n * Validates an input path. A `.zip` is checked as the delivered artifact; any\n * other path is treated as a pre-build `index.html` and gets the document\n * checks only — there is no size or hash to report yet.\n */\nexport function validateBundle(\n inputPath: string,\n maxBytes: number = DEFAULT_MAX_BYTES,\n): ValidationResult {\n if (extname(inputPath).toLowerCase() === '.zip') {\n return validateZipBytes(readFileSync(inputPath), maxBytes);\n }\n const html = readFileSync(inputPath, 'utf-8');\n const findings = [...checkSelfContained(html), ...lintClientHtml(html)];\n return {\n ok: !findings.some((f) => f.severity === 'error'),\n entry: inputPath,\n size: null,\n hash: null,\n findings: errorsFirst(findings),\n };\n}\n\nexport type CliCommand = 'build' | 'validate' | 'dev';\n\nexport interface CliArgs {\n /** Subcommand. Defaults to `build` so pre-0.19 invocations keep working. */\n command: CliCommand;\n htmlPath: string;\n outPath: string;\n maxBytes: number;\n /** `validate` only: treat warnings as failures (exit code 1). */\n strict: boolean;\n /** `dev` only: harness scenario. */\n scenario: string;\n /** `dev` only: HTTP port. */\n port: number;\n /** `dev` only: overrides the scenario's nativeVersion (`'null'` for null). */\n nativeVersion: string | undefined;\n help: boolean;\n}\n\nconst DEFAULT_OUT = 'dist/whitelabel-bundle.zip';\nexport const DEFAULT_DEV_PORT = 5173;\n\n/**\n * Minimal argv parse (no deps): `--html/-i`, `--out/-o`, `--max-bytes`,\n * `--strict`, `--scenario`, `--port`, `--help/-h`, plus the `build`,\n * `validate` and `dev` subcommands.\n */\nexport function parseArgs(argv: string[]): CliArgs {\n const args: CliArgs = {\n command: 'build',\n htmlPath: '',\n outPath: DEFAULT_OUT,\n maxBytes: DEFAULT_MAX_BYTES,\n strict: false,\n scenario: 'default',\n port: DEFAULT_DEV_PORT,\n nativeVersion: undefined,\n help: false,\n };\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n switch (token) {\n case '--help':\n case '-h':\n args.help = true;\n break;\n case '--html':\n case '-i':\n case '--input':\n args.htmlPath = argv[++i] ?? '';\n break;\n case '--out':\n case '-o':\n args.outPath = argv[++i] ?? DEFAULT_OUT;\n break;\n case '--max-bytes':\n args.maxBytes = Number.parseInt(argv[++i] ?? '', 10) || DEFAULT_MAX_BYTES;\n break;\n case '--strict':\n args.strict = true;\n break;\n case 'build':\n args.command = 'build';\n break;\n case 'validate':\n args.command = 'validate';\n break;\n case 'dev':\n args.command = 'dev';\n break;\n case '--scenario':\n args.scenario = argv[++i] ?? 'default';\n break;\n case '--native-version':\n args.nativeVersion = argv[++i] ?? 'null';\n break;\n case '--port':\n args.port = Number.parseInt(argv[++i] ?? '', 10) || DEFAULT_DEV_PORT;\n break;\n default:\n // First positional becomes the input (ergonomics: `build dist/index.html`).\n if (token && !token.startsWith('-') && !args.htmlPath) args.htmlPath = token;\n }\n }\n return args;\n}\n\nexport const USAGE = `condor-mobile-bridge — tooling for Condor Canvas client bundles.\n\nUsage:\n npx condor-mobile-bridge build -i <html> [-o <zip>]\n npx condor-mobile-bridge validate -i <zip|html> [--strict]\n npx condor-mobile-bridge dev -i <html|zip|dir> [--scenario <name>] [--native-version <v|null>] [--port <n>]\n\nCommands:\n build Inline a dist/index.html into a self-contained .zip.\n validate Check a bundle against every rule the Canvas app enforces, plus\n the APIs the sandbox and the CSP block at runtime.\n dev Serve the bundle in a browser harness that behaves like the app:\n same sandbox, shell and policy, and a simulated native side.\n Re-reads the input on every reload. Scenarios: default,\n cold-start, no-devices, shared-serial, offline.\n\nOptions:\n -i, --html <path> Input. build: dist/index.html. validate: .zip or .html. Required.\n -o, --out <path> build only: output .zip (default: ${DEFAULT_OUT}).\n --max-bytes <n> Size limit in bytes (default: ${DEFAULT_MAX_BYTES} = 2 MB).\n --strict validate only: exit 1 on warnings too, not just errors.\n --scenario <n> dev only: device behaviour to simulate (default: default).\n --port <n> dev only: HTTP port (default: ${DEFAULT_DEV_PORT}).\n --native-version <v|null>\n dev only: nativeVersion the harness reports (default\n 0.17.0). 'null' reproduces a shell that could not\n reach the native side.\n -h, --help Show this help.`;\n","/**\n * cli-dev.ts — the `dev` subcommand: a local HTTP server hosting the bundle in\n * the development harness (`src/dev/harness.ts`).\n *\n * The page it serves is the **shell** frame, with the app's CSP; the bundle\n * runs inside it in `<iframe sandbox=\"allow-scripts\">`, so the network, storage\n * and API restrictions of a device apply in the browser too. The input is\n * re-read on every request: rebuild, reload, done.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { createServer, type Server } from 'node:http';\nimport { dirname, extname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { strFromU8, unzipSync } from 'fflate';\nimport { inlineHtml } from './cli-core';\nimport { CANVAS_CSP } from './dev/policy';\nimport { SCENARIOS } from './dev/scenarios';\n\n/**\n * Reads the bundle's `index.html` from a file, a `dist/` directory or a `.zip`.\n * An HTML file is inlined exactly as `build` does (scripts, styles, media), so\n * a `dist/` with `index.html` + `main.js` runs as it will in the `.zip`.\n */\nexport function readClientHtml(input: string): string {\n const path = resolve(input);\n if (existsSync(path) && statSync(path).isDirectory()) {\n return inlineHtml(join(path, 'index.html'));\n }\n if (extname(path).toLowerCase() === '.zip') {\n const files = unzipSync(new Uint8Array(readFileSync(path)));\n const entry = files['index.html'];\n if (!entry) throw new Error(`${input}: no index.html at the root of the zip.`);\n return strFromU8(entry);\n }\n return inlineHtml(path);\n}\n\nconst escapeHtml = (s: string): string =>\n s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n\n/** The harness page. Exported for tests. */\n/**\n * The harness page. `nativeVersion` overrides the scenario's (`'null'` → null).\n * Exported for tests.\n */\nexport function harnessPage(scenario: string, nativeVersion?: string): string {\n const options = Object.entries(SCENARIOS)\n .map(\n ([name, s]) =>\n `<option value=\"${name}\" title=\"${escapeHtml(s.description)}\"${\n name === scenario ? ' selected' : ''\n }>${name}</option>`,\n )\n .join('');\n const description = escapeHtml(SCENARIOS[scenario as keyof typeof SCENARIOS]?.description ?? '');\n // JSON in an inline script: escape every `<` so no `</script>` or `<!--` can close it.\n const scenarioJson = JSON.stringify(scenario).replace(/</g, '\\\\u003c');\n const nativeJson =\n JSON.stringify(\n nativeVersion === undefined ? undefined : nativeVersion === 'null' ? null : nativeVersion,\n )?.replace(/</g, '\\\\u003c') ?? 'undefined';\n const nativeLabel = escapeHtml(\n nativeVersion === undefined ? '' : `nativeVersion ${nativeVersion}`,\n );\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"${CANVAS_CSP}\">\n<title>Condor Canvas — dev harness</title>\n<style>\n body { margin: 0; font: 13px system-ui, sans-serif; background: #e9ebef; color: #1b1f24; }\n header { display: flex; gap: 12px; align-items: center; padding: 8px 16px; background: #1b1f24; color: #fff; flex-wrap: wrap; }\n header p { margin: 0; opacity: .8; flex: 1 1 320px; }\n main { display: flex; justify-content: center; padding: 16px; }\n #device { width: 390px; height: 780px; max-width: 100%; border-radius: 28px; overflow: hidden; box-shadow: 0 10px 40px rgba(0,0,0,.25); background: #fff; }\n</style>\n</head>\n<body>\n<header>\n <strong>Condor Canvas · dev harness</strong>\n <label>Scenario <select id=\"scenario\">${options}</select></label>\n <button id=\"back\" type=\"button\" title=\"The OS back button: reaches the bundle only after it reported canGoBack true\">◀ OS back</button>\n <span>${nativeLabel}</span>\n <p>${description}</p>\n</header>\n<main><div id=\"device\"></div></main>\n<script src=\"/__condor/harness.js\"></script>\n<script>\n var scenario = ${scenarioJson};\n var nativeVersion = ${nativeJson};\n var harness = null;\n document.getElementById('scenario').addEventListener('change', function (e) {\n var params = new URLSearchParams(location.search);\n params.set('scenario', e.target.value);\n location.search = params.toString();\n });\n document.getElementById('back').addEventListener('click', function () {\n if (harness) harness.pressBack();\n });\n var chosen = CondorDevHarness.SCENARIOS[scenario];\n if (nativeVersion !== undefined) chosen = Object.assign({}, chosen, { nativeVersion: nativeVersion });\n fetch('/__condor/client.html')\n .then(function (r) { if (!r.ok) throw new Error('could not read the bundle: HTTP ' + r.status); return r.text(); })\n .then(function (html) {\n return CondorDevHarness.createDevHarness({ html: html, scenario: chosen, mount: document.getElementById('device') });\n })\n .then(function (h) { harness = h; })\n .catch(function (err) { document.getElementById('device').textContent = String(err); console.error(err); });\n</script>\n</body>\n</html>`;\n}\n\n/** Path of the IIFE harness build, next to the compiled CLI in `dist/`. */\nfunction harnessScriptPath(): string {\n const here =\n typeof __dirname !== 'undefined' ? __dirname : dirname(fileURLToPath(import.meta.url));\n return join(here, 'dev-harness.global.js');\n}\n\nexport function startDevServer(opts: {\n input: string;\n scenario: string;\n port: number;\n nativeVersion?: string;\n}): Server {\n if (!(opts.scenario in SCENARIOS)) {\n throw new Error(\n `Unknown scenario \"${opts.scenario}\". Known: ${Object.keys(SCENARIOS).join(', ')}.`,\n );\n }\n // Fail before listening if the input cannot be read.\n readClientHtml(opts.input);\n\n const server = createServer((req, res) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n try {\n if (url.pathname === '/__condor/client.html') {\n res.writeHead(200, {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n });\n res.end(readClientHtml(opts.input));\n return;\n }\n if (url.pathname === '/__condor/harness.js') {\n res.writeHead(200, {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': 'no-store',\n });\n res.end(readFileSync(harnessScriptPath()));\n return;\n }\n if (url.pathname === '/') {\n const scenario = url.searchParams.get('scenario') ?? opts.scenario;\n res.writeHead(200, {\n 'content-type': 'text/html; charset=utf-8',\n 'content-security-policy': CANVAS_CSP,\n 'cache-control': 'no-store',\n });\n const nativeVersion = url.searchParams.get('nativeVersion') ?? opts.nativeVersion;\n res.end(harnessPage(scenario in SCENARIOS ? scenario : opts.scenario, nativeVersion));\n return;\n }\n res.writeHead(404).end();\n } catch (err) {\n res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });\n res.end(String(err instanceof Error ? err.message : err));\n }\n });\n server.listen(opts.port, '127.0.0.1');\n return server;\n}\n","/**\n * Catalogue of the JS↔Native bridge keys.\n *\n * Mirrors the JS-facing side of `ForegroundComCoreKeys` in `condor_core`.\n * The strings here are what JavaScript receives through\n * `window.CondorBridge.emit(key, payload)`.\n *\n * Thirteen keys exist. A sandboxed client can subscribe to twelve of them:\n * `dfu` is denied by the shell policy and skipped natively. See\n * `docs/bridge-contract.md` for what each one carries and when it is emitted.\n */\nexport const BRIDGE_KEYS = {\n pingPong: 'pingPong',\n userDevice: 'userDevice',\n deviceLightSensors: 'deviceLightSensors',\n syncTime: 'syncTime',\n realTime: 'realTime',\n deleteMemory: 'deleteMemory',\n deviceNotification: 'deviceNotification',\n deviceConnection: 'deviceConnection',\n sensorLog: 'sensorLog',\n dfu: 'dfu',\n systemStatus: 'systemStatus',\n /**\n * Native → client: the OS back button was pressed and the client had\n * reported internal history via `reportNavigation(true)`. Go back exactly\n * ONE internal page. Emitted only when the native side decided to delegate\n * the back gesture. See `BridgeClient.onBack`.\n */\n navigationBack: 'navigationBack',\n /**\n * Native → client: the app's language state. Carries the raw device locale\n * AND the language explicitly chosen in the app Settings, so the client can\n * apply its own precedence rule — including rendering a language the native\n * chrome does not support. Emitted on attach, after `handshake-ack`, and on\n * every change in Settings. See `LanguagePayload`.\n */\n language: 'language',\n} as const;\n\nexport type BridgeKey = (typeof BRIDGE_KEYS)[keyof typeof BRIDGE_KEYS];\n","/**\n * The shell policy of the Condor Canvas app, reproduced for the development\n * harness so a command the app refuses is refused in the browser too.\n *\n * Mirrors `apps/canvas/web-mock-src/src/shell.ts` (see\n * `contract/bridge-contract.json` → `verifiedAgainst.sources.shellPolicy`).\n * `tests/dev-harness.test.ts` derives the same lists from the contract and\n * fails if they drift.\n */\n\nimport { BRIDGE_KEYS } from '../keys';\nimport type { ShellPolicy } from '../shell-messages';\n\nexport const CANVAS_POLICY: ShellPolicy = {\n readOnlyKeys: [\n BRIDGE_KEYS.userDevice,\n BRIDGE_KEYS.deviceConnection,\n BRIDGE_KEYS.deviceLightSensors,\n BRIDGE_KEYS.deviceNotification,\n BRIDGE_KEYS.pingPong,\n BRIDGE_KEYS.realTime,\n BRIDGE_KEYS.syncTime,\n BRIDGE_KEYS.deleteMemory,\n BRIDGE_KEYS.sensorLog,\n BRIDGE_KEYS.systemStatus,\n BRIDGE_KEYS.navigationBack,\n BRIDGE_KEYS.language,\n ],\n allowedCommands: [\n 'userDevice',\n 'realTime',\n 'openSettings',\n 'deviceConnection',\n 'ping',\n 'jsError',\n 'sensorLog',\n 'setStatusBarColor',\n 'requestPermission',\n 'navigationState',\n 'language',\n ],\n requiresConfirmation: ['syncTime', 'deleteMemory', 'logout'],\n deniedCommands: ['dfu'],\n};\n\n/** CSP of the app shell, inherited by the client's `srcdoc` iframe. */\nexport const CANVAS_CSP =\n \"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; \" +\n \"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-src 'self'; \" +\n \"object-src 'none'; base-uri 'none'; form-action 'none';\";\n","/**\n * Realistic fixture data for the development harness.\n *\n * Shapes follow the typed payloads in `../payloads`, which mirror the Dart\n * `toMap()` of `condor_core`. Timestamps that the device produces (`log_time`)\n * are **device-local** wall-clock strings, built with local `Date` getters —\n * never `toISOString()`.\n */\n\nimport type {\n DeviceConfigItem,\n DeviceTelemetryItem,\n DeviceUserConfigItem,\n SensorLogItem,\n SensorLogPayload,\n SensorLogQueryPayload,\n SystemStatusPayload,\n UserDevicePayload,\n} from '../payloads';\n\n/** Default log period of an ActLumus, in seconds. Programmable per device. */\nexport const DEFAULT_LOG_PERIOD_S = 60;\n\nconst pad = (n: number): string => String(n).padStart(2, '0');\n\n/** `YYYY-MM-DD HH:MM:SS` in local time — the format of `log_time`. */\nexport function formatLocalTimestamp(date: Date): string {\n return (\n `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +\n `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n );\n}\n\n/** Parses a local `YYYY-MM-DD HH:MM:SS` back to epoch ms. */\nexport function parseLocalTimestamp(value: string): number {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/.exec(value);\n if (!m) return Number.NaN;\n const [, y, mo, d, h, mi, s] = m.map(Number) as number[];\n return new Date(y ?? 0, (mo ?? 1) - 1, d ?? 1, h ?? 0, mi ?? 0, s ?? 0).getTime();\n}\n\ninterface DeviceSpec {\n deviceId: number;\n serialNo: number;\n modelId?: DeviceConfigItem['modelId'];\n bodyPart: DeviceConfigItem['deviceBodyPart'];\n name: string;\n battery: number;\n charging: boolean;\n syncedMinutesAgo: number;\n syncError?: string;\n}\n\nfunction config(spec: DeviceSpec): DeviceConfigItem {\n const item: DeviceConfigItem = {\n deviceId: spec.deviceId,\n serialNo: spec.serialNo,\n deviceBodyPart: spec.bodyPart,\n bleConnectionPeriod: 5,\n autosync: true,\n eraseDeviceMemory: false,\n autoEraseDeviceMemory: false,\n autoEraseDeviceMemoryThreshold: 80,\n readSensorsMemory: false,\n startDevice: false,\n readFullMemory: false,\n allowFirmwareUpdate: true,\n };\n if (spec.modelId) item.modelId = spec.modelId;\n return item;\n}\n\nfunction telemetry(spec: DeviceSpec, now: number): DeviceTelemetryItem {\n return {\n serialNo: spec.serialNo,\n deviceId: spec.deviceId,\n updataDateTime: now - spec.syncedMinutesAgo * 60_000,\n deviceName: spec.name,\n deviceVersion: spec.modelId === 'actlumus_plus' ? '3.0.2' : '2.1.0',\n hardwareVersion: spec.modelId === 'actlumus_plus' ? 'B' : 'A',\n deviceDateTime: now - spec.syncedMinutesAgo * 60_000,\n memoryDataUsage: 37.5,\n memorySystemUsage: 4.2,\n batteryLevel: spec.battery,\n batteryVoltage: 3.7 + spec.battery / 1000,\n isCharging: spec.charging,\n isOnDock: spec.charging,\n syncErrors: spec.syncError\n ? [\n {\n serialNo: spec.serialNo,\n attemptDate: now - 10 * 60_000,\n message: spec.syncError,\n messageCode: 'SYNC_FAILED',\n },\n ]\n : [],\n };\n}\n\nfunction userConfig(spec: DeviceSpec): DeviceUserConfigItem {\n return {\n serialNo: spec.serialNo,\n deviceId: spec.deviceId,\n syncTime: false,\n realTime: false,\n deleteMemory: false,\n readAllMemory: false,\n readAllSystemLog: false,\n };\n}\n\nfunction payloadOf(specs: DeviceSpec[], now = Date.now()): UserDevicePayload {\n return {\n lastUpdate: now,\n devicesConfig: specs.map(config),\n devicesTelemetry: specs.map((s) => telemetry(s, now)),\n devicesUserConfig: specs.map(userConfig),\n };\n}\n\n/** Two devices with distinct serial numbers: the common case. */\nexport function twoDevices(now = Date.now()): UserDevicePayload {\n return payloadOf(\n [\n {\n deviceId: 9001,\n serialNo: 4534,\n modelId: 'actlumus',\n bodyPart: 'wrist',\n name: 'ActLumus 4534',\n battery: 82,\n charging: false,\n syncedMinutesAgo: 12,\n },\n {\n deviceId: 9002,\n serialNo: 5120,\n modelId: 'actlumus_plus',\n bodyPart: 'necklace',\n name: 'ActLumus Plus 5120',\n battery: 41,\n charging: true,\n syncedMinutesAgo: 190,\n syncError: 'Could not read the device memory.',\n },\n ],\n now,\n );\n}\n\n/**\n * An ActLumus and an ActLumus Plus sharing serial number 7047 — real data\n * looked like this for the first pilot account. Only `deviceId` tells them\n * apart.\n */\nexport function sharedSerial(now = Date.now()): UserDevicePayload {\n return payloadOf(\n [\n {\n deviceId: 9101,\n serialNo: 7047,\n bodyPart: 'wrist',\n name: 'ActLumus 7047',\n battery: 67,\n charging: false,\n syncedMinutesAgo: 30,\n },\n {\n deviceId: 9102,\n serialNo: 7047,\n modelId: 'actlumus_plus',\n bodyPart: 'necklace',\n name: 'ActLumus Plus 7047',\n battery: 93,\n charging: false,\n syncedMinutesAgo: 8,\n },\n ],\n now,\n );\n}\n\nexport function systemStatus(overrides: Partial<SystemStatusPayload> = {}): SystemStatusPayload {\n return {\n bluetooth: true,\n internet: true,\n permission: true,\n hasDevices: true,\n missingOptionalPermissions: [],\n missingEssentialPermissions: [],\n deviceSyncError: {},\n deviceSyncErrorById: {},\n ...overrides,\n };\n}\n\n/** Light follows a daylight curve so charts look like real data. */\nfunction lightAt(epochMs: number, serialNo: number): { photopic: number; melanopic: number } {\n const d = new Date(epochMs);\n const hour = d.getHours() + d.getMinutes() / 60;\n const daylight = Math.max(0, Math.sin(((hour - 6) / 12) * Math.PI));\n const noise = ((epochMs / 60_000 + serialNo) % 7) / 7;\n const photopic = Math.round((daylight * 1800 + noise * 40) * 10) / 10;\n return { photopic, melanopic: Math.round(photopic * 0.62 * 10) / 10 };\n}\n\nfunction logAt(epochMs: number, serialNo: number, deviceId: number): SensorLogItem {\n const { photopic, melanopic } = lightAt(epochMs, serialNo);\n return {\n id: Math.floor(epochMs / 1000) * 10 + (serialNo % 10),\n log_time: formatLocalTimestamp(new Date(epochMs)),\n log_type: 1,\n body_part: 'wrist',\n temperature: 31.5,\n lux_photopic: photopic,\n lux_melanopic: melanopic,\n device_id: deviceId,\n act_data_pim: 120,\n };\n}\n\nconst HISTORY_DAYS = 14;\nconst encodeCursor = (epochMs: number): string => `mock:${epochMs}`;\nconst decodeCursor = (cursor: string): number => Number(cursor.slice('mock:'.length));\n\n/**\n * Answers a `sensorLog` query with the backend's paging semantics:\n * - no range: the most recent `limit` logs; older pages through `endingBefore`;\n * - with `startTime`: the oldest logs of the range first; newer pages through\n * `startingAfter` (with only `endTime`: the most recent before it);\n * - `logs` always chronological ascending; `hasMore` / `hasPrevious` computed\n * within the range.\n */\nexport function sensorLogPage(\n query: SensorLogQueryPayload,\n opts: { now?: number; periodS?: number; deviceId?: number } = {},\n): SensorLogPayload {\n const now = opts.now ?? Date.now();\n const periodMs = (opts.periodS ?? DEFAULT_LOG_PERIOD_S) * 1000;\n const limit = query.limit ?? 10;\n if (limit < 1 || limit > 1000) {\n return { requestId: query.requestId, success: false, error: 'INVALID_LIMIT' };\n }\n if (query.startingAfter && query.endingBefore) {\n return { requestId: query.requestId, success: false, error: 'CONFLICTING_CURSORS' };\n }\n\n const newest = Math.floor(now / periodMs) * periodMs;\n const oldest = newest - HISTORY_DAYS * 86_400_000;\n const rangeStart = query.startTime ? parseLocalTimestamp(query.startTime) : oldest;\n const rangeEnd = query.endTime ? parseLocalTimestamp(query.endTime) - 1 : newest;\n if (Number.isNaN(rangeStart) || Number.isNaN(rangeEnd) || rangeStart > rangeEnd + 1) {\n return { requestId: query.requestId, success: false, error: 'INVALID_TIME_RANGE' };\n }\n const first = Math.max(oldest, Math.ceil(rangeStart / periodMs) * periodMs);\n const last = Math.min(newest, Math.floor(rangeEnd / periodMs) * periodMs);\n\n let from: number;\n let to: number;\n if (query.endingBefore) {\n to = Math.min(last, decodeCursor(query.endingBefore) - periodMs);\n from = Math.max(first, to - (limit - 1) * periodMs);\n } else if (query.startingAfter) {\n from = Math.max(first, decodeCursor(query.startingAfter) + periodMs);\n to = Math.min(last, from + (limit - 1) * periodMs);\n } else if (query.startTime) {\n from = first;\n to = Math.min(last, from + (limit - 1) * periodMs);\n } else {\n to = last;\n from = Math.max(first, to - (limit - 1) * periodMs);\n }\n\n const logs: SensorLogItem[] = [];\n for (let t = from; t <= to; t += periodMs) {\n logs.push(logAt(t, query.serialNo, opts.deviceId ?? 0));\n }\n return {\n requestId: query.requestId,\n success: true,\n logs,\n startingAfter: logs.length ? encodeCursor(to) : null,\n endingBefore: logs.length ? encodeCursor(from) : null,\n hasMore: logs.length > 0 && to < last,\n hasPrevious: logs.length > 0 && from > first,\n };\n}\n","/**\n * Scenarios for the development harness — the device behaviours that a plain\n * \"answer everything at once\" mock hides.\n *\n * Each one reproduces something the Condor Canvas app really does, so a bundle\n * that survives every scenario in the browser survives them on a device.\n */\n\nimport type { SystemStatusPayload, UserDevicePayload } from '../payloads';\nimport { sharedSerial, systemStatus, twoDevices } from './fixtures';\n\n/** Native schema version the harness reports by default. */\nexport const HARNESS_NATIVE_VERSION = '0.17.0';\n\nexport interface Scenario {\n /** Shown in the harness toolbar. */\n description: string;\n /**\n * Relayed to the client by the handshake. `null` reproduces a shell that\n * could not reach the native side: the client receives `nativeVersion: null`.\n */\n nativeVersion: string | null;\n /** Delay of every native reply, in ms. A pair draws uniformly from the range. */\n latencyMs: number | [min: number, max: number];\n /**\n * Time until the app's background service is up, in ms after the page loads.\n * Until then `ping` and `userDevice` are **dropped without a reply** — on\n * the device they travel to that service, and a message sent before it runs\n * is lost.\n */\n serviceStartMs: number;\n /**\n * `userDevice` never answers. Today the app replies only when the device\n * list loads, so an account with no linked device gets silence.\n */\n userDeviceSilent: boolean;\n /** When set, every `sensorLog` reply fails with this `error`. */\n sensorLogError?: string;\n /** Log period of the devices, in seconds (programmable; default 60). */\n logPeriodS: number;\n systemStatus: SystemStatusPayload;\n devices: () => UserDevicePayload;\n}\n\nexport type ScenarioName = 'default' | 'cold-start' | 'no-devices' | 'shared-serial' | 'offline';\n\nconst base: Scenario = {\n description: 'Two devices, background service already running, realistic latency.',\n nativeVersion: HARNESS_NATIVE_VERSION,\n latencyMs: [80, 250],\n serviceStartMs: 0,\n userDeviceSilent: false,\n logPeriodS: 60,\n systemStatus: systemStatus(),\n devices: () => twoDevices(),\n};\n\nexport const SCENARIOS: Record<ScenarioName, Scenario> = {\n default: base,\n 'cold-start': {\n ...base,\n description:\n 'App launched from cold: the background service takes 4 s to start, and ' +\n 'every ping/userDevice sent before that is lost. A bundle that asks once ' +\n 'stays on its loading screen forever.',\n serviceStartMs: 4000,\n },\n 'no-devices': {\n ...base,\n description:\n 'Account with no linked device: userDevice never answers and ' +\n 'systemStatus.hasDevices is false. Your bundle must show an empty state.',\n userDeviceSilent: true,\n systemStatus: systemStatus({ hasDevices: false }),\n },\n 'shared-serial': {\n ...base,\n description:\n 'An ActLumus and an ActLumus Plus share serial number 7047. Only deviceId ' +\n 'tells them apart; sensorLog cannot address one of them.',\n devices: () => sharedSerial(),\n },\n offline: {\n ...base,\n description:\n 'No internet. systemStatus.internet is false and sensorLog fails; ' +\n 'userDevice answers from the cache.',\n sensorLogError: 'Connection failed',\n systemStatus: systemStatus({ internet: false }),\n },\n};\n\nexport function resolveScenario(scenario: ScenarioName | Scenario | undefined): Scenario {\n if (scenario === undefined) return SCENARIOS.default;\n if (typeof scenario === 'string') {\n const found = SCENARIOS[scenario];\n if (!found) {\n throw new Error(\n `condor-mobile-bridge dev: unknown scenario \"${scenario}\". ` +\n `Known: ${Object.keys(SCENARIOS).join(', ')}.`,\n );\n }\n return found;\n }\n return scenario;\n}\n"],"mappings":";;;;AAMA,IAAAA,kBAAyC;AACzC,IAAAC,oBAAiC;;;ACcjC,yBAA2B;AAC3B,qBAA6B;AAC7B,uBAA0C;AAC1C,oBAA4C;AAC5C,8BAAwC;AAGjC,IAAM,oBAAoB,IAAI,OAAO;AAG5C,IAAM,cAAc,oBAAI,KAAK,sBAAsB;AAG5C,IAAM,aAAqC;AAAA,EAChD,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AACX;AAGA,SAAS,mBAAmB,KAAsB;AAChD,SAAO,mBAAmB,KAAK,GAAG,KAAK,UAAU,KAAK,GAAG,KAAK,qBAAqB,KAAK,GAAG;AAC7F;AAGA,SAAS,eAAe,KAAqB;AAC3C,SAAO,IAAI,MAAM,MAAM,EAAE,CAAC,KAAK;AACjC;AAUA,SAAS,aAAa,UAAkB,aAAqB,KAAqB;AAChF,QAAM,QAAQ,eAAe,GAAG;AAChC,SAAO,MAAM,WAAW,GAAG,QAAI,0BAAQ,UAAU,IAAI,KAAK,EAAE,QAAI,0BAAQ,aAAa,KAAK;AAC5F;AAGO,SAAS,UAAU,UAA0B;AAClD,QAAM,YAAQ,6BAAa,QAAQ;AACnC,QAAM,OAAO,eAAW,0BAAQ,QAAQ,EAAE,Y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