@idolchat/miniapp-sdk 0.0.0-stage → 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IdolChat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # @idolchat/miniapp-sdk
2
2
 
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.
3
+ The SDK an IdolChat mini app uses to talk to its host (the iOS and Android apps, and the
4
+ console's Play simulator).
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ npm install @idolchat/miniapp-sdk
10
+ ```
11
+
12
+ ## With a bundler (ESM)
13
+
14
+ ```ts
15
+ import { miniApp } from "@idolchat/miniapp-sdk";
16
+
17
+ // `miniApp` is undefined only outside a browser (e.g. server-side rendering).
18
+ const sdk = miniApp!;
19
+ await sdk.app.init();
20
+ await sdk.app.setLoadingProgress(100);
21
+ await sdk.app.ready(); // hides the host's splash
22
+ ```
23
+
24
+ Importing the package creates the page-wide instance and publishes it as `window.MiniApp`.
25
+ Types ship with the package.
26
+
27
+ ## Without a bundler (`<script>`)
28
+
29
+ The host only runs scripts from your own bundle, so a CDN `<script src>` will not load. Install
30
+ the package and ship its script-tag build inside your bundle:
31
+
32
+ ```sh
33
+ npm install @idolchat/miniapp-sdk
34
+ cp node_modules/@idolchat/miniapp-sdk/dist/miniapp-sdk.js .
35
+ ```
36
+
37
+ ```html
38
+ <script src="miniapp-sdk.js"></script>
39
+ <script src="main.js"></script>
40
+ ```
41
+
42
+ ```js
43
+ // main.js: the platform CSP blocks inline <script> blocks, so app code lives in a file.
44
+ const sdk = window.MiniApp;
45
+ sdk.app.init().then(() => sdk.app.ready());
46
+ ```
47
+
48
+ Shipping it in the zip means a reviewed version keeps the exact SDK it was reviewed with.
49
+
50
+ ## Testing in a browser tab
51
+
52
+ Opened on its own (or with `idolchat-miniapp dev`), the page talks to a built-in mock host. Vary it
53
+ from the URL: `?startapp=<param>`, `?theme=dark`, `?profile=0`, `?notifications=granted|denied|prompt`,
54
+ and `?user=<name>` (1-32 chars of `[A-Za-z0-9_-]`) for another test user, with an id stable per name
55
+ and the name `Mock User <name>` once profile consent is granted.
56
+
57
+ From the browser console, `__idolchatMock` fires what IdolChat would (it never exists in IdolChat):
58
+
59
+ ```js
60
+ __idolchatMock.emit("ui.themeChanged", { colorScheme: "dark" });
61
+ __idolchatMock.emit("lifecycle.pause", { reason: "call" });
62
+ await __idolchatMock.close(); // back button if shown, else onBeforeClose (up to 3 s), then closing
63
+ ```
64
+
65
+ `emit` takes any host event: `ui.backButtonPressed`, `ui.themeChanged`, `ui.viewportChanged`
66
+ `{ width, height }`, `lifecycle.pause` `{ reason }`, `lifecycle.resume` and `permissions.changed` `{ name, state }`.
67
+
68
+ ## Documentation
69
+
70
+ The IdolChat Mini App developer guide, which IdolChat sends to partners, covers every method, the
71
+ manifest, the bundle rules, verifying users on your server, and deploying. Host implementers: see the
72
+ protocol specification in the IdolChat repository docs.
73
+
74
+ ## Versions
75
+
76
+ The package's semver is separate from the protocol version (`v: 1`, manifest `"sdk": "1"`): only a
77
+ protocol break bumps the major.
package/dist/host.mjs ADDED
@@ -0,0 +1,225 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/protocol.ts
6
+ var PROTOCOL_VERSION = 1;
7
+ var MiniAppError = class extends Error {
8
+ constructor(code, message) {
9
+ super(message);
10
+ __publicField(this, "code");
11
+ this.name = "MiniAppError";
12
+ this.code = code;
13
+ }
14
+ toWire() {
15
+ return { code: this.code, message: this.message };
16
+ }
17
+ };
18
+ var isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
19
+ var str = (x) => typeof x === "string" ? x : void 0;
20
+ function decode(raw) {
21
+ let m = raw;
22
+ if (typeof raw === "string") {
23
+ try {
24
+ m = JSON.parse(raw);
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ return isRecord(m) && m.v === PROTOCOL_VERSION ? m : null;
30
+ }
31
+ function parseError(e) {
32
+ return { code: str(e.code) ?? "INTERNAL_ERROR", message: str(e.message) ?? "" };
33
+ }
34
+ function parseCallMessage(raw) {
35
+ const m = decode(raw);
36
+ if (!m || typeof m.id !== "string" || typeof m.method !== "string") return null;
37
+ return { v: 1, id: m.id, method: m.method, params: m.params, gesture: m.gesture === true };
38
+ }
39
+
40
+ // src/methods.ts
41
+ var STORAGE_LIMIT_BYTES = 1024 * 1024;
42
+ var START_PARAM_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
43
+ var STORY_TEXT_MAX = 500;
44
+ var LAUNCH_NONCE_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
45
+ var METHOD_SCOPES = {
46
+ "auth.requestProfile": "profile",
47
+ "qr.scan": "camera",
48
+ "location.get": "location",
49
+ "media.saveImage": "photos",
50
+ "notifications.requestPermission": "notifications"
51
+ };
52
+ var SCOPE_OF = new Map(Object.entries(METHOD_SCOPES));
53
+ var scopeOf = (method) => SCOPE_OF.get(method);
54
+
55
+ // src/validate.ts
56
+ function invalid(reason) {
57
+ throw new MiniAppError("INVALID_PARAMS", reason);
58
+ }
59
+ function requiredString(p, name) {
60
+ const v = p[name];
61
+ return typeof v === "string" ? v : invalid(`${name} must be a string`);
62
+ }
63
+ var optionalString = (p, name) => p[name] === void 0 ? void 0 : requiredString(p, name);
64
+ var isNonBlank = (v) => typeof v === "string" && v.trim() !== "";
65
+ function shareText(p, required) {
66
+ const text = required ? requiredString(p, "text") : optionalString(p, "text");
67
+ if (text !== void 0 && !isNonBlank(text)) invalid("text must not be empty");
68
+ }
69
+ function oneOf(p, name, values) {
70
+ const v = p[name];
71
+ return values.find((x) => x === v) ?? invalid(`${name} must be one of ${values.join(", ")}`);
72
+ }
73
+ function hexColor(p) {
74
+ const v = p.color;
75
+ return typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v) ? v : invalid("color must be #rrggbb");
76
+ }
77
+ function storyContent(p) {
78
+ const text = optionalString(p, "text");
79
+ if (text === void 0) {
80
+ if (p.image === void 0) invalid("a story needs an image or text");
81
+ return;
82
+ }
83
+ const n = text.trim().length;
84
+ if (n < 1 || n > STORY_TEXT_MAX) invalid(`text must be 1-${STORY_TEXT_MAX} chars`);
85
+ }
86
+ function analyticsEvent(p) {
87
+ const name = requiredString(p, "name");
88
+ if (name.length === 0) invalid("name must not be empty");
89
+ const props = p.props ?? {};
90
+ if (!isRecord(props) || Array.isArray(props)) return invalid("props must be an object");
91
+ for (const [k, v] of Object.entries(props)) {
92
+ if (typeof v !== "string" && typeof v !== "boolean" && !(typeof v === "number" && Number.isFinite(v)))
93
+ invalid(`props.${k} must be a string, number or boolean`);
94
+ }
95
+ return { name, props };
96
+ }
97
+
98
+ // src/share-image.ts
99
+ var SHARE_IMAGE_LIMITS = {
100
+ maxBytes: 2 * 1024 * 1024,
101
+ maxSide: 2048,
102
+ types: ["image/png", "image/jpeg", "image/webp"]
103
+ };
104
+ var DATA_URL = /^data:([^;,]+);base64,/;
105
+ var BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
106
+ var MAX_ENCODED = Math.ceil(SHARE_IMAGE_LIMITS.maxBytes / 3) * 4;
107
+ function checkShareImage(image) {
108
+ if (typeof image !== "string") return { ok: false, reason: "image must be a data: URL string" };
109
+ const head = DATA_URL.exec(image.slice(0, 40));
110
+ if (!head) return { ok: false, reason: "image must be a base64 data: URL" };
111
+ const type = SHARE_IMAGE_LIMITS.types.find((t) => t === head[1]);
112
+ if (!type)
113
+ return { ok: false, reason: `image type must be ${SHARE_IMAGE_LIMITS.types.join(", ")}` };
114
+ const body = image.slice(head[0].length);
115
+ if (body.length > MAX_ENCODED)
116
+ return { ok: false, reason: `image is over ${SHARE_IMAGE_LIMITS.maxBytes} bytes` };
117
+ if (body.length === 0 || body.length % 4 !== 0 || !BASE64.test(body))
118
+ return { ok: false, reason: "image is not valid base64" };
119
+ const bytes = body.length / 4 * 3 - (body.endsWith("==") ? 2 : body.endsWith("=") ? 1 : 0);
120
+ if (bytes > SHARE_IMAGE_LIMITS.maxBytes)
121
+ return { ok: false, reason: `image is over ${SHARE_IMAGE_LIMITS.maxBytes} bytes` };
122
+ return { ok: true, type, bytes };
123
+ }
124
+
125
+ // src/host/postmessage-host.ts
126
+ var REQUEST_TIMEOUT_MS = 3e3;
127
+ function createPostMessageHost(opts) {
128
+ const win = opts.window ?? window;
129
+ const targetOrigin = opts.appOrigin === "null" ? "*" : opts.appOrigin;
130
+ const pending = /* @__PURE__ */ new Map();
131
+ let seq = 0;
132
+ const post = (msg) => opts.iframe.contentWindow?.postMessage(msg, targetOrigin);
133
+ const settleReply = (p) => {
134
+ if (!isRecord(p) || typeof p.id !== "string") return;
135
+ const entry = pending.get(p.id);
136
+ if (!entry) return;
137
+ pending.delete(p.id);
138
+ clearTimeout(entry.timer);
139
+ if (p.ok === true) entry.resolve(p.data);
140
+ else {
141
+ const e = parseError(isRecord(p.error) ? p.error : {});
142
+ entry.reject(new MiniAppError(e.code, e.message || "request failed"));
143
+ }
144
+ };
145
+ const dispatch = async (call) => {
146
+ const { id, method } = call;
147
+ opts.onEvent?.({ kind: "call", method, id, gesture: call.gesture });
148
+ const handler = Object.hasOwn(opts.handlers, method) ? opts.handlers[method] : void 0;
149
+ let msg;
150
+ try {
151
+ if (!handler)
152
+ throw new MiniAppError("METHOD_NOT_SUPPORTED", `host does not support ${method}`);
153
+ const data = await handler(call.params, { method, gesture: call.gesture });
154
+ msg = { v: 1, type: "result", id, ok: true, data: data ?? {} };
155
+ } catch (err) {
156
+ const error = err instanceof MiniAppError ? err.toWire() : { code: "INTERNAL_ERROR", message: "host handler failed" };
157
+ msg = { v: 1, type: "result", id, ok: false, error };
158
+ }
159
+ opts.onEvent?.(
160
+ msg.ok ? { kind: "result", method, id, ok: true } : { kind: "result", method, id, ok: false, error: msg.error }
161
+ );
162
+ post(msg);
163
+ };
164
+ const onMessage = (event) => {
165
+ if (!("source" in event && "origin" in event && "data" in event)) return;
166
+ const origin = String(event.origin);
167
+ const contentWindow = opts.iframe.contentWindow;
168
+ if (!contentWindow || event.source !== contentWindow) {
169
+ opts.onEvent?.({ kind: "rejected", reason: "source", origin });
170
+ return;
171
+ }
172
+ if (origin !== opts.appOrigin) {
173
+ opts.onEvent?.({ kind: "rejected", reason: "origin", origin });
174
+ return;
175
+ }
176
+ const call = parseCallMessage(event.data);
177
+ if (!call) {
178
+ opts.onEvent?.({ kind: "rejected", reason: "malformed", origin });
179
+ return;
180
+ }
181
+ if (call.method === "_reply") settleReply(call.params);
182
+ else void dispatch(call);
183
+ };
184
+ win.addEventListener("message", onMessage);
185
+ return {
186
+ emit(name, data) {
187
+ post({ v: 1, type: "event", name, data });
188
+ },
189
+ request(name, data, timeoutMs = REQUEST_TIMEOUT_MS) {
190
+ const id = `r_${++seq}`;
191
+ return new Promise((resolve, reject) => {
192
+ const timer = setTimeout(() => {
193
+ pending.delete(id);
194
+ reject(new MiniAppError("TIMEOUT", `${name} got no reply within ${timeoutMs} ms`));
195
+ }, timeoutMs);
196
+ pending.set(id, { resolve, reject, timer });
197
+ post({ v: 1, type: "request", id, name, data, timeoutMs });
198
+ });
199
+ },
200
+ dispose() {
201
+ win.removeEventListener("message", onMessage);
202
+ for (const [id, p] of pending) {
203
+ clearTimeout(p.timer);
204
+ p.reject(new MiniAppError("CANCELLED", "host disposed"));
205
+ pending.delete(id);
206
+ }
207
+ }
208
+ };
209
+ }
210
+ export {
211
+ LAUNCH_NONCE_PATTERN,
212
+ METHOD_SCOPES,
213
+ MiniAppError,
214
+ SHARE_IMAGE_LIMITS,
215
+ START_PARAM_PATTERN,
216
+ STORY_TEXT_MAX,
217
+ analyticsEvent,
218
+ checkShareImage,
219
+ createPostMessageHost,
220
+ hexColor,
221
+ oneOf,
222
+ scopeOf,
223
+ shareText,
224
+ storyContent
225
+ };