@primitiv/cli 0.19.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/LICENSE.txt ADDED
@@ -0,0 +1,190 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Thomas Piquet (THP Software)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @primitiv/cli
2
+
3
+ > **Status: Prototype** - API is unstable and may change between minor versions.
4
+
5
+ CLI tool for scaffolding Primitiv game projects.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ # Run directly (no install) — always fetches the latest version
11
+ npx @primitiv/cli@latest create my-game
12
+
13
+ # Or install globally
14
+ npm i -g @primitiv/cli@latest
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```bash
20
+ primitiv create [project-name]
21
+ ```
22
+
23
+ You will be prompted to choose a template:
24
+
25
+ | Template | Description |
26
+ |---|---|
27
+ | **standalone** | Everything in the browser, single player |
28
+ | **fullstack** | Client + Server in the same project |
29
+ | **client** | Connected client to a remote server |
30
+ | **server** | Headless server only |
31
+
32
+ For non-standalone templates, you will also choose a transport:
33
+
34
+ | Transport | Description |
35
+ |---|---|
36
+ | **uws** | WebSocket via uWebSockets.js (simplest) |
37
+ | **webrtc-direct** | WebRTC with direct signaling |
38
+ | **webrtc-relay** | WebRTC with relay signaling |
39
+ | **webrtc-lite** | WebRTC ICE-lite (single UDP port) |
40
+
41
+ ## Example
42
+
43
+ ```bash
44
+ npx @primitiv/cli@latest create my-game
45
+ # → Select: standalone
46
+ # → Project created!
47
+
48
+ # For nightly version
49
+ npx @primitiv/cli@nightly create my-game
50
+
51
+ cd my-game
52
+ pnpm install
53
+ pnpm dev
54
+ ```
55
+
56
+ For documentation, examples, and guides, visit **[primitivengine.com](https://primitivengine.com/)**.
57
+
58
+ ## 📄 License
59
+
60
+ Apache-2.0 - See [LICENSE.txt](./LICENSE.txt).
package/dist/index.cjs ADDED
@@ -0,0 +1,353 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var F=Object.create;var L=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var z=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of X(t))!Y.call(e,o)&&o!==n&&L(e,o,{get:()=>t[o],enumerable:!(i=K(t,o))||i.enumerable});return e};var q=(e,t,n)=>(n=e!=null?F(J(e)):{},z(t||!e||!e.__esModule?L(n,"default",{value:e,enumerable:!0}):n,e));var V=require("fs"),_=require("path"),N=require("url");var r=q(require("@clack/prompts"),1),u=require("fs"),E=require("child_process"),p=require("path");function s(e,t,n,i){let o={name:e.name,version:"0.0.1",private:!0,type:"module",scripts:i,dependencies:t,devDependencies:n};return JSON.stringify(o,null,2)+`
3
+ `}function l(e){let t=e?.node?["ES2022"]:["ES2022","DOM","DOM.Iterable"],n=e?.node?["node"]:void 0,i={target:"ES2022",module:"ESNext",moduleResolution:"bundler",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,declaration:!0,declarationMap:!0,sourceMap:!0,outDir:"./dist",rootDir:"./src",lib:t};return n&&(i.types=n),JSON.stringify({compilerOptions:i,include:["src/**/*"],exclude:["node_modules","dist"]},null,2)+`
4
+ `}function g(){return`import {
5
+ Engine,
6
+ User,
7
+ Layer,
8
+ Display,
9
+ OrderBuilder,
10
+ Vector2,
11
+ KeyboardInput,
12
+ InputDeviceType,
13
+ type IApplication,
14
+ type IRuntime,
15
+ } from '@primitiv/engine';
16
+
17
+ // \u2500\u2500\u2500 Grid dimensions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
18
+ const WIDTH = 22;
19
+ const HEIGHT = 14;
20
+
21
+ // \u2500\u2500\u2500 Palette color IDs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
22
+ const BG_COLOR = 0;
23
+ const SNAKE_COLOR = 2;
24
+ const DANGER_COLOR = 3;
25
+ const FOOD_COLOR = 4;
26
+ const TEXT_COLOR = 5;
27
+
28
+ // \u2500\u2500\u2500 Per-user state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29
+
30
+ interface SnakeUserData {
31
+ gameLayer: Layer;
32
+ snake: { x: number; y: number }[];
33
+ direction: { x: number; y: number };
34
+ nextDirection: { x: number; y: number };
35
+ food: { x: number; y: number };
36
+ alive: boolean;
37
+ score: number;
38
+ moveTimer: number;
39
+ }
40
+
41
+ function spawnFood(
42
+ snake: { x: number; y: number }[],
43
+ ): { x: number; y: number } {
44
+ let x: number, y: number;
45
+ do {
46
+ x = 1 + Math.floor(Math.random() * (WIDTH - 2));
47
+ y = 1 + Math.floor(Math.random() * (HEIGHT - 2));
48
+ } while (snake.some((s) => s.x === x && s.y === y));
49
+ return { x, y };
50
+ }
51
+
52
+ // \u2500\u2500\u2500 Application \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
53
+
54
+ export class Game implements IApplication<Engine, User<SnakeUserData>> {
55
+ async init(runtime: IRuntime, engine: Engine) {
56
+ engine.loadPaletteToSlot(0, [
57
+ { colorId: BG_COLOR, r: 12, g: 14, b: 20, a: 255 },
58
+ { colorId: SNAKE_COLOR, r: 50, g: 180, b: 130, a: 255 },
59
+ { colorId: DANGER_COLOR, r: 210, g: 60, b: 60, a: 255 },
60
+ { colorId: FOOD_COLOR, r: 230, g: 170, b: 40, a: 255 },
61
+ { colorId: TEXT_COLOR, r: 190, g: 200, b: 210, a: 255 },
62
+ ]);
63
+ runtime.setTickRate(20);
64
+ }
65
+
66
+ initUser(_runtime: IRuntime, _engine: Engine, user: User<SnakeUserData>) {
67
+ const display = new Display(0, WIDTH, HEIGHT);
68
+ user.addDisplay(display);
69
+ display.switchPalette(0);
70
+
71
+ // Layer 0: static walls (drawn once)
72
+ const wallLayer = new Layer(new Vector2(0, 0), 0, WIDTH, HEIGHT, {
73
+ mustBeReliable: true,
74
+ });
75
+ user.addLayer(wallLayer);
76
+
77
+ wallLayer.setOrders([
78
+ OrderBuilder.fill(' ', BG_COLOR, BG_COLOR),
79
+ OrderBuilder.line(0, 0, WIDTH - 1, 0, {
80
+ charCode: ' ',
81
+ bgColor: TEXT_COLOR,
82
+ }),
83
+ OrderBuilder.line(0, HEIGHT - 1, WIDTH - 1, HEIGHT - 1, {
84
+ charCode: ' ',
85
+ bgColor: TEXT_COLOR,
86
+ }),
87
+ OrderBuilder.line(0, 0, 0, HEIGHT - 1, {
88
+ charCode: ' ',
89
+ bgColor: TEXT_COLOR,
90
+ }),
91
+ OrderBuilder.line(WIDTH - 1, 0, WIDTH - 1, HEIGHT - 1, {
92
+ charCode: ' ',
93
+ bgColor: TEXT_COLOR,
94
+ }),
95
+ OrderBuilder.text(1, 0, ' SNAKE ', BG_COLOR, TEXT_COLOR),
96
+ ]);
97
+
98
+ // Layer 1: dynamic game state (rebuilt every tick)
99
+ const gameLayer = new Layer(new Vector2(0, 0), 1, WIDTH, HEIGHT);
100
+ user.addLayer(gameLayer);
101
+
102
+ const snake = [
103
+ { x: 6, y: 7 },
104
+ { x: 5, y: 7 },
105
+ { x: 4, y: 7 },
106
+ ];
107
+ user.data = {
108
+ gameLayer,
109
+ snake,
110
+ direction: { x: 1, y: 0 },
111
+ nextDirection: { x: 1, y: 0 },
112
+ food: spawnFood(snake),
113
+ alive: true,
114
+ score: 0,
115
+ moveTimer: 0,
116
+ };
117
+
118
+ // Input: arrow keys
119
+ const registry = user.getInputBindingRegistry();
120
+ registry.defineAxis(0, 'MX', [
121
+ {
122
+ sourceId: 0,
123
+ type: InputDeviceType.Keyboard,
124
+ negativeKey: KeyboardInput.ArrowLeft,
125
+ positiveKey: KeyboardInput.ArrowRight,
126
+ },
127
+ ]);
128
+ registry.defineAxis(1, 'MY', [
129
+ {
130
+ sourceId: 1,
131
+ type: InputDeviceType.Keyboard,
132
+ negativeKey: KeyboardInput.ArrowUp,
133
+ positiveKey: KeyboardInput.ArrowDown,
134
+ },
135
+ ]);
136
+ }
137
+
138
+ updateUser(
139
+ _runtime: IRuntime,
140
+ _engine: Engine,
141
+ user: User<SnakeUserData>,
142
+ ) {
143
+ const data = user.data;
144
+
145
+ // 1. Read input \u2014 prevent 180\xB0 reversal
146
+ const inputX = Math.round(user.getAxis('MX'));
147
+ const inputY = Math.round(user.getAxis('MY'));
148
+ if (inputX && inputX !== -data.direction.x)
149
+ data.nextDirection = { x: inputX, y: 0 };
150
+ else if (inputY && inputY !== -data.direction.y)
151
+ data.nextDirection = { x: 0, y: inputY };
152
+
153
+ // 2. Advance game state
154
+ data.moveTimer += 8;
155
+ if (data.alive && data.moveTimer >= 20) {
156
+ data.moveTimer -= 20;
157
+
158
+ data.direction = data.nextDirection;
159
+ const head = {
160
+ x: data.snake[0].x + data.direction.x,
161
+ y: data.snake[0].y + data.direction.y,
162
+ };
163
+
164
+ const hitsWall =
165
+ head.x < 1 ||
166
+ head.x >= WIDTH - 1 ||
167
+ head.y < 1 ||
168
+ head.y >= HEIGHT - 1;
169
+ const hitsSelf = data.snake.some(
170
+ (s) => s.x === head.x && s.y === head.y,
171
+ );
172
+
173
+ if (hitsWall || hitsSelf) {
174
+ data.alive = false;
175
+ } else {
176
+ data.snake.unshift(head);
177
+ if (head.x === data.food.x && head.y === data.food.y) {
178
+ data.score++;
179
+ data.food = spawnFood(data.snake);
180
+ } else {
181
+ data.snake.pop();
182
+ }
183
+ }
184
+ }
185
+
186
+ // 3. Draw game state
187
+ const orders = [
188
+ OrderBuilder.text(10, 0, \` Score: \${data.score} \`, BG_COLOR, TEXT_COLOR),
189
+ OrderBuilder.char(data.food.x, data.food.y, '\u2666', FOOD_COLOR, 255),
190
+ OrderBuilder.polyline(data.snake, '\u2588', SNAKE_COLOR),
191
+ OrderBuilder.char(
192
+ data.snake[0].x,
193
+ data.snake[0].y,
194
+ '@',
195
+ SNAKE_COLOR,
196
+ 255,
197
+ ),
198
+ ];
199
+
200
+ if (!data.alive) {
201
+ orders.push(
202
+ OrderBuilder.text(6, 6, ' GAME OVER! ', DANGER_COLOR, TEXT_COLOR),
203
+ );
204
+ }
205
+
206
+ data.gameLayer.setOrders(orders);
207
+ }
208
+
209
+ update() {}
210
+ }
211
+ `}function f(e,t="./src/main.ts"){return`<!DOCTYPE html>
212
+ <html lang="en">
213
+ <head>
214
+ <meta charset="UTF-8" />
215
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
216
+ <title>${e.name}</title>
217
+ <style>
218
+ * { margin: 0; padding: 0; box-sizing: border-box; }
219
+ html, body { width: 100%; height: 100%; background: #0f0f23; overflow: hidden; }
220
+ #game { width: 100%; height: 100%; }
221
+ </style>
222
+ </head>
223
+ <body>
224
+ <div id="game"></div>
225
+ <script type="module" src="${t}"></script>
226
+ </body>
227
+ </html>
228
+ `}function y(){return`import { defineConfig } from 'vite';
229
+
230
+ export default defineConfig({});
231
+ `}function c(){return`node_modules
232
+ dist
233
+ `}var Q={standalone:{"npm run dev":"Start the development server","npm run build":"Build for production","npm run preview":"Preview the production build"},fullstack:{"npm run dev":"Start client and server simultaneously","npm run dev:client":"Start the client only","npm run dev:server":"Start the server only","npm run build":"Build client and server for production","npm run start":"Start the production server"},client:{"npm run dev":"Start the development server","npm run build":"Build for production","npm run preview":"Preview the production build"},server:{"npm run dev":"Start the server in watch mode","npm run build":"Build for production","npm run start":"Start the production server"}};function d(e,t){let n=Q[t],i=Object.entries(n).map(([o,R])=>`| \`${o}\` | ${R} |`).join(`
234
+ `);return`# ${e}
235
+
236
+ A [Primitiv](https://primitivengine.com) game project.
237
+
238
+ ## Getting Started
239
+
240
+ \`\`\`bash
241
+ npm run dev
242
+ \`\`\`
243
+
244
+ ## Available Scripts
245
+
246
+ | Command | Description |
247
+ |---------|-------------|
248
+ ${i}
249
+
250
+ ## Learn More
251
+
252
+ - [Primitiv Documentation](https://primitivengine.com)
253
+ - [Primitiv GitHub](https://github.com/thp-software/primitiv)
254
+ `}function D(e){return{"package.json":s(e,{"@primitiv/engine":e.primitivVersion,"@primitiv/client":e.primitivVersion},{typescript:"^5.6.3",vite:"^6.0.0"},{dev:"vite",build:"tsc && vite build",preview:"vite preview"}),"tsconfig.json":l(),"vite.config.ts":y(),".gitignore":c(),"README.md":d(e.name,"standalone"),"index.html":f(e),"src/game.ts":g(),"src/main.ts":Z()}}function Z(){return`import { ClientRuntime } from '@primitiv/client';
255
+ import { Game } from './game.js';
256
+
257
+ const client = new ClientRuntime({
258
+ mode: 'standalone',
259
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
260
+ standalone: {
261
+ application: new Game(),
262
+ userId: 'local-player',
263
+ username: 'Player',
264
+ },
265
+ });
266
+ `}function x(e){switch(e){case"webrtc-direct":case"webrtc-relay":return`{
267
+ mode: 'webrtc-full',
268
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
269
+ webrtcFull: { url: 'ws://localhost:3000' },
270
+ }`;case"webrtc-lite":return`{
271
+ mode: 'webrtc-lite',
272
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
273
+ webrtcLite: { url: 'ws://localhost:3000' },
274
+ }`;default:return`{
275
+ mode: 'uws',
276
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
277
+ uws: { url: 'ws://localhost:3000' },
278
+ }`}}function O(e){switch(e){case"webrtc-direct":return` transport: 'webrtc-direct',
279
+ webrtcDirect: { port: 3000, stunServers: ['stun:stun.l.google.com:19302'] },
280
+ `;case"webrtc-relay":return` transport: 'webrtc-relay',
281
+ webrtcRelay: {
282
+ port: 3000,
283
+ signalingUrl: 'wss://your-relay-server.com',
284
+ sessionId: 'my-game',
285
+ stunServers: ['stun:stun.l.google.com:19302'],
286
+ },
287
+ `;case"webrtc-lite":return` transport: 'webrtc-lite',
288
+ webrtcLite: { port: 3000 },
289
+ `;default:return` transport: 'uws',
290
+ uws: { port: 3000 },
291
+ `}}function M(e){return{"package.json":ee(e),".gitignore":c(),"README.md":d(e.name,"fullstack"),"client/package.json":s({name:`${e.name}-client`},{"@primitiv/engine":e.primitivVersion,"@primitiv/client":e.primitivVersion},{typescript:"^5.6.3",vite:"^6.0.0"},{dev:"vite",build:"tsc && vite build",preview:"vite preview"}),"client/tsconfig.json":l(),"client/vite.config.ts":y(),"client/index.html":f({name:e.name}),"client/src/main.ts":te(e),"server/package.json":s({name:`${e.name}-server`},{"@primitiv/engine":e.primitivVersion,"@primitiv/server":e.primitivVersion},{"@types/node":"^20.0.0",typescript:"^5.6.3",tsx:"^4.19.4"},{dev:"tsx watch src/main.ts",build:"tsc",start:"tsx src/main.ts"}),"server/tsconfig.json":l({node:!0}),"server/src/game.ts":g(),"server/src/main.ts":re(e)}}function ee(e){let t={name:e.name,version:"0.0.1",private:!0,scripts:{"dev:client":"npm run dev --prefix client","dev:server":"npm run dev --prefix server",dev:'concurrently "npm:dev:*"',build:"npm run build --prefix server && npm run build --prefix client",start:"npm run start --prefix server"},devDependencies:{concurrently:"^9.2.1"}};return JSON.stringify(t,null,2)+`
292
+ `}function te(e){return`import { ClientRuntime } from '@primitiv/client';
293
+
294
+ const client = new ClientRuntime(${x(e.transport)});
295
+ `}function re(e){return`import { RuntimeServer } from '@primitiv/server';
296
+ import { Game } from './game.js';
297
+
298
+ const server = new RuntimeServer({
299
+ application: new Game(),
300
+ ${O(e.transport)}});
301
+
302
+ server.start().catch((err) => {
303
+ console.error('Failed to start server:', err);
304
+ });
305
+ `}function j(e){return{"package.json":s(e,{"@primitiv/engine":e.primitivVersion,"@primitiv/client":e.primitivVersion},{typescript:"^5.6.3",vite:"^6.0.0"},{dev:"vite",build:"tsc && vite build",preview:"vite preview"}),"tsconfig.json":l(),"vite.config.ts":y(),".gitignore":c(),"README.md":d(e.name,"client"),"index.html":f(e),"src/main.ts":ne(e)}}function ne(e){return`import { ClientRuntime } from '@primitiv/client';
306
+
307
+ const client = new ClientRuntime(${x(e.transport)});
308
+ `}function H(e){return{"package.json":s(e,{"@primitiv/engine":e.primitivVersion,"@primitiv/server":e.primitivVersion},{"@types/node":"^20.0.0",typescript:"^5.6.3",tsx:"^4.19.4"},{dev:"tsx watch src/main.ts",build:"tsc",start:"tsx src/main.ts"}),"tsconfig.json":l({node:!0}),".gitignore":c(),"README.md":d(e.name,"server"),"src/game.ts":g(),"src/main.ts":ie(e)}}function ie(e){return`import { RuntimeServer } from '@primitiv/server';
309
+ import { Game } from './game.js';
310
+
311
+ const server = new RuntimeServer({
312
+ application: new Game(),
313
+ ${O(e.transport)}});
314
+
315
+ server.start().catch((err) => {
316
+ console.error('Failed to start server:', err);
317
+ });
318
+ `}function P(e,t){return{standalone:()=>D(t),fullstack:()=>M(t),client:()=>j(t),server:()=>H(t)}[e]()}var A=["standalone","fullstack","client","server"],G=["uws","webrtc-direct","webrtc-relay","webrtc-lite"],B=["latest","nightly"];function oe(e){try{let t=(0,E.execSync)("npm view @primitiv/engine dist-tags --json",{stdio:["ignore","pipe","ignore"],timeout:1e4}).toString(),i=JSON.parse(t)[e];if(!i)throw new Error(`No "${e}" tag found`);return e==="nightly"?i:`^${i}`}catch{throw new Error(`Could not resolve Primitiv version for "${e}" channel.
319
+ Make sure you have an internet connection and @primitiv/engine is published.`)}}var ae=`
320
+ ____ _ _ _ _
321
+ | _ \\__ __(_)________ (_) |_(_)_ __
322
+ | |_) | __| | _ _ \\| | __| \\ \\ / /
323
+ | __/| | | | | | | | | | |_| |\\ V /
324
+ |_| |_| |_|_| |_| |_|_|\\__|_| \\_/
325
+ `;async function $(e,t){console.log(ae),console.log(` Primitiv Engine \u2014 CLI v${e}
326
+ `),r.intro("Create a new Primitiv project"),t.template&&!A.includes(t.template)&&(r.cancel(`Invalid template "${t.template}". Choose: ${A.join(", ")}`),process.exit(1)),t.transport&&!G.includes(t.transport)&&(r.cancel(`Invalid transport "${t.transport}". Choose: ${G.join(", ")}`),process.exit(1)),t.channel&&!B.includes(t.channel)&&(r.cancel(`Invalid channel "${t.channel}". Choose: ${B.join(", ")}`),process.exit(1));let n=await r.group({name:()=>t.name?Promise.resolve(t.name):r.text({message:"Project name",placeholder:"my-game",validate:a=>{if(!a)return"Project name is required";if(a!=="."&&!/^[a-z0-9-_]+$/i.test(a))return'Only alphanumeric characters, dashes and underscores (or "." for current directory)'}}),template:()=>t.template?Promise.resolve(t.template):r.select({message:"Template",options:[{value:"standalone",label:"standalone",hint:"Everything in the browser, single player"},{value:"fullstack",label:"fullstack",hint:"Client + Server in the same project"},{value:"client",label:"client",hint:"Connected client to a remote server"},{value:"server",label:"server",hint:"Headless server only"}]}),transport:({results:a})=>a.template==="standalone"?Promise.resolve(void 0):t.transport?Promise.resolve(t.transport):r.select({message:"Transport",options:[{value:"uws",label:"uws",hint:"WebSocket via uWebSockets.js \u2014 simplest"},{value:"webrtc-direct",label:"webrtc-direct",hint:"WebRTC with direct signaling"},{value:"webrtc-relay",label:"webrtc-relay",hint:"WebRTC with relay signaling"},{value:"webrtc-lite",label:"webrtc-lite",hint:"WebRTC ICE-lite (single UDP port)"}]}),channel:()=>t.channel?Promise.resolve(t.channel):r.select({message:"Version",options:[{value:"latest",label:"latest",hint:"Latest stable release"},{value:"nightly",label:"nightly",hint:"Latest nightly build (may be unstable)"}]})},{onCancel:()=>{r.cancel("Operation cancelled"),process.exit(0)}}),i=n.name,o=n.template,R=n.transport??"uws",k=n.channel,h=i===".",m=h?(0,p.resolve)(process.cwd()):(0,p.resolve)(process.cwd(),i),W=h?(0,p.basename)(m):i;!h&&(0,u.existsSync)(m)&&(r.cancel(`Directory "${i}" already exists`),process.exit(1)),h&&(0,u.readdirSync)(m).length>0&&(r.cancel("Current directory is not empty"),process.exit(1));let T=r.spinner();T.start(`Resolving Primitiv ${k} version...`);let I;try{I=oe(k)}catch(a){T.stop("Failed"),r.cancel(a.message),process.exit(1)}T.stop(`Using @primitiv/* @ ${I}`);let U=P(o,{name:W,transport:R,primitivVersion:I});T.start("Scaffolding project...");for(let[a,w]of Object.entries(U)){let C=(0,p.join)(m,a);(0,u.mkdirSync)((0,p.join)(C,".."),{recursive:!0}),(0,u.writeFileSync)(C,w)}T.stop("Project created");let b;if(t.install==="true")b=!0;else if(t.install==="false")b=!1;else{let a=await r.confirm({message:"Install dependencies?"});r.isCancel(a)&&(r.cancel("Operation cancelled"),process.exit(0)),b=a}if(b){r.log.step("Installing dependencies...");let a=o==="fullstack"?[(0,p.join)(m,"client"),(0,p.join)(m,"server"),m]:[m],w=!1;for(let C of a)try{(0,E.execSync)("npm install",{cwd:C,stdio:"inherit"})}catch{w=!0;break}w?r.log.warn(`npm install failed \u2014 you may need to install dependencies manually.
327
+ This can happen if the Primitiv packages are not yet published at this version.`):r.log.success("Dependencies installed")}let v=h?[]:[`cd ${i}`];b||(o==="fullstack"&&(v.push("npm install --prefix client"),v.push("npm install --prefix server")),v.push("npm install")),v.push("npm run dev"),r.note(v.join(`
328
+ `),"Next steps"),r.outro("Happy coding!")}var me={},S=JSON.parse((0,V.readFileSync)((0,_.join)((0,_.dirname)((0,N.fileURLToPath)(me.url)),"..","package.json"),"utf-8")).version;function se(e){let t={};for(let n=0;n<e.length;n++){let i=e[n];i==="--install"?t.install="true":i==="--no-install"?t.install="false":i.startsWith("--")&&n+1<e.length&&!e[n+1].startsWith("--")&&(t[i.slice(2)]=e[n+1],n++)}return t}var le=`
329
+ Usage:
330
+ primitiv create [project-name] [options]
331
+
332
+ Options:
333
+ --template <value> Template: standalone, fullstack, client, server
334
+ --transport <value> Transport: uws, webrtc-direct, webrtc-relay, webrtc-lite
335
+ --channel <value> Version channel: latest, nightly
336
+ --install Install dependencies after scaffolding
337
+ --no-install Skip dependency installation
338
+ --help, -h Show this help message
339
+
340
+ Examples:
341
+ primitiv create my-game
342
+ primitiv create my-game --template standalone --channel latest
343
+ primitiv create . --template fullstack --transport uws --channel nightly --install
344
+ `;async function pe(){let e=process.argv.slice(2),t=e[0];if(t==="create"){if(e.includes("--help")||e.includes("-h")){console.log(le);return}let n=e[1]&&!e[1].startsWith("--")?e[1]:void 0,i=se(e.slice(1));await $(S,{name:n,template:i.template,transport:i.transport,channel:i.channel,install:i.install})}else console.log(t==="--version"||t==="-v"?S:`
345
+ primitiv v${S} \u2014 CLI for the Primitiv game engine
346
+
347
+ Usage:
348
+ primitiv create [project-name] Create a new Primitiv project
349
+
350
+ Options:
351
+ --version, -v Show version
352
+ --help, -h Show this help message
353
+ `)}pe();
@@ -0,0 +1,2 @@
1
+
2
+ export { };
package/dist/index.mjs ADDED
@@ -0,0 +1,353 @@
1
+ #!/usr/bin/env node
2
+ import{readFileSync as te}from"fs";import{dirname as re,join as ne}from"path";import{fileURLToPath as ie}from"url";import*as r from"@clack/prompts";import{mkdirSync as J,writeFileSync as Y,existsSync as z,readdirSync as q}from"fs";import{execSync as A}from"child_process";import{basename as Q,join as x,resolve as M}from"path";function a(e,t,i,n){let l={name:e.name,version:"0.0.1",private:!0,type:"module",scripts:n,dependencies:t,devDependencies:i};return JSON.stringify(l,null,2)+`
3
+ `}function s(e){let t=e?.node?["ES2022"]:["ES2022","DOM","DOM.Iterable"],i=e?.node?["node"]:void 0,n={target:"ES2022",module:"ESNext",moduleResolution:"bundler",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,declaration:!0,declarationMap:!0,sourceMap:!0,outDir:"./dist",rootDir:"./src",lib:t};return i&&(n.types=i),JSON.stringify({compilerOptions:n,include:["src/**/*"],exclude:["node_modules","dist"]},null,2)+`
4
+ `}function d(){return`import {
5
+ Engine,
6
+ User,
7
+ Layer,
8
+ Display,
9
+ OrderBuilder,
10
+ Vector2,
11
+ KeyboardInput,
12
+ InputDeviceType,
13
+ type IApplication,
14
+ type IRuntime,
15
+ } from '@primitiv/engine';
16
+
17
+ // \u2500\u2500\u2500 Grid dimensions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
18
+ const WIDTH = 22;
19
+ const HEIGHT = 14;
20
+
21
+ // \u2500\u2500\u2500 Palette color IDs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
22
+ const BG_COLOR = 0;
23
+ const SNAKE_COLOR = 2;
24
+ const DANGER_COLOR = 3;
25
+ const FOOD_COLOR = 4;
26
+ const TEXT_COLOR = 5;
27
+
28
+ // \u2500\u2500\u2500 Per-user state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29
+
30
+ interface SnakeUserData {
31
+ gameLayer: Layer;
32
+ snake: { x: number; y: number }[];
33
+ direction: { x: number; y: number };
34
+ nextDirection: { x: number; y: number };
35
+ food: { x: number; y: number };
36
+ alive: boolean;
37
+ score: number;
38
+ moveTimer: number;
39
+ }
40
+
41
+ function spawnFood(
42
+ snake: { x: number; y: number }[],
43
+ ): { x: number; y: number } {
44
+ let x: number, y: number;
45
+ do {
46
+ x = 1 + Math.floor(Math.random() * (WIDTH - 2));
47
+ y = 1 + Math.floor(Math.random() * (HEIGHT - 2));
48
+ } while (snake.some((s) => s.x === x && s.y === y));
49
+ return { x, y };
50
+ }
51
+
52
+ // \u2500\u2500\u2500 Application \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
53
+
54
+ export class Game implements IApplication<Engine, User<SnakeUserData>> {
55
+ async init(runtime: IRuntime, engine: Engine) {
56
+ engine.loadPaletteToSlot(0, [
57
+ { colorId: BG_COLOR, r: 12, g: 14, b: 20, a: 255 },
58
+ { colorId: SNAKE_COLOR, r: 50, g: 180, b: 130, a: 255 },
59
+ { colorId: DANGER_COLOR, r: 210, g: 60, b: 60, a: 255 },
60
+ { colorId: FOOD_COLOR, r: 230, g: 170, b: 40, a: 255 },
61
+ { colorId: TEXT_COLOR, r: 190, g: 200, b: 210, a: 255 },
62
+ ]);
63
+ runtime.setTickRate(20);
64
+ }
65
+
66
+ initUser(_runtime: IRuntime, _engine: Engine, user: User<SnakeUserData>) {
67
+ const display = new Display(0, WIDTH, HEIGHT);
68
+ user.addDisplay(display);
69
+ display.switchPalette(0);
70
+
71
+ // Layer 0: static walls (drawn once)
72
+ const wallLayer = new Layer(new Vector2(0, 0), 0, WIDTH, HEIGHT, {
73
+ mustBeReliable: true,
74
+ });
75
+ user.addLayer(wallLayer);
76
+
77
+ wallLayer.setOrders([
78
+ OrderBuilder.fill(' ', BG_COLOR, BG_COLOR),
79
+ OrderBuilder.line(0, 0, WIDTH - 1, 0, {
80
+ charCode: ' ',
81
+ bgColor: TEXT_COLOR,
82
+ }),
83
+ OrderBuilder.line(0, HEIGHT - 1, WIDTH - 1, HEIGHT - 1, {
84
+ charCode: ' ',
85
+ bgColor: TEXT_COLOR,
86
+ }),
87
+ OrderBuilder.line(0, 0, 0, HEIGHT - 1, {
88
+ charCode: ' ',
89
+ bgColor: TEXT_COLOR,
90
+ }),
91
+ OrderBuilder.line(WIDTH - 1, 0, WIDTH - 1, HEIGHT - 1, {
92
+ charCode: ' ',
93
+ bgColor: TEXT_COLOR,
94
+ }),
95
+ OrderBuilder.text(1, 0, ' SNAKE ', BG_COLOR, TEXT_COLOR),
96
+ ]);
97
+
98
+ // Layer 1: dynamic game state (rebuilt every tick)
99
+ const gameLayer = new Layer(new Vector2(0, 0), 1, WIDTH, HEIGHT);
100
+ user.addLayer(gameLayer);
101
+
102
+ const snake = [
103
+ { x: 6, y: 7 },
104
+ { x: 5, y: 7 },
105
+ { x: 4, y: 7 },
106
+ ];
107
+ user.data = {
108
+ gameLayer,
109
+ snake,
110
+ direction: { x: 1, y: 0 },
111
+ nextDirection: { x: 1, y: 0 },
112
+ food: spawnFood(snake),
113
+ alive: true,
114
+ score: 0,
115
+ moveTimer: 0,
116
+ };
117
+
118
+ // Input: arrow keys
119
+ const registry = user.getInputBindingRegistry();
120
+ registry.defineAxis(0, 'MX', [
121
+ {
122
+ sourceId: 0,
123
+ type: InputDeviceType.Keyboard,
124
+ negativeKey: KeyboardInput.ArrowLeft,
125
+ positiveKey: KeyboardInput.ArrowRight,
126
+ },
127
+ ]);
128
+ registry.defineAxis(1, 'MY', [
129
+ {
130
+ sourceId: 1,
131
+ type: InputDeviceType.Keyboard,
132
+ negativeKey: KeyboardInput.ArrowUp,
133
+ positiveKey: KeyboardInput.ArrowDown,
134
+ },
135
+ ]);
136
+ }
137
+
138
+ updateUser(
139
+ _runtime: IRuntime,
140
+ _engine: Engine,
141
+ user: User<SnakeUserData>,
142
+ ) {
143
+ const data = user.data;
144
+
145
+ // 1. Read input \u2014 prevent 180\xB0 reversal
146
+ const inputX = Math.round(user.getAxis('MX'));
147
+ const inputY = Math.round(user.getAxis('MY'));
148
+ if (inputX && inputX !== -data.direction.x)
149
+ data.nextDirection = { x: inputX, y: 0 };
150
+ else if (inputY && inputY !== -data.direction.y)
151
+ data.nextDirection = { x: 0, y: inputY };
152
+
153
+ // 2. Advance game state
154
+ data.moveTimer += 8;
155
+ if (data.alive && data.moveTimer >= 20) {
156
+ data.moveTimer -= 20;
157
+
158
+ data.direction = data.nextDirection;
159
+ const head = {
160
+ x: data.snake[0].x + data.direction.x,
161
+ y: data.snake[0].y + data.direction.y,
162
+ };
163
+
164
+ const hitsWall =
165
+ head.x < 1 ||
166
+ head.x >= WIDTH - 1 ||
167
+ head.y < 1 ||
168
+ head.y >= HEIGHT - 1;
169
+ const hitsSelf = data.snake.some(
170
+ (s) => s.x === head.x && s.y === head.y,
171
+ );
172
+
173
+ if (hitsWall || hitsSelf) {
174
+ data.alive = false;
175
+ } else {
176
+ data.snake.unshift(head);
177
+ if (head.x === data.food.x && head.y === data.food.y) {
178
+ data.score++;
179
+ data.food = spawnFood(data.snake);
180
+ } else {
181
+ data.snake.pop();
182
+ }
183
+ }
184
+ }
185
+
186
+ // 3. Draw game state
187
+ const orders = [
188
+ OrderBuilder.text(10, 0, \` Score: \${data.score} \`, BG_COLOR, TEXT_COLOR),
189
+ OrderBuilder.char(data.food.x, data.food.y, '\u2666', FOOD_COLOR, 255),
190
+ OrderBuilder.polyline(data.snake, '\u2588', SNAKE_COLOR),
191
+ OrderBuilder.char(
192
+ data.snake[0].x,
193
+ data.snake[0].y,
194
+ '@',
195
+ SNAKE_COLOR,
196
+ 255,
197
+ ),
198
+ ];
199
+
200
+ if (!data.alive) {
201
+ orders.push(
202
+ OrderBuilder.text(6, 6, ' GAME OVER! ', DANGER_COLOR, TEXT_COLOR),
203
+ );
204
+ }
205
+
206
+ data.gameLayer.setOrders(orders);
207
+ }
208
+
209
+ update() {}
210
+ }
211
+ `}function u(e,t="./src/main.ts"){return`<!DOCTYPE html>
212
+ <html lang="en">
213
+ <head>
214
+ <meta charset="UTF-8" />
215
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
216
+ <title>${e.name}</title>
217
+ <style>
218
+ * { margin: 0; padding: 0; box-sizing: border-box; }
219
+ html, body { width: 100%; height: 100%; background: #0f0f23; overflow: hidden; }
220
+ #game { width: 100%; height: 100%; }
221
+ </style>
222
+ </head>
223
+ <body>
224
+ <div id="game"></div>
225
+ <script type="module" src="${t}"></script>
226
+ </body>
227
+ </html>
228
+ `}function f(){return`import { defineConfig } from 'vite';
229
+
230
+ export default defineConfig({});
231
+ `}function m(){return`node_modules
232
+ dist
233
+ `}var V={standalone:{"npm run dev":"Start the development server","npm run build":"Build for production","npm run preview":"Preview the production build"},fullstack:{"npm run dev":"Start client and server simultaneously","npm run dev:client":"Start the client only","npm run dev:server":"Start the server only","npm run build":"Build client and server for production","npm run start":"Start the production server"},client:{"npm run dev":"Start the development server","npm run build":"Build for production","npm run preview":"Preview the production build"},server:{"npm run dev":"Start the server in watch mode","npm run build":"Build for production","npm run start":"Start the production server"}};function c(e,t){let i=V[t],n=Object.entries(i).map(([l,O])=>`| \`${l}\` | ${O} |`).join(`
234
+ `);return`# ${e}
235
+
236
+ A [Primitiv](https://primitivengine.com) game project.
237
+
238
+ ## Getting Started
239
+
240
+ \`\`\`bash
241
+ npm run dev
242
+ \`\`\`
243
+
244
+ ## Available Scripts
245
+
246
+ | Command | Description |
247
+ |---------|-------------|
248
+ ${n}
249
+
250
+ ## Learn More
251
+
252
+ - [Primitiv Documentation](https://primitivengine.com)
253
+ - [Primitiv GitHub](https://github.com/thp-software/primitiv)
254
+ `}function E(e){return{"package.json":a(e,{"@primitiv/engine":e.primitivVersion,"@primitiv/client":e.primitivVersion},{typescript:"^5.6.3",vite:"^6.0.0"},{dev:"vite",build:"tsc && vite build",preview:"vite preview"}),"tsconfig.json":s(),"vite.config.ts":f(),".gitignore":m(),"README.md":c(e.name,"standalone"),"index.html":u(e),"src/game.ts":d(),"src/main.ts":N()}}function N(){return`import { ClientRuntime } from '@primitiv/client';
255
+ import { Game } from './game.js';
256
+
257
+ const client = new ClientRuntime({
258
+ mode: 'standalone',
259
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
260
+ standalone: {
261
+ application: new Game(),
262
+ userId: 'local-player',
263
+ username: 'Player',
264
+ },
265
+ });
266
+ `}function w(e){switch(e){case"webrtc-direct":case"webrtc-relay":return`{
267
+ mode: 'webrtc-full',
268
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
269
+ webrtcFull: { url: 'ws://localhost:3000' },
270
+ }`;case"webrtc-lite":return`{
271
+ mode: 'webrtc-lite',
272
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
273
+ webrtcLite: { url: 'ws://localhost:3000' },
274
+ }`;default:return`{
275
+ mode: 'uws',
276
+ displays: [{ displayId: 0, container: document.getElementById('game')! }],
277
+ uws: { url: 'ws://localhost:3000' },
278
+ }`}}function C(e){switch(e){case"webrtc-direct":return` transport: 'webrtc-direct',
279
+ webrtcDirect: { port: 3000, stunServers: ['stun:stun.l.google.com:19302'] },
280
+ `;case"webrtc-relay":return` transport: 'webrtc-relay',
281
+ webrtcRelay: {
282
+ port: 3000,
283
+ signalingUrl: 'wss://your-relay-server.com',
284
+ sessionId: 'my-game',
285
+ stunServers: ['stun:stun.l.google.com:19302'],
286
+ },
287
+ `;case"webrtc-lite":return` transport: 'webrtc-lite',
288
+ webrtcLite: { port: 3000 },
289
+ `;default:return` transport: 'uws',
290
+ uws: { port: 3000 },
291
+ `}}function S(e){return{"package.json":W(e),".gitignore":m(),"README.md":c(e.name,"fullstack"),"client/package.json":a({name:`${e.name}-client`},{"@primitiv/engine":e.primitivVersion,"@primitiv/client":e.primitivVersion},{typescript:"^5.6.3",vite:"^6.0.0"},{dev:"vite",build:"tsc && vite build",preview:"vite preview"}),"client/tsconfig.json":s(),"client/vite.config.ts":f(),"client/index.html":u({name:e.name}),"client/src/main.ts":U(e),"server/package.json":a({name:`${e.name}-server`},{"@primitiv/engine":e.primitivVersion,"@primitiv/server":e.primitivVersion},{"@types/node":"^20.0.0",typescript:"^5.6.3",tsx:"^4.19.4"},{dev:"tsx watch src/main.ts",build:"tsc",start:"tsx src/main.ts"}),"server/tsconfig.json":s({node:!0}),"server/src/game.ts":d(),"server/src/main.ts":F(e)}}function W(e){let t={name:e.name,version:"0.0.1",private:!0,scripts:{"dev:client":"npm run dev --prefix client","dev:server":"npm run dev --prefix server",dev:'concurrently "npm:dev:*"',build:"npm run build --prefix server && npm run build --prefix client",start:"npm run start --prefix server"},devDependencies:{concurrently:"^9.2.1"}};return JSON.stringify(t,null,2)+`
292
+ `}function U(e){return`import { ClientRuntime } from '@primitiv/client';
293
+
294
+ const client = new ClientRuntime(${w(e.transport)});
295
+ `}function F(e){return`import { RuntimeServer } from '@primitiv/server';
296
+ import { Game } from './game.js';
297
+
298
+ const server = new RuntimeServer({
299
+ application: new Game(),
300
+ ${C(e.transport)}});
301
+
302
+ server.start().catch((err) => {
303
+ console.error('Failed to start server:', err);
304
+ });
305
+ `}function k(e){return{"package.json":a(e,{"@primitiv/engine":e.primitivVersion,"@primitiv/client":e.primitivVersion},{typescript:"^5.6.3",vite:"^6.0.0"},{dev:"vite",build:"tsc && vite build",preview:"vite preview"}),"tsconfig.json":s(),"vite.config.ts":f(),".gitignore":m(),"README.md":c(e.name,"client"),"index.html":u(e),"src/main.ts":K(e)}}function K(e){return`import { ClientRuntime } from '@primitiv/client';
306
+
307
+ const client = new ClientRuntime(${w(e.transport)});
308
+ `}function L(e){return{"package.json":a(e,{"@primitiv/engine":e.primitivVersion,"@primitiv/server":e.primitivVersion},{"@types/node":"^20.0.0",typescript:"^5.6.3",tsx:"^4.19.4"},{dev:"tsx watch src/main.ts",build:"tsc",start:"tsx src/main.ts"}),"tsconfig.json":s({node:!0}),".gitignore":m(),"README.md":c(e.name,"server"),"src/game.ts":d(),"src/main.ts":X(e)}}function X(e){return`import { RuntimeServer } from '@primitiv/server';
309
+ import { Game } from './game.js';
310
+
311
+ const server = new RuntimeServer({
312
+ application: new Game(),
313
+ ${C(e.transport)}});
314
+
315
+ server.start().catch((err) => {
316
+ console.error('Failed to start server:', err);
317
+ });
318
+ `}function D(e,t){return{standalone:()=>E(t),fullstack:()=>S(t),client:()=>k(t),server:()=>L(t)}[e]()}var j=["standalone","fullstack","client","server"],H=["uws","webrtc-direct","webrtc-relay","webrtc-lite"],P=["latest","nightly"];function Z(e){try{let t=A("npm view @primitiv/engine dist-tags --json",{stdio:["ignore","pipe","ignore"],timeout:1e4}).toString(),n=JSON.parse(t)[e];if(!n)throw new Error(`No "${e}" tag found`);return e==="nightly"?n:`^${n}`}catch{throw new Error(`Could not resolve Primitiv version for "${e}" channel.
319
+ Make sure you have an internet connection and @primitiv/engine is published.`)}}var ee=`
320
+ ____ _ _ _ _
321
+ | _ \\__ __(_)________ (_) |_(_)_ __
322
+ | |_) | __| | _ _ \\| | __| \\ \\ / /
323
+ | __/| | | | | | | | | | |_| |\\ V /
324
+ |_| |_| |_|_| |_| |_|_|\\__|_| \\_/
325
+ `;async function G(e,t){console.log(ee),console.log(` Primitiv Engine \u2014 CLI v${e}
326
+ `),r.intro("Create a new Primitiv project"),t.template&&!j.includes(t.template)&&(r.cancel(`Invalid template "${t.template}". Choose: ${j.join(", ")}`),process.exit(1)),t.transport&&!H.includes(t.transport)&&(r.cancel(`Invalid transport "${t.transport}". Choose: ${H.join(", ")}`),process.exit(1)),t.channel&&!P.includes(t.channel)&&(r.cancel(`Invalid channel "${t.channel}". Choose: ${P.join(", ")}`),process.exit(1));let i=await r.group({name:()=>t.name?Promise.resolve(t.name):r.text({message:"Project name",placeholder:"my-game",validate:o=>{if(!o)return"Project name is required";if(o!=="."&&!/^[a-z0-9-_]+$/i.test(o))return'Only alphanumeric characters, dashes and underscores (or "." for current directory)'}}),template:()=>t.template?Promise.resolve(t.template):r.select({message:"Template",options:[{value:"standalone",label:"standalone",hint:"Everything in the browser, single player"},{value:"fullstack",label:"fullstack",hint:"Client + Server in the same project"},{value:"client",label:"client",hint:"Connected client to a remote server"},{value:"server",label:"server",hint:"Headless server only"}]}),transport:({results:o})=>o.template==="standalone"?Promise.resolve(void 0):t.transport?Promise.resolve(t.transport):r.select({message:"Transport",options:[{value:"uws",label:"uws",hint:"WebSocket via uWebSockets.js \u2014 simplest"},{value:"webrtc-direct",label:"webrtc-direct",hint:"WebRTC with direct signaling"},{value:"webrtc-relay",label:"webrtc-relay",hint:"WebRTC with relay signaling"},{value:"webrtc-lite",label:"webrtc-lite",hint:"WebRTC ICE-lite (single UDP port)"}]}),channel:()=>t.channel?Promise.resolve(t.channel):r.select({message:"Version",options:[{value:"latest",label:"latest",hint:"Latest stable release"},{value:"nightly",label:"nightly",hint:"Latest nightly build (may be unstable)"}]})},{onCancel:()=>{r.cancel("Operation cancelled"),process.exit(0)}}),n=i.name,l=i.template,O=i.transport??"uws",I=i.channel,v=n===".",p=v?M(process.cwd()):M(process.cwd(),n),B=v?Q(p):n;!v&&z(p)&&(r.cancel(`Directory "${n}" already exists`),process.exit(1)),v&&q(p).length>0&&(r.cancel("Current directory is not empty"),process.exit(1));let y=r.spinner();y.start(`Resolving Primitiv ${I} version...`);let _;try{_=Z(I)}catch(o){y.stop("Failed"),r.cancel(o.message),process.exit(1)}y.stop(`Using @primitiv/* @ ${_}`);let $=D(l,{name:B,transport:O,primitivVersion:_});y.start("Scaffolding project...");for(let[o,T]of Object.entries($)){let b=x(p,o);J(x(b,".."),{recursive:!0}),Y(b,T)}y.stop("Project created");let h;if(t.install==="true")h=!0;else if(t.install==="false")h=!1;else{let o=await r.confirm({message:"Install dependencies?"});r.isCancel(o)&&(r.cancel("Operation cancelled"),process.exit(0)),h=o}if(h){r.log.step("Installing dependencies...");let o=l==="fullstack"?[x(p,"client"),x(p,"server"),p]:[p],T=!1;for(let b of o)try{A("npm install",{cwd:b,stdio:"inherit"})}catch{T=!0;break}T?r.log.warn(`npm install failed \u2014 you may need to install dependencies manually.
327
+ This can happen if the Primitiv packages are not yet published at this version.`):r.log.success("Dependencies installed")}let g=v?[]:[`cd ${n}`];h||(l==="fullstack"&&(g.push("npm install --prefix client"),g.push("npm install --prefix server")),g.push("npm install")),g.push("npm run dev"),r.note(g.join(`
328
+ `),"Next steps"),r.outro("Happy coding!")}var R=JSON.parse(te(ne(re(ie(import.meta.url)),"..","package.json"),"utf-8")).version;function oe(e){let t={};for(let i=0;i<e.length;i++){let n=e[i];n==="--install"?t.install="true":n==="--no-install"?t.install="false":n.startsWith("--")&&i+1<e.length&&!e[i+1].startsWith("--")&&(t[n.slice(2)]=e[i+1],i++)}return t}var ae=`
329
+ Usage:
330
+ primitiv create [project-name] [options]
331
+
332
+ Options:
333
+ --template <value> Template: standalone, fullstack, client, server
334
+ --transport <value> Transport: uws, webrtc-direct, webrtc-relay, webrtc-lite
335
+ --channel <value> Version channel: latest, nightly
336
+ --install Install dependencies after scaffolding
337
+ --no-install Skip dependency installation
338
+ --help, -h Show this help message
339
+
340
+ Examples:
341
+ primitiv create my-game
342
+ primitiv create my-game --template standalone --channel latest
343
+ primitiv create . --template fullstack --transport uws --channel nightly --install
344
+ `;async function se(){let e=process.argv.slice(2),t=e[0];if(t==="create"){if(e.includes("--help")||e.includes("-h")){console.log(ae);return}let i=e[1]&&!e[1].startsWith("--")?e[1]:void 0,n=oe(e.slice(1));await G(R,{name:i,template:n.template,transport:n.transport,channel:n.channel,install:n.install})}else console.log(t==="--version"||t==="-v"?R:`
345
+ primitiv v${R} \u2014 CLI for the Primitiv game engine
346
+
347
+ Usage:
348
+ primitiv create [project-name] Create a new Primitiv project
349
+
350
+ Options:
351
+ --version, -v Show version
352
+ --help, -h Show this help message
353
+ `)}se();
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@primitiv/cli",
3
+ "version": "0.19.0",
4
+ "description": "CLI tool for scaffolding Primitiv game projects",
5
+ "author": "THP Software",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/thp-software/primitiv",
9
+ "directory": "packages/cli"
10
+ },
11
+ "homepage": "https://primitivengine.com",
12
+ "bugs": {
13
+ "url": "https://github.com/thp-software/primitiv/issues"
14
+ },
15
+ "license": "Apache-2.0",
16
+ "type": "module",
17
+ "bin": {
18
+ "primitiv": "./dist/index.mjs"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE.txt"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18.0.0"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@clack/prompts": "^0.9.1"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^20.0.0",
36
+ "typescript": "^5.6.3"
37
+ },
38
+ "scripts": {
39
+ "build": "rimraf dist && node ../../scripts/build-package.mjs packages/cli",
40
+ "dev": "tsc --watch",
41
+ "clean": "rimraf dist",
42
+ "typecheck": "tsc --noEmit"
43
+ }
44
+ }