@iwsdk/cli 1.1.0 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +106 -2
  2. package/dist/agent-adapters.d.ts +12 -1
  3. package/dist/agent-adapters.d.ts.map +1 -1
  4. package/dist/agent-guidance/files/.agents/skills/iwsdk-build-model/SKILL.md +312 -0
  5. package/dist/agent-guidance/files/.agents/skills/iwsdk-build-model/agents/openai.yaml +4 -0
  6. package/dist/agent-guidance/files/.agents/skills/iwsdk-build-model/assets/hardsurface.ts.template +599 -0
  7. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/SKILL.md +277 -0
  8. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/agents/openai.yaml +4 -0
  9. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/environment-recipes.md +234 -0
  10. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/extended-workflow.md +166 -0
  11. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/image-intake.md +190 -0
  12. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/scene-composition.md +80 -0
  13. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/scene-format.md +466 -0
  14. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/scene-review.md +66 -0
  15. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/references/text-intake.md +80 -0
  16. package/dist/agent-guidance/files/.agents/skills/iwsdk-debug/SKILL.md +74 -0
  17. package/dist/agent-guidance/files/.agents/skills/iwsdk-depth-occlusion/SKILL.md +88 -0
  18. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/SKILL.md +46 -0
  19. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/api-reference.md +1532 -0
  20. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/headless-rendering.md +96 -0
  21. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/iterate.md +267 -0
  22. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/planner.md +307 -0
  23. package/dist/agent-guidance/files/.agents/skills/iwsdk-glasses-test/SKILL.md +282 -0
  24. package/dist/agent-guidance/files/.agents/skills/iwsdk-grab/SKILL.md +75 -0
  25. package/dist/agent-guidance/files/.agents/skills/iwsdk-hosting/SKILL.md +179 -0
  26. package/dist/agent-guidance/files/.agents/skills/iwsdk-hosting/references/existing-hosts.md +181 -0
  27. package/dist/agent-guidance/files/.agents/skills/iwsdk-hosting/references/vercel.md +114 -0
  28. package/dist/agent-guidance/files/.agents/skills/iwsdk-native-xr-test/SKILL.md +262 -0
  29. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/SKILL.md +217 -0
  30. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  31. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/sw.js.template +241 -0
  32. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  33. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/build-step.md +71 -0
  34. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/page.md +70 -0
  35. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/service-worker.md +107 -0
  36. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/testing.md +57 -0
  37. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/SKILL.md +106 -0
  38. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/component-reference.md +152 -0
  39. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/tuning-and-config.md +102 -0
  40. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/workflows.md +309 -0
  41. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/SKILL.md +230 -0
  42. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/app-modes.md +104 -0
  43. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/bubblewrap.md +219 -0
  44. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +149 -0
  45. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/store-upload.md +104 -0
  46. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/troubleshooting.md +208 -0
  47. package/dist/agent-guidance/files/.agents/skills/iwsdk-ray/SKILL.md +70 -0
  48. package/dist/agent-guidance/files/.agents/skills/iwsdk-ui/SKILL.md +335 -0
  49. package/dist/agent-guidance/files/.agents/skills/iwsdk-upgrade/SKILL.md +74 -0
  50. package/dist/agent-guidance/files/.claude/agents/iwsdk-project-code-reviewer.md +521 -0
  51. package/dist/agent-guidance/files/.claude/rules/assets-and-manifest.md +60 -0
  52. package/dist/agent-guidance/files/.claude/rules/ecs-api.md +103 -0
  53. package/dist/agent-guidance/files/.claude/rules/scene-json.md +72 -0
  54. package/dist/agent-guidance/files/.claude/rules/uikitml.md +66 -0
  55. package/dist/agent-guidance/files/.claude/settings.json +30 -0
  56. package/dist/agent-guidance/files/.claude/skills/iwsdk-build-model/SKILL.md +312 -0
  57. package/dist/agent-guidance/files/.claude/skills/iwsdk-build-model/agents/openai.yaml +4 -0
  58. package/dist/agent-guidance/files/.claude/skills/iwsdk-build-model/assets/hardsurface.ts.template +599 -0
  59. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/SKILL.md +277 -0
  60. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/agents/openai.yaml +4 -0
  61. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/environment-recipes.md +234 -0
  62. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/extended-workflow.md +166 -0
  63. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/image-intake.md +190 -0
  64. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/scene-composition.md +80 -0
  65. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/scene-format.md +466 -0
  66. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/scene-review.md +66 -0
  67. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/references/text-intake.md +80 -0
  68. package/dist/agent-guidance/files/.claude/skills/iwsdk-debug/SKILL.md +74 -0
  69. package/dist/agent-guidance/files/.claude/skills/iwsdk-depth-occlusion/SKILL.md +88 -0
  70. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/SKILL.md +46 -0
  71. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/api-reference.md +1532 -0
  72. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/headless-rendering.md +96 -0
  73. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/iterate.md +267 -0
  74. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/planner.md +307 -0
  75. package/dist/agent-guidance/files/.claude/skills/iwsdk-glasses-test/SKILL.md +282 -0
  76. package/dist/agent-guidance/files/.claude/skills/iwsdk-grab/SKILL.md +75 -0
  77. package/dist/agent-guidance/files/.claude/skills/iwsdk-hosting/SKILL.md +179 -0
  78. package/dist/agent-guidance/files/.claude/skills/iwsdk-hosting/references/existing-hosts.md +181 -0
  79. package/dist/agent-guidance/files/.claude/skills/iwsdk-hosting/references/vercel.md +114 -0
  80. package/dist/agent-guidance/files/.claude/skills/iwsdk-native-xr-test/SKILL.md +262 -0
  81. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/SKILL.md +217 -0
  82. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  83. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/sw.js.template +241 -0
  84. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  85. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/build-step.md +71 -0
  86. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/page.md +70 -0
  87. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/service-worker.md +107 -0
  88. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/testing.md +57 -0
  89. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/SKILL.md +106 -0
  90. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/component-reference.md +152 -0
  91. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/tuning-and-config.md +102 -0
  92. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/workflows.md +309 -0
  93. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/SKILL.md +230 -0
  94. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/app-modes.md +104 -0
  95. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/bubblewrap.md +219 -0
  96. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +149 -0
  97. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/store-upload.md +104 -0
  98. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/troubleshooting.md +208 -0
  99. package/dist/agent-guidance/files/.claude/skills/iwsdk-ray/SKILL.md +70 -0
  100. package/dist/agent-guidance/files/.claude/skills/iwsdk-ui/SKILL.md +335 -0
  101. package/dist/agent-guidance/files/.claude/skills/iwsdk-upgrade/SKILL.md +74 -0
  102. package/dist/agent-guidance/files/.cursor/rules/assets-and-manifest.mdc +62 -0
  103. package/dist/agent-guidance/files/.cursor/rules/ecs-api.mdc +105 -0
  104. package/dist/agent-guidance/files/.cursor/rules/scene-json.mdc +74 -0
  105. package/dist/agent-guidance/files/.cursor/rules/uikitml.mdc +68 -0
  106. package/dist/agent-guidance/files/.github/instructions/assets-and-manifest.instructions.md +55 -0
  107. package/dist/agent-guidance/files/.github/instructions/ecs-api.instructions.md +101 -0
  108. package/dist/agent-guidance/files/.github/instructions/scene-json.instructions.md +71 -0
  109. package/dist/agent-guidance/files/.github/instructions/uikitml.instructions.md +65 -0
  110. package/{guidance → dist/agent-guidance/files}/AGENTS.md +107 -27
  111. package/dist/agent-guidance/files/CLAUDE.md +3 -0
  112. package/dist/agent-guidance/files/public/scenes/AGENTS.md +72 -0
  113. package/dist/agent-guidance/files/public/ui/AGENTS.md +66 -0
  114. package/dist/agent-guidance/files/src/AGENTS.md +153 -0
  115. package/dist/agent-guidance/manifest.json +954 -0
  116. package/dist/agent-guidance.d.ts +140 -0
  117. package/dist/agent-guidance.d.ts.map +1 -0
  118. package/dist/agent-guidance.js +3612 -0
  119. package/dist/agent-guidance.js.map +1 -0
  120. package/dist/cli.js +4010 -750
  121. package/dist/cli.js.map +1 -1
  122. package/dist/commands/adapter.d.ts +1 -0
  123. package/dist/commands/adapter.d.ts.map +1 -1
  124. package/dist/commands/agents.d.ts +11 -0
  125. package/dist/commands/agents.d.ts.map +1 -0
  126. package/dist/commands/browser.d.ts +11 -0
  127. package/dist/commands/browser.d.ts.map +1 -1
  128. package/dist/commands/dev.d.ts +1 -0
  129. package/dist/commands/dev.d.ts.map +1 -1
  130. package/dist/commands/reference.d.ts +15 -1
  131. package/dist/commands/reference.d.ts.map +1 -1
  132. package/dist/commands/runtime.d.ts.map +1 -1
  133. package/dist/commands/upgrade.d.ts +138 -0
  134. package/dist/commands/upgrade.d.ts.map +1 -0
  135. package/dist/contract.js +32 -0
  136. package/dist/contract.js.map +1 -1
  137. package/dist/guidance-refresh.d.ts +53 -0
  138. package/dist/guidance-refresh.d.ts.map +1 -0
  139. package/dist/help.d.ts +2 -0
  140. package/dist/help.d.ts.map +1 -1
  141. package/dist/index.d.ts.map +1 -1
  142. package/dist/index.js +6114 -508
  143. package/dist/index.js.map +1 -1
  144. package/dist/mcp-stdio.d.ts.map +1 -1
  145. package/dist/metavr-telemetry.d.ts +6 -0
  146. package/dist/metavr-telemetry.d.ts.map +1 -1
  147. package/dist/migrations/iwsdk-migrate-0-5/SKILL.md +413 -0
  148. package/dist/migrations.d.ts +36 -0
  149. package/dist/migrations.d.ts.map +1 -0
  150. package/dist/package-manager.d.ts +34 -0
  151. package/dist/package-manager.d.ts.map +1 -0
  152. package/dist/release-notes.d.ts +28 -0
  153. package/dist/release-notes.d.ts.map +1 -0
  154. package/dist/release-notes.json +1506 -0
  155. package/dist/runtime-contract.d.ts +8 -0
  156. package/dist/runtime-contract.d.ts.map +1 -1
  157. package/dist/runtime-telemetry.d.ts +8 -1
  158. package/dist/runtime-telemetry.d.ts.map +1 -1
  159. package/dist/version.d.ts +1 -1
  160. package/package.json +9 -3
@@ -0,0 +1,217 @@
1
+ ---
2
+ name: iwsdk-offline
3
+ description: Make an IWSDK app run with no connection after one online visit — a service worker that keeps one hash-checked copy of the current release, downloads each file once, and swaps releases only when nothing would be interrupted. Use when the app must work offline or survive a dropped connection, when an installed PWA/TWA must launch without a network, or when an offline copy serves a stale release, misses files, or downloads everything twice.
4
+ argument-hint: '[offline goal, e.g. "work offline" or "launch offline from the Store"]'
5
+ ---
6
+
7
+ # Offline Copy
8
+
9
+ A built IWSDK app is a static `dist/`, so it can run with no connection once a
10
+ service worker holds a complete copy of it. This design keeps exactly one
11
+ release on the device: the build lists every file with its SHA-256, the worker
12
+ copies that list and answers from it cache-first, and the page alone decides
13
+ when the next release takes over. Each file crosses the wire once, nothing
14
+ unchecked is kept, and a release never swaps mid-session.
15
+
16
+ User request is in `$ARGUMENTS`.
17
+
18
+ ```
19
+ 1. Sort the files → release list, kept on request, or never cached
20
+ 2. Copy the kit → build script, worker template, page module + build step
21
+ 3. Adapt the worker → cache names and PINNED third-party paths
22
+ 4. Wire the page → startOffline() and keepOfflineCopy() in src/index.ts
23
+ 5. Hosting → sw.js uncached, hashed files immutable [iwsdk-hosting]
24
+ 6. Verify → first visit, reload, offline, update, mid-session, two pages
25
+ ```
26
+
27
+ The kit in `assets/` was tested end to end in Chromium against an IWSDK starter
28
+ build — first visit, reload, offline, update, and an update during an XR
29
+ session. Copy it verbatim and change only what steps 2–4 name; a rewrite loses
30
+ that.
31
+
32
+ ## Step 1 — Sort the files
33
+
34
+ Ask of every file the build emits or the app fetches:
35
+
36
+ | Question | If yes |
37
+ | --- | --- |
38
+ | Does the build produce it, and does every user need it to run? | release list — copied at install |
39
+ | Do only some users need it (extra levels, other languages' fonts, HD packs)? | `ON_REQUEST` — kept the first time it is fetched |
40
+ | Is it a third-party file at a version named in its URL? | `PINNED` — kept in a long-lived cache on first fetch |
41
+ | Does the server decide it per user or per moment (APIs, sign-in, analytics, any non-GET)? | never cached |
42
+
43
+ What the user creates — saves, settings, progress — belongs in IndexedDB or
44
+ `localStorage`, never in the release cache, which is replaced on every update.
45
+
46
+ IWSDK and the starter fetch from other origins at runtime, and the kit's
47
+ `PINNED` already matches all three:
48
+
49
+ - **Controller models** —
50
+ `https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/<profile>/<handedness>.glb`.
51
+ The path is hard-coded, so the worker's cache is the only way to keep them
52
+ offline. `@1.0` is a release line, not one version; the worker keeps the
53
+ first copy it receives, and keeps the other hand's model with it.
54
+ - **Draco and KTX2 decoders** — `https://unpkg.com/three@0.<revision>.0/…`,
55
+ fetched only when the app loads compressed glTF files or KTX2 textures. Apps
56
+ cannot point IWSDK at self-hosted decoders.
57
+
58
+ - **Stock models** — the starter's `src/assets.ts` loads them from
59
+ `https://cdn.jsdelivr.net/npm/@iwsdk/example-assets@0.4.2/assets/…`. Mirroring
60
+ them under `public/` with `VITE_IWSDK_EXAMPLE_ASSET_BASE_URL` is better:
61
+ mirrored files become release files and are hash-checked like any other.
62
+ Then delete that path from `PINNED`.
63
+
64
+ ## Step 2 — Copy the kit
65
+
66
+ ```bash
67
+ kit="$(dirname "$(find .claude/skills .agents/skills -path '*/iwsdk-offline/assets/sw.js.template' -print -quit)")"
68
+ mkdir -p scripts
69
+ cp "$kit/write-service-worker.mjs.template" scripts/write-service-worker.mjs
70
+ cp "$kit/sw.js.template" scripts/sw.js.template
71
+ cp "$kit/offline.ts.template" src/offline.ts
72
+ ```
73
+
74
+ In a JavaScript project, save the page module as `src/offline.js` and delete
75
+ its type annotations; nothing else changes. A TypeScript project needs the `.ts`
76
+ file: the scaffold's `tsconfig.json` has no `allowJs`. The worker keeps its
77
+ `.template` extension so Vite, `tsc`, and linters never touch its placeholders.
78
+
79
+ Make the build script the last step of `build` in `package.json`:
80
+
81
+ ```json
82
+ "build": "vite build && node scripts/write-service-worker.mjs dist scripts/sw.js.template"
83
+ ```
84
+
85
+ Run it after `vite build`, never from a plugin's `closeBundle` hook: every
86
+ plugin must have finished writing, or a late file is missing from the list and
87
+ never kept. Its `LEFT_OUT` rules skip source maps (the starter emits them unless
88
+ `NODE_ENV=production`) and `AGENTS.md` (the scaffold keeps agent instructions in
89
+ `public/ui/` and `public/scenes/`, so Vite publishes them); add the app's own
90
+ `LEFT_OUT` and `ON_REQUEST` rules from step 1. Rules, hash signals, and a
91
+ duplicate finder: [`references/build-step.md`](references/build-step.md).
92
+
93
+ ## Step 3 — Adapt the worker
94
+
95
+ In `scripts/sw.js.template`, change only:
96
+
97
+ - **`PREFIX`, `KEPT`, `HASH`** — rename for the app. `KEPT` must not start with
98
+ `PREFIX`, or the next activation deletes the third-party cache.
99
+ - **`PINNED`** — the kit pins `three@0.185.0` and `example-assets@0.4.2`, the
100
+ versions new projects get. Match `three@` to the project's `three` in
101
+ `package.json` (`super-three@0.181.0` → `three@0.181.0`) and
102
+ `example-assets@` to `src/assets.ts`, delete paths the app never loads, and
103
+ add any other third-party paths from step 1. If the app fetches nothing from
104
+ other origins, delete `PINNED`, `PAIRED`, `thirdParty()`, `keepPinned()`, and
105
+ `keepPair()`.
106
+
107
+ Never add `skipWaiting()` to `install` or `activate`, and never revalidate in
108
+ `fetch`: the page alone decides when a release takes over, and answers are
109
+ cache-first so that a page is exactly its release. The worker grants a
110
+ take-over only while the asking page is the app's only open page, because it
111
+ moves every open page onto the new release. Request routing, hash checks,
112
+ and updates: [`references/service-worker.md`](references/service-worker.md).
113
+
114
+ ## Step 4 — Wire the page
115
+
116
+ In `src/index.ts`:
117
+
118
+ ```ts
119
+ import { VisibilityState, World } from '@iwsdk/core';
120
+ import { checkIdle, keepOfflineCopy, startOffline } from './offline.js';
121
+
122
+ let world: World | undefined;
123
+ const isIdle = () =>
124
+ world?.visibilityState.peek() === VisibilityState.NonImmersive;
125
+ startOffline(isIdle); // before World.create()
126
+
127
+ World.create(container, projectOptions).then((created) => {
128
+ world = created;
129
+ // …system registration…
130
+ keepOfflineCopy(isIdle); // after the first screen, not at startup
131
+ created.visibilityState.subscribe(() => checkIdle()); // a session just ended
132
+ });
133
+ ```
134
+
135
+ `isIdle()` must be `false` whenever a reload would interrupt anything: an XR
136
+ session (covered above), an unsaved edit, a game in progress. Call
137
+ `checkIdle()` whenever one of those ends, so a release that installed
138
+ meanwhile takes over then rather than at the next load. Registering only
139
+ once `World.create()` has resolved lets the worker take every file from the
140
+ HTTP cache instead of downloading it a second time. The reason for each line:
141
+ [`references/page.md`](references/page.md).
142
+
143
+ ## Step 5 — Hosting
144
+
145
+ | Path | Header |
146
+ | --- | --- |
147
+ | `/sw.js` | `Cache-Control: no-cache` |
148
+ | `/assets/*` (Vite's hashed output) | `public, max-age=31536000, immutable` |
149
+ | Unhashed files: images, models, fonts, data | a short `max-age`, optionally `stale-while-revalidate` |
150
+ | HTML | `no-cache` or a short `max-age` |
151
+ | Every path, if a CSP is sent | `worker-src 'self'`, and a `connect-src` naming each `PINNED` path |
152
+
153
+ Serve `sw.js` from the root of the scope it controls; a worker cannot control
154
+ pages above its own folder. It needs a secure context — HTTPS, or
155
+ `http://localhost` for testing. On a host the developer owns, these headers are
156
+ part of the upload handoff, so take them through `iwsdk-hosting`. Then verify:
157
+
158
+ ```bash
159
+ curl -sI https://<DOMAIN>/sw.js | grep -i '^cache-control' # want no-cache
160
+ ```
161
+
162
+ The `vercel.json` headers for Vercel are in
163
+ [`references/service-worker.md`](references/service-worker.md).
164
+
165
+ ## Step 6 — Verify
166
+
167
+ `npm run dev` serves no `sw.js`, so registration fails quietly there and proves
168
+ nothing — verify a production build. Six checks, each about what crosses the
169
+ wire:
170
+
171
+ 1. **First visit** — the release cache holds every listed file, and no file was
172
+ sent in full twice.
173
+ 2. **Reload** — the server is asked for nothing but `sw.js`.
174
+ 3. **Offline** — with the network off, a reload starts the app and kept files
175
+ are served.
176
+ 4. **Update while idle** — only the changed file downloads, the new release
177
+ takes over, and the old release cache is gone.
178
+ 5. **Update mid-session** — the page is not reloaded during the session; when
179
+ it ends, the new release takes over.
180
+ 6. **Two pages open** — an update takes over neither page; once one remains,
181
+ its next idle moment or load takes it.
182
+
183
+ The harness rules (logging server, no Playwright routes, persistent profile,
184
+ polling loops) and headset testing over `adb reverse`:
185
+ [`references/testing.md`](references/testing.md).
186
+
187
+ ## Installed apps (PWA/TWA)
188
+
189
+ A packaged Quest app loads `<DOMAIN>` like any page, so the same copy serves it
190
+ offline — after **one online launch**, which is when the copy is made.
191
+
192
+ - `start_url` and `scope` in the manifest must sit inside the worker's scope;
193
+ `/sw.js` covers the whole origin. The worker ignores query strings, so
194
+ `"start_url": "/?source=pwa"` is served the cached `index.html`.
195
+ - The manifest and its icons live in `public/`, so they are in the release list.
196
+ - A web redeploy installs in the background during a launch and takes over when
197
+ the app is idle (no XR session), or on the launch after that — one launch later than without
198
+ the copy. Native changes still need a new APK.
199
+ - An immersive app that auto-enters XR (`iwsdk-pwa-packaging` step 1) spends the
200
+ launch tap on `world.launchXR()`. When a release is waiting, `startOffline()`
201
+ reloads the page at startup to take it, so verify on the headset that the
202
+ reloaded page still enters XR before shipping.
203
+
204
+ ## Reference Files
205
+
206
+ | File | Load when |
207
+ | ---- | --------- |
208
+ | [`assets/`](assets/) | Step 2 — `write-service-worker.mjs.template`, `sw.js.template`, `offline.ts.template`; copy, never retype |
209
+ | [`references/build-step.md`](references/build-step.md) | Step 2 — `LEFT_OUT` and `ON_REQUEST`, hash signals, duplicate files |
210
+ | [`references/service-worker.md`](references/service-worker.md) | Step 3 — request routing, what to keep, hash checks, updates, Vercel headers |
211
+ | [`references/page.md`](references/page.md) | Step 4 — what each part of the page module does, and the wiring |
212
+ | [`references/testing.md`](references/testing.md) | Step 6 — the five checks, the harness, headset testing |
213
+
214
+ Publishing the build and its headers is the `iwsdk-hosting` skill, and packaging
215
+ it into a Quest APK is `iwsdk-pwa-packaging`. This skill only makes it work
216
+ offline.
217
+ <!-- iwsdk-agent-guidance version=1.2.0-rc.1 sha256=7f4f5034d84d6f0aaf3c353603e4d6d18eb99d107c5946ec018f8674e1001f38 name=iwsdk-offline (installed by IWSDK; `npx @iwsdk/cli@latest agents sync` refreshes it and leaves it alone once edited) -->
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ // src/offline.ts: the page's side. Call startOffline() first thing at startup, keepOfflineCopy()
9
+ // once the first screen is up, and checkIdle() whenever the app becomes idle (an XR session ends).
10
+ // isIdle() is your app's own test: would a reload now interrupt nothing?
11
+
12
+ export function startOffline(isIdle: () => boolean): void {
13
+ if (!('serviceWorker' in navigator)) return;
14
+ const hadCopy = navigator.serviceWorker.controller != null;
15
+ navigator.serviceWorker
16
+ .getRegistration()
17
+ .then((registration) => {
18
+ if (registration == null) return;
19
+ // A release that finished installing on an earlier visit takes over before anything starts.
20
+ if (registration.waiting != null && hadCopy)
21
+ takeOver(registration.waiting);
22
+ else watch(registration, isIdle);
23
+ })
24
+ .catch(() => {});
25
+ }
26
+
27
+ export function keepOfflineCopy(isIdle: () => boolean): void {
28
+ if (!('serviceWorker' in navigator)) return;
29
+ navigator.serviceWorker
30
+ .register('./sw.js', { scope: './' })
31
+ .then((registration) => {
32
+ watch(registration, isIdle);
33
+ // Ask the browser not to evict the copy under storage pressure. It decides without a prompt.
34
+ navigator.storage?.persist?.().catch(() => {});
35
+ // Tell the worker what the page fetched before it took control, so it can keep optional files.
36
+ new PerformanceObserver((list) => {
37
+ const fetched = list.getEntries().map((entry) => entry.name);
38
+ navigator.serviceWorker.ready.then((ready) =>
39
+ ready.active?.postMessage({ fetched }),
40
+ );
41
+ }).observe({ type: 'resource', buffered: true });
42
+ })
43
+ .catch(() => {
44
+ // No offline copy (storage turned off, some private windows): the app still runs online.
45
+ });
46
+ }
47
+
48
+ // A release that installed while the app was busy waits; call this when the app becomes idle to
49
+ // let it take over now rather than at the next load.
50
+ export function checkIdle(): void {
51
+ retry?.();
52
+ }
53
+
54
+ const watched = new WeakSet<ServiceWorkerRegistration>();
55
+ let retry: (() => void) | undefined;
56
+
57
+ function watch(
58
+ registration: ServiceWorkerRegistration,
59
+ isIdle: () => boolean,
60
+ ): void {
61
+ if (watched.has(registration)) return;
62
+ watched.add(registration);
63
+ const follow = (worker: ServiceWorker | null) => {
64
+ if (worker == null) return;
65
+ const settled = () => {
66
+ // Otherwise the release waits, and the next load takes it at startup.
67
+ if (
68
+ worker.state === 'installed' &&
69
+ navigator.serviceWorker.controller != null &&
70
+ isIdle()
71
+ ) {
72
+ takeOver(worker);
73
+ }
74
+ };
75
+ if (worker.state === 'installed') settled();
76
+ else worker.addEventListener('statechange', settled);
77
+ };
78
+ retry = () => follow(registration.waiting);
79
+ follow(registration.waiting);
80
+ follow(registration.installing); // an update the navigation started before this script ran
81
+ registration.addEventListener('updatefound', () =>
82
+ follow(registration.installing),
83
+ );
84
+ }
85
+
86
+ let listening = false;
87
+
88
+ // The worker takes over only if this is the only page of the app open; asking again later is safe.
89
+ function takeOver(worker: ServiceWorker): void {
90
+ if (!listening) {
91
+ listening = true;
92
+ navigator.serviceWorker.addEventListener(
93
+ 'controllerchange',
94
+ () => location.reload(),
95
+ { once: true },
96
+ );
97
+ }
98
+ worker.postMessage('take-over');
99
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ // scripts/sw.js.template: copied to dist/sw.js by write-service-worker.mjs, with the placeholders filled in.
9
+ // Plain JavaScript with no imports: it is copied, not bundled.
10
+ const RELEASE = '__RELEASE__';
11
+ const FILES = __FILES__; // path -> sha256: copied at install
12
+ const ON_REQUEST = __ON_REQUEST__; // path -> sha256: kept the first time the page fetches it
13
+ const PREFIX = 'myapp-release-'; // every release's cache; activation deletes all but its own
14
+ const CACHE = PREFIX + RELEASE;
15
+ const HASH = 'x-content-sha256'; // each cached copy carries its hash, so a later release can reuse it
16
+ const KEPT = 'myapp-third-party'; // outside PREFIX, so no release's activation deletes it
17
+ // Third-party paths kept once per device: IWSDK's controller models, the three.js decoders it
18
+ // fetches for Draco or KTX2 assets, and the starter's stock models. Match three@ to your app's
19
+ // three.js revision and example-assets@ to src/assets.ts, or delete what the app never loads.
20
+ const PINNED =
21
+ /^https:\/\/(cdn\.jsdelivr\.net\/npm\/@webxr-input-profiles\/assets@1\.0\/|unpkg\.com\/three@0\.185\.0\/|cdn\.jsdelivr\.net\/npm\/@iwsdk\/example-assets@0\.4\.2\/)/;
22
+ // A controller model and its other hand: keeping one keeps both, so a user who only ever held one
23
+ // controller online still sees both offline.
24
+ const PAIRED =
25
+ /^(https:\/\/cdn\.jsdelivr\.net\/npm\/@webxr-input-profiles\/assets@1\.0\/dist\/profiles\/[^/]+\/)(left|right)\.glb$/;
26
+ const scope = new URL(self.registration.scope);
27
+
28
+ const urlOf = (path) => new URL(path, scope).href;
29
+
30
+ async function sha256(body) {
31
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', body));
32
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join(
33
+ '',
34
+ );
35
+ }
36
+
37
+ // What goes in the cache: a fresh Response carrying its hash. A redirected response cannot
38
+ // answer a navigation, so the fetched one is never stored as it is.
39
+ function copyOf(response, body, hash) {
40
+ const headers = new Headers(response.headers);
41
+ headers.set(HASH, hash);
42
+ return new Response(body, {
43
+ status: response.status,
44
+ statusText: response.statusText,
45
+ headers,
46
+ });
47
+ }
48
+
49
+ // This exact file from the network, or null if this route has another version of it.
50
+ async function fetchChecked(url, hash, mode) {
51
+ const response = await fetch(url, { cache: mode });
52
+ if (!response.ok) throw new Error(`${url}: ${response.status}`);
53
+ const body = await response.arrayBuffer();
54
+ return (await sha256(body)) === hash ? copyOf(response, body, hash) : null;
55
+ }
56
+
57
+ // This exact file as an earlier release holds it.
58
+ async function heldCopy(url, hash) {
59
+ for (const name of await caches.keys()) {
60
+ if (!name.startsWith(PREFIX) || name === CACHE) continue;
61
+ const held = await (await caches.open(name)).match(url);
62
+ if (held?.headers.get(HASH) === hash) return held;
63
+ }
64
+ return null;
65
+ }
66
+
67
+ // With as little downloading as possible: an earlier release's copy, then the HTTP cache (which
68
+ // holds what the page has just loaded), then the server, asked to revalidate.
69
+ async function obtain(url, hash) {
70
+ const copy =
71
+ (await heldCopy(url, hash)) ??
72
+ (await fetchChecked(url, hash, 'default')) ??
73
+ (await fetchChecked(url, hash, 'no-cache'));
74
+ if (copy == null)
75
+ throw new Error(`${url}: the server has no copy with sha256 ${hash}`);
76
+ return copy;
77
+ }
78
+
79
+ self.addEventListener('install', (event) => {
80
+ event.waitUntil(
81
+ (async () => {
82
+ const cache = await caches.open(CACHE);
83
+ const queue = Object.entries(FILES);
84
+ const lane = async () => {
85
+ for (let next = queue.pop(); next != null; next = queue.pop()) {
86
+ const [path, hash] = next;
87
+ if ((await cache.match(urlOf(path)))?.headers.get(HASH) === hash)
88
+ continue; // a resumed install
89
+ await cache.put(urlOf(path), await obtain(urlOf(path), hash));
90
+ }
91
+ };
92
+ // Any failure fails the install, and the browser tries again on a later visit.
93
+ await Promise.all(Array.from({ length: 6 }, lane));
94
+ // Carry across what an earlier release kept on request, if it is unchanged. Fetch nothing else.
95
+ for (const [path, hash] of Object.entries(ON_REQUEST)) {
96
+ const held = await heldCopy(urlOf(path), hash);
97
+ if (held != null) await cache.put(urlOf(path), held);
98
+ }
99
+ })(),
100
+ );
101
+ });
102
+
103
+ self.addEventListener('activate', (event) => {
104
+ event.waitUntil(
105
+ (async () => {
106
+ for (const name of await caches.keys()) {
107
+ if (name.startsWith(PREFIX) && name !== CACHE)
108
+ await caches.delete(name);
109
+ }
110
+ await self.clients.claim(); // the first visit's page is served from the copy from now on
111
+ })(),
112
+ );
113
+ });
114
+
115
+ // A path relative to the scope, or null. The query string is ignored, so /?source=app is /.
116
+ function scopedPath(href) {
117
+ const url = new URL(href);
118
+ if (url.origin !== scope.origin || !url.pathname.startsWith(scope.pathname))
119
+ return null;
120
+ return decodeURIComponent(url.pathname.slice(scope.pathname.length));
121
+ }
122
+
123
+ // Keeps an ON_REQUEST file the page fetched before this worker controlled it.
124
+ async function keepReported(path) {
125
+ const cache = await caches.open(CACHE);
126
+ const hash = ON_REQUEST[path];
127
+ if ((await cache.match(urlOf(path)))?.headers.get(HASH) === hash) return;
128
+ await cache.put(urlOf(path), await obtain(urlOf(path), hash));
129
+ }
130
+
131
+ // Keeps an ON_REQUEST file fetched through this worker, if it is this release's version.
132
+ async function keepFetched(path, response) {
133
+ const body = await response.arrayBuffer();
134
+ const hash = ON_REQUEST[path];
135
+ if ((await sha256(body)) !== hash) return; // a stale copy from a CDN edge: served once, never kept
136
+ await (
137
+ await caches.open(CACHE)
138
+ ).put(urlOf(path), copyOf(response, body, hash));
139
+ }
140
+
141
+ // A pinned third-party file: kept the first time, then served from the cache on every visit.
142
+ async function thirdParty(event) {
143
+ const cache = await caches.open(KEPT);
144
+ const held = await cache.match(event.request.url);
145
+ if (held != null) return held;
146
+ const response = await fetch(event.request);
147
+ // Only a CORS response can be kept: an opaque one (status 0) has ok === false.
148
+ if (response.ok) {
149
+ event.waitUntil(
150
+ Promise.all([
151
+ cache.put(event.request.url, response.clone()),
152
+ keepPair(event.request.url),
153
+ ]).catch(() => {}),
154
+ );
155
+ }
156
+ return response;
157
+ }
158
+
159
+ // Keeps a pinned third-party file the page fetched before this worker controlled it.
160
+ async function keepPinned(url) {
161
+ const cache = await caches.open(KEPT);
162
+ if ((await cache.match(url)) == null) {
163
+ const response = await fetch(url); // from the HTTP cache when it can
164
+ if (response.ok) await cache.put(url, response);
165
+ }
166
+ await keepPair(url);
167
+ }
168
+
169
+ // Keeps the other hand's controller model, if url is one.
170
+ async function keepPair(url) {
171
+ const match = PAIRED.exec(url);
172
+ if (match == null) return;
173
+ const other = `${match[1]}${match[2] === 'left' ? 'right' : 'left'}.glb`;
174
+ const cache = await caches.open(KEPT);
175
+ if ((await cache.match(other)) != null) return;
176
+ const response = await fetch(other);
177
+ if (response.ok) await cache.put(other, response);
178
+ }
179
+
180
+ // Taking over moves every open page of this scope onto the new release, and the old release's
181
+ // cache is deleted under them. So it happens only when the asking page is the only one open;
182
+ // otherwise the release waits for a later request, or until every page has closed.
183
+ async function takeOver() {
184
+ const pages = await self.clients.matchAll({
185
+ type: 'window',
186
+ includeUncontrolled: true,
187
+ });
188
+ if (pages.filter((page) => scopedPath(page.url) != null).length <= 1)
189
+ await self.skipWaiting();
190
+ }
191
+
192
+ self.addEventListener('message', (event) => {
193
+ if (event.data === 'take-over') {
194
+ event.waitUntil(takeOver());
195
+ } else if (Array.isArray(event.data?.fetched)) {
196
+ const hrefs = event.data.fetched.filter((href) => typeof href === 'string');
197
+ const ours = hrefs
198
+ .map(scopedPath)
199
+ .filter((path) => path != null && Object.hasOwn(ON_REQUEST, path));
200
+ const pinned = hrefs.filter((href) => PINNED.test(href));
201
+ event.waitUntil(
202
+ Promise.allSettled([
203
+ ...ours.map(keepReported),
204
+ ...pinned.map(keepPinned),
205
+ ]),
206
+ );
207
+ }
208
+ });
209
+
210
+ self.addEventListener('fetch', (event) => {
211
+ const { request } = event;
212
+ if (request.method !== 'GET') return; // never cache writes
213
+ if (PINNED.test(request.url)) {
214
+ event.respondWith(thirdParty(event));
215
+ return;
216
+ }
217
+ let path = scopedPath(request.url);
218
+ if (
219
+ path != null &&
220
+ request.mode === 'navigate' &&
221
+ (path === '' || path.endsWith('/'))
222
+ )
223
+ path += 'index.html';
224
+ if (
225
+ path == null ||
226
+ !(Object.hasOwn(FILES, path) || Object.hasOwn(ON_REQUEST, path))
227
+ )
228
+ return; // not ours
229
+ event.respondWith(
230
+ (async () => {
231
+ const held = await (await caches.open(CACHE)).match(urlOf(path));
232
+ if (held != null) return held;
233
+ // Missing: an ON_REQUEST file not fetched before, or a cache the browser evicted.
234
+ const response = await fetch(request);
235
+ if (response.ok && Object.hasOwn(ON_REQUEST, path)) {
236
+ event.waitUntil(keepFetched(path, response.clone()).catch(() => {}));
237
+ }
238
+ return response;
239
+ })(),
240
+ );
241
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ // scripts/write-service-worker.mjs: run after the build, once every output file is in dist/.
9
+ // node scripts/write-service-worker.mjs dist scripts/sw.js.template
10
+ import { createHash } from 'node:crypto';
11
+ import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
12
+ import { join, relative, sep } from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+
15
+ // Never listed: the worker itself, source maps, files only crawlers or link previews fetch, and
16
+ // the AGENTS.md guidance an IWSDK project keeps under public/.
17
+ const LEFT_OUT = [
18
+ /^sw\.js$/,
19
+ /\.map$/,
20
+ /^(robots\.txt|sitemap\.xml|llms\.txt|og-image\.png)$/,
21
+ /(^|\/)AGENTS\.md$/,
22
+ ];
23
+ // Listed, but kept only once the page fetches them: files that only some users need.
24
+ const ON_REQUEST = [/^fonts\/(ja|ko|zh)-/, /^levels\/extra-/];
25
+
26
+ function* walk(dir) {
27
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
28
+ const full = join(dir, entry.name);
29
+ if (entry.isDirectory()) yield* walk(full);
30
+ else yield full;
31
+ }
32
+ }
33
+
34
+ export function writeServiceWorker(dist, template) {
35
+ const files = {};
36
+ const onRequest = {};
37
+ const paths = [...walk(dist)]
38
+ .map((full) => relative(dist, full).split(sep).join('/'))
39
+ .sort();
40
+ for (const path of paths) {
41
+ if (LEFT_OUT.some((rule) => rule.test(path))) continue;
42
+ const hash = createHash('sha256')
43
+ .update(readFileSync(join(dist, path)))
44
+ .digest('hex');
45
+ (ON_REQUEST.some((rule) => rule.test(path)) ? onRequest : files)[path] =
46
+ hash;
47
+ }
48
+ // The release is named by its contents, so an unchanged build writes a byte-identical sw.js.
49
+ const release = createHash('sha256')
50
+ .update(JSON.stringify({ files, onRequest }))
51
+ .digest('hex')
52
+ .slice(0, 16);
53
+ const worker = readFileSync(template, 'utf8')
54
+ .replace("'__RELEASE__'", () => JSON.stringify(release))
55
+ .replace('__FILES__', () => JSON.stringify(files, null, 2))
56
+ .replace('__ON_REQUEST__', () => JSON.stringify(onRequest, null, 2));
57
+ writeFileSync(join(dist, 'sw.js'), worker);
58
+ return { release, files, onRequest };
59
+ }
60
+
61
+ if (
62
+ process.argv[1] &&
63
+ import.meta.url === pathToFileURL(process.argv[1]).href
64
+ ) {
65
+ const { release, files, onRequest } = writeServiceWorker(
66
+ process.argv[2] ?? 'dist',
67
+ process.argv[3] ?? 'scripts/sw.js.template',
68
+ );
69
+ console.log(
70
+ `sw.js: release ${release}, ${Object.keys(files).length} files, ${Object.keys(onRequest).length} on request`,
71
+ );
72
+ }