@oasiz/sdk 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,157 +1,92 @@
1
- # Oasiz game SDKs
1
+ # @oasiz/sdk
2
2
 
3
- Games on Oasiz can integrate using either of these official SDKs:
3
+ Typed SDK for integrating games with the Oasiz platform. Handles score submission, haptic feedback, cross-session state persistence, multiplayer room codes, navigation hooks, and app lifecycle events for local development.
4
4
 
5
- | Platform | Package | Use for |
6
- | --- | --- | --- |
7
- | **HTML5 / TypeScript** | [`@oasiz/sdk`](#html5--typescript-oasizsdk) (npm) | Canvas, Phaser, custom JS/TS, any browser game |
8
- | **Unity WebGL** | [Unity runtime](#unity-webgl-sdk) in this repo (`packages/OasizSDK/`) | Unity projects targeting WebGL |
9
-
10
- Both talk to the same host bridges (`window.submitScore`, `__oasizLeaveGame`, layout APIs, custom DOM events such as `oasiz:pause`, etc.). Unsupported hosts no-op safely; local dev usually logs warnings instead of crashing.
11
-
12
- ---
13
-
14
- ## HTML5 / TypeScript (`@oasiz/sdk`)
15
-
16
- Typed SDK for integrating browser games with the Oasiz platform: score, haptics, cross-session state, multiplayer hooks, layout (safe area, leaderboard visibility), graphics performance, navigation (back / leave), and lifecycle events.
17
-
18
- ### Install
5
+ ## Install
19
6
 
20
7
  ```bash
21
- npm install @oasiz/sdk
8
+ npm install @oasiz/sdk@^0.1.0
22
9
  ```
23
10
 
24
- The published package includes ESM, CommonJS, and TypeScript declarations.
25
-
26
11
  ## Quick start
27
12
 
28
13
  ```ts
29
14
  import { oasiz } from "@oasiz/sdk";
30
15
 
31
- // 0. Optional local app preview for web development
32
- if (import.meta.env.DEV) {
33
- oasiz.enableAppSimulator();
34
- }
16
+ // 1. Emit score normalization config once on init
17
+ oasiz.emitScoreConfig({
18
+ anchors: [
19
+ { raw: 30, normalized: 100 },
20
+ { raw: 60, normalized: 300 },
21
+ { raw: 120, normalized: 600 },
22
+ { raw: 300, normalized: 950 },
23
+ ],
24
+ });
35
25
 
36
- // 1. Load persisted state at the start of each session
26
+ // 2. Load persisted state at the start of each session
37
27
  const state = oasiz.loadGameState();
38
28
  let level = typeof state.level === "number" ? state.level : 1;
39
29
 
40
- // 2. Save state at checkpoints
30
+ // 3. Save state at checkpoints
41
31
  oasiz.saveGameState({ level, coins: 42 });
42
32
 
43
- // 3. Trigger haptics on key events
33
+ // 4. Trigger haptics on key events
44
34
  oasiz.triggerHaptic("medium");
45
35
 
46
- // 4. Respect the host's top safe area (percent of viewport height → CSS vh)
47
- document.documentElement.style.setProperty(
48
- "--safe-top",
49
- `${oasiz.safeAreaTop}vh`,
50
- );
51
-
52
- // 5. Pick graphics settings for this device
53
- const graphics = oasiz.getGraphicsPerformance();
54
- renderer.setPixelRatio(graphics.tier === "high" ? 1.5 : graphics.tier === "medium" ? 1.25 : 1);
55
-
56
- // 6. Submit score when the game ends
36
+ // 5. Submit score when the game ends
57
37
  oasiz.submitScore(score);
58
-
59
- // 7. Optionally hide the leaderboard while a custom overlay is open
60
- oasiz.setLeaderboardVisible(false);
61
-
62
- // 8. Optionally surface console logs in-game while debugging
63
- oasiz.enableLogOverlay({
64
- enabled: new URLSearchParams(window.location.search).has("oasizLogs"),
65
- collapsed: true,
66
- });
67
38
  ```
68
39
 
69
- ### Local app simulator
40
+ ---
41
+
42
+ ## Score
70
43
 
71
- #### `oasiz.enableAppSimulator(options?: AppSimulatorOptions): AppSimulatorHandle`
44
+ ### `oasiz.submitScore(score: number)`
72
45
 
73
- Opt-in local web helper for previewing a game inside Oasiz-style mobile chrome. It simulates the app back button, leaderboard pill, like/comment hub, comments modal, and leaderboard modal while also injecting local safe-area and viewport-inset bridge values.
46
+ Submit the player's final score at game over. Call this exactly once per session, when the game ends. The platform handles leaderboard persistence do not track high scores locally.
74
47
 
75
48
  ```ts
76
- if (import.meta.env.DEV) {
77
- oasiz.enableAppSimulator();
49
+ private onGameOver(): void {
50
+ oasiz.submitScore(Math.floor(this.score));
78
51
  }
79
-
80
- oasiz.onBackButton(() => {
81
- togglePauseMenu();
82
- });
83
52
  ```
84
53
 
85
- By default, the game is placed inside a centered phone-sized box so developers can resize their browser around the same shape the app uses. The default device is `iphone-17-pro-max` (`440 × 956` CSS pixels). You can change the preview:
86
-
87
- ```ts
88
- const appPreview = oasiz.enableAppSimulator({
89
- device: "iphone-17-pro-max",
90
- likes: 2400,
91
- comments: 18,
92
- score: 12400,
93
- });
54
+ - `score` must be a non-negative integer. Floats are floored automatically.
55
+ - Do not call on intermediate scores or level completions, only on final game over.
94
56
 
95
- debugCommentsButton.onclick = () => appPreview.openComments();
96
- debugLeaderboardButton.onclick = () => appPreview.openLeaderboard();
97
- ```
57
+ ---
98
58
 
99
- Set `frame: false` if your own dev harness already renders the game in a phone frame.
100
-
101
- The simulator includes the back-button test bridge, so Escape, browser Back, and the simulated app back button all route through the same `oasiz.onBackButton(...)` handler when back override is active. Use `enableBackButtonTesting()` directly only when you want back simulation without app chrome.
102
-
103
- Supported `device` presets:
104
-
105
- | Device option | CSS viewport |
106
- | --- | --- |
107
- | `iphone-11` | `414 × 896` |
108
- | `iphone-11-pro` | `375 × 812` |
109
- | `iphone-11-pro-max` | `414 × 896` |
110
- | `iphone-12-mini` | `375 × 812` |
111
- | `iphone-12` | `390 × 844` |
112
- | `iphone-12-pro` | `390 × 844` |
113
- | `iphone-12-pro-max` | `428 × 926` |
114
- | `iphone-13-mini` | `375 × 812` |
115
- | `iphone-13` | `390 × 844` |
116
- | `iphone-13-pro` | `390 × 844` |
117
- | `iphone-13-pro-max` | `428 × 926` |
118
- | `iphone-14` | `390 × 844` |
119
- | `iphone-14-plus` | `428 × 926` |
120
- | `iphone-14-pro` | `393 × 852` |
121
- | `iphone-14-pro-max` | `430 × 932` |
122
- | `iphone-15` | `393 × 852` |
123
- | `iphone-15-plus` | `430 × 932` |
124
- | `iphone-15-pro` | `393 × 852` |
125
- | `iphone-15-pro-max` | `430 × 932` |
126
- | `iphone-16` | `393 × 852` |
127
- | `iphone-16-plus` | `430 × 932` |
128
- | `iphone-16-pro` | `402 × 874` |
129
- | `iphone-16-pro-max` | `440 × 956` |
130
- | `iphone-16e` | `390 × 844` |
131
- | `iphone-17` | `402 × 874` |
132
- | `iphone-17-pro` | `402 × 874` |
133
- | `iphone-17-pro-max` | `440 × 956` |
134
- | `iphone-17e` | `390 × 844` |
135
- | `iphone-air` | `420 × 912` |
136
-
137
- ### Score
138
-
139
- #### `oasiz.submitScore(score: number)`
59
+ ### `oasiz.emitScoreConfig(config)`
140
60
 
141
- Submit the player's final score at game over. Call this exactly once per session, when the game ends. The platform handles leaderboard persistence — do not track high scores locally.
61
+ Maps raw score values to the platform's normalized 0–1000 scale. Call once during initialization, not every frame.
142
62
 
143
63
  ```ts
144
- private onGameOver(): void {
145
- oasiz.submitScore(Math.floor(this.score));
146
- }
64
+ oasiz.emitScoreConfig({
65
+ anchors: [
66
+ { raw: 10, normalized: 100 }, // beginner
67
+ { raw: 30, normalized: 300 }, // good
68
+ { raw: 75, normalized: 600 }, // great
69
+ { raw: 200, normalized: 950 }, // godlike
70
+ ],
71
+ });
147
72
  ```
148
73
 
149
- - `score` must be a non-negative integer. Floats are floored automatically.
150
- - Do not call on intermediate scores or level completions, only on final game over.
74
+ **Anchor rules:**
75
+ - Exactly 4 anchors required.
76
+ - `raw` values must be strictly increasing.
77
+ - `normalized` values must end at exactly `950`.
78
+ - Choose thresholds based on realistic player skill bands.
79
+
80
+ **Practical guidance by game type:**
81
+ - Survival / time games → use seconds survived as `raw`
82
+ - Score accumulation games → use points as `raw`
83
+ - Puzzle games → use level reached or stars earned as `raw`
84
+
85
+ ---
151
86
 
152
- ### Haptics
87
+ ## Haptics
153
88
 
154
- #### `oasiz.triggerHaptic(type: HapticType)`
89
+ ### `oasiz.triggerHaptic(type: HapticType)`
155
90
 
156
91
  Trigger native haptic feedback. Always guard with the user's haptics setting.
157
92
 
@@ -160,7 +95,7 @@ type HapticType = "light" | "medium" | "heavy" | "success" | "error";
160
95
  ```
161
96
 
162
97
  | Type | When to use |
163
- | --- | --- |
98
+ |---|---|
164
99
  | `"light"` | UI button taps, menu navigation, D-pad press |
165
100
  | `"medium"` | Collecting items, standard collisions, scoring |
166
101
  | `"heavy"` | Explosions, major impacts, screen shake |
@@ -191,45 +126,20 @@ private onGameOver(): void {
191
126
 
192
127
  Haptics are throttled internally (50ms cooldown) to prevent spam.
193
128
 
194
- ### Debugging
195
-
196
- #### `oasiz.enableLogOverlay(options?: LogOverlayOptions)`
197
-
198
- Mount an opt-in in-game console viewer for local debugging, QA sessions, or creator support. It mirrors `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` into a floating overlay inside the game iframe. The overlay can be collapsed, repositioned by dragging the top bar, and resized from the bottom-right corner while the action buttons remain clickable.
199
-
200
- ```ts
201
- const logOverlay = oasiz.enableLogOverlay({
202
- enabled: new URLSearchParams(window.location.search).has("oasizLogs"),
203
- collapsed: true,
204
- });
205
-
206
- console.log("[Boot] Scene ready");
207
-
208
- // Optional cleanup if your game tears down and remounts
209
- logOverlay.destroy();
210
- ```
211
-
212
- Options:
213
-
214
- - `enabled`: defaults to `true`. Pass your own flag or query-param check here.
215
- - `collapsed`: start with only the toggle pill visible.
216
- - `maxEntries`: cap retained log lines. Defaults to `200`.
217
- - `title`: optional label shown at the top of the panel. Defaults to `SDK Logs`.
218
-
219
- The returned handle supports `show()`, `hide()`, `clear()`, `isVisible()`, and `destroy()`.
129
+ ---
220
130
 
221
- ### Game state persistence
131
+ ## Game state persistence
222
132
 
223
133
  Persist cross-session data such as unlocked levels, inventory, or lifetime stats. State is stored per-user per-game in the Oasiz backend — available across devices and app reinstalls.
224
134
 
225
- #### `oasiz.loadGameState(): Record<string, unknown>`
135
+ ### `oasiz.loadGameState(): Record<string, unknown>`
226
136
 
227
137
  Returns the player's saved state synchronously. Returns `{}` if no state has been saved yet. Call once at the start of the game.
228
138
 
229
139
  ```ts
230
140
  private initFromSavedState(): void {
231
141
  const state = oasiz.loadGameState();
232
- this.level = typeof state.level === "number" ? state.level : 1;
142
+ this.level = typeof state.level === "number" ? state.level : 1;
233
143
  this.lifetimeHits = typeof state.lifetimeHits === "number" ? state.lifetimeHits : 0;
234
144
  this.unlockedSkins = Array.isArray(state.unlockedSkins) ? state.unlockedSkins : [];
235
145
  }
@@ -237,7 +147,7 @@ private initFromSavedState(): void {
237
147
 
238
148
  Always validate the shape of loaded data — it may be `{}` on first play.
239
149
 
240
- #### `oasiz.saveGameState(state: Record<string, unknown>)`
150
+ ### `oasiz.saveGameState(state: Record<string, unknown>)`
241
151
 
242
152
  Queues a debounced save. Saves are batched automatically — call freely at checkpoints without worrying about request spam.
243
153
 
@@ -254,12 +164,11 @@ private onLevelComplete(): void {
254
164
  ```
255
165
 
256
166
  **Rules:**
257
-
258
167
  - State must be a plain JSON object (not an array or primitive).
259
168
  - Do not use `localStorage` for cross-session progress — use `saveGameState` so data syncs across platforms.
260
169
  - Do not store scores here — scores are submitted via `submitScore`.
261
170
 
262
- #### `oasiz.flushGameState()`
171
+ ### `oasiz.flushGameState()`
263
172
 
264
173
  Forces an immediate write, bypassing the debounce. Use at important checkpoints like game over or before the page unloads.
265
174
 
@@ -271,122 +180,19 @@ private onGameOver(): void {
271
180
  }
272
181
  ```
273
182
 
274
- ### Layout
275
-
276
- Use runtime viewport insets instead of direct CSS `env(safe-area-inset-*)` reads or hardcoded offsets. The SDK resolves host-provided Oasiz values first, then browser CSS `env(safe-area-inset-*)`, then legacy `constant(safe-area-inset-*)`, and finally `0`.
277
-
278
- The top inset preserves the existing Oasiz game-safe top behavior: host chrome, invite UI, and leaderboard clearance can contribute to it. Left, right, and bottom are device safe-area insets today and may include future host UI obstructions.
279
-
280
- #### `oasiz.getViewportInsets(): ViewportInsets`
281
-
282
- Returns effective viewport insets in both CSS pixels and normalized percentages:
283
-
284
- ```ts
285
- const insets = oasiz.getViewportInsets();
286
- hud.style.paddingTop = `${insets.pixels.top}px`;
287
- hud.style.paddingRight = `${insets.pixels.right}px`;
288
- hud.style.paddingBottom = `${insets.pixels.bottom}px`;
289
- hud.style.paddingLeft = `${insets.pixels.left}px`;
290
- ```
291
-
292
- Percentages use the matching active viewport axis:
293
-
294
- - `top` / `bottom` are percentages of viewport height
295
- - `left` / `right` are percentages of viewport width
296
-
297
- Hosts may expose pixels via `window.getViewportInsets()` or `window.__OASIZ_VIEWPORT_INSETS__`, for example `{ top, right, bottom, left }` or `{ pixels: { top, right, bottom, left } }`. Hosts may expose percentages via `window.getViewportInsetsPercent()`, `window.__OASIZ_VIEWPORT_INSETS_PERCENT__`, or a `percent` object. Per-side globals such as `window.__OASIZ_SAFE_AREA_BOTTOM__` are also supported.
298
-
299
- #### `oasiz.getSafeAreaTop(): number`
300
-
301
- Legacy alias for `oasiz.getViewportInsets().percent.top`. Returns the top inset as a percentage of viewport height (0–100). To get pixels in JavaScript, prefer `oasiz.getViewportInsets().pixels.top`. In CSS, the percent value matches **`vh`** units (for example `12.5vh` for 12.5% of the viewport height). Unsupported hosts return `0`.
302
-
303
- ```ts
304
- const safeTopPct = oasiz.getSafeAreaTop();
305
- document.documentElement.style.setProperty("--safe-top", `${safeTopPct}vh`);
306
- ```
307
-
308
- #### `oasiz.safeAreaTop`
309
-
310
- Getter alias for `getSafeAreaTop()`.
311
-
312
- #### `oasiz.viewportInsets`
313
-
314
- Getter alias for `getViewportInsets()`.
315
-
316
- Recommended CSS pattern:
317
-
318
- ```css
319
- :root {
320
- --safe-top: 0px;
321
- }
322
-
323
- #top-bar {
324
- padding-top: var(--safe-top);
325
- }
326
- ```
327
-
328
- #### `oasiz.setLeaderboardVisible(visible: boolean): void`
329
-
330
- Show or hide the host leaderboard UI from inside the game. This only affects the leaderboard; back and social controls remain visible. Calls `window.__oasizSetLeaderboardVisible` when present.
331
-
332
- ```ts
333
- function openCustomOverlay(): void {
334
- oasiz.setLeaderboardVisible(false);
335
- }
336
-
337
- function closeCustomOverlay(): void {
338
- oasiz.setLeaderboardVisible(true);
339
- }
340
- ```
341
-
342
- Unsupported hosts safely no-op.
343
-
344
- ### Graphics performance
345
-
346
- #### `oasiz.getGraphicsPerformance(): GraphicsPerformanceMetric`
347
-
348
- Returns a recommended FPS target and suggested rendering tier:
349
-
350
- ```ts
351
- const graphics = oasiz.getGraphicsPerformance();
352
-
353
- switch (graphics.tier) {
354
- case "high":
355
- enablePostProcessing();
356
- renderer.setPixelRatio(1.5);
357
- break;
358
- case "medium":
359
- renderer.setPixelRatio(1.25);
360
- break;
361
- case "low":
362
- disableHeavyParticles();
363
- renderer.setPixelRatio(1);
364
- break;
365
- case "minimal":
366
- disableOptionalEffects();
367
- renderer.setPixelRatio(0.75);
368
- break;
369
- }
370
- ```
371
-
372
- The returned object is `{ fps, tier }`, where `fps` is the recommended render target and `tier` is `"minimal"`, `"low"`, `"medium"`, or `"high"`. Hosts can inject measured values with `window.getGraphicsPerformance()` or `window.__OASIZ_GRAPHICS_PERFORMANCE__`; otherwise the SDK estimates from browser, device, and WebGL capability signals.
373
-
374
- #### `oasiz.graphicsPerformance`
375
-
376
- Getter alias for `getGraphicsPerformance()`.
183
+ ---
377
184
 
378
- ### Lifecycle
185
+ ## Lifecycle
379
186
 
380
187
  The platform dispatches lifecycle events when the app goes to the background or returns to the foreground. Subscribe to pause game loops and audio accordingly.
381
188
 
382
- #### `oasiz.onPause(callback: () => void): Unsubscribe`
383
-
384
- #### `oasiz.onResume(callback: () => void): Unsubscribe`
189
+ ### `oasiz.onPause(callback: () => void): Unsubscribe`
190
+ ### `oasiz.onResume(callback: () => void): Unsubscribe`
385
191
 
386
192
  Both return an unsubscribe function.
387
193
 
388
194
  ```ts
389
- const offPause = oasiz.onPause(() => {
195
+ const offPause = oasiz.onPause(() => {
390
196
  this.gameLoop.stop();
391
197
  this.bgMusic.pause();
392
198
  });
@@ -401,17 +207,19 @@ offPause();
401
207
  offResume();
402
208
  ```
403
209
 
404
- ### Navigation
210
+ ---
211
+
212
+ ## Navigation
405
213
 
406
214
  Use navigation hooks when your game needs to control back behavior (Android back / web Escape) or participate in host-driven close events.
407
215
 
408
- #### `oasiz.onBackButton(callback: () => void): Unsubscribe`
216
+ ### `oasiz.onBackButton(callback: () => void): Unsubscribe`
409
217
 
410
218
  Registers a callback for platform back actions. While at least one back listener is subscribed, back actions are routed to your game instead of immediately closing it.
411
219
 
412
220
  Use this for pause menus, in-game overlays, or custom back-stack behavior.
413
221
 
414
- **If your callback throws**, the SDK calls `leaveGame()` (host close) and **rethrows** the error so you still see it in devtools or error reporting. Non-`Error` throws are normalized to an `Error` (strings become the message; otherwise `"Back button callback failed."`).
222
+ If your callback throws, Oasiz falls back to closing the game and returning the player to Oasiz home before rethrowing the error for debugging/reporting.
415
223
 
416
224
  ```ts
417
225
  const offBack = oasiz.onBackButton(() => {
@@ -426,30 +234,7 @@ const offBack = oasiz.onBackButton(() => {
426
234
  offBack();
427
235
  ```
428
236
 
429
- #### `oasiz.enableBackButtonTesting(options?: BackButtonTestingOptions): BackButtonTestingHandle`
430
-
431
- Opt-in local web helper for testing back override behavior without the Oasiz app bridge. Call it before registering `onBackButton` in local development:
432
-
433
- ```ts
434
- if (import.meta.env.DEV) {
435
- oasiz.enableBackButtonTesting();
436
- }
437
-
438
- const offBack = oasiz.onBackButton(() => {
439
- closePauseMenuOrOpenIt();
440
- });
441
- ```
442
-
443
- While a back listener is active, the helper maps Escape to the same `oasiz:back` event the app sends. By default it also traps one browser-history entry so the browser Back button dispatches `oasiz:back` instead of leaving the page.
444
-
445
- ```ts
446
- const backTest = oasiz.enableBackButtonTesting({ browserHistory: false });
447
- testBackButton.onclick = () => backTest.triggerBack();
448
- ```
449
-
450
- The returned handle also exposes `triggerLeave()` and `destroy()`. This helper is for local/dev web testing; in the app, the real bridge still owns back behavior.
451
-
452
- #### `oasiz.leaveGame(): void`
237
+ ### `oasiz.leaveGame(): void`
453
238
 
454
239
  Programmatically request the host to close the current game (for example, from a Quit button inside your game UI).
455
240
 
@@ -484,13 +269,13 @@ const offLeave = oasiz.onLeaveGame(() => {
484
269
  offLeave();
485
270
  ```
486
271
 
487
- ### Multiplayer
272
+ ---
488
273
 
489
- #### `oasiz.shareRoomCode(code: string | null, options?: { inviteOverride?: boolean })`
274
+ ## Multiplayer
490
275
 
491
- Notify the platform of the active multiplayer room so friends can join via the invite system. Pass `null` when leaving a room.
276
+ ### `oasiz.shareRoomCode(code: string | null)`
492
277
 
493
- Set `inviteOverride: true` when your game wants to hide the platform invite pill and render its own invite button/UI. The platform still tracks the room code, but your game owns the invite entry point.
278
+ Notify the platform of the active multiplayer room so friends can join via the invite system. Pass `null` when leaving a room.
494
279
 
495
280
  ```ts
496
281
  import { insertCoin, getRoomCode } from "playroomkit";
@@ -503,26 +288,7 @@ oasiz.shareRoomCode(getRoomCode());
503
288
  oasiz.shareRoomCode(null);
504
289
  ```
505
290
 
506
- ```ts
507
- // Game-owned invite UI: hide the platform pill, keep room tracking
508
- oasiz.shareRoomCode(getRoomCode(), { inviteOverride: true });
509
- ```
510
-
511
- #### `oasiz.openInviteModal(): void`
512
-
513
- Opens the platform invite-friends UI when the bridge is available. Typically used together with `shareRoomCode` (for example, your own invite button calls this).
514
-
515
- ```ts
516
- import { openInviteModal, shareRoomCode } from "@oasiz/sdk";
517
-
518
- shareRoomCode("ABCD", { inviteOverride: true });
519
-
520
- inviteButton.addEventListener("click", () => {
521
- openInviteModal();
522
- });
523
- ```
524
-
525
- #### Read-only injected values
291
+ ### Read-only injected values
526
292
 
527
293
  These are populated by the platform before the game loads. Always check for `undefined` before using.
528
294
 
@@ -536,31 +302,25 @@ if (oasiz.roomCode) {
536
302
  }
537
303
 
538
304
  // Player identity for multiplayer games
539
- const name = oasiz.playerName;
305
+ const name = oasiz.playerName;
540
306
  const avatar = oasiz.playerAvatar;
541
307
  ```
542
308
 
543
- ### Named exports
309
+ ---
310
+
311
+ ## Named exports
544
312
 
545
313
  All methods are also available as named exports if you prefer not to use the `oasiz` namespace object:
546
314
 
547
315
  ```ts
548
316
  import {
549
317
  submitScore,
550
- share,
318
+ emitScoreConfig,
551
319
  triggerHaptic,
552
320
  loadGameState,
553
321
  saveGameState,
554
322
  flushGameState,
555
323
  shareRoomCode,
556
- openInviteModal,
557
- enableAppSimulator,
558
- enableLogOverlay,
559
- enableBackButtonTesting,
560
- getGraphicsPerformance,
561
- getSafeAreaTop,
562
- getViewportInsets,
563
- setLeaderboardVisible,
564
324
  onPause,
565
325
  onResume,
566
326
  onBackButton,
@@ -573,232 +333,18 @@ import {
573
333
  } from "@oasiz/sdk";
574
334
  ```
575
335
 
576
- ### TypeScript types
577
-
578
- ```ts
579
- import type {
580
- AppSimulatorDevice,
581
- AppSimulatorDeviceName,
582
- AppSimulatorHandle,
583
- AppSimulatorOptions,
584
- AppSimulatorOrientation,
585
- BackButtonTestingHandle,
586
- BackButtonTestingOptions,
587
- GameState,
588
- GraphicsPerformanceMetric,
589
- GraphicsPerformanceTier,
590
- HapticType,
591
- LogOverlayEntry,
592
- LogOverlayHandle,
593
- LogOverlayLevel,
594
- LogOverlayOptions,
595
- ShareRequest,
596
- ShareRoomCodeOptions,
597
- Unsubscribe,
598
- } from "@oasiz/sdk";
599
- ```
600
-
601
336
  ---
602
337
 
603
- ## Unity WebGL SDK
604
-
605
- C# API and **WebGL-only** `OasizBridge.jslib` live in this repository at **`packages/OasizSDK/`**. Copy the **`OasizSDK`** folder into your Unity project under **`Assets/`** (for example `Assets/OasizSDK`).
606
-
607
- ### Setup
608
-
609
- 1. Copy `packages/OasizSDK` from this repo into `Assets/OasizSDK`.
610
- 2. Ensure the **WebGL** platform is selected for release builds; the `.jslib` under `Runtime/Plugins/WebGL/` is included automatically for WebGL.
611
- 3. Add an **`OasizSDK`** component to a persistent GameObject early (for example a bootstrap scene), **or** rely on `OasizSDK.Instance` which creates a `DontDestroyOnLoad` object. The component registers listeners for `oasiz:pause`, `oasiz:resume`, `oasiz:back`, and `oasiz:leave` via `SendMessage`.
612
-
613
- ### Quick start
614
-
615
- ```csharp
616
- using Oasiz;
617
- using UnityEngine;
618
-
619
- public class GameManager : MonoBehaviour
620
- {
621
- void Start()
622
- {
623
- // Ensure the singleton is initialized early
624
- _ = OasizSDK.Instance;
625
-
626
- // Subscribe to lifecycle events
627
- OasizSDK.OnPause += OnPause;
628
- OasizSDK.OnResume += OnResume;
629
-
630
- // Offset UI for the host's top safe area (0–100 percent of Screen.height)
631
- float safeTopPct = OasizSDK.SafeAreaTop;
632
- float safeTopPx = safeTopPct / 100f * Screen.height;
633
- Debug.Log($"Safe area top: {safeTopPx}px ({safeTopPct}% of height)");
634
-
635
- // Pick visual settings for the current device
636
- GraphicsPerformanceMetric graphics = OasizSDK.GetGraphicsPerformance();
637
- Debug.Log($"Graphics tier: {graphics.tier} ({graphics.fps} FPS target)");
638
-
639
- // Emit score normalization anchors
640
- OasizSDK.EmitScoreConfig(new ScoreConfig(
641
- new ScoreAnchor(10, 100),
642
- new ScoreAnchor(30, 300),
643
- new ScoreAnchor(75, 600),
644
- new ScoreAnchor(200, 950)
645
- ));
646
- }
647
-
648
- void OnGameOver(int finalScore)
649
- {
650
- OasizSDK.SubmitScore(finalScore);
651
- OasizSDK.FlushGameState();
652
- OasizSDK.SetLeaderboardVisible(true);
653
- }
654
-
655
- void OnGameplayStart()
656
- {
657
- OasizSDK.SetLeaderboardVisible(false);
658
- }
659
-
660
- void OnPause() => Time.timeScale = 0f;
661
- void OnResume() => Time.timeScale = 1f;
662
-
663
- void OnDestroy()
664
- {
665
- OasizSDK.OnPause -= OnPause;
666
- OasizSDK.OnResume -= OnResume;
667
- }
668
- }
669
- ```
670
-
671
- ### API parity (TypeScript → C#)
672
-
673
- | HTML5 (`@oasiz/sdk`) | Unity (`Oasiz` namespace) |
674
- | --- | --- |
675
- | `oasiz.submitScore(n)` | `OasizSDK.SubmitScore(int)` |
676
- | `oasiz.triggerHaptic(type)` | `OasizSDK.TriggerHaptic(HapticType)` |
677
- | `oasiz.loadGameState()` | `OasizSDK.LoadGameState()` → `Dictionary<string, object>` |
678
- | `oasiz.saveGameState(obj)` | `OasizSDK.SaveGameState(Dictionary<string, object>)` |
679
- | `oasiz.flushGameState()` | `OasizSDK.FlushGameState()` |
680
- | `oasiz.getViewportInsets()` / `viewportInsets` | `OasizSDK.GetViewportInsets()` (`ViewportInsets`, each side 0–100, % of matching viewport axis) |
681
- | `oasiz.getSafeAreaTop()` / `safeAreaTop` | `OasizSDK.GetSafeAreaTop()` / `OasizSDK.SafeAreaTop` (`float`, 0–100, % of viewport height; legacy alias for top viewport inset) |
682
- | `oasiz.setLeaderboardVisible(v)` | `OasizSDK.SetLeaderboardVisible(bool)` |
683
- | `oasiz.getGraphicsPerformance()` / `graphicsPerformance` | `OasizSDK.GetGraphicsPerformance()` / `OasizSDK.GraphicsPerformance` (`GraphicsPerformanceMetric`, recommended FPS plus `minimal` / `low` / `medium` / `high`) |
684
- | `oasiz.onPause` / `onResume` | `OasizSDK.OnPause` / `OnResume` static events |
685
- | `oasiz.onBackButton` | `OasizSDK.OnBackButton` or `SubscribeBackButton(Action)` (reference-counts `__oasizSetBackOverride`) |
686
- | `oasiz.enableBackButtonTesting()` | `OasizSDK.EnableBackButtonTesting()` (WebGL local/dev helper for Escape/browser Back testing) |
687
- | `oasiz.onLeaveGame` | `OasizSDK.OnLeaveGame` |
688
- | `oasiz.leaveGame()` | `OasizSDK.LeaveGame()` |
689
- | `oasiz.share(request)` | `OasizSDK.Share(ShareRequest)` |
690
- | `oasiz.shareRoomCode` | `OasizSDK.ShareRoomCode(string, ShareRoomCodeOptions)` |
691
- | `oasiz.openInviteModal()` | `OasizSDK.OpenInviteModal()` |
692
- | `oasiz.gameId` / `roomCode` / ... | `OasizSDK.GameId` / `RoomCode` / `PlayerName` / `PlayerAvatar` |
693
- | -- | `OasizSDK.EmitScoreConfig(ScoreConfig)` → `window.emitScoreConfig` (Unity-only helper for normalized score UI) |
694
- | `oasiz.enableLogOverlay` | `OasizSDK.EnableLogOverlay(LogOverlayOptions)` (see note below) |
695
- | -- | `OasizSDK.AppendLogOverlay(level, message, stackTrace)` (see note below) |
696
-
697
- ### Local back-button testing (Unity WebGL)
698
-
699
- For local WebGL builds outside the Oasiz app, install the dev bridge before testing your subscribed back handler:
700
-
701
- ```csharp
702
- #if DEVELOPMENT_BUILD || UNITY_EDITOR
703
- OasizSDK.EnableBackButtonTesting();
704
- #endif
705
-
706
- Action unsubscribeBack = OasizSDK.SubscribeBackButton(() =>
707
- {
708
- TogglePauseMenu();
709
- });
710
- ```
711
-
712
- While the override is active, Escape and the browser Back button dispatch the same `oasiz:back` event that the app bridge sends. You can disable either input with `OasizSDK.EnableBackButtonTesting(keyboard: false)` or `OasizSDK.EnableBackButtonTesting(browserHistory: false)`.
713
-
714
- ### Share (Unity)
715
-
716
- HTML5 **`oasiz.share`** returns a **Promise** you can `await`. Unity **`OasizSDK.Share(ShareRequest)`** returns **`void`**: C# validation throws **`ArgumentException`** with the same rules as TypeScript (at least one of text, score, or image; non-negative integer score; `http(s)` or `data:image/...;base64,...` image). The call forwards JSON to **`window.__oasizShareRequest`**. If the host promise rejects, the **WebGL `.jslib` logs the error** to the browser console.
717
-
718
- ```csharp
719
- OasizSDK.Share(new ShareRequest
720
- {
721
- Text = "Beat this run!",
722
- Score = 1200,
723
- Image = "https://example.com/card.png",
724
- });
725
- ```
726
-
727
- ### Types
728
-
729
- ```csharp
730
- // Haptic feedback intensity
731
- public enum HapticType { Light, Medium, Heavy, Success, Error }
732
-
733
- // Score normalization (exactly 4 anchors required)
734
- public struct ScoreAnchor { public int raw; public int normalized; }
735
- public struct ScoreConfig { public ScoreAnchor[] anchors; }
736
-
737
- // Host share sheet (text / score / image URL or data URL)
738
- public class ShareRequest
739
- {
740
- public string Text { get; set; }
741
- public int? Score { get; set; }
742
- public string Image { get; set; }
743
- }
744
-
745
- // Multiplayer invite options
746
- public class ShareRoomCodeOptions { public bool InviteOverride { get; set; } }
747
-
748
- // Log overlay configuration
749
- public class LogOverlayOptions
750
- {
751
- public bool Enabled { get; set; } = true;
752
- public bool Collapsed { get; set; } = false;
753
- public int MaxEntries { get; set; } = 200;
754
- public string Title { get; set; } = "SDK Logs";
755
- }
756
-
757
- // Log overlay lifecycle handle
758
- public class LogOverlayHandle
759
- {
760
- public void Clear();
761
- public void Hide();
762
- public void Show();
763
- public bool IsVisible();
764
- public void Destroy();
765
- }
766
- ```
767
-
768
- ### Back button and errors
769
-
770
- Matching the HTML5 SDK: if any **`OnBackButton`** handler throws, **`OasizSDK.LeaveGame()`** is invoked and the **original exception is rethrown** (`throw;` preserves the stack trace). Use **`SubscribeBackButton`** when you want an unsubscribe delegate; you can also use `OnBackButton +=` / `-=` directly.
771
-
772
- ```csharp
773
- // Subscribe with automatic unsubscribe support
774
- var offBack = OasizSDK.SubscribeBackButton(() =>
775
- {
776
- if (isPaused)
777
- Resume();
778
- else
779
- Pause();
780
- });
338
+ ## TypeScript types
781
339
 
782
- // Unsubscribe when no longer needed
783
- offBack();
340
+ ```ts
341
+ import type { HapticType, ScoreConfig, ScoreAnchor, GameState } from "@oasiz/sdk";
784
342
  ```
785
343
 
786
- ### Editor vs WebGL builds
787
-
788
- In the **Unity Editor**, bridge calls are mostly **logged** and return safe defaults (for example safe area `0`, `null` platform IDs). Real host integration applies to **WebGL player** builds running inside Oasiz.
789
-
790
- ### Log overlay (Unity)
791
-
792
- The C# API for the log overlay exists for API compatibility, but the **default `OasizBridge.jslib` in this repo does not inject DOM UI** — `EnableLogOverlay` / `AppendLogOverlay` are no-ops at the JavaScript layer. Use Unity's console and device logs for debugging unless you replace or extend the `.jslib` on your side.
793
-
794
- `AppendLogOverlay(level, message, stackTrace)` lets you pipe `Debug.Log` output into the overlay manually, since many embedded WebViews do not route Unity player logs through `console.log`. Valid levels: `"debug"`, `"log"`, `"info"`, `"warn"`, `"error"`.
795
-
796
344
  ---
797
345
 
798
346
  ## Local development
799
347
 
800
- ### HTML5 / TypeScript
801
-
802
348
  All methods safely no-op when the platform bridges are not injected. In development mode a console warning is logged so you know the call was made:
803
349
 
804
350
  ```
@@ -806,7 +352,3 @@ All methods safely no-op when the platform bridges are not injected. In developm
806
352
  ```
807
353
 
808
354
  No crashes, no special setup required for local dev.
809
-
810
- ### Unity WebGL
811
-
812
- The `.jslib` logs warnings when `window.*` bridges are missing (for example `submitScore`, `__oasizLeaveGame`). The Editor path avoids calling native plugins and prints `Debug.Log` for most operations instead.