dewdrop-sdk 0.5.6 → 0.6.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/src/evaluate.js DELETED
@@ -1,57 +0,0 @@
1
- // A page the dev server serves offers `dewdrop.evaluate(code)`, as a dev
2
- // version's page on Dewdrop does, so one script drives the game in both.
3
- // `code`, a string or a function sent as its source text called with
4
- // nothing, runs at the page's top level, as the browser's console runs
5
- // what is typed into it: what the game puts on `globalThis` is in reach and
6
- // its modules' own bindings are not. The call resolves with the value the
7
- // code came to as JSON carries it, a promise's once it settles, `undefined`
8
- // for none, or rejects with an Error carrying the text of what the code
9
- // threw; code, waiting calls and values past what Dewdrop takes are
10
- // refused in Dewdrop's words. The plugin puts `evaluateScript` in the
11
- // page's head; it is `offerEvaluate`'s own text, so the function imports
12
- // nothing and is written without a `<`.
13
-
14
- // What Dewdrop takes: the bytes of a call's code, the calls waiting at
15
- // once, and the bytes of a value's JSON.
16
- export const LIMITS = Object.freeze({ code: 32764, waiting: 16, value: 65530 });
17
-
18
- // Offers `dewdrop.evaluate` on `scope`, the page's window, within `limits`.
19
- // Assigned rather than defined, since the game shares the window here.
20
- export function offerEvaluate(scope, limits) {
21
- const run = scope.eval;
22
- const encoder = new scope.TextEncoder();
23
- const describe = (error) => {
24
- try {
25
- return error !== null && typeof error === 'object' && typeof error.stack === 'string' ? error.stack : String(error);
26
- } catch {
27
- return '[unprintable]';
28
- }
29
- };
30
- let waiting = 0;
31
- async function evaluate(code) {
32
- if (typeof code === 'function') code = `(${code})()`;
33
- else if (typeof code !== 'string') throw new TypeError('dewdrop.evaluate takes a string or a function');
34
- if (waiting >= limits.waiting) throw new RangeError(`dewdrop.evaluate has ${limits.waiting} calls waiting already`);
35
- const bytes = encoder.encode(code).length;
36
- if (bytes > limits.code) throw new RangeError(`dewdrop.evaluate takes code of at most ${limits.code} bytes, not ${bytes}`);
37
- waiting += 1;
38
- let text;
39
- try {
40
- text = JSON.stringify(await run(code));
41
- } catch (error) {
42
- throw new Error(describe(error));
43
- } finally {
44
- waiting -= 1;
45
- }
46
- if (text === undefined) return undefined;
47
- const length = encoder.encode(text).length;
48
- if (length > limits.value) throw new Error(`the value is ${length} bytes as JSON, more than the ${limits.value} an answer carries`);
49
- return JSON.parse(text);
50
- }
51
- scope.dewdrop = Object.freeze({ evaluate });
52
- }
53
-
54
- // The script the plugin puts in a page the dev server serves.
55
- export function evaluateScript() {
56
- return `(${offerEvaluate})(window, ${JSON.stringify(LIMITS)});`;
57
- }
package/src/fresh.js DELETED
@@ -1,103 +0,0 @@
1
- // A page the dev server serves starts with its storage empty, as a game
2
- // does on Dewdrop. The plugin puts `freshScript` in the page's head, where
3
- // it runs before any of the game's code: it empties `localStorage` there
4
- // and then, and deletes every IndexedDB database but the one the dev
5
- // server keeps saves in. Listing the databases takes a moment, so until
6
- // their deletes are asked for, the first open of each name asks for the
7
- // name's delete first, and the browser, which serves a name's opens and
8
- // deletes in the order they are asked for, hands the game an empty
9
- // database all the same. The script is `freshStorage`'s own text, so the
10
- // function imports nothing and is written without a `<`: the script
11
- // escapes every `<` it carries, since a `</script>` would end it early.
12
-
13
- // The database the dev server keeps saves in, out of the game's sight, and
14
- // the name of the global symbol the page's script leaves what `saves`
15
- // needs under.
16
- export const SAVES_DATABASE = 'dewdrop-saves';
17
- export const SAVES_STATE = 'dewdrop.saves';
18
-
19
- // Empties the storage of `scope`, the page's window, but `database`, and
20
- // leaves under `Symbol.for(state)`: `game`, `database`, `ready`, which
21
- // resolves once every other database is gone and rejects when one cannot
22
- // go, and `connected`, whether the page holds a database open or is
23
- // opening one.
24
- export function freshStorage(scope, { game, database, state }) {
25
- scope.localStorage.clear();
26
- const factory = scope.indexedDB;
27
- const open = factory.open;
28
- const list = factory.databases;
29
- // The page's connections and the opens not yet answered.
30
- const held = new Set();
31
- // The names that are empty, or will be once the opens asked for so far
32
- // are answered: the saves' own, which is never emptied, and each name
33
- // whose delete has been asked for.
34
- const cleared = new Set([database]);
35
- const deletes = [];
36
- let listed = false;
37
- let refuse;
38
- const refused = new Promise((resolve, reject) => { refuse = reject; });
39
-
40
- function clear(name) {
41
- cleared.add(name);
42
- const request = factory.deleteDatabase(name);
43
- deletes.push(new Promise((resolve, reject) => {
44
- request.addEventListener('success', () => resolve());
45
- request.addEventListener('error', () => reject(request.error));
46
- // Another tab of the dev server holds the database: the browser
47
- // deletes it once that tab lets go, and until then this page is not
48
- // empty and its saves are refused.
49
- request.addEventListener('blocked', () => {
50
- const what = `another tab holds the IndexedDB database ${JSON.stringify(name)} open, so this page did not start empty`;
51
- scope.console.warn(`[dewdrop] ${what}: close that tab, then reload this one`);
52
- refuse(new DOMException(`${what}: close that tab, then reload this one`, 'InvalidStateError'));
53
- });
54
- }));
55
- }
56
-
57
- factory.open = function (name) {
58
- if (!listed && !cleared.has(String(name))) clear(String(name));
59
- const request = Reflect.apply(open, this, arguments);
60
- held.add(request);
61
- request.addEventListener('error', () => held.delete(request));
62
- request.addEventListener('success', () => {
63
- held.delete(request);
64
- const db = request.result;
65
- held.add(db);
66
- db.addEventListener('close', () => held.delete(db));
67
- const close = db.close;
68
- db.close = function () {
69
- held.delete(db);
70
- return Reflect.apply(close, this, arguments);
71
- };
72
- });
73
- return request;
74
- };
75
-
76
- const reset = Promise.resolve()
77
- .then(() => Reflect.apply(list, factory, []))
78
- .then((found) => {
79
- for (const { name } of found) if (!cleared.has(name)) clear(name);
80
- listed = true;
81
- return Promise.allSettled(deletes);
82
- });
83
- const ready = Promise.race([refused, reset.then(() => Promise.all(deletes)).then(() => undefined)]);
84
- ready.catch(() => {});
85
-
86
- // The game lists its databases as they are once the deletes are done,
87
- // without the saves' own.
88
- factory.databases = function () {
89
- return reset
90
- .then(() => Reflect.apply(list, this, arguments))
91
- .then((found) => found.filter((each) => each.name !== database));
92
- };
93
-
94
- Object.defineProperty(scope, Symbol.for(state), {
95
- value: Object.freeze({ game, database, ready, connected: () => held.size !== 0 }),
96
- });
97
- }
98
-
99
- // The script the plugin puts in a page the dev server serves, for `game`.
100
- export function freshScript(game) {
101
- const options = { game, database: SAVES_DATABASE, state: SAVES_STATE };
102
- return `(${freshStorage})(window, ${JSON.stringify(options)});`.replace(/</g, '\\u003c');
103
- }
package/src/llm.js DELETED
@@ -1,96 +0,0 @@
1
- // `llm.fetch` and `llm.providers` on a developer's machine: a model call
2
- // carried by the Vite dev server's route (see ./vite.js) with the key from
3
- // the developer's own environment, so a game's code is the same here and
4
- // on Dewdrop and the key never reaches the browser; and the providers that
5
- // route holds keys for. The checks and their messages are Dewdrop's, so a
6
- // call that fails here fails there the same way.
7
- import { MAX_LLM_HEADERS, MAX_LLM_INFLIGHT, MAX_LLM_REQUEST_BYTES } from './providers.js';
8
- import { NO_ROUTE, ROUTE_HEADER, routeUrl } from './route.js';
9
-
10
- let inflight = 0;
11
-
12
- // The bytes a call counts against its cap: its method, URL, headers, and
13
- // body, plus four bytes for the call and four for each length and count.
14
- function requestBytes(method, url, headers, bodyLength) {
15
- const utf8 = (text) => new TextEncoder().encode(text).length;
16
- let size = 4 + 4 + utf8(method) + 4 + utf8(url) + 4;
17
- for (const [name, value] of headers) size += 4 + utf8(name) + 4 + utf8(value);
18
- return size + 4 + bodyLength;
19
- }
20
-
21
- function base64(bytes) {
22
- let binary = '';
23
- for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
24
- return btoa(binary);
25
- }
26
-
27
- // The checks a call fails before it is posted are made as it is made, as
28
- // on Dewdrop, so a fifth call while four are outstanding is refused
29
- // whether or not the four have posted yet. A call counts as outstanding
30
- // from its acceptance until the route answers, an aborted one included:
31
- // aborting rejects the caller at once and drops the answer, but the call
32
- // itself has gone.
33
- function fetchModel(input, init) {
34
- return new Promise((resolve, reject) => {
35
- let request;
36
- try { request = new Request(input, init); } catch (error) { reject(error); return; }
37
- if (request.signal.aborted) { reject(request.signal.reason); return; }
38
- // Only HTTPS leaves the game; whether the host is a provider is the
39
- // route's to say, and it refuses a call it will not carry with the
40
- // reason.
41
- const url = new URL(request.url);
42
- if (url.protocol !== 'https:') {
43
- reject(new TypeError(`llm.fetch: ${url.origin} is not a model provider Dewdrop carries calls to`));
44
- return;
45
- }
46
- const headers = [...request.headers];
47
- if (headers.length > MAX_LLM_HEADERS) {
48
- reject(new RangeError(`llm.fetch: a call names at most ${MAX_LLM_HEADERS} headers`));
49
- return;
50
- }
51
- if (inflight >= MAX_LLM_INFLIGHT) {
52
- reject(new RangeError(`llm.fetch: at most ${MAX_LLM_INFLIGHT} calls are outstanding at once`));
53
- return;
54
- }
55
- inflight += 1;
56
- const onAbort = () => reject(request.signal.reason);
57
- request.signal.addEventListener('abort', onAbort, { once: true });
58
- carry(request, headers).then(resolve, reject).finally(() => {
59
- inflight -= 1;
60
- request.signal.removeEventListener('abort', onAbort);
61
- });
62
- });
63
- }
64
-
65
- // Posts one accepted call to the route and returns its answer.
66
- async function carry(request, headers) {
67
- const body = new Uint8Array(await request.arrayBuffer());
68
- if (requestBytes(request.method, request.url, headers, body.length) > MAX_LLM_REQUEST_BYTES) {
69
- throw new RangeError(`llm.fetch: a call is at most ${MAX_LLM_REQUEST_BYTES} bytes with its headers and body`);
70
- }
71
- const response = await globalThis.fetch(routeUrl(), {
72
- method: 'POST',
73
- headers: { 'content-type': 'application/json' },
74
- body: JSON.stringify({ url: request.url, method: request.method, headers, body: base64(body) }),
75
- });
76
- if (!response.headers.has(ROUTE_HEADER)) throw new TypeError(`llm.fetch: ${NO_ROUTE}`);
77
- const reason = response.headers.get('x-dew-error');
78
- if (reason !== null) throw new TypeError(`llm.fetch: ${reason}`);
79
- return response;
80
- }
81
-
82
- // The providers' hosts the dev server holds keys for: asked of its route,
83
- // once, since the browser cannot read the developer's environment.
84
- let known = null;
85
- async function providers() {
86
- if (known === null) {
87
- const response = await globalThis.fetch(routeUrl());
88
- if (!response.headers.has(ROUTE_HEADER)) throw new TypeError(`llm.providers: ${NO_ROUTE}`);
89
- const reason = response.headers.get('x-dew-error');
90
- if (reason !== null) throw new TypeError(`llm.providers: ${reason}`);
91
- known = Object.freeze((await response.json()).hosts.map(String));
92
- }
93
- return known;
94
- }
95
-
96
- export const llm = Object.freeze({ fetch: fetchModel, providers });
package/src/net.js DELETED
@@ -1,165 +0,0 @@
1
- // The message surface's shared half: the caps, a message measured as
2
- // Dewdrop measures it, the envelope a frame's sends travel in over the dev
3
- // server's socket, and the outbox and inbox that hold a game's messages to
4
- // the caps. The checks and their messages are Dewdrop's, so a send that
5
- // fails here fails on Dewdrop the same way.
6
-
7
- // The limits Dewdrop holds a game to.
8
- export const MAX_NET_MESSAGE_BYTES = 64 << 10;
9
- export const MAX_NET_CLIENT_FRAME_BYTES = 16 << 10;
10
- export const MAX_NET_BACKEND_FRAME_BYTES = 256 << 10;
11
- export const MAX_NET_INBOX_BYTES = 256 << 10;
12
- // What each message costs beyond its bytes, toward its frame's cap and
13
- // the inbox's, an empty message included.
14
- export const NET_RECORD_HEADER_BYTES = 16;
15
- // The most bytes a player's label takes: the name the player joined
16
- // under, which the backend hears on the join.
17
- export const MAX_NET_PLAYER_BYTES = 64;
18
- // The most players a room seats, and the most clients it holds: a room's
19
- // size is 1 to this.
20
- export const MAX_NET_CLIENTS = 100;
21
- // The players a room seats when its page names no size: the most a game's
22
- // room seats on Dewdrop until its developer says otherwise.
23
- export const DEFAULT_ROOM_PLAYERS = 8;
24
- // How often the local backend ticks: sixty times a second.
25
- export const NET_TICK_MS = 1000 / 60;
26
-
27
- // A message's kind and bytes: a string as UTF-8 text, an ArrayBuffer or a
28
- // view of one as binary; anything else is refused, `op` naming the call.
29
- export function measure(op, data) {
30
- if (typeof data === 'string') return { text: true, bytes: new TextEncoder().encode(data) };
31
- if (Object.prototype.toString.call(data) === '[object ArrayBuffer]') return { text: false, bytes: new Uint8Array(data) };
32
- if (ArrayBuffer.isView(data)) return { text: false, bytes: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) };
33
- throw new TypeError(`${op}: a message is a string, an ArrayBuffer, or a view of one`);
34
- }
35
-
36
- // Bytes as base64, as the dev server's socket carries them.
37
- function base64(bytes) {
38
- let binary = '';
39
- for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
40
- return btoa(binary);
41
- }
42
-
43
- function unbase64(text) {
44
- const binary = atob(text);
45
- const bytes = new Uint8Array(binary.length);
46
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
47
- return bytes.buffer;
48
- }
49
-
50
- // One message as the envelope carries it: text as itself, bytes as base64.
51
- export function pack(op, data) {
52
- const { text, bytes } = measure(op, data);
53
- return text ? { t: 's', d: data, n: bytes.length } : { t: 'b', d: base64(bytes), n: bytes.length };
54
- }
55
-
56
- // A message out of the envelope: a string, or a fresh ArrayBuffer.
57
- export function unpack(item) {
58
- return item.t === 's' ? item.d : unbase64(item.d);
59
- }
60
-
61
- // A player's or a backend's sends for one frame, held to the message cap
62
- // and to its `frameCap`, each message costing its bytes plus
63
- // `NET_RECORD_HEADER_BYTES`: `push` queues one message for the frame,
64
- // refusing past either cap, and `flush` takes the frame's items and starts
65
- // the next.
66
- export function createOutbox(frameCap) {
67
- let sent = 0;
68
- let items = [];
69
- return {
70
- push(op, to, data) {
71
- const item = pack(op, data);
72
- if (item.n > MAX_NET_MESSAGE_BYTES) throw new RangeError(`${op}: a message is at most ${MAX_NET_MESSAGE_BYTES} bytes`);
73
- const cost = NET_RECORD_HEADER_BYTES + item.n;
74
- if (sent + cost > frameCap) throw new RangeError(`${op}: a frame sends at most ${frameCap} bytes`);
75
- sent += cost;
76
- items.push({ to, ...item });
77
- },
78
- flush() {
79
- const frame = items;
80
- items = [];
81
- sent = 0;
82
- return frame;
83
- },
84
- };
85
- }
86
-
87
- // A receiver's inbox, held to its cap: `receive` keeps the records handed
88
- // over — messages, and for a backend joins and leaves — and past the cap
89
- // drops every message not yet drained for one gap, joins and leaves kept;
90
- // `drain` takes what is held, in order.
91
- export function createInbox() {
92
- let held = [];
93
- let bytes = 0;
94
- const size = (record) => NET_RECORD_HEADER_BYTES + (record.n ?? 0);
95
- return {
96
- receive(records) {
97
- for (const record of records) {
98
- const needed = size(record);
99
- if (record.kind === 'message' && bytes + needed > MAX_NET_INBOX_BYTES) {
100
- held = held.filter((each) => each.kind === 'join' || each.kind === 'leave');
101
- held.push({ kind: 'gap' });
102
- bytes = held.reduce((sum, each) => sum + size(each), 0);
103
- continue;
104
- }
105
- held.push(record);
106
- bytes += needed;
107
- }
108
- },
109
- drain() {
110
- const records = held;
111
- held = [];
112
- bytes = 0;
113
- return records;
114
- },
115
- };
116
- }
117
-
118
- // A player's label held to its cap: text cut at the cap on a character
119
- // boundary, since a cut through a character would name no one; anything
120
- // but a string is the empty label.
121
- export function label(text) {
122
- if (typeof text !== 'string') return '';
123
- const { read } = new TextEncoder().encodeInto(text, new Uint8Array(MAX_NET_PLAYER_BYTES));
124
- return text.slice(0, read);
125
- }
126
-
127
- // Whether this is the backend's thread, which `attachClients` says: the
128
- // client's surface is unavailable there, as on Dewdrop.
129
- export const side = { backend: false };
130
-
131
- // The `on<event>` handler properties of an EventTarget, as a browser
132
- // defines them: set to a function, it listens; set to anything else, it
133
- // stops.
134
- export function defineHandlers(proto, types) {
135
- const bound = new WeakMap();
136
- for (const type of types) {
137
- Object.defineProperty(proto, `on${type}`, {
138
- configurable: true,
139
- enumerable: true,
140
- get() { return bound.get(this)?.[type]?.fn ?? null; },
141
- set(fn) {
142
- const mine = bound.get(this) ?? {};
143
- bound.set(this, mine);
144
- if (mine[type]) this.removeEventListener(type, mine[type].listener);
145
- delete mine[type];
146
- if (typeof fn !== 'function') return;
147
- const listener = (event) => fn.call(this, event);
148
- mine[type] = { fn, listener };
149
- this.addEventListener(type, listener);
150
- },
151
- });
152
- }
153
- }
154
-
155
- // An event about one client, as a backend hears them: a message event, as
156
- // on Dewdrop, with `client` the number the backend knows the client by,
157
- // `data` the message when there is one, and on a join `player`, the label
158
- // the client joined under.
159
- export class ClientEvent extends MessageEvent {
160
- constructor(type, { client, data = null, player } = {}) {
161
- super(type, { data });
162
- this.client = client;
163
- if (player !== undefined) this.player = player;
164
- }
165
- }
package/src/providers.js DELETED
@@ -1,20 +0,0 @@
1
- // The providers Dewdrop carries a game's model calls to, each with the
2
- // variable the dev server reads its key from and the header that carries
3
- // the key, and the limits Dewdrop holds a call to.
4
-
5
- export const PROVIDERS = [
6
- { host: 'api.openai.com', keyVar: 'OPENAI_API_KEY', header: 'authorization', prefix: 'Bearer ' },
7
- { host: 'api.anthropic.com', keyVar: 'ANTHROPIC_API_KEY', header: 'x-api-key', prefix: '' },
8
- { host: 'generativelanguage.googleapis.com', keyVar: 'GEMINI_API_KEY', header: 'x-goog-api-key', prefix: '' },
9
- ];
10
-
11
- // The most bytes one call carries with its method, URL, headers, and body.
12
- export const MAX_LLM_REQUEST_BYTES = 64 << 10;
13
- // The most headers one call names.
14
- export const MAX_LLM_HEADERS = 16;
15
- // The most bytes of a provider's response body; a longer one fails whole.
16
- export const MAX_LLM_RESPONSE_BYTES = 32 << 10;
17
- // The most calls a game has outstanding at once.
18
- export const MAX_LLM_INFLIGHT = 4;
19
- // How long a call may take from sending to its last byte.
20
- export const LLM_TIMEOUT_MS = 60_000;
package/src/route.js DELETED
@@ -1,36 +0,0 @@
1
- // The contract between the package's two halves: the dev server route
2
- // `llm` calls, how its answers are told apart from a page served without
3
- // it, where a backend finds the dev server from its thread, and what a
4
- // page served without the plugin says when it calls `backend` or `saves`.
5
-
6
- // The dev server route the local `llm.fetch` posts to, and the header
7
- // every answer from it carries, so a page served without the route — a
8
- // dev server missing the plugin, a static host — is told apart from a
9
- // provider's own 404.
10
- export const DEV_ROUTE = '/__dew/llm';
11
- export const ROUTE_HEADER = 'x-dew-route';
12
- export const NO_ROUTE = `no model-call route at ${DEV_ROUTE}: add the dew() plugin to vite.config.js, or run the game on Dewdrop`;
13
-
14
- import { side } from './net.js';
15
-
16
- // Where `llm.fetch` posts from where it runs: the page's own origin in a
17
- // browser, and from the backend's thread the dev server's, which the
18
- // plugin's host tells it; a host that could not learn it — a dev server
19
- // in middleware mode with no `server.origin` — is said so.
20
- export function routeUrl() {
21
- if (typeof window !== 'undefined') return DEV_ROUTE;
22
- const origin = process.env.DEW_DEV_ORIGIN ?? '';
23
- if (side.backend && origin === '') {
24
- throw new TypeError("the dev server's address is unknown to the backend: set server.origin in vite.config.js");
25
- }
26
- return origin + DEV_ROUTE;
27
- }
28
-
29
- // The message a client sends without a channel to its backend: a page
30
- // served without the plugin, or a build served by a static host.
31
- export const NO_CHANNEL = 'no backend channel: add the dew() plugin to vite.config.js, or run the game on Dewdrop';
32
-
33
- // The message `saves` gives in a page without the plugin's script, which
34
- // starts the page's storage empty: a page served without the plugin, or a
35
- // build served by a static host.
36
- export const NO_SAVES = 'no saves here: add the dew() plugin to vite.config.js, or run the game on Dewdrop';