@littlepartytime/sdk 2.0.1 → 2.2.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/GAME_DEV_GUIDE.md CHANGED
@@ -22,11 +22,16 @@ my-game/
22
22
  ├── vite.config.ts # Build configuration
23
23
  ├── vitest.config.ts # Test configuration
24
24
  ├── tsconfig.json
25
- ├── assets/ # Required game images
25
+ ├── assets/ # Game images and custom assets
26
26
  │ ├── icon.png # 1:1 (256x256+) - game list icon
27
27
  │ ├── banner.png # 16:9 (640x360+) - lobby banner
28
28
  │ ├── cover.png # 21:9 (840x360+) - store/featured cover
29
- └── splash.png # 9:21 (360x840+) - loading screen
29
+ ├── splash.png # 9:21 (360x840+) - loading screen
30
+ │ ├── cards/ # Custom game assets (optional)
31
+ │ │ ├── king.png
32
+ │ │ └── queen.png
33
+ │ └── sounds/
34
+ │ └── flip.mp3
30
35
  ├── src/
31
36
  │ ├── config.ts # GameConfig - metadata
32
37
  │ ├── engine.ts # GameEngine - server-side logic
@@ -592,7 +597,12 @@ The `.zip` upload package contains:
592
597
  ├── icon.png # 1:1 game icon
593
598
  ├── banner.png # 16:9 banner
594
599
  ├── cover.png # 21:9 cover
595
- └── splash.png # 9:21 splash screen
600
+ ├── splash.png # 9:21 splash screen
601
+ └── assets/ # Custom game assets (if any)
602
+ ├── cards/
603
+ │ └── king.png
604
+ └── sounds/
605
+ └── flip.mp3
596
606
  ```
597
607
 
598
608
  ### Configuration
@@ -663,18 +673,61 @@ Every game must include 4 images in the `assets/` directory. These are validated
663
673
 
664
674
  The `pack` command reads these images, validates them, and includes them in the zip with canonical names (`icon.png`, `banner.png`, etc.).
665
675
 
666
- ### In-Game Assets (Audio, Fonts, etc.)
676
+ ### Custom Game Assets
667
677
 
668
- For assets used inside your game UI (not the 4 required images above), use one of these approaches:
678
+ For assets used inside your game UI (card images, sound effects, fonts, etc.), place them in subdirectories under `assets/`:
679
+
680
+ ```
681
+ assets/
682
+ ├── icon.png # Platform display images (root level, required)
683
+ ├── banner.png
684
+ ├── cover.png
685
+ ├── splash.png
686
+ ├── cards/ # Custom game assets (subdirectories)
687
+ │ ├── king.png
688
+ │ └── queen.png
689
+ └── sounds/
690
+ └── flip.mp3
691
+ ```
692
+
693
+ Access custom assets in your renderer via `platform.getAssetUrl()`:
694
+
695
+ ```tsx
696
+ export default function GameRenderer({ platform, state }: GameRendererProps) {
697
+ const cardImg = platform.getAssetUrl('cards/king.png');
698
+ const flipSound = platform.getAssetUrl('sounds/flip.mp3');
699
+
700
+ return (
701
+ <div>
702
+ <img src={cardImg} alt="King" />
703
+ <audio src={flipSound} />
704
+ </div>
705
+ );
706
+ }
707
+ ```
708
+
709
+ **How it works:**
710
+ - During `lpt-dev-kit dev`: returns a local URL (e.g., `http://localhost:4000/assets/cards/king.png`)
711
+ - In production: returns a CDN URL (the platform uploads assets to OSS automatically)
712
+
713
+ **Validation rules (enforced by `pack` command):**
714
+
715
+ | Rule | Limit |
716
+ |------|-------|
717
+ | Single file size | ≤ 20MB |
718
+ | Total assets size | ≤ 100MB |
719
+ | Allowed file types | `.png`, `.jpg`, `.jpeg`, `.webp`, `.svg`, `.gif`, `.mp3`, `.wav`, `.ogg`, `.json`, `.woff2`, `.woff` |
720
+ | Path rules | No `..`, no spaces |
721
+
722
+ **Alternative approaches for small assets:**
669
723
 
670
724
  | Approach | When to Use | How |
671
725
  |----------|-------------|-----|
672
- | **Inline in bundle** | Small assets (icons, sounds < 100KB) | Vite automatically inlines assets below `assetsInlineLimit` (default 4KB) as data URLs. Increase the limit in `vite.config.ts` if needed: `build: { assetsInlineLimit: 100000 }` |
673
- | **External URL** | Large assets (images, audio, video) | Host on a CDN or external server, reference by absolute URL in your code |
674
- | **CSS/SVG** | UI elements, icons | Use Tailwind CSS utilities, inline SVG components, or CSS gradients/shapes |
675
- | **Emoji/Unicode** | Simple visual indicators | Use Unicode characters directly in JSX |
726
+ | **Inline in bundle** | Tiny assets (< 4KB) | Vite automatically inlines as data URLs |
727
+ | **CSS/SVG** | UI elements, icons | Tailwind CSS utilities or inline SVG components |
728
+ | **Emoji/Unicode** | Simple visual indicators | Unicode characters directly in JSX |
676
729
 
677
- > **Tip:** Keep your bundle under 5MB. The `pack` command warns if `bundle.js` exceeds this limit.
730
+ > **Tip:** Use `platform.getAssetUrl()` for assets 100KB+ instead of inlining them into the bundle.
678
731
 
679
732
  ### Submitting Your Game
680
733
 
@@ -695,6 +748,47 @@ For assets used inside your game UI (not the 4 required images above), use one o
695
748
  | `on(event, handler)` | Listens for events from the server |
696
749
  | `off(event, handler)` | Removes an event listener |
697
750
  | `reportResult(result)` | Reports game results (called by platform, not games) |
751
+ | `getAssetUrl(path)` | Returns the runtime URL for a custom asset (e.g., `"cards/king.png"` → CDN URL) |
752
+ | `getDeviceCapabilities()` | Returns `{ haptics: boolean, motion: boolean }` indicating available device features |
753
+ | `haptic(type, option?)` | Triggers haptic feedback. `type`: `'impact'` / `'notification'` / `'selection'`. Silent no-op if unsupported |
754
+ | `onShake(handler)` | Listens for device shake events. Returns an unsubscribe function |
755
+ | `onTilt(handler)` | Streams device tilt data (`{ alpha, beta, gamma }`) at ~60fps. Returns an unsubscribe function |
756
+
757
+ #### Device Capabilities & Graceful Degradation
758
+
759
+ Games can query runtime capabilities via `getDeviceCapabilities()` and provide fallback UI:
760
+
761
+ ```tsx
762
+ const caps = platform.getDeviceCapabilities();
763
+
764
+ // Shake: use motion sensor or fall back to a button
765
+ useEffect(() => {
766
+ if (!caps.motion) return;
767
+ return platform.onShake(() => {
768
+ platform.haptic('impact', 'heavy');
769
+ platform.send({ type: 'ROLL_DICE' });
770
+ });
771
+ }, [platform, caps.motion]);
772
+
773
+ // Tilt: stream orientation data for motion-controlled games
774
+ useEffect(() => {
775
+ if (!caps.motion) return;
776
+ return platform.onTilt((tilt) => {
777
+ // tilt.beta = front/back (-180~180), tilt.gamma = left/right (-90~90)
778
+ updateBallPosition(tilt.gamma, tilt.beta);
779
+ });
780
+ }, [platform, caps.motion]);
781
+
782
+ // Haptic feedback on user action (silent no-op if unsupported)
783
+ platform.haptic('impact', 'light');
784
+ ```
785
+
786
+ | Environment | Haptics | Motion (Shake/Tilt) |
787
+ |---|---|---|
788
+ | Native App (iOS/Android) | Full support (Impact/Notification/Selection) | Full support |
789
+ | Web (Android Chrome) | Basic vibration | Supported |
790
+ | Web (iOS Safari) | Not supported (silent) | Requires permission (handled by platform) |
791
+ | Dev-kit preview | Not supported (silent) | Not supported |
698
792
 
699
793
  ### Events the renderer should listen for
700
794
 
@@ -753,6 +847,113 @@ Use these CSS variables / Tailwind classes for consistent styling:
753
847
  | Display font | `--font-display` | `font-display` |
754
848
  | Body font | `--font-body` | `font-body` |
755
849
 
850
+ ## Platform Runtime Constraints
851
+
852
+ The production platform runs game engines inside a Node.js `vm` sandbox. The dev-kit (`npm run dev`) automatically enforces key constraints so issues surface during local development, not after deployment.
853
+
854
+ ### Timer APIs Are Disabled
855
+
856
+ The sandbox replaces `setTimeout`, `setInterval`, `clearTimeout`, and `clearInterval` with no-ops. Calling them inside engine code will:
857
+
858
+ - **In production**: silently do nothing (the callback is never executed)
859
+ - **In dev-kit**: print a warning to the console and return `0`
860
+
861
+ ```typescript
862
+ // BAD - will not work in production
863
+ handleAction(state, playerId, action) {
864
+ setTimeout(() => {
865
+ // This callback will NEVER run in the sandbox
866
+ }, 2000);
867
+ return { ...state, phase: 'animating' };
868
+ }
869
+
870
+ // GOOD - let the client handle timing
871
+ handleAction(state, playerId, action) {
872
+ return { ...state, phase: 'animating' };
873
+ }
874
+ // In renderer: after animation completes, send a follow-up action:
875
+ // platform.send({ type: 'ANIMATION_DONE' })
876
+ // Engine handles ANIMATION_DONE to advance to the next phase.
877
+ ```
878
+
879
+ ### State Must Be JSON-Serializable
880
+
881
+ The platform stores game state in Redis via `JSON.stringify` / `JSON.parse` round-trips. Non-serializable types will silently lose data:
882
+
883
+ | Type | After JSON Round-Trip | Result |
884
+ |------|----------------------|--------|
885
+ | `Map` | `{}` | Data lost |
886
+ | `Set` | `{}` | Data lost |
887
+ | `Date` | `"2026-02-10T..."` (string) | Type changed |
888
+ | `undefined` | Removed | Field disappears |
889
+ | `RegExp` | `{}` | Data lost |
890
+ | Function | Removed | Lost |
891
+
892
+ The dev-kit checks your state after every `init()` and `handleAction()` call and prints warnings if non-serializable types are detected.
893
+
894
+ ```typescript
895
+ // BAD
896
+ data: {
897
+ players: new Map([['p1', { score: 0 }]]),
898
+ seen: new Set(['card-1']),
899
+ createdAt: new Date(),
900
+ }
901
+
902
+ // GOOD
903
+ data: {
904
+ players: { p1: { score: 0 } },
905
+ seen: ['card-1'],
906
+ createdAt: '2026-02-10T00:00:00.000Z',
907
+ }
908
+ ```
909
+
910
+ ### Engine Instance Is Shared
911
+
912
+ The platform loads your engine bundle once and reuses it across all game rooms. This means **module-level mutable variables are shared between games**:
913
+
914
+ ```typescript
915
+ // BAD - shared across all rooms!
916
+ let gameCounter = 0;
917
+
918
+ const engine: GameEngine = {
919
+ init(players) {
920
+ gameCounter++; // Will increment across different rooms
921
+ // ...
922
+ },
923
+ };
924
+
925
+ // GOOD - all state lives in GameState
926
+ const engine: GameEngine = {
927
+ init(players) {
928
+ return {
929
+ phase: 'playing',
930
+ players: players.map(p => ({ id: p.id })),
931
+ data: { roundNumber: 1 }, // State is per-room
932
+ };
933
+ },
934
+ };
935
+ ```
936
+
937
+ ### Restricted Global Variables
938
+
939
+ The following globals are `undefined` in the sandbox:
940
+
941
+ | Global | Alternative |
942
+ |--------|-------------|
943
+ | `fetch` | Not available. Engines cannot make network calls. |
944
+ | `process` | Not available. |
945
+ | `globalThis` | Not available. |
946
+ | `global` | Not available. |
947
+
948
+ Available built-ins: `Math`, `JSON`, `Date`, `Array`, `Object`, `Map`, `Set`, `Number`, `String`, `Boolean`, `Error`, `TypeError`, `RangeError`, `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `console` (log/error/warn).
949
+
950
+ ### `require()` Whitelist
951
+
952
+ Only the following modules can be required in engine code (all are stubs for compatibility):
953
+ `react`, `react/jsx-runtime`, `react-dom`, `react-dom/client`
954
+
955
+ Any other `require()` call will throw an error.
956
+
756
957
  ## Data Flow Diagram
757
958
 
758
959
  ```
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export type { Player, GameAction, GameResult, Platform } from './types';
1
+ export type { Player, GameAction, GameResult, Platform, HapticImpactStyle, HapticNotificationType, DeviceTilt, DeviceCapabilities, } from './types';
2
2
  export type { PlayerState, GameState, GameAssets, GameConfig, GameEngine, GameRendererProps } from './interfaces';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxE,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,MAAM,EACN,UAAU,EACV,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,sBAAsB,EACtB,UAAU,EACV,kBAAkB,GACnB,MAAM,SAAS,CAAC;AACjB,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
package/dist/types.d.ts CHANGED
@@ -17,6 +17,20 @@ export interface GameResult {
17
17
  }[];
18
18
  data?: Record<string, unknown>;
19
19
  }
20
+ export type HapticImpactStyle = 'light' | 'medium' | 'heavy';
21
+ export type HapticNotificationType = 'success' | 'warning' | 'error';
22
+ export interface DeviceTilt {
23
+ /** 绕 z 轴旋转 (0~360) —— 指南针方向 */
24
+ alpha: number;
25
+ /** 绕 x 轴旋转 (-180~180) —— 前后倾斜 */
26
+ beta: number;
27
+ /** 绕 y 轴旋转 (-90~90) —— 左右倾斜 */
28
+ gamma: number;
29
+ }
30
+ export interface DeviceCapabilities {
31
+ haptics: boolean;
32
+ motion: boolean;
33
+ }
20
34
  export interface Platform {
21
35
  getPlayers(): Player[];
22
36
  getLocalPlayer(): Player;
@@ -24,5 +38,31 @@ export interface Platform {
24
38
  on(event: string, handler: (...args: unknown[]) => void): void;
25
39
  off(event: string, handler: (...args: unknown[]) => void): void;
26
40
  reportResult(result: GameResult): void;
41
+ /**
42
+ * 获取游戏资产的运行时 URL。
43
+ * @param path - 相对于游戏 assets/ 目录的路径,如 "cards/king.png"、"sounds/flip.mp3"
44
+ * @returns 可直接用于 <img src> / <audio src> / fetch() 的完整 URL
45
+ */
46
+ getAssetUrl(path: string): string;
47
+ /**
48
+ * 查询当前运行环境的设备能力。
49
+ * 游戏可据此决定是否启用某些交互,或提供视觉降级方案。
50
+ */
51
+ getDeviceCapabilities(): DeviceCapabilities;
52
+ /**
53
+ * 触发震动反馈。不支持时静默忽略。
54
+ */
55
+ haptic(type: 'impact' | 'notification' | 'selection', option?: HapticImpactStyle | HapticNotificationType): void;
56
+ /**
57
+ * 监听摇晃事件。平台负责处理权限请求和加速度阈值判定。
58
+ * @returns 取消监听的函数
59
+ */
60
+ onShake(handler: () => void): () => void;
61
+ /**
62
+ * 监听设备倾斜数据流。平台负责处理权限请求。
63
+ * @param handler 约 60fps 回调
64
+ * @returns 取消监听的函数
65
+ */
66
+ onTilt(handler: (tilt: DeviceTilt) => void): () => void;
27
67
  }
28
68
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,EAA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AG,WAAW,EAC7C,MAAM,CAAC,EAAE,iBAAiB,GAAG,sBAAsB,GAClD,IAAI,CAAC;IAER;;;OAGG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAEzC;;;;OAIG;IACH,MAAM,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACzD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@littlepartytime/sdk",
3
- "version": "2.0.1",
3
+ "version": "2.2.0",
4
4
  "description": "Game SDK for Little Party Time platform - type definitions and testing utilities",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",