@iwsdk/create 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 (118) hide show
  1. package/README.md +68 -16
  2. package/dist/cli.js +7917 -3404
  3. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-build-model/SKILL.md +1 -0
  4. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-compose-scene/SKILL.md +3 -2
  5. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-debug/SKILL.md +1 -0
  6. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-depth-occlusion/SKILL.md +1 -0
  7. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-dev/SKILL.md +1 -0
  8. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-dev/references/api-reference.md +8 -1
  9. package/dist/guidance/files/.agents/skills/iwsdk-dev/references/headless-rendering.md +96 -0
  10. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-dev/references/iterate.md +16 -7
  11. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-dev/references/planner.md +9 -5
  12. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-glasses-test/SKILL.md +1 -0
  13. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-grab/SKILL.md +1 -0
  14. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-hosting/SKILL.md +3 -1
  15. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-native-xr-test/SKILL.md +17 -1
  16. package/dist/guidance/files/.agents/skills/iwsdk-offline/SKILL.md +217 -0
  17. package/dist/guidance/files/.agents/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  18. package/dist/guidance/files/.agents/skills/iwsdk-offline/assets/sw.js.template +241 -0
  19. package/dist/guidance/files/.agents/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  20. package/dist/guidance/files/.agents/skills/iwsdk-offline/references/build-step.md +71 -0
  21. package/dist/guidance/files/.agents/skills/iwsdk-offline/references/page.md +70 -0
  22. package/dist/guidance/files/.agents/skills/iwsdk-offline/references/service-worker.md +107 -0
  23. package/dist/guidance/files/.agents/skills/iwsdk-offline/references/testing.md +57 -0
  24. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-physics/SKILL.md +1 -0
  25. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-physics/references/tuning-and-config.md +1 -0
  26. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-physics/references/workflows.md +9 -3
  27. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-pwa-packaging/SKILL.md +13 -1
  28. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +1 -1
  29. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-pwa-packaging/references/troubleshooting.md +30 -0
  30. package/dist/guidance/{agents → files}/.agents/skills/iwsdk-ray/SKILL.md +1 -0
  31. package/dist/guidance/{claude/.claude → files/.agents}/skills/iwsdk-ui/SKILL.md +17 -7
  32. package/dist/guidance/files/.agents/skills/iwsdk-upgrade/SKILL.md +74 -0
  33. package/dist/guidance/{claude → files}/.claude/agents/iwsdk-project-code-reviewer.md +1 -0
  34. package/dist/guidance/{claude → files}/.claude/rules/assets-and-manifest.md +3 -0
  35. package/dist/guidance/{claude → files}/.claude/rules/ecs-api.md +1 -0
  36. package/dist/guidance/{claude → files}/.claude/rules/scene-json.md +1 -0
  37. package/dist/guidance/{claude → files}/.claude/rules/uikitml.md +1 -0
  38. package/dist/guidance/{claude → files}/.claude/settings.json +9 -3
  39. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-build-model/SKILL.md +1 -0
  40. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-compose-scene/SKILL.md +3 -2
  41. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-debug/SKILL.md +1 -0
  42. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-depth-occlusion/SKILL.md +1 -0
  43. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-dev/SKILL.md +1 -0
  44. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-dev/references/api-reference.md +8 -1
  45. package/dist/guidance/files/.claude/skills/iwsdk-dev/references/headless-rendering.md +96 -0
  46. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-dev/references/iterate.md +16 -7
  47. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-dev/references/planner.md +9 -5
  48. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-glasses-test/SKILL.md +1 -0
  49. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-grab/SKILL.md +1 -0
  50. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-hosting/SKILL.md +3 -1
  51. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-native-xr-test/SKILL.md +17 -1
  52. package/dist/guidance/files/.claude/skills/iwsdk-offline/SKILL.md +217 -0
  53. package/dist/guidance/files/.claude/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  54. package/dist/guidance/files/.claude/skills/iwsdk-offline/assets/sw.js.template +241 -0
  55. package/dist/guidance/files/.claude/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  56. package/dist/guidance/files/.claude/skills/iwsdk-offline/references/build-step.md +71 -0
  57. package/dist/guidance/files/.claude/skills/iwsdk-offline/references/page.md +70 -0
  58. package/dist/guidance/files/.claude/skills/iwsdk-offline/references/service-worker.md +107 -0
  59. package/dist/guidance/files/.claude/skills/iwsdk-offline/references/testing.md +57 -0
  60. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-physics/SKILL.md +1 -0
  61. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-physics/references/tuning-and-config.md +1 -0
  62. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-physics/references/workflows.md +9 -3
  63. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-pwa-packaging/SKILL.md +13 -1
  64. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +1 -1
  65. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-pwa-packaging/references/troubleshooting.md +30 -0
  66. package/dist/guidance/{claude → files}/.claude/skills/iwsdk-ray/SKILL.md +1 -0
  67. package/dist/guidance/{agents/.agents → files/.claude}/skills/iwsdk-ui/SKILL.md +17 -7
  68. package/dist/guidance/files/.claude/skills/iwsdk-upgrade/SKILL.md +74 -0
  69. package/dist/guidance/{cursor → files}/.cursor/rules/assets-and-manifest.mdc +3 -0
  70. package/dist/guidance/{cursor → files}/.cursor/rules/ecs-api.mdc +1 -0
  71. package/dist/guidance/{cursor → files}/.cursor/rules/scene-json.mdc +1 -0
  72. package/dist/guidance/{cursor → files}/.cursor/rules/uikitml.mdc +1 -0
  73. package/dist/guidance/{copilot → files}/.github/instructions/assets-and-manifest.instructions.md +2 -1
  74. package/dist/guidance/{copilot → files}/.github/instructions/ecs-api.instructions.md +1 -0
  75. package/dist/guidance/{copilot → files}/.github/instructions/scene-json.instructions.md +1 -0
  76. package/dist/guidance/{copilot → files}/.github/instructions/uikitml.instructions.md +1 -0
  77. package/dist/guidance/{common → files}/AGENTS.md +107 -27
  78. package/dist/guidance/{scoped-agents → files}/public/scenes/AGENTS.md +2 -0
  79. package/dist/guidance/{scoped-agents → files}/public/ui/AGENTS.md +2 -0
  80. package/dist/guidance/{scoped-agents → files}/src/AGENTS.md +2 -0
  81. package/dist/guidance/manifest.json +954 -0
  82. package/dist/template/common/.codex/config.toml +2 -0
  83. package/package.json +5 -5
  84. package/scripts/verify-release-ready.mjs +1 -2
  85. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-build-model/agents/openai.yaml +0 -0
  86. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-build-model/assets/hardsurface.ts.template +0 -0
  87. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/agents/openai.yaml +0 -0
  88. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/environment-recipes.md +0 -0
  89. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/extended-workflow.md +0 -0
  90. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/image-intake.md +0 -0
  91. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/scene-composition.md +0 -0
  92. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/scene-format.md +0 -0
  93. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/scene-review.md +0 -0
  94. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-compose-scene/references/text-intake.md +0 -0
  95. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-hosting/references/existing-hosts.md +0 -0
  96. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-hosting/references/vercel.md +0 -0
  97. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-physics/references/component-reference.md +0 -0
  98. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-pwa-packaging/references/app-modes.md +0 -0
  99. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-pwa-packaging/references/bubblewrap.md +0 -0
  100. /package/dist/guidance/{agents → files}/.agents/skills/iwsdk-pwa-packaging/references/store-upload.md +0 -0
  101. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-build-model/agents/openai.yaml +0 -0
  102. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-build-model/assets/hardsurface.ts.template +0 -0
  103. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/agents/openai.yaml +0 -0
  104. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/environment-recipes.md +0 -0
  105. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/extended-workflow.md +0 -0
  106. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/image-intake.md +0 -0
  107. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/scene-composition.md +0 -0
  108. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/scene-format.md +0 -0
  109. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/scene-review.md +0 -0
  110. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-compose-scene/references/text-intake.md +0 -0
  111. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-hosting/references/existing-hosts.md +0 -0
  112. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-hosting/references/vercel.md +0 -0
  113. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-physics/references/component-reference.md +0 -0
  114. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-pwa-packaging/references/app-modes.md +0 -0
  115. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-pwa-packaging/references/bubblewrap.md +0 -0
  116. /package/dist/guidance/{claude → files}/.claude/skills/iwsdk-pwa-packaging/references/store-upload.md +0 -0
  117. /package/dist/guidance/{claude → files}/CLAUDE.md +0 -0
  118. /package/dist/{guidance/codex → template/common-js}/.codex/config.toml +0 -0
@@ -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
+ }
@@ -0,0 +1,71 @@
1
+ # Build Step
2
+
3
+ `scripts/write-service-worker.mjs` (copied from
4
+ `assets/write-service-worker.mjs.template`) runs after `vite build`, once every
5
+ output file — `public/` included — is in `dist/`. It hashes each file, sorts it
6
+ into a list, names the release, and writes `dist/sw.js` from
7
+ `scripts/sw.js.template`.
8
+
9
+ ```json
10
+ {
11
+ "scripts": {
12
+ "build": "vite build && node scripts/write-service-worker.mjs dist scripts/sw.js.template"
13
+ }
14
+ }
15
+ ```
16
+
17
+ It prints `sw.js: release <name>, <n> files, <m> on request`. Read that line
18
+ after every change to the rules.
19
+
20
+ ## Rewrite the rules for the app
21
+
22
+ - **`LEFT_OUT`** — never listed. Keep the worker itself, source maps, crawler
23
+ and link-preview files, and `AGENTS.md`; add anything nothing requests.
24
+ - **`ON_REQUEST`** — listed with its hash, but copied only once the page fetches
25
+ it. Use it for files only some users need: copying them for everyone costs
26
+ every user for the benefit of a few. The kit's two rules
27
+ (`fonts/(ja|ko|zh)-`, `levels/extra-`) are examples; replace them.
28
+
29
+ ## Three details that matter
30
+
31
+ - The paths are sorted before hashing, so the same output always gives the same
32
+ release name, and an unchanged build writes a byte-identical `sw.js`, which
33
+ browsers ignore.
34
+ - The placeholders are replaced through functions, because a replacement string
35
+ would read `$&` in a file name as a pattern.
36
+ - The script must run after every file exists: a file written later is missing
37
+ from the list, so it is never kept. That is why it runs after `vite build`
38
+ rather than from a plugin's `closeBundle` hook.
39
+
40
+ ## Identify files by hash
41
+
42
+ Decide everything by the SHA-256 of a file's bytes, never by its name, date, or
43
+ version number. The one hash answers three questions: did the file change since
44
+ the last release, is a copy already on the device, and is the copy just
45
+ downloaded the right one.
46
+
47
+ | Signal | Decide by it? | Why |
48
+ | --- | --- | --- |
49
+ | SHA-256 of the bytes, computed at build | yes | the same bytes give the same hash on any machine |
50
+ | Hashed file names (`index-3f9a2c.js`) | only for Vite's own output | files copied from `public/` keep their names when their content changes |
51
+ | Modification time | no | a fresh checkout or a CI build gives every file a new time |
52
+ | `ETag` or `Last-Modified` | no | each server or CDN edge computes its own |
53
+ | One version number for the whole app | only as a label | a new number makes every file look changed, so every user downloads everything again |
54
+
55
+ ## Duplicate files
56
+
57
+ Two paths with identical bytes share a hash but are stored twice, because the
58
+ Cache API keys entries by URL. To find them, group the list by hash inside
59
+ `writeServiceWorker()` (`Object.groupBy` needs Node.js 21 or later):
60
+
61
+ ```js
62
+ const byHash = Object.groupBy(Object.entries(files), ([, hash]) => hash);
63
+ for (const group of Object.values(byHash)) {
64
+ if (group.length > 1)
65
+ console.warn('same bytes:', group.map(([path]) => path).join(', '));
66
+ }
67
+ ```
68
+
69
+ One duplicate is built in: the page loads `/`, but the list names `index.html`,
70
+ so a first visit fetches the entry page twice under two URLs. It is usually a
71
+ few kilobytes; list the entry page under its own URL if that matters.
@@ -0,0 +1,70 @@
1
+ # Page Side
2
+
3
+ `src/offline.ts` (copied from `assets/offline.ts.template`) decides two moments:
4
+ when the copy is made, and when a new release may take over. It exports three
5
+ functions:
6
+
7
+ - **`startOffline(isIdle)`** — call first thing at startup. If a release
8
+ finished installing on an earlier visit, it takes over before anything
9
+ starts; otherwise it watches for one.
10
+ - **`keepOfflineCopy(isIdle)`** — call once the first screen is up. It registers
11
+ `./sw.js`, asks the browser to keep the copy with `navigator.storage.persist()`,
12
+ and reports what the page fetched before the worker existed.
13
+ - **`checkIdle()`** — call whenever the app becomes idle, such as when an XR
14
+ session ends. A release that installed while the app was busy takes over
15
+ then, instead of waiting for the next load.
16
+
17
+ In a JavaScript project, save it as `src/offline.js` and delete the type
18
+ annotations. In a TypeScript project it must be `.ts`: the scaffold's
19
+ `tsconfig.json` has no `allowJs`, so importing a `.js` module fails
20
+ `npm run typecheck`.
21
+
22
+ ## Wiring in `src/index.ts`
23
+
24
+ ```ts
25
+ import { VisibilityState, World } from '@iwsdk/core';
26
+ import projectOptions from 'virtual:iwsdk-project';
27
+ import { checkIdle, keepOfflineCopy, startOffline } from './offline.js';
28
+
29
+ let world: World | undefined;
30
+ const isIdle = () =>
31
+ world?.visibilityState.peek() === VisibilityState.NonImmersive;
32
+ startOffline(isIdle);
33
+
34
+ World.create(
35
+ document.getElementById('scene-container') as HTMLDivElement,
36
+ projectOptions,
37
+ ).then((created) => {
38
+ world = created;
39
+ // ... register your systems ...
40
+ keepOfflineCopy(isIdle);
41
+ created.visibilityState.subscribe(() => checkIdle());
42
+ });
43
+ ```
44
+
45
+ ## Why each part is there
46
+
47
+ - **Register after the first screen, not at startup.** Registered at startup,
48
+ the worker downloads the release while the page is still downloading it, so
49
+ every file comes down twice. Registered later, the worker takes each file from
50
+ the HTTP cache instead.
51
+ - **Report what came before the worker.** Files the page fetched before the
52
+ worker existed never passed through it. The buffered `PerformanceObserver`
53
+ reports them, and the worker keeps the optional and pinned ones among them.
54
+ The browser buffers 250 resource entries by default; if the first load fetches
55
+ more, raise the limit early with `performance.setResourceTimingBufferSize()`.
56
+ - **Define idle for the app.** `isIdle()` must be `false` whenever a reload
57
+ could lose work or interrupt a session. No XR session is the IWSDK baseline;
58
+ add the app's own state, such as an unsaved edit or a game in progress, and
59
+ call `checkIdle()` when that state ends. When `isIdle()` is `true` and a new
60
+ release has installed, the page sends `'take-over'`, listens for
61
+ `controllerchange`, and reloads into the new release. The worker ignores the
62
+ request while another page of the app is open, so asking again later is safe.
63
+ - **Catch an install already under way.** The browser checks `sw.js` as the page
64
+ navigates, so an update can be installing before the page's script runs, its
65
+ `updatefound` already gone. `watch()` follows `registration.waiting`,
66
+ `registration.installing`, and the next `updatefound`, so none is missed.
67
+ - **Mirror the connection.** `navigator.onLine` and the `online` and `offline`
68
+ events say whether the device has a network, not whether the server answers.
69
+ Use them to disable or explain features that need a connection, and still
70
+ handle failed requests.
@@ -0,0 +1,107 @@
1
+ # Service Worker
2
+
3
+ `scripts/sw.js.template` (copied from `assets/sw.js.template`) has three
4
+ placeholders — `RELEASE`, `FILES`, and `ON_REQUEST` — that the build step fills
5
+ in. It is plain JavaScript with no imports, so it is copied, not bundled. Install
6
+ copies the release, activate removes older releases, and fetch answers from the
7
+ copy.
8
+
9
+ ## Request routing
10
+
11
+ | Request | Answered from |
12
+ | --- | --- |
13
+ | Anything but a GET | the network, untouched |
14
+ | A pinned third-party URL | its long-lived cache; else the network, and kept |
15
+ | A path in `FILES` | the release cache; the network only if the browser evicted it |
16
+ | A path in `ON_REQUEST` | the release cache once kept; until then the network, kept if its hash matches |
17
+ | A navigation to a folder, such as the site root | that folder's `index.html` from the release cache |
18
+ | Anything else | the network, untouched |
19
+
20
+ ## What to change
21
+
22
+ - **`PREFIX`, `KEPT`, `HASH`** — rename for the app. `KEPT` must not start with
23
+ `PREFIX`, or the next activation deletes it.
24
+ - **`PINNED`** — covers IWSDK's controller models, the three.js decoders, and
25
+ the starter's stock models on jsDelivr. Match `three@` to the project's
26
+ three.js revision and `example-assets@` to `src/assets.ts`, and delete the
27
+ stock-model path if the app mirrors those files or never loads them. If the
28
+ app fetches nothing from other origins, delete `PINNED`, `PAIRED`,
29
+ `thirdParty()`, `keepPinned()`, and `keepPair()`.
30
+
31
+ Third-party files often come in families. IWSDK's controller models come as
32
+ `left.glb` and `right.glb` in the same profile folder, so `PAIRED` keeps the
33
+ other hand's model whenever one is kept: a user who only ever used one
34
+ controller online still has both offline. Add a rule like it for any other
35
+ family the app fetches piece by piece.
36
+
37
+ ## Behaviour to keep
38
+
39
+ - **Cache-first, with no revalidation.** A page loaded from the copy is exactly
40
+ its release, and a new release arrives only through `sw.js`.
41
+ - **Query strings are ignored**, so a start URL such as `/?source=pwa` gets the
42
+ cached `index.html`.
43
+ - **No `skipWaiting()` of its own.** The worker calls it only on the page's
44
+ `'take-over'` message; the page decides when a release takes over.
45
+ - **A take-over needs the asking page to be alone.** `skipWaiting()` moves every
46
+ open page of the scope onto the new release, and activation deletes the old
47
+ release's cache under them: a second tab in the middle of an XR session would
48
+ load the new release's files, or none offline. So the worker grants
49
+ `'take-over'` only when one window of the scope is open; otherwise the release
50
+ waits until every page has closed, and the browser activates it then.
51
+ - **Only CORS responses are kept.** A `no-cors` request returns an opaque
52
+ response with status `0` and an unreadable body, which cannot be checked.
53
+
54
+ ## Where the hash is compared
55
+
56
+ - **At build.** The release is named by a hash of its whole file list, so it
57
+ changes exactly when a listed file changes.
58
+ - **At install, file by file.** The worker looks in this release's own cache
59
+ first (an interrupted install resumes), then in earlier releases' caches, then
60
+ in the HTTP cache, and only then asks the server. Each cached copy carries its
61
+ hash in an `x-content-sha256` header, so an unchanged file is copied across,
62
+ never downloaded.
63
+ - **After every download.** The bytes are hashed before they are cached. A
64
+ mismatch is asked for again with `cache: 'no-cache'`, and a second mismatch
65
+ fails the install, which the browser retries on a later visit. This catches
66
+ stale CDN edges and a deploy that is still spreading.
67
+ - **On a first visit.** The page downloads its files before the worker exists,
68
+ and the worker takes them from the HTTP cache, so nothing crosses the wire
69
+ twice.
70
+ - **For optional files.** The same check runs when one is first fetched: a
71
+ stale copy is served that once and never kept.
72
+ - **For third-party files.** They have no hash in the list. The pinned URL is
73
+ their identity, and each is kept once per device.
74
+
75
+ ## Updates
76
+
77
+ A new release installs beside the old one and waits. The page decides when it
78
+ takes over: at once if `isIdle()` is `true`, when the app next calls
79
+ `checkIdle()` while idle, or otherwise at the next load, before the app builds
80
+ anything — each time only if no other page of the app is open. Installing reuses every unchanged file from the old
81
+ release's cache by its hash, so an update downloads only what changed. Optional
82
+ files the old release kept come across while their hash is unchanged, and the
83
+ third-party cache is never touched. After `'take-over'`, activation deletes the
84
+ older release caches and claims the page, which sees `controllerchange` and
85
+ reloads from the new copy.
86
+
87
+ ## Vercel headers
88
+
89
+ ```json
90
+ {
91
+ "headers": [
92
+ {
93
+ "source": "/sw.js",
94
+ "headers": [{ "key": "Cache-Control", "value": "no-cache" }]
95
+ },
96
+ {
97
+ "source": "/assets/(.*)",
98
+ "headers": [
99
+ {
100
+ "key": "Cache-Control",
101
+ "value": "public, max-age=31536000, immutable"
102
+ }
103
+ ]
104
+ }
105
+ ]
106
+ }
107
+ ```
@@ -0,0 +1,57 @@
1
+ # Testing the Offline Copy
2
+
3
+ Six checks prove the design. Each is about what crosses the wire, so the test
4
+ watches the wire.
5
+
6
+ | # | Check | Pass when |
7
+ | - | ----- | --------- |
8
+ | 1 | First visit | the release cache holds every listed file; no file was sent in full twice; no optional file nobody asked for was downloaded; optional and pinned files fetched before the worker existed are kept |
9
+ | 2 | Reload | the server is asked for nothing but `sw.js` |
10
+ | 3 | Offline | with the network off, a reload starts the app and kept files are served; an optional file never fetched online is missing, as it should be |
11
+ | 4 | Update while idle | after one file changes, only that file is downloaded; the new release takes over; the old release cache is gone; kept optional files came across |
12
+ | 5 | Update mid-session | the page is not reloaded during the session; when it ends, the new release takes over |
13
+ | 6 | Two pages open | an update while a second page of the app is open takes over neither page; once only one remains, the next idle moment or load takes it |
14
+
15
+ ## Harness
16
+
17
+ - **A logging server.** Serve the built `dist/` from a small server that logs
18
+ every request and answers revalidations with ETags and `304`, as a real host
19
+ does. Count only full `200` responses per path: a path sent twice is a
20
+ duplicate download.
21
+ - **No request interception.** Playwright turns the HTTP cache off whenever a
22
+ route is registered, and the first copy is made from that cache.
23
+ - **A persistent browser profile** (`launchPersistentContext`). It keeps the
24
+ HTTP cache on disk, as on a real device; an in-memory cache may refuse a large
25
+ file.
26
+ - **Polling loops.** Wait by calling `page.evaluate()` in a loop.
27
+ `page.waitForFunction()` does not wait for an async predicate, because a
28
+ promise counts as truthy.
29
+ - **An offline switch.** `context.setOffline(true)` takes the context offline
30
+ for check 3.
31
+ - **An XR session for check 5.** In desktop Chromium the injected IWER emulator
32
+ provides one: call `world.launchXR()` and wait until `world.visibilityState`
33
+ leaves `'non-immersive'`, so `isIdle()` is `false`.
34
+
35
+ Playwright attaches to every service worker, and that can stall activation after
36
+ `skipWaiting()` for over a minute, in some runs and not in others. If checks 4
37
+ or 5 hang on the take-over, drive them over the Chrome DevTools Protocol with
38
+ only the page attached, or by hand.
39
+
40
+ ## On the headset
41
+
42
+ Test a production build: `npm run dev` serves no `sw.js`. Build, serve `dist/`
43
+ over plain HTTP on a local port, and forward it so that
44
+ `http://localhost:<port>` counts as a secure context in Meta Quest Browser:
45
+
46
+ ```bash
47
+ npm run build
48
+ python3 -m http.server 4173 --bind 127.0.0.1 --directory dist
49
+ adb reverse tcp:4173 tcp:4173 # then open http://localhost:4173 on the headset
50
+ ```
51
+
52
+ Not `npx vite preview`: the IWSDK Vite plugin serves it over HTTPS with a
53
+ self-signed certificate, and Quest Browser refuses to register a service worker
54
+ from a page with a certificate error.
55
+
56
+ Clear the origin's storage between runs, for example with the DevTools
57
+ Protocol's `Storage.clearDataForOrigin`, or the site settings in the browser.
@@ -103,3 +103,4 @@ authored render cover deliberate framing.
103
103
  Make at most one focused correction, then replay the same observation. Stop
104
104
  when the requested bodies, collisions, and final state are evidenced. Resume
105
105
  ECS time and leave the app in a stable state.
106
+ <!-- iwsdk-agent-guidance version=1.2.0-rc.1 sha256=24a1d1e5a61472ec045759f5e385de1843df34b6e43613dcd6b591c439ec69f1 name=iwsdk-physics (installed by IWSDK; `npx @iwsdk/cli@latest agents sync` refreshes it and leaves it alone once edited) -->
@@ -45,6 +45,7 @@ The project manifest accepts execution, frequency, and interpolation options:
45
45
  - `useWorker` defaults to `true`. Set it to `false` to run the same runtime and message protocol on the main thread.
46
46
  - `updateFrequency` defaults to 60 Hz and is capped at 240 Hz.
47
47
  - `interpolation` defaults to `true` and smooths rendered transforms between fixed physics snapshots.
48
+ - `applyScale` defaults to `false`. `Auto` shapes and mesh-derived `ConvexHull`/`TriMesh` shapes always use the object's world scale. Shapes with explicit `dimensions` ignore it unless `applyScale` is `true`; a scaled object with explicit dimensions logs a one-time warning. Prefer `applyScale: true` in new projects and author dimensions in the object's unscaled units.
48
49
 
49
50
  The system also accepts a reactive `gravity` config (defaults to Earth gravity):
50
51
 
@@ -70,7 +70,10 @@ envEntity.addComponent(PhysicsBody, { state: PhysicsState.Static });
70
70
 
71
71
  ### Creating a Kinematic Moving Platform
72
72
 
73
- Kinematic bodies are moved by code and push dynamic objects:
73
+ Kinematic bodies follow their Object3D: move it from a system and the body sweeps
74
+ there over the next physics steps, pushing dynamic objects and carrying anything
75
+ resting on it. When the Object3D stops, the body stops with it. Don't apply
76
+ `PhysicsManipulation` to a kinematic body; it is ignored with a warning.
74
77
 
75
78
  ```typescript
76
79
  // Setup
@@ -110,7 +113,10 @@ physics.setBodyTransform(entity, {
110
113
  ```
111
114
 
112
115
  Velocity is cleared by default. Pass `{ resetVelocity: false }` only when a teleport
113
- must preserve motion. `gravityFactor`, `linearDamping`, and `angularDamping` can be
116
+ must preserve motion. The pose is relative to the entity's parent, like
117
+ `object3D.position`; pass `{ space: 'world' }` for a world-space pose. Physics
118
+ simulates in world space, so bodies may live under a moved level root or another
119
+ entity. `gravityFactor`, `linearDamping`, and `angularDamping` can be
114
120
  changed reactively with `entity.setValue`; changing motion state or shape requires
115
121
  deliberate body lifecycle handling.
116
122
 
@@ -140,7 +146,7 @@ entity.addComponent(DistanceGrabbable, {
140
146
  });
141
147
  ```
142
148
 
143
- When grabbed, the `GrabSystem` drives the held body kinematically (via `HP_Body_SetTargetQTransform`), making the object follow the hand. On release, the object resumes dynamic simulation with natural velocity for realistic throwing. Note: near-field grabs do not add `Hovered`/`Pressed` tags — assert grab behavior with ECS snapshot/diff, not tag queries.
149
+ When grabbed, the `PhysicsSystem` makes a dynamic body kinematic and drives it toward the hand pose, so it pushes other bodies without being knocked out of the hand. A pose jump faster than a hand can move, such as an emulator controller teleport, moves the held body without sweeping it through its neighbours. On release, the body is dynamic again and leaves with the hand's recent velocity, smoothed over about 50 ms and capped at 10 m/s. Note: near-field grabs do not add `Hovered`/`Pressed` tags — assert grab behavior with ECS snapshot/diff, not tag queries.
144
150
 
145
151
  ### Reading Velocity for Game Logic
146
152