File size: 12,974 Bytes
914f53d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | /// <reference types="bun-types" />
import {afterEach, beforeEach, describe, expect, setSystemTime, test} from "bun:test"
import {createHash} from "node:crypto"
import {mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync} from "fs"
import {tmpdir} from "os"
import {join} from "path"
import JSZip from "jszip"
import {
buildProjectSnapshot,
buildProjectZip,
classifyWatchEvent,
listProjectFiles,
reloadSignalsForBatch,
startDevSidecar,
} from "./dev-server"
describe("listProjectFiles — dist/ inclusion", () => {
let root: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "mentra-dev-test-"))
})
afterEach(() => {
rmSync(root, {recursive: true, force: true})
})
function touch(rel: string, contents = "// stub") {
const abs = join(root, rel)
mkdirSync(join(abs, ".."), {recursive: true})
writeFileSync(abs, contents)
}
// Convenience: the zip-internal entry names the function produces.
const entries = (root: string) => listProjectFiles(root).map((f) => f.entry)
test("ships both build bundles with the dist/ prefix stripped off the entry names", () => {
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test"}')
touch("dist/background/index.js")
touch("dist/ui/index.html")
touch("dist/ui/main.js")
touch("src/background/index.ts")
const listed = listProjectFiles(root)
// disk paths keep dist/ (that's where the files live)…
expect(listed.map((f) => f.disk)).toContain("dist/background/index.js")
// …but zip entry names drop it, matching miniapp.json's entry.* paths.
expect(entries(root)).toContain("background/index.js")
expect(entries(root)).toContain("ui/index.html")
expect(entries(root)).toContain("ui/main.js")
expect(entries(root)).toContain("miniapp.json")
expect(entries(root)).not.toContain("dist/background/index.js")
})
test("strict allowlist: source + build config + node_modules + public are NOT shipped", () => {
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test"}')
touch("dist/background/index.js")
touch("src/background/index.ts")
touch("package.json")
touch("tsconfig.json")
touch("build.ts")
touch("bunfig.toml")
touch("node_modules/x/index.js")
touch("public/fonts/big.ttf")
const listed = entries(root)
expect(listed.some((p) => p.startsWith("src/"))).toBe(false)
expect(listed.some((p) => p.startsWith("public/"))).toBe(false)
expect(listed.some((p) => p.startsWith("node_modules/"))).toBe(false)
expect(listed).not.toContain("package.json")
expect(listed).not.toContain("tsconfig.json")
expect(listed).not.toContain("build.ts")
expect(listed).not.toContain("bunfig.toml")
expect(listed).toContain("miniapp.json")
expect(listed).toContain("background/index.js")
})
test("ships the manifest-declared icon and skips unrelated images", () => {
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test","icon":"my-icon.png"}')
touch("my-icon.png")
touch("other-image.png")
touch("dist/background/index.js")
const listed = entries(root)
expect(listed).toContain("my-icon.png")
expect(listed).not.toContain("other-image.png")
})
test("defaults to icon.png when manifest does not declare an icon", () => {
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test"}')
touch("icon.png")
touch("dist/background/index.js")
const listed = entries(root)
expect(listed).toContain("icon.png")
})
test("skips icon if it is missing from disk (manifest may be stale)", () => {
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test","icon":"icon.png"}')
touch("dist/background/index.js")
const listed = entries(root)
expect(listed).not.toContain("icon.png")
})
})
describe("buildProjectZip — two-output bundle contract", () => {
let root: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "mentra-zip-test-"))
})
afterEach(() => {
rmSync(root, {recursive: true, force: true})
})
function touch(rel: string, contents = "// stub") {
const abs = join(root, rel)
mkdirSync(join(abs, ".."), {recursive: true})
writeFileSync(abs, contents)
}
test("zip ships both bundles at the root (dist/ prefix stripped), manifest at root", async () => {
touch("miniapp.json", '{"packageName":"com.test","version":"1.0.0","name":"Test","hardwareRequirements":[]}')
touch("dist/background/index.js", "console.log('bg')")
touch("dist/ui/index.html", "<!doctype html><html></html>")
touch("dist/ui/main.js", "console.log('ui')")
const buf = await buildProjectZip(root)
const zip = await JSZip.loadAsync(buf)
expect(zip.files["miniapp.json"]).toBeDefined()
expect(zip.files["background/index.js"]).toBeDefined()
expect(zip.files["ui/index.html"]).toBeDefined()
expect(zip.files["ui/main.js"]).toBeDefined()
// The on-disk dist/ prefix must not leak into the zip layout.
expect(zip.files["dist/background/index.js"]).toBeUndefined()
})
test("zip preserves file contents byte-for-byte", async () => {
touch("miniapp.json", '{"a":1}')
touch("dist/background/index.js", "/* bg-stub */")
const buf = await buildProjectZip(root)
const zip = await JSZip.loadAsync(buf)
const manifest = await zip.files["miniapp.json"]!.async("string")
const bg = await zip.files["background/index.js"]!.async("string")
expect(manifest).toBe('{"a":1}')
expect(bg).toBe("/* bg-stub */")
})
})
describe("buildProjectSnapshot: the ZIP the served miniapp.json names", () => {
let root: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "mentra-snapshot-test-"))
})
afterEach(() => {
setSystemTime()
rmSync(root, {recursive: true, force: true})
})
function touch(rel: string, contents = "// stub") {
const abs = join(root, rel)
mkdirSync(join(abs, ".."), {recursive: true})
writeFileSync(abs, contents)
}
const manifest = '{"packageName":"com.test","version":"1.0.0","name":"Test","hardwareRequirements":[]}'
test("names the ZIP's SHA-256 and the miniapp.json inside it", async () => {
touch("miniapp.json", manifest)
touch("dist/background/index.js", "console.log('bg')")
const snapshot = await buildProjectSnapshot(root)
expect(snapshot.sha256).toBe(createHash("sha256").update(snapshot.zip).digest("hex"))
expect(snapshot.manifest).toBe(manifest)
const zip = await JSZip.loadAsync(snapshot.zip)
expect(await zip.files["miniapp.json"]!.async("string")).toBe(manifest)
})
test("the same files make the same ZIP, whenever it is built", async () => {
touch("miniapp.json", manifest)
touch("dist/background/index.js", "console.log('bg')")
touch("dist/ui/assets/main.js", "console.log('ui')")
setSystemTime(new Date("2026-01-01T10:00:00Z"))
const first = await buildProjectSnapshot(root)
setSystemTime(new Date("2026-06-01T18:30:07Z"))
const second = await buildProjectSnapshot(root)
expect(second.sha256).toBe(first.sha256)
expect(Buffer.from(second.zip).equals(Buffer.from(first.zip))).toBe(true)
expect(await buildProjectZip(root)).toEqual(second.zip)
})
test("changed files make a different ZIP", async () => {
touch("miniapp.json", manifest)
touch("dist/background/index.js", "console.log('bg')")
const before = await buildProjectSnapshot(root)
touch("dist/background/index.js", "console.log('bg 2')")
expect((await buildProjectSnapshot(root)).sha256).not.toBe(before.sha256)
})
test("a project without miniapp.json has no manifest", async () => {
touch("dist/background/index.js")
expect((await buildProjectSnapshot(root)).manifest).toBeNull()
})
})
describe("classifyWatchEvent: which layer a watcher event touched", () => {
test("POSIX paths: background respawns, UI and other files reload", () => {
expect(classifyWatchEvent("src/background/index.ts", "/")).toBe("respawn-bg")
expect(classifyWatchEvent("packages/app/src/background/index.ts", "/")).toBe("respawn-bg")
expect(classifyWatchEvent("src/ui/App.tsx", "/")).toBe("reload")
expect(classifyWatchEvent("miniapp.json", "/")).toBe("reload")
})
test("POSIX paths: build output, dependencies and bare directory events are ignored", () => {
expect(classifyWatchEvent(".", "/")).toBe("ignore")
expect(classifyWatchEvent("dist", "/")).toBe("ignore")
expect(classifyWatchEvent("dist/background/index.js", "/")).toBe("ignore")
expect(classifyWatchEvent("node_modules/jszip/index.js", "/")).toBe("ignore")
expect(classifyWatchEvent(".git/index", "/")).toBe("ignore")
expect(classifyWatchEvent("build/app.zip", "/")).toBe("ignore")
expect(classifyWatchEvent(".next/cache", "/")).toBe("ignore")
})
// Windows fs.watch reports paths with backslashes (Mentra-Community/MentraOS#3888).
test("Windows paths: background respawns, UI and other files reload", () => {
expect(classifyWatchEvent("src\\background\\index.ts", "\\")).toBe("respawn-bg")
expect(classifyWatchEvent("packages\\app\\src\\background\\index.ts", "\\")).toBe("respawn-bg")
expect(classifyWatchEvent("src\\ui\\App.tsx", "\\")).toBe("reload")
})
test("Windows paths: build output and dependencies are ignored", () => {
expect(classifyWatchEvent("dist\\background\\index.js", "\\")).toBe("ignore")
expect(classifyWatchEvent("node_modules\\jszip\\index.js", "\\")).toBe("ignore")
expect(classifyWatchEvent(".git\\index", "\\")).toBe("ignore")
})
test("a backslash is left alone on platforms where it is not the separator", () => {
expect(classifyWatchEvent("src\\background\\index.ts", "/")).toBe("reload")
})
})
describe("classifyWatchEvent: shared code", () => {
test("src/shared/ is imported by both layers, so it needs both", () => {
expect(classifyWatchEvent("src/shared/channels.ts", "/")).toBe("both")
expect(classifyWatchEvent("packages/app/src/shared/channels.ts", "/")).toBe("both")
expect(classifyWatchEvent("src\\shared\\channels.ts", "\\")).toBe("both")
})
})
describe("reloadSignalsForBatch: what one save sends the phone", () => {
test("one layer sends its own signal", () => {
expect(reloadSignalsForBatch(["reload", "reload"])).toEqual(["reload"])
expect(reloadSignalsForBatch(["respawn-bg"])).toEqual(["respawn-bg"])
})
test("both layers send both, the background first", () => {
expect(reloadSignalsForBatch(["reload", "respawn-bg"])).toEqual(["respawn-bg", "reload"])
expect(reloadSignalsForBatch(["respawn-bg", "reload"])).toEqual(["respawn-bg", "reload"])
expect(reloadSignalsForBatch(["both"])).toEqual(["respawn-bg", "reload"])
})
test("an empty batch sends nothing", () => {
expect(reloadSignalsForBatch([])).toEqual([])
})
})
describe("startDevSidecar: a save that touches both layers", () => {
let dir: string
let sidecar: ReturnType<typeof startDevSidecar> | null = null
beforeEach(() => {
dir = realpathSync(mkdtempSync(join(tmpdir(), "mentra-dev-sidecar-")))
mkdirSync(join(dir, "src", "ui"), {recursive: true})
mkdirSync(join(dir, "src", "background"), {recursive: true})
})
afterEach(() => {
sidecar?.stop()
sidecar = null
rmSync(dir, {recursive: true, force: true})
})
test("respawns the background and reloads the screen", async () => {
const port = 47_000 + Math.floor(Math.random() * 2_000)
sidecar = startDevSidecar({port, watchDir: dir, silent: true})
const received: string[] = []
const ws = new WebSocket(`ws://127.0.0.1:${port}/__mentra_dev`)
await new Promise<void>((resolve, reject) => {
ws.onopen = () => resolve()
ws.onerror = () => reject(new Error("sidecar socket failed"))
})
ws.onmessage = (event) => received.push(JSON.parse(String(event.data)).type)
// Let the watcher settle before the save.
await Bun.sleep(1_000)
writeFileSync(join(dir, "src", "ui", "App.tsx"), "export const ui = 2\n")
writeFileSync(join(dir, "src", "background", "index.ts"), "export const bg = 2\n")
const deadline = Date.now() + 10_000
const both = () => received.includes("respawn-bg") && received.includes("reload")
while (!both() && Date.now() < deadline) await Bun.sleep(50)
ws.close()
// One batch sends ["respawn-bg", "reload"]; on a slow machine the two writes can land in separate batches. Either
// way the screen reloads, which a lone respawn-bg never did.
expect([...new Set(received)].sort()).toEqual(["reload", "respawn-bg"])
}, 20_000)
})
|