@arcadible/sdk 0.0.0-stage → 0.3.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 ADDED
@@ -0,0 +1,176 @@
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 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 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 those 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
package/README.md CHANGED
@@ -1,3 +1,62 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://arcadible.com">
3
+ <img src="https://adn-arcadible.imgix.net/images/i18n/core/www/appicon-512.png?w=256" alt="Arcadible" height="96">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">Arcadible SDK</h1>
8
+
9
+ <p align="center">
10
+ Saves that carry over from one version of your game to the next.
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://developer.arcadible.com/references/arcadible-sdk">Docs</a> ·
15
+ <a href="https://developer.arcadible.com/build/saves">Saves</a> ·
16
+ <a href="https://arcadible.com">Arcadible</a> ·
17
+ <a href="https://studio.arcadible.com">Studio</a>
18
+ </p>
19
+
20
+ <br>
21
+
22
+ Each version of a game on [Arcadible](https://arcadible.com) has its own origin, so its browser storage starts empty with every update. Saves made through the Arcadible SDK are kept by the play page instead, on the player's device, so they carry over. The SDK is optional, and saves are all it does.
23
+
24
+ ## Install
25
+
26
+ ```sh
27
+ npm install @arcadible/sdk
28
+ ```
29
+
30
+ For a game with a build step, such as a Vite project. A game without one includes the hosted script instead, served on Arcadible from every game's own origin:
31
+
32
+ ```html
33
+ <script src="/arcadible/sdk/v1.js"></script>
34
+ ```
35
+
36
+ ## Save and load
37
+
38
+ ```js
39
+ import { arcadible } from "@arcadible/sdk";
40
+
41
+ await arcadible.ready;
42
+
43
+ const saved = arcadible.saves.readSync("progress");
44
+ const progress = saved ? JSON.parse(saved) : { level: 1 };
45
+
46
+ await arcadible.saves.write("progress", JSON.stringify(progress));
47
+ ```
48
+
49
+ A save is a name holding one string. `ready` settles once the game's saves have loaded, and never fails; from then on, `readSync` answers from memory. Every call that fails rejects with an `ArcadibleError`, whose `code` says what to do.
50
+
51
+ Off Arcadible, such as on your dev server, the package works on its own, with the same rules and limits: saves are kept on the page's own origin, and `arcadible.build` is `null`.
52
+
53
+ ## Learn more
54
+
55
+ - [Saves](https://developer.arcadible.com/build/saves): adding the SDK, what to save, and other versions' saves.
56
+ - [`arcadible.saves`](https://developer.arcadible.com/references/arcadible-sdk/saves): every call, what it returns, and when it fails.
57
+ - [Arcadible SDK](https://developer.arcadible.com/references/arcadible-sdk): `ready` and `build`, and every code.
58
+ - [Limits](https://developer.arcadible.com/references/limits#saves): how many saves, and how large.
59
+
60
+ ## License
61
+
62
+ Apache-2.0
@@ -0,0 +1,16 @@
1
+ import { type Welcome } from "./protocol.js";
2
+ import type { Server } from "./server.js";
3
+ export type BusOptions = {
4
+ client: string;
5
+ window?: Window | undefined;
6
+ origins?: readonly string[] | undefined;
7
+ handshakeTimeout?: number | undefined;
8
+ requestTimeout?: number | undefined;
9
+ standalone: () => Server;
10
+ };
11
+ export type Bus = {
12
+ readonly welcomed: Promise<Welcome>;
13
+ request(name: string, params?: object): Promise<unknown>;
14
+ on(name: string, listener: (data: unknown) => void): () => void;
15
+ };
16
+ export declare function openBus(options: BusOptions): Bus;
@@ -0,0 +1,133 @@
1
+ // The game's end of the bus: it says hello to the play page, and stands
2
+ // alone when no page answers, running the page's end itself, in its own
3
+ // page, so the rules are the same.
4
+ // [import]
5
+ import { ArcadibleError, BUS_VERSION, Codes, HANDSHAKE_TIMEOUT, HOST_ORIGINS, isMessage, isWelcome, REQUEST_TIMEOUT, } from "./protocol.js";
6
+ // [function]
7
+ export function openBus(options) {
8
+ const win = options.window ?? (typeof window === "undefined" ? undefined : window);
9
+ const origins = options.origins ?? HOST_ORIGINS;
10
+ const requestTimeout = options.requestTimeout ?? REQUEST_TIMEOUT;
11
+ let state = "waiting";
12
+ let port = null;
13
+ let nextId = 1;
14
+ let handshakeTimer;
15
+ const pending = new Map();
16
+ const listeners = new Map();
17
+ let welcome = () => undefined;
18
+ const welcomed = new Promise((resolve) => {
19
+ welcome = resolve;
20
+ });
21
+ // [function]
22
+ const onPortMessage = function (event) {
23
+ const message = event.data;
24
+ if (!isMessage(message))
25
+ return;
26
+ handle(message);
27
+ };
28
+ // [function]
29
+ const handle = function (message) {
30
+ if (message.kind === "response") {
31
+ const call = pending.get(message.id);
32
+ if (!call)
33
+ return;
34
+ pending.delete(message.id);
35
+ clearTimeout(call.timer);
36
+ if ("error" in message) {
37
+ const { code, message: text } = message.error;
38
+ call.reject(new ArcadibleError(code, text));
39
+ }
40
+ else {
41
+ call.resolve(message.result);
42
+ }
43
+ }
44
+ else if (message.kind === "event") {
45
+ for (const listener of [...(listeners.get(message.name) ?? [])]) {
46
+ listener(message.data);
47
+ }
48
+ }
49
+ else {
50
+ // the page asks nothing yet; a newer page's request gets `unsupported`.
51
+ port?.postMessage({
52
+ kind: "response",
53
+ id: message.id,
54
+ error: {
55
+ code: Codes.Unsupported,
56
+ message: `Unknown request: ${message.name}`,
57
+ },
58
+ });
59
+ }
60
+ };
61
+ // [function]
62
+ const attach = function (link, body) {
63
+ port = link;
64
+ port.onmessage = onPortMessage;
65
+ welcome(body);
66
+ };
67
+ // [function]
68
+ // no play page: the page's end runs here, over a channel within this page.
69
+ const standAlone = function () {
70
+ if (state !== "waiting")
71
+ return;
72
+ state = "standalone";
73
+ win?.removeEventListener("message", onWindowMessage);
74
+ const channel = new MessageChannel();
75
+ attach(channel.port1, options.standalone().connect(channel.port2));
76
+ };
77
+ // [function]
78
+ const onWindowMessage = function (event) {
79
+ if (state !== "waiting" ||
80
+ !win ||
81
+ event.source !== win.parent ||
82
+ !origins.includes(event.origin) ||
83
+ !isWelcome(event.data) ||
84
+ !event.ports[0]) {
85
+ return;
86
+ }
87
+ state = "connected";
88
+ clearTimeout(handshakeTimer);
89
+ win.removeEventListener("message", onWindowMessage);
90
+ attach(event.ports[0], event.data);
91
+ };
92
+ // [start]
93
+ if (!win || win.parent === win) {
94
+ // not in a frame, so there's no play page to wait for.
95
+ standAlone();
96
+ }
97
+ else {
98
+ win.addEventListener("message", onWindowMessage);
99
+ handshakeTimer = setTimeout(standAlone, options.handshakeTimeout ?? HANDSHAKE_TIMEOUT);
100
+ win.parent.postMessage({ arcadible: "hello", v: BUS_VERSION, client: options.client }, "*");
101
+ }
102
+ return {
103
+ welcomed,
104
+ async request(name, params) {
105
+ await welcomed;
106
+ // welcomed, so there's a channel: the play page's, or this page's own.
107
+ const link = port;
108
+ if (!link) {
109
+ throw new ArcadibleError(Codes.Unavailable, "Not connected.");
110
+ }
111
+ const id = nextId++;
112
+ return new Promise((resolve, reject) => {
113
+ const timer = setTimeout(() => {
114
+ pending.delete(id);
115
+ reject(new ArcadibleError(Codes.Timeout, `${name} timed out.`));
116
+ }, requestTimeout);
117
+ pending.set(id, { resolve, reject, timer });
118
+ link.postMessage({ kind: "request", id, name, params });
119
+ });
120
+ },
121
+ on(name, listener) {
122
+ let set = listeners.get(name);
123
+ if (!set) {
124
+ set = new Set();
125
+ listeners.set(name, set);
126
+ }
127
+ set.add(listener);
128
+ return () => {
129
+ set.delete(listener);
130
+ };
131
+ },
132
+ };
133
+ }
@@ -0,0 +1,68 @@
1
+ export declare const BUS_VERSION = 1;
2
+ export declare const HANDSHAKE_TIMEOUT = 1000;
3
+ export declare const REQUEST_TIMEOUT = 10000;
4
+ export declare const HOST_ORIGINS: readonly string[];
5
+ export declare const MAX_IN_FLIGHT = 64;
6
+ export declare const MAX_MESSAGE: number;
7
+ export declare const Codes: {
8
+ readonly Busy: "busy";
9
+ readonly Full: "full";
10
+ readonly Invalid: "invalid";
11
+ readonly NotReady: "not_ready";
12
+ readonly Timeout: "timeout";
13
+ readonly TooLarge: "too_large";
14
+ readonly TooMany: "too_many";
15
+ readonly Unavailable: "unavailable";
16
+ readonly Unsupported: "unsupported";
17
+ };
18
+ export type Code = (typeof Codes)[keyof typeof Codes];
19
+ export type Build = {
20
+ version: string;
21
+ channel: string;
22
+ };
23
+ export type Hello = {
24
+ arcadible: "hello";
25
+ v: number;
26
+ client: string;
27
+ };
28
+ export type Welcome = {
29
+ arcadible: "welcome";
30
+ v: number;
31
+ build: Build | null;
32
+ };
33
+ export type ErrorBody = {
34
+ code: string;
35
+ message: string;
36
+ };
37
+ export type Request = {
38
+ kind: "request";
39
+ id: number;
40
+ name: string;
41
+ params?: unknown;
42
+ };
43
+ export type Response = {
44
+ kind: "response";
45
+ id: number;
46
+ result: unknown;
47
+ } | {
48
+ kind: "response";
49
+ id: number;
50
+ error: ErrorBody;
51
+ };
52
+ export type BusEvent = {
53
+ kind: "event";
54
+ name: string;
55
+ data?: unknown;
56
+ };
57
+ export type Message = Request | Response | BusEvent;
58
+ export declare class ArcadibleError extends Error {
59
+ readonly code: Code;
60
+ constructor(code: Code, message: string);
61
+ toJSON(): ErrorBody;
62
+ }
63
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
64
+ export declare function isHello(value: unknown): value is Hello;
65
+ export declare function isWelcome(value: unknown): value is Welcome;
66
+ export declare function isMessage(value: unknown): value is Message;
67
+ export declare function utf8Size(text: string): number;
68
+ export declare function messageSize(value: unknown, limit?: number): number;
@@ -0,0 +1,140 @@
1
+ // The bus's rules, shared by both ends so they can't drift apart: the
2
+ // handshake, the message shapes, the error codes, and the limits on what
3
+ // crosses it (DESIGN.md, section 4). It knows nothing of any module.
4
+ // [declare]
5
+ // The bus's own version: the handshake and the message shapes. New modules,
6
+ // names, and fields are additions within it.
7
+ export const BUS_VERSION = 1;
8
+ // How long a game waits for the play page's welcome before it stands alone.
9
+ export const HANDSHAKE_TIMEOUT = 1000;
10
+ // How long a request waits for its response.
11
+ export const REQUEST_TIMEOUT = 10_000;
12
+ // The play pages a game accepts a welcome from: production's only. A
13
+ // development page (play.arcadible.test, `arc preview`) is passed with
14
+ // `createClient({ origins })`, never trusted by what games ship, since a
15
+ // hostile network could pose as an http one.
16
+ export const HOST_ORIGINS = ["https://play.arcadible.com"];
17
+ // The most requests one game can have waiting on the page; past it, a
18
+ // request fails with `busy`.
19
+ export const MAX_IN_FLIGHT = 64;
20
+ // One message, checked by the side that receives it: room for a whole 1 MB
21
+ // save, and the rest of the message.
22
+ export const MAX_MESSAGE = 1024 * 1024 + 64 * 1024;
23
+ // [declare]
24
+ // Every code a call can fail with. Worth retrying: `busy`, `timeout`, and
25
+ // `unavailable`. Not: `full` (the device has no room; the player must free
26
+ // some), `invalid`, `too_large`, and `too_many`. More may come: a game
27
+ // treats a code it doesn't know as `unavailable`.
28
+ export const Codes = {
29
+ Busy: "busy",
30
+ Full: "full",
31
+ Invalid: "invalid",
32
+ NotReady: "not_ready",
33
+ Timeout: "timeout",
34
+ TooLarge: "too_large",
35
+ TooMany: "too_many",
36
+ Unavailable: "unavailable",
37
+ Unsupported: "unsupported",
38
+ };
39
+ // [class]
40
+ // A failed call. Match on `code`; the message is for people.
41
+ export class ArcadibleError extends Error {
42
+ // [field]
43
+ code;
44
+ // [constructor]
45
+ constructor(code, message) {
46
+ super(message);
47
+ this.code = code;
48
+ this.name = "ArcadibleError";
49
+ }
50
+ // [method]
51
+ toJSON() {
52
+ return { code: this.code, message: this.message };
53
+ }
54
+ }
55
+ // [function]
56
+ export function isObject(value) {
57
+ return typeof value === "object" && value !== null;
58
+ }
59
+ // [function]
60
+ export function isHello(value) {
61
+ return (isObject(value) &&
62
+ value["arcadible"] === "hello" &&
63
+ typeof value["v"] === "number" &&
64
+ value["v"] >= 1);
65
+ }
66
+ // [function]
67
+ export function isWelcome(value) {
68
+ return (isObject(value) &&
69
+ value["arcadible"] === "welcome" &&
70
+ value["v"] === BUS_VERSION);
71
+ }
72
+ // [function]
73
+ export function isMessage(value) {
74
+ if (!isObject(value))
75
+ return false;
76
+ switch (value["kind"]) {
77
+ case "request":
78
+ return (typeof value["id"] === "number" && typeof value["name"] === "string");
79
+ case "response":
80
+ return typeof value["id"] === "number";
81
+ case "event":
82
+ return typeof value["name"] === "string";
83
+ default:
84
+ return false;
85
+ }
86
+ }
87
+ // [function]
88
+ // A string's size in UTF-8 bytes, without encoding it.
89
+ export function utf8Size(text) {
90
+ let size = 0;
91
+ for (let i = 0; i < text.length; i++) {
92
+ const unit = text.charCodeAt(i);
93
+ if (unit < 0x80)
94
+ size += 1;
95
+ else if (unit < 0x800)
96
+ size += 2;
97
+ else if (unit >= 0xd800 && unit <= 0xdbff) {
98
+ // a pair is one 4-byte character.
99
+ size += 4;
100
+ i++;
101
+ }
102
+ else
103
+ size += 3;
104
+ }
105
+ return size;
106
+ }
107
+ // [function]
108
+ // A rough size of a message as the browser copies it: strings by their
109
+ // UTF-8 bytes, and a few bytes for anything else. It only has to be close
110
+ // enough to refuse a message far over the limit, so it stops counting once
111
+ // past `limit`, and counts an object it has seen (a cycle) once.
112
+ export function messageSize(value, limit = Number.POSITIVE_INFINITY) {
113
+ const seen = new WeakSet();
114
+ let size = 0;
115
+ const stack = [value];
116
+ while (stack.length > 0 && size <= limit) {
117
+ const item = stack.pop();
118
+ if (typeof item === "string")
119
+ size += utf8Size(item) + 2;
120
+ else if (!isObject(item))
121
+ size += 8;
122
+ else if (seen.has(item))
123
+ size += 8;
124
+ else {
125
+ seen.add(item);
126
+ size += 2;
127
+ if (Array.isArray(item)) {
128
+ for (const entry of item)
129
+ stack.push(entry);
130
+ }
131
+ else {
132
+ for (const [key, entry] of Object.entries(item)) {
133
+ size += utf8Size(key);
134
+ stack.push(entry);
135
+ }
136
+ }
137
+ }
138
+ }
139
+ return size;
140
+ }
@@ -0,0 +1,32 @@
1
+ import { type Build, type Welcome } from "./protocol.js";
2
+ export type Params = Record<string, unknown>;
3
+ export type Handler = {
4
+ run(params: Params): Promise<unknown>;
5
+ coalesce?(params: Params): string;
6
+ };
7
+ export type ModuleContext = {
8
+ broadcast(name: string, data: unknown): void;
9
+ };
10
+ export type Module = {
11
+ handlers: Record<string, Handler>;
12
+ open?(send: (name: string, data: unknown) => void): Promise<void>;
13
+ close?(): void;
14
+ };
15
+ export type ServerOptions = {
16
+ build: Build | null;
17
+ modules: ((context: ModuleContext) => Module)[];
18
+ };
19
+ export type Server = {
20
+ connect(port: MessagePort): Welcome;
21
+ disconnect(port: MessagePort): void;
22
+ close(): void;
23
+ };
24
+ export declare function createServer(options: ServerOptions): Server;
25
+ export declare function answerHellos({ frame, origin, server, window: win, }: {
26
+ frame: HTMLIFrameElement;
27
+ origin: string;
28
+ server: Server;
29
+ window: Window;
30
+ }): {
31
+ close(): void;
32
+ };