dewdrop-sdk 0.7.0 → 0.9.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/package.json CHANGED
@@ -1,12 +1,18 @@
1
1
  {
2
2
  "name": "dewdrop-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "The Vite plugin that builds a three.js game for Dewdrop.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": {
8
- ".": "./src/index.js",
9
- "./vite": "./src/vite.js"
8
+ ".": {
9
+ "types": "./src/index.d.ts",
10
+ "default": "./src/index.js"
11
+ },
12
+ "./vite": {
13
+ "types": "./src/vite.d.ts",
14
+ "default": "./src/vite.js"
15
+ }
10
16
  },
11
17
  "files": [
12
18
  "src",
package/src/build.js CHANGED
@@ -34,9 +34,12 @@ export const ASSETS_DIR = 'ui';
34
34
  // have before the entry ran: on Dewdrop the game starts from the entry
35
35
  // rather than the page, so the page's head (the stylesheets Vite linked,
36
36
  // the title) and its body (a loading screen, a HUD's containers) reach the
37
- // document through the entry, the page's scripts dropped.
37
+ // document through the entry, the page's scripts dropped. The block is one
38
+ // line, every line break of the page escaped in its string, so the entry's
39
+ // code starts a line down.
38
40
  export function openPage(html) {
39
- return `{ const page = new DOMParser().parseFromString(${JSON.stringify(html)}, 'text/html'); `
41
+ const literal = JSON.stringify(html).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
42
+ return `{ const page = new DOMParser().parseFromString(${literal}, 'text/html'); `
40
43
  + `for (const script of page.querySelectorAll('script')) script.remove(); `
41
44
  + `document.head.append(...page.head.childNodes); document.body.append(...page.body.childNodes); }\n`;
42
45
  }
package/src/index.d.ts ADDED
@@ -0,0 +1,141 @@
1
+ // The types of what `dewdrop-sdk` exports to a game on Dewdrop, which
2
+ // supplies the values where the game runs (src/index.js is only the stub a
3
+ // build without the plugin reaches). Each name here is one the runtime's
4
+ // module exports, as tests/sync.test.mjs checks.
5
+
6
+ /** Calls to the model providers' APIs, carried by Dewdrop with the developer's keys. */
7
+ export interface Llm {
8
+ /** A `fetch` to a provider's HTTPS API; the answer is read whole (`text()`, `json()`, `arrayBuffer()`), not streamed. */
9
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
10
+ /** The providers' hosts the game may call, such as `'api.anthropic.com'`. */
11
+ providers(): Promise<readonly string[]>;
12
+ }
13
+
14
+ /** A message as it arrives: a string sent as text, or an ArrayBuffer sent as binary. */
15
+ export type NetData = string | ArrayBuffer;
16
+
17
+ /** What a message can be sent as: text, or binary from an ArrayBuffer or a view of one. */
18
+ export type NetSendable = string | ArrayBuffer | ArrayBufferView;
19
+
20
+ export interface BackendEventMap {
21
+ message: MessageEvent<NetData>;
22
+ gap: Event;
23
+ }
24
+
25
+ /** A client's side of its room's backend. */
26
+ export interface Backend extends EventTarget {
27
+ /** Sends a message to the backend. */
28
+ send(data: NetSendable): void;
29
+ onmessage: ((this: Backend, event: MessageEvent<NetData>) => void) | null;
30
+ /** Some messages were dropped before they arrived. */
31
+ ongap: ((this: Backend, event: Event) => void) | null;
32
+ addEventListener<K extends keyof BackendEventMap>(type: K, listener: (this: Backend, event: BackendEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
33
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
34
+ removeEventListener<K extends keyof BackendEventMap>(type: K, listener: (this: Backend, event: BackendEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
35
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
36
+ }
37
+
38
+ /** An event about one client, as the backend hears it. */
39
+ export interface ClientEvent extends MessageEvent<NetData> {
40
+ /** The number Dewdrop gave the client, from 1. */
41
+ readonly client: number;
42
+ /** On a `join`, the player the client was admitted as. */
43
+ readonly player?: string;
44
+ }
45
+
46
+ export interface ClientsEventMap {
47
+ join: ClientEvent;
48
+ leave: ClientEvent;
49
+ message: ClientEvent;
50
+ gap: Event;
51
+ }
52
+
53
+ /** The backend's side of its room's clients. */
54
+ export interface Clients extends EventTarget {
55
+ /** Sends a message to one client. */
56
+ send(to: number, data: NetSendable): void;
57
+ /** Sends a message to every client. */
58
+ broadcast(data: NetSendable): void;
59
+ /** The most players the room seats. */
60
+ readonly capacity: number;
61
+ onjoin: ((this: Clients, event: ClientEvent) => void) | null;
62
+ onleave: ((this: Clients, event: ClientEvent) => void) | null;
63
+ onmessage: ((this: Clients, event: ClientEvent) => void) | null;
64
+ /** Some messages were dropped before they arrived. */
65
+ ongap: ((this: Clients, event: Event) => void) | null;
66
+ addEventListener<K extends keyof ClientsEventMap>(type: K, listener: (this: Clients, event: ClientsEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
67
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
68
+ removeEventListener<K extends keyof ClientsEventMap>(type: K, listener: (this: Clients, event: ClientsEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
69
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
70
+ }
71
+
72
+ /** A player's progress, kept in Dewdrop's storage. */
73
+ export interface Saves {
74
+ /** Puts the player's last save in place; `true` when there was one. */
75
+ load(): Promise<boolean>;
76
+ /** Keeps what `storage` and `indexedDB` hold now; resolves once it's kept. */
77
+ save(): Promise<void>;
78
+ /** The game's `localStorage`, once the first `load()` is done. */
79
+ readonly storage: Storage;
80
+ /** The game's IndexedDB, once the first `load()` is done. */
81
+ readonly indexedDB: IDBFactory;
82
+ }
83
+
84
+ /** Why a session ends ahead of time. */
85
+ export type EndingReason = 'restart' | 'update' | 'idle' | 'elsewhere' | 'away' | 'exit';
86
+
87
+ /** When the session will end ahead of time, and why. */
88
+ export interface Ending {
89
+ /** Milliseconds since the Unix epoch, as `Date.now()` counts. */
90
+ readonly at: number;
91
+ readonly reason: EndingReason;
92
+ }
93
+
94
+ export interface SessionEventMap {
95
+ ending: Event;
96
+ }
97
+
98
+ /** The player's session. */
99
+ export interface Session extends EventTarget {
100
+ /** When the session ends ahead of time, or `null`. */
101
+ readonly ending: Ending | null;
102
+ /** True in the game's dev version. */
103
+ readonly dev: boolean;
104
+ /** True while the player plays by touch. */
105
+ readonly mobile: boolean;
106
+ /** Ends the session and sends the player out of the game. */
107
+ exit(): void;
108
+ /** Lets the view turn portrait when the player holds their phone upright. */
109
+ allowPortrait(): void;
110
+ onending: ((this: Session, event: Event) => void) | null;
111
+ addEventListener<K extends keyof SessionEventMap>(type: K, listener: (this: Session, event: SessionEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
112
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
113
+ removeEventListener<K extends keyof SessionEventMap>(type: K, listener: (this: Session, event: SessionEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
114
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
115
+ }
116
+
117
+ /** The player's microphone, as the game reads it. */
118
+ export interface VoiceCapture {
119
+ /** The chunks that arrived since the last read: mono samples at `voice.SAMPLE_RATE`, in order. */
120
+ read(): Int16Array[];
121
+ /** Ends the capture. */
122
+ stop(): void;
123
+ }
124
+
125
+ export interface Voice {
126
+ /** Starts reading a live microphone stream from `navigator.mediaDevices.getUserMedia`; one at a time. */
127
+ capture(stream: MediaStream): VoiceCapture;
128
+ /** The chunks' sample rate. */
129
+ readonly SAMPLE_RATE: 48000;
130
+ }
131
+
132
+ export declare const llm: Llm;
133
+ /** In a client, its room's backend. */
134
+ export declare const backend: Backend;
135
+ /** In a backend, its room's clients. */
136
+ export declare const clients: Clients;
137
+ /** The player the session was admitted as, `''` for none and in a backend. */
138
+ export declare const player: string;
139
+ export declare const saves: Saves;
140
+ export declare const session: Session;
141
+ export declare const voice: Voice;
package/src/vite.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ // The type of the Vite plugin `dewdrop-sdk/vite` exports.
2
+ import type { Plugin } from 'vite';
3
+
4
+ /** The Vite plugin that makes every `vite build` a Dewdrop build. */
5
+ export default function dew(): Plugin;
package/src/vite.js CHANGED
@@ -4,7 +4,8 @@
4
4
  // output, no module preload, a root base, the files Vite emits under
5
5
  // `ui/`, the built page opened in the document by the entry, and the
6
6
  // build's record beside it, `dewdrop-build.json`; a game with a backend
7
- // gets a second chunk beside it, `backend.js`. Vite's dev
7
+ // gets a second chunk beside it, `backend.js`. Each chunk's source map is
8
+ // written beside it and named by none. Vite's dev
8
9
  // server is refused, since a game plays on Dewdrop alone: the refusal
9
10
  // says where. The plugin imports nothing from Vite itself, so it works
10
11
  // linked from a checkout as well as installed, on Vite 3 through 8.
@@ -13,6 +14,25 @@ import { resolve } from 'node:path';
13
14
  import { ASSETS_DIR, BACKEND_FILE, BUILD_RECORD_FILE, ENTRY_FILE, PAGE_FILE, buildRecord, detectViteMajor, openPage, outputOptions } from './build.js';
14
15
  import { ON_DEWDROP } from './message.js';
15
16
 
17
+ const BACKEND_SOURCES = ['backend.js', 'backend.ts', 'src/backend.js', 'src/backend.ts'];
18
+
19
+ // Every build writes source maps beside its chunks, `main.js.map` and
20
+ // `backend.js.map`, for the developer's own tools to read positions in the
21
+ // built code back to the source by; the chunks name no map, so nothing
22
+ // that runs them looks one up.
23
+ const SOURCE_MAPS = 'hidden';
24
+
25
+ // An emitted file's text, given as a string or as bytes.
26
+ const text = (source) => source instanceof Uint8Array ? new TextDecoder().decode(source) : String(source);
27
+
28
+ // A source map's JSON with its mappings moved down a line, for a chunk
29
+ // given a line above its code.
30
+ function shiftMap(json) {
31
+ const map = JSON.parse(json);
32
+ map.mappings = `;${map.mappings}`;
33
+ return JSON.stringify(map);
34
+ }
35
+
16
36
  // The imports Dewdrop supplies, left in the output: three and the paths
17
37
  // into it, and the SDK by its name. Dewdrop supplies nothing else, a path
18
38
  // into the SDK included, so the build takes every other import in.
@@ -20,10 +40,10 @@ export function isRuntimeModule(id) {
20
40
  return id === 'three' || id.startsWith('three/') || id === 'dewdrop-sdk';
21
41
  }
22
42
 
23
- // Where a project's backend is: `backend.js` at the root, else
24
- // `src/backend.js`, else none.
43
+ // Where a project's backend is: `backend.js` or `backend.ts` at the root,
44
+ // else in `src/`, else none. It is built as `backend.js` either way.
25
45
  export function backendEntry(root) {
26
- for (const name of [BACKEND_FILE, `src/${BACKEND_FILE}`]) {
46
+ for (const name of BACKEND_SOURCES) {
27
47
  const file = resolve(root, name);
28
48
  if (existsSync(file)) return file;
29
49
  }
@@ -45,6 +65,7 @@ export default function dew() {
45
65
  build: {
46
66
  modulePreload: false,
47
67
  assetsDir: ASSETS_DIR,
68
+ sourcemap: SOURCE_MAPS,
48
69
  rollupOptions: {
49
70
  external: isRuntimeModule,
50
71
  output: outputOptions(major),
@@ -63,6 +84,7 @@ export default function dew() {
63
84
  build: {
64
85
  emptyOutDir: false,
65
86
  copyPublicDir: false,
87
+ sourcemap: SOURCE_MAPS,
66
88
  rollupOptions: {
67
89
  input: entry,
68
90
  output: outputOptions(major, BACKEND_FILE),
@@ -90,8 +112,15 @@ export default function dew() {
90
112
  this.emitFile({ type: 'asset', fileName: BUILD_RECORD_FILE, source: buildRecord() });
91
113
  const page = bundle[PAGE_FILE];
92
114
  if (page?.type !== 'asset') return;
93
- const html = page.source instanceof Uint8Array ? new TextDecoder().decode(page.source) : String(page.source);
94
- chunk.code = openPage(html) + chunk.code;
115
+ chunk.code = openPage(text(page.source)) + chunk.code;
116
+ // The page opens on a line of its own above the entry's code, so the
117
+ // entry's map moves down a line: an empty line first in its mappings.
118
+ // Rollup from 3 on and Rolldown have emitted the map as a file of the
119
+ // bundle by now, so that file moves; Rollup 2, under Vite 3, writes
120
+ // the file later from the chunk's map, so that moves as well.
121
+ if (chunk.map) chunk.map.mappings = `;${chunk.map.mappings}`;
122
+ const map = bundle[chunk.sourcemapFileName ?? `${ENTRY_FILE}.map`];
123
+ if (map?.type === 'asset') map.source = shiftMap(text(map.source));
95
124
  },
96
125
  },
97
126
  };