@idolchat/miniapp-sdk 0.0.0-stage โ 0.2.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 +21 -0
- package/README.md +76 -2
- package/dist/host.mjs +225 -0
- package/dist/index.mjs +1304 -0
- package/dist/miniapp-sdk.js +16 -0
- package/dist/types/client.d.ts +173 -0
- package/dist/types/core.d.ts +46 -0
- package/dist/types/host/postmessage-host.d.ts +56 -0
- package/dist/types/index.d.ts +18 -0
- package/dist/types/methods.d.ts +34 -0
- package/dist/types/modules/app.d.ts +18 -0
- package/dist/types/modules/device.d.ts +37 -0
- package/dist/types/modules/links.d.ts +42 -0
- package/dist/types/modules/platform.d.ts +52 -0
- package/dist/types/modules/storage.d.ts +13 -0
- package/dist/types/modules/ui.d.ts +49 -0
- package/dist/types/protocol.d.ts +87 -0
- package/dist/types/share-image.d.ts +17 -0
- package/dist/types/transport/android.d.ts +10 -0
- package/dist/types/transport/detect.d.ts +28 -0
- package/dist/types/transport/ios.d.ts +16 -0
- package/dist/types/transport/mock.d.ts +77 -0
- package/dist/types/transport/native.d.ts +12 -0
- package/dist/types/transport/postmessage.d.ts +4 -0
- package/dist/types/transport/sha256.d.ts +2 -0
- package/dist/types/transport/types.d.ts +8 -0
- package/dist/types/validate.d.ts +29 -0
- package/global.d.ts +16 -0
- package/package.json +34 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1304 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
|
|
3
|
+
var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
|
|
4
|
+
|
|
5
|
+
// src/methods.ts
|
|
6
|
+
var METHODS = [
|
|
7
|
+
"app.init",
|
|
8
|
+
"app.ready",
|
|
9
|
+
"app.setLoadingProgress",
|
|
10
|
+
"app.close",
|
|
11
|
+
"ui.showToast",
|
|
12
|
+
"ui.showAlert",
|
|
13
|
+
"ui.showConfirm",
|
|
14
|
+
"ui.showPopup",
|
|
15
|
+
"ui.setBackButtonVisible",
|
|
16
|
+
"ui.setHeaderColor",
|
|
17
|
+
"ui.setBackgroundColor",
|
|
18
|
+
"ui.setOrientation",
|
|
19
|
+
"ui.getTheme",
|
|
20
|
+
"haptic.impact",
|
|
21
|
+
"haptic.notification",
|
|
22
|
+
"haptic.selection",
|
|
23
|
+
"storage.get",
|
|
24
|
+
"storage.getMany",
|
|
25
|
+
"storage.set",
|
|
26
|
+
"storage.remove",
|
|
27
|
+
"storage.keys",
|
|
28
|
+
"storage.clear",
|
|
29
|
+
"link.open",
|
|
30
|
+
"clipboard.writeText",
|
|
31
|
+
"clipboard.readText",
|
|
32
|
+
"share.system",
|
|
33
|
+
"share.toChat",
|
|
34
|
+
"share.toPost",
|
|
35
|
+
"share.toStory",
|
|
36
|
+
"analytics.track",
|
|
37
|
+
"device.getInfo",
|
|
38
|
+
"permissions.query",
|
|
39
|
+
"permissions.request",
|
|
40
|
+
"qr.scan",
|
|
41
|
+
"location.get",
|
|
42
|
+
"media.saveImage",
|
|
43
|
+
"auth.getLaunchToken",
|
|
44
|
+
"auth.requestProfile",
|
|
45
|
+
"payment.open",
|
|
46
|
+
"notifications.requestPermission",
|
|
47
|
+
"notifications.getPermission",
|
|
48
|
+
"ads.loadRewarded",
|
|
49
|
+
"ads.showRewarded",
|
|
50
|
+
"ads.loadInterstitial",
|
|
51
|
+
"ads.showInterstitial",
|
|
52
|
+
"ads.showBanner",
|
|
53
|
+
"ads.hideBanner"
|
|
54
|
+
];
|
|
55
|
+
var EVENTS = [
|
|
56
|
+
"lifecycle.pause",
|
|
57
|
+
"lifecycle.resume",
|
|
58
|
+
"lifecycle.closing",
|
|
59
|
+
"ui.backButtonPressed",
|
|
60
|
+
"ui.themeChanged",
|
|
61
|
+
"ui.viewportChanged",
|
|
62
|
+
"permissions.changed",
|
|
63
|
+
"ads.loaded",
|
|
64
|
+
"ads.failed",
|
|
65
|
+
"ads.shown",
|
|
66
|
+
"ads.closed",
|
|
67
|
+
"ads.rewarded"
|
|
68
|
+
];
|
|
69
|
+
var REQUESTS = ["app.beforeClose", "ads.beforeBreak"];
|
|
70
|
+
function waitsOnUser(method) {
|
|
71
|
+
return method.startsWith("payment.") || method.startsWith("ads.") || method.startsWith("share.") || method === "ui.showAlert" || method === "ui.showConfirm" || method === "ui.showPopup" || method === "permissions.request" || // Every ๐ call can open IdolChat's first-use permission dialog (protocol ยง6).
|
|
72
|
+
scopeOf(method) !== void 0;
|
|
73
|
+
}
|
|
74
|
+
var STORAGE_LIMIT_BYTES = 1024 * 1024;
|
|
75
|
+
var STORAGE_KEY_MAX = 128;
|
|
76
|
+
var START_PARAM_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
77
|
+
var STORY_TEXT_MAX = 500;
|
|
78
|
+
var LAUNCH_NONCE_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
79
|
+
var GESTURE_METHODS = /* @__PURE__ */ new Set([
|
|
80
|
+
"link.open",
|
|
81
|
+
"clipboard.writeText",
|
|
82
|
+
"clipboard.readText",
|
|
83
|
+
"share.system",
|
|
84
|
+
"share.toChat",
|
|
85
|
+
"share.toPost",
|
|
86
|
+
"share.toStory",
|
|
87
|
+
"permissions.request",
|
|
88
|
+
"qr.scan",
|
|
89
|
+
"media.saveImage",
|
|
90
|
+
"payment.open",
|
|
91
|
+
"notifications.requestPermission",
|
|
92
|
+
"ads.showRewarded"
|
|
93
|
+
]);
|
|
94
|
+
var PERMISSION_NAMES = [
|
|
95
|
+
"profile",
|
|
96
|
+
"camera",
|
|
97
|
+
"microphone",
|
|
98
|
+
"location",
|
|
99
|
+
"notifications",
|
|
100
|
+
"photos"
|
|
101
|
+
];
|
|
102
|
+
var METHOD_SCOPES = {
|
|
103
|
+
"auth.requestProfile": "profile",
|
|
104
|
+
"qr.scan": "camera",
|
|
105
|
+
"location.get": "location",
|
|
106
|
+
"media.saveImage": "photos",
|
|
107
|
+
"notifications.requestPermission": "notifications"
|
|
108
|
+
};
|
|
109
|
+
var SCOPE_OF = new Map(Object.entries(METHOD_SCOPES));
|
|
110
|
+
var scopeOf = (method) => SCOPE_OF.get(method);
|
|
111
|
+
|
|
112
|
+
// src/protocol.ts
|
|
113
|
+
var PROTOCOL_VERSION = 1;
|
|
114
|
+
var ERROR_CODES = [
|
|
115
|
+
"METHOD_NOT_SUPPORTED",
|
|
116
|
+
"INVALID_PARAMS",
|
|
117
|
+
"TIMEOUT",
|
|
118
|
+
"QUOTA_EXCEEDED",
|
|
119
|
+
"PERMISSION_DENIED",
|
|
120
|
+
"CANCELLED",
|
|
121
|
+
"INTERNAL_ERROR"
|
|
122
|
+
];
|
|
123
|
+
var MiniAppError = class extends Error {
|
|
124
|
+
constructor(code, message) {
|
|
125
|
+
super(message);
|
|
126
|
+
__publicField(this, "code");
|
|
127
|
+
this.name = "MiniAppError";
|
|
128
|
+
this.code = code;
|
|
129
|
+
}
|
|
130
|
+
toWire() {
|
|
131
|
+
return { code: this.code, message: this.message };
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
var isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
|
|
135
|
+
var str = (x) => typeof x === "string" ? x : void 0;
|
|
136
|
+
function decode(raw) {
|
|
137
|
+
let m = raw;
|
|
138
|
+
if (typeof raw === "string") {
|
|
139
|
+
try {
|
|
140
|
+
m = JSON.parse(raw);
|
|
141
|
+
} catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return isRecord(m) && m.v === PROTOCOL_VERSION ? m : null;
|
|
146
|
+
}
|
|
147
|
+
function parseHostMessage(raw) {
|
|
148
|
+
const m = decode(raw);
|
|
149
|
+
if (!m) return null;
|
|
150
|
+
const id = str(m.id);
|
|
151
|
+
const name = str(m.name);
|
|
152
|
+
switch (m.type) {
|
|
153
|
+
case "result":
|
|
154
|
+
if (id === void 0) return null;
|
|
155
|
+
if (m.ok === true) return { v: 1, type: "result", id, ok: true, data: m.data };
|
|
156
|
+
if (m.ok !== false || !isRecord(m.error)) return null;
|
|
157
|
+
return { v: 1, type: "result", id, ok: false, error: parseError(m.error) };
|
|
158
|
+
case "event":
|
|
159
|
+
return name === void 0 ? null : { v: 1, type: "event", name, data: m.data };
|
|
160
|
+
case "request":
|
|
161
|
+
if (id === void 0 || name === void 0) return null;
|
|
162
|
+
return {
|
|
163
|
+
v: 1,
|
|
164
|
+
type: "request",
|
|
165
|
+
id,
|
|
166
|
+
name,
|
|
167
|
+
data: m.data,
|
|
168
|
+
timeoutMs: typeof m.timeoutMs === "number" ? m.timeoutMs : 3e3
|
|
169
|
+
};
|
|
170
|
+
default:
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function parseError(e) {
|
|
175
|
+
return { code: str(e.code) ?? "INTERNAL_ERROR", message: str(e.message) ?? "" };
|
|
176
|
+
}
|
|
177
|
+
function parseCallMessage(raw) {
|
|
178
|
+
const m = decode(raw);
|
|
179
|
+
if (!m || typeof m.id !== "string" || typeof m.method !== "string") return null;
|
|
180
|
+
return { v: 1, id: m.id, method: m.method, params: m.params, gesture: m.gesture === true };
|
|
181
|
+
}
|
|
182
|
+
function parseUser(u) {
|
|
183
|
+
if (!isRecord(u) || typeof u.id !== "string") return null;
|
|
184
|
+
return {
|
|
185
|
+
id: u.id,
|
|
186
|
+
displayName: str(u.displayName),
|
|
187
|
+
avatarUrl: str(u.avatarUrl),
|
|
188
|
+
locale: str(u.locale)
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function parseInitResult(r) {
|
|
192
|
+
if (!isRecord(r)) throw new MiniAppError("INTERNAL_ERROR", "app.init returned no result");
|
|
193
|
+
return {
|
|
194
|
+
protocol: typeof r.protocol === "number" ? r.protocol : PROTOCOL_VERSION,
|
|
195
|
+
methods: Array.isArray(r.methods) ? r.methods.filter((x) => typeof x === "string") : [],
|
|
196
|
+
limits: isRecord(r.limits) ? r.limits : {},
|
|
197
|
+
user: parseUser(r.user),
|
|
198
|
+
startParam: str(r.startParam) ?? null,
|
|
199
|
+
launchToken: str(r.launchToken) ?? null
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// src/core.ts
|
|
204
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
205
|
+
var GESTURE_WINDOW_MS = 1e4;
|
|
206
|
+
var MiniAppCore = class {
|
|
207
|
+
constructor(transport, opts = {}) {
|
|
208
|
+
__publicField(this, "transport");
|
|
209
|
+
__publicField(this, "timeoutMs");
|
|
210
|
+
__publicField(this, "now");
|
|
211
|
+
__publicField(this, "pending", /* @__PURE__ */ new Map());
|
|
212
|
+
__publicField(this, "events", /* @__PURE__ */ new Map());
|
|
213
|
+
__publicField(this, "requests", /* @__PURE__ */ new Map());
|
|
214
|
+
__publicField(this, "seq", 0);
|
|
215
|
+
__publicField(this, "lastGestureAt", Number.NEGATIVE_INFINITY);
|
|
216
|
+
__publicField(this, "initPromise");
|
|
217
|
+
__publicField(this, "methods");
|
|
218
|
+
this.transport = transport;
|
|
219
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
220
|
+
this.now = opts.now ?? Date.now;
|
|
221
|
+
const mark = () => {
|
|
222
|
+
this.lastGestureAt = this.now();
|
|
223
|
+
};
|
|
224
|
+
opts.gestureTarget?.addEventListener("pointerdown", mark, { capture: true });
|
|
225
|
+
opts.gestureTarget?.addEventListener("keydown", mark, { capture: true });
|
|
226
|
+
transport.listen((raw) => this.receive(raw));
|
|
227
|
+
}
|
|
228
|
+
/** Negotiates once; every other call waits for it. */
|
|
229
|
+
init() {
|
|
230
|
+
this.initPromise ?? (this.initPromise = this.send("app.init", { protocol: 1 }, {}).then(
|
|
231
|
+
(raw) => {
|
|
232
|
+
const r = parseInitResult(raw);
|
|
233
|
+
this.methods = new Set(r.methods);
|
|
234
|
+
return r;
|
|
235
|
+
},
|
|
236
|
+
(err) => {
|
|
237
|
+
this.initPromise = void 0;
|
|
238
|
+
throw err;
|
|
239
|
+
}
|
|
240
|
+
));
|
|
241
|
+
return this.initPromise;
|
|
242
|
+
}
|
|
243
|
+
/** False until `init()` has resolved, then whether the host lists the method. */
|
|
244
|
+
supports(method) {
|
|
245
|
+
return this.methods?.has(method) ?? false;
|
|
246
|
+
}
|
|
247
|
+
/** `T` is the result shape the protocol documents for `method`; the host is trusted to honour it. */
|
|
248
|
+
async call(method, params, opts = {}) {
|
|
249
|
+
const init = await this.init();
|
|
250
|
+
let data = init;
|
|
251
|
+
if (method !== "app.init") {
|
|
252
|
+
if (!this.supports(method))
|
|
253
|
+
throw new MiniAppError("METHOD_NOT_SUPPORTED", `host does not support ${method}`);
|
|
254
|
+
data = await this.send(method, params, opts);
|
|
255
|
+
}
|
|
256
|
+
return data;
|
|
257
|
+
}
|
|
258
|
+
/** `T` is the event payload the protocol documents for `name`. */
|
|
259
|
+
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- T types the subscriber's payload
|
|
260
|
+
on(name, handler) {
|
|
261
|
+
const h = (data) => handler(data);
|
|
262
|
+
let set = this.events.get(name);
|
|
263
|
+
if (!set) this.events.set(name, set = /* @__PURE__ */ new Set());
|
|
264
|
+
set.add(h);
|
|
265
|
+
return () => set.delete(h);
|
|
266
|
+
}
|
|
267
|
+
/** One handler per request name; the latest registration wins. */
|
|
268
|
+
onRequest(name, handler) {
|
|
269
|
+
this.requests.set(name, handler);
|
|
270
|
+
return () => {
|
|
271
|
+
if (this.requests.get(name) === handler) this.requests.delete(name);
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
nextId() {
|
|
275
|
+
return `c_${++this.seq}`;
|
|
276
|
+
}
|
|
277
|
+
hasGesture() {
|
|
278
|
+
return this.now() - this.lastGestureAt <= GESTURE_WINDOW_MS;
|
|
279
|
+
}
|
|
280
|
+
post(method, params, id) {
|
|
281
|
+
const msg = { v: 1, id, method, gesture: this.hasGesture() };
|
|
282
|
+
if (params !== void 0) msg.params = params;
|
|
283
|
+
this.transport.send(msg);
|
|
284
|
+
}
|
|
285
|
+
send(method, params, opts) {
|
|
286
|
+
const id = this.nextId();
|
|
287
|
+
const ms = opts.timeoutMs ?? (waitsOnUser(method) ? 0 : this.timeoutMs);
|
|
288
|
+
return new Promise((resolve, reject) => {
|
|
289
|
+
const timer = ms > 0 ? setTimeout(() => {
|
|
290
|
+
this.pending.delete(id);
|
|
291
|
+
reject(new MiniAppError("TIMEOUT", `${method} timed out after ${ms} ms`));
|
|
292
|
+
}, ms) : void 0;
|
|
293
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
294
|
+
try {
|
|
295
|
+
this.post(method, params, id);
|
|
296
|
+
} catch (err) {
|
|
297
|
+
clearTimeout(timer);
|
|
298
|
+
this.pending.delete(id);
|
|
299
|
+
reject(new MiniAppError("INTERNAL_ERROR", `transport failed: ${String(err)}`));
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
receive(raw) {
|
|
304
|
+
const msg = parseHostMessage(raw);
|
|
305
|
+
if (!msg) return;
|
|
306
|
+
if (msg.type === "result") {
|
|
307
|
+
const p = this.pending.get(msg.id);
|
|
308
|
+
if (!p) return;
|
|
309
|
+
this.pending.delete(msg.id);
|
|
310
|
+
clearTimeout(p.timer);
|
|
311
|
+
if (msg.ok) p.resolve(msg.data);
|
|
312
|
+
else p.reject(new MiniAppError(msg.error.code, msg.error.message));
|
|
313
|
+
} else if (msg.type === "event") {
|
|
314
|
+
for (const h of this.events.get(msg.name) ?? []) {
|
|
315
|
+
try {
|
|
316
|
+
h(msg.data);
|
|
317
|
+
} catch (err) {
|
|
318
|
+
setTimeout(() => {
|
|
319
|
+
throw err;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
} else {
|
|
324
|
+
void this.answer(msg);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async answer(req) {
|
|
328
|
+
const handler = this.requests.get(req.name);
|
|
329
|
+
let reply;
|
|
330
|
+
if (!handler) {
|
|
331
|
+
reply = { id: req.id, ok: false, error: { code: "METHOD_NOT_SUPPORTED", message: req.name } };
|
|
332
|
+
} else {
|
|
333
|
+
try {
|
|
334
|
+
reply = { id: req.id, ok: true, data: await handler(req.data) };
|
|
335
|
+
} catch (err) {
|
|
336
|
+
const e = err instanceof MiniAppError ? err : new MiniAppError("INTERNAL_ERROR", String(err));
|
|
337
|
+
reply = { id: req.id, ok: false, error: e.toWire() };
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
this.post("_reply", reply, this.nextId());
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// src/modules/app.ts
|
|
345
|
+
function appModule(core) {
|
|
346
|
+
return {
|
|
347
|
+
init: () => core.init(),
|
|
348
|
+
ready: () => core.call("app.ready"),
|
|
349
|
+
/** 0โ100. */
|
|
350
|
+
setLoadingProgress: (progress2) => core.call("app.setLoadingProgress", {
|
|
351
|
+
progress: Math.max(0, Math.min(100, Math.round(progress2)))
|
|
352
|
+
}),
|
|
353
|
+
close: () => core.call("app.close")
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
function lifecycleModule(core) {
|
|
357
|
+
return {
|
|
358
|
+
onPause: (cb) => core.on("lifecycle.pause", cb),
|
|
359
|
+
onResume: (cb) => core.on("lifecycle.resume", cb),
|
|
360
|
+
onClosing: (cb) => core.on("lifecycle.closing", cb),
|
|
361
|
+
/** The host waits up to the request's timeout (3 s) for this to settle, e.g. to flush a save. */
|
|
362
|
+
onBeforeClose: (handler) => core.onRequest("app.beforeClose", handler)
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// src/modules/device.ts
|
|
367
|
+
function deviceModule(core) {
|
|
368
|
+
return {
|
|
369
|
+
getInfo: () => core.call("device.getInfo")
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function permissionsModule(core) {
|
|
373
|
+
return {
|
|
374
|
+
query: (name) => core.call("permissions.query", { name }),
|
|
375
|
+
request: (name) => core.call("permissions.request", { name }),
|
|
376
|
+
onChanged: (cb) => core.on("permissions.changed", cb)
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
function qrModule(core) {
|
|
380
|
+
return { scan: () => core.call("qr.scan") };
|
|
381
|
+
}
|
|
382
|
+
function locationModule(core) {
|
|
383
|
+
return {
|
|
384
|
+
get: () => core.call("location.get")
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
function mediaModule(core) {
|
|
388
|
+
return {
|
|
389
|
+
/** `dataUrl` must be a `data:image/...` URL. */
|
|
390
|
+
saveImage: (dataUrl) => core.call("media.saveImage", { dataUrl })
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// src/share-image.ts
|
|
395
|
+
var SHARE_IMAGE_LIMITS = {
|
|
396
|
+
maxBytes: 2 * 1024 * 1024,
|
|
397
|
+
maxSide: 2048,
|
|
398
|
+
types: ["image/png", "image/jpeg", "image/webp"]
|
|
399
|
+
};
|
|
400
|
+
var DATA_URL = /^data:([^;,]+);base64,/;
|
|
401
|
+
var BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
402
|
+
var MAX_ENCODED = Math.ceil(SHARE_IMAGE_LIMITS.maxBytes / 3) * 4;
|
|
403
|
+
function checkShareImage(image) {
|
|
404
|
+
if (typeof image !== "string") return { ok: false, reason: "image must be a data: URL string" };
|
|
405
|
+
const head = DATA_URL.exec(image.slice(0, 40));
|
|
406
|
+
if (!head) return { ok: false, reason: "image must be a base64 data: URL" };
|
|
407
|
+
const type = SHARE_IMAGE_LIMITS.types.find((t) => t === head[1]);
|
|
408
|
+
if (!type)
|
|
409
|
+
return { ok: false, reason: `image type must be ${SHARE_IMAGE_LIMITS.types.join(", ")}` };
|
|
410
|
+
const body = image.slice(head[0].length);
|
|
411
|
+
if (body.length > MAX_ENCODED)
|
|
412
|
+
return { ok: false, reason: `image is over ${SHARE_IMAGE_LIMITS.maxBytes} bytes` };
|
|
413
|
+
if (body.length === 0 || body.length % 4 !== 0 || !BASE64.test(body))
|
|
414
|
+
return { ok: false, reason: "image is not valid base64" };
|
|
415
|
+
const bytes = body.length / 4 * 3 - (body.endsWith("==") ? 2 : body.endsWith("=") ? 1 : 0);
|
|
416
|
+
if (bytes > SHARE_IMAGE_LIMITS.maxBytes)
|
|
417
|
+
return { ok: false, reason: `image is over ${SHARE_IMAGE_LIMITS.maxBytes} bytes` };
|
|
418
|
+
return { ok: true, type, bytes };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// src/validate.ts
|
|
422
|
+
function invalid(reason) {
|
|
423
|
+
throw new MiniAppError("INVALID_PARAMS", reason);
|
|
424
|
+
}
|
|
425
|
+
function requiredString(p, name) {
|
|
426
|
+
const v = p[name];
|
|
427
|
+
return typeof v === "string" ? v : invalid(`${name} must be a string`);
|
|
428
|
+
}
|
|
429
|
+
var optionalString = (p, name) => p[name] === void 0 ? void 0 : requiredString(p, name);
|
|
430
|
+
var isNonBlank = (v) => typeof v === "string" && v.trim() !== "";
|
|
431
|
+
function shareText(p, required) {
|
|
432
|
+
const text = required ? requiredString(p, "text") : optionalString(p, "text");
|
|
433
|
+
if (text !== void 0 && !isNonBlank(text)) invalid("text must not be empty");
|
|
434
|
+
}
|
|
435
|
+
function oneOf(p, name, values) {
|
|
436
|
+
const v = p[name];
|
|
437
|
+
return values.find((x) => x === v) ?? invalid(`${name} must be one of ${values.join(", ")}`);
|
|
438
|
+
}
|
|
439
|
+
function hexColor(p) {
|
|
440
|
+
const v = p.color;
|
|
441
|
+
return typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v) ? v : invalid("color must be #rrggbb");
|
|
442
|
+
}
|
|
443
|
+
function progress(p) {
|
|
444
|
+
const v = p.progress;
|
|
445
|
+
return typeof v === "number" && Number.isFinite(v) ? Math.max(0, Math.min(100, v)) : invalid("progress must be a number from 0 to 100");
|
|
446
|
+
}
|
|
447
|
+
function webUrl(p, name = "url") {
|
|
448
|
+
const v = p[name];
|
|
449
|
+
if (typeof v === "string") {
|
|
450
|
+
try {
|
|
451
|
+
const url = new URL(v);
|
|
452
|
+
if (url.protocol === "https:" || url.protocol === "http:") return url.href;
|
|
453
|
+
} catch {
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return invalid(`${name} must be an http(s) URL`);
|
|
457
|
+
}
|
|
458
|
+
function startParam(p) {
|
|
459
|
+
const v = p.startParam;
|
|
460
|
+
if (v === void 0) return void 0;
|
|
461
|
+
return typeof v === "string" && START_PARAM_PATTERN.test(v) ? v : invalid("startParam must be 1-64 chars of [A-Za-z0-9_-]");
|
|
462
|
+
}
|
|
463
|
+
function storyContent(p) {
|
|
464
|
+
const text = optionalString(p, "text");
|
|
465
|
+
if (text === void 0) {
|
|
466
|
+
if (p.image === void 0) invalid("a story needs an image or text");
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
const n = text.trim().length;
|
|
470
|
+
if (n < 1 || n > STORY_TEXT_MAX) invalid(`text must be 1-${STORY_TEXT_MAX} chars`);
|
|
471
|
+
}
|
|
472
|
+
var permissionName = (p) => oneOf(p, "name", PERMISSION_NAMES);
|
|
473
|
+
function popupButtons(p) {
|
|
474
|
+
const v = p.buttons;
|
|
475
|
+
if (!Array.isArray(v) || v.length === 0 || v.length > 3) invalid("buttons must hold 1-3 buttons");
|
|
476
|
+
return v.map((b) => {
|
|
477
|
+
const bp = isRecord(b) ? b : {};
|
|
478
|
+
const type = bp.type === "cancel" || bp.type === "destructive" ? bp.type : "default";
|
|
479
|
+
return { id: requiredString(bp, "id"), text: requiredString(bp, "text"), type };
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
function analyticsEvent(p) {
|
|
483
|
+
const name = requiredString(p, "name");
|
|
484
|
+
if (name.length === 0) invalid("name must not be empty");
|
|
485
|
+
const props = p.props ?? {};
|
|
486
|
+
if (!isRecord(props) || Array.isArray(props)) return invalid("props must be an object");
|
|
487
|
+
for (const [k, v] of Object.entries(props)) {
|
|
488
|
+
if (typeof v !== "string" && typeof v !== "boolean" && !(typeof v === "number" && Number.isFinite(v)))
|
|
489
|
+
invalid(`props.${k} must be a string, number or boolean`);
|
|
490
|
+
}
|
|
491
|
+
return { name, props };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// src/modules/links.ts
|
|
495
|
+
function linkModule(core) {
|
|
496
|
+
return { open: (url) => core.call("link.open", { url }) };
|
|
497
|
+
}
|
|
498
|
+
function clipboardModule(core) {
|
|
499
|
+
return {
|
|
500
|
+
writeText: (text) => core.call("clipboard.writeText", { text }),
|
|
501
|
+
readText: async () => (await core.call("clipboard.readText")).text
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
function share(core, method, p, text) {
|
|
505
|
+
if (text && (p.text !== void 0 || text === "required") && !isNonBlank(p.text))
|
|
506
|
+
return Promise.reject(new MiniAppError("INVALID_PARAMS", "text must not be empty"));
|
|
507
|
+
if (p.image !== void 0) {
|
|
508
|
+
const c = checkShareImage(p.image);
|
|
509
|
+
if (!c.ok) return Promise.reject(new MiniAppError("INVALID_PARAMS", c.reason));
|
|
510
|
+
}
|
|
511
|
+
return core.call(method, p);
|
|
512
|
+
}
|
|
513
|
+
function shareModule(core) {
|
|
514
|
+
return {
|
|
515
|
+
/** The OS share sheet; resolves once it closes. */
|
|
516
|
+
system: (p) => share(core, "share.system", p),
|
|
517
|
+
/** The user picks chats; the message is sent as the user. */
|
|
518
|
+
toChat: (p) => share(core, "share.toChat", p, "required"),
|
|
519
|
+
/** IdolChat's post composer, prefilled with the text, image and the app's card. */
|
|
520
|
+
toPost: (p) => share(core, "share.toPost", p, "nonBlank"),
|
|
521
|
+
/** IdolChat's story composer; a story needs `image` or `text` (1โ500 chars). */
|
|
522
|
+
toStory: (p) => share(core, "share.toStory", p, "nonBlank")
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
function analyticsModule(core) {
|
|
526
|
+
return {
|
|
527
|
+
track: (name, props) => core.call("analytics.track", { name, props })
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// src/modules/platform.ts
|
|
532
|
+
var withProfile = (u) => u && (u.displayName ?? u.avatarUrl ?? u.locale) !== void 0 ? u : null;
|
|
533
|
+
function authModule(core) {
|
|
534
|
+
let profileAsk;
|
|
535
|
+
const askProfile = async () => {
|
|
536
|
+
const init = await core.init();
|
|
537
|
+
if (!core.supports("auth.requestProfile")) return { user: withProfile(init.user) };
|
|
538
|
+
const r = await core.call("auth.requestProfile");
|
|
539
|
+
return { user: parseUser(r?.user) };
|
|
540
|
+
};
|
|
541
|
+
return {
|
|
542
|
+
/** A fresh EdDSA JWT for the app's server to verify (protocol ยง7); `nonce` is echoed. */
|
|
543
|
+
getLaunchToken: async (p = {}) => (await core.call("auth.getLaunchToken", p)).token,
|
|
544
|
+
/**
|
|
545
|
+
* The user's name and avatar, asking the first time (ADR-0030); `user` is null when refused.
|
|
546
|
+
* A host that does not list the method asked at open, so its `app.init` user is the answer.
|
|
547
|
+
* Concurrent calls share one request, as they share the host's one dialog.
|
|
548
|
+
*/
|
|
549
|
+
requestProfile: () => profileAsk ?? (profileAsk = askProfile().finally(() => {
|
|
550
|
+
profileAsk = void 0;
|
|
551
|
+
}))
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
function paymentModule(core) {
|
|
555
|
+
return {
|
|
556
|
+
/** IdolChat's confirm dialog for your server's invoice; grant from the webhook, never this result. */
|
|
557
|
+
open: (p) => core.call("payment.open", p)
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
function notificationsModule(core) {
|
|
561
|
+
return {
|
|
562
|
+
/** Prompts the user; the host records the answer so the app's server may notify this user. */
|
|
563
|
+
requestPermission: () => core.call("notifications.requestPermission"),
|
|
564
|
+
/** Never prompts. */
|
|
565
|
+
getPermission: () => core.call("notifications.getPermission")
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function adsModule(core) {
|
|
569
|
+
return {
|
|
570
|
+
loadRewarded: (placement) => core.call("ads.loadRewarded", { placement }),
|
|
571
|
+
showRewarded: (placement) => core.call("ads.showRewarded", { placement }),
|
|
572
|
+
loadInterstitial: (placement) => core.call("ads.loadInterstitial", { placement }),
|
|
573
|
+
showInterstitial: (placement) => core.call("ads.showInterstitial", { placement }),
|
|
574
|
+
showBanner: (p) => core.call("ads.showBanner", p),
|
|
575
|
+
hideBanner: () => core.call("ads.hideBanner"),
|
|
576
|
+
on: (name, cb) => core.on(name, cb),
|
|
577
|
+
/** The host asks before an ad break; resolve once the app is paused. */
|
|
578
|
+
onBeforeBreak: (handler) => core.onRequest("ads.beforeBreak", handler)
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// src/modules/storage.ts
|
|
583
|
+
function storageModule(core) {
|
|
584
|
+
return {
|
|
585
|
+
get: async (key2) => (await core.call("storage.get", { key: key2 })).value ?? null,
|
|
586
|
+
getMany: async (keys) => (await core.call("storage.getMany", { keys })).values,
|
|
587
|
+
set: (key2, value) => core.call("storage.set", { key: key2, value }),
|
|
588
|
+
remove: (key2) => core.call("storage.remove", { key: key2 }),
|
|
589
|
+
keys: async () => (await core.call("storage.keys")).keys,
|
|
590
|
+
clear: () => core.call("storage.clear")
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// src/modules/ui.ts
|
|
595
|
+
function uiModule(core) {
|
|
596
|
+
return {
|
|
597
|
+
showToast: (p) => core.call("ui.showToast", p),
|
|
598
|
+
showAlert: (p) => core.call("ui.showAlert", p),
|
|
599
|
+
showConfirm: (p) => core.call("ui.showConfirm", p),
|
|
600
|
+
showPopup: (p) => core.call("ui.showPopup", p),
|
|
601
|
+
setBackButtonVisible: (visible) => core.call("ui.setBackButtonVisible", { visible }),
|
|
602
|
+
setHeaderColor: (color) => core.call("ui.setHeaderColor", { color }),
|
|
603
|
+
setBackgroundColor: (color) => core.call("ui.setBackgroundColor", { color }),
|
|
604
|
+
setOrientation: (orientation) => core.call("ui.setOrientation", { orientation }),
|
|
605
|
+
getTheme: () => core.call("ui.getTheme"),
|
|
606
|
+
onBackButtonPressed: (cb) => core.on("ui.backButtonPressed", cb),
|
|
607
|
+
onThemeChanged: (cb) => core.on("ui.themeChanged", cb),
|
|
608
|
+
onViewportChanged: (cb) => core.on("ui.viewportChanged", cb)
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
function hapticModule(core) {
|
|
612
|
+
return {
|
|
613
|
+
impact: (style = "medium") => core.call("haptic.impact", { style }),
|
|
614
|
+
notification: (type) => core.call("haptic.notification", { type }),
|
|
615
|
+
selection: () => core.call("haptic.selection")
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// src/client.ts
|
|
620
|
+
var SDK_VERSION = "0.1.0";
|
|
621
|
+
function createMiniApp(transport, opts) {
|
|
622
|
+
const core = new MiniAppCore(transport, opts);
|
|
623
|
+
return {
|
|
624
|
+
version: SDK_VERSION,
|
|
625
|
+
transport: transport.name,
|
|
626
|
+
supports: (method) => core.supports(method),
|
|
627
|
+
call: (method, params, o) => core.call(method, params, o),
|
|
628
|
+
on: (name, cb) => core.on(name, cb),
|
|
629
|
+
app: appModule(core),
|
|
630
|
+
lifecycle: lifecycleModule(core),
|
|
631
|
+
ui: uiModule(core),
|
|
632
|
+
haptic: hapticModule(core),
|
|
633
|
+
storage: storageModule(core),
|
|
634
|
+
link: linkModule(core),
|
|
635
|
+
clipboard: clipboardModule(core),
|
|
636
|
+
share: shareModule(core),
|
|
637
|
+
analytics: analyticsModule(core),
|
|
638
|
+
device: deviceModule(core),
|
|
639
|
+
permissions: permissionsModule(core),
|
|
640
|
+
qr: qrModule(core),
|
|
641
|
+
location: locationModule(core),
|
|
642
|
+
media: mediaModule(core),
|
|
643
|
+
auth: authModule(core),
|
|
644
|
+
payment: paymentModule(core),
|
|
645
|
+
notifications: notificationsModule(core),
|
|
646
|
+
ads: adsModule(core)
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/transport/native.ts
|
|
651
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
652
|
+
function listenNative(win, onMessage) {
|
|
653
|
+
win.__idcMiniApp ?? (win.__idcMiniApp = {
|
|
654
|
+
_dispatch(raw) {
|
|
655
|
+
for (const l of listeners) l(raw);
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
listeners.add(onMessage);
|
|
659
|
+
return () => listeners.delete(onMessage);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// src/transport/android.ts
|
|
663
|
+
var isAndroid = (win) => typeof win.MiniAppAndroid?.call === "function";
|
|
664
|
+
function createAndroidTransport(win) {
|
|
665
|
+
return {
|
|
666
|
+
name: "android",
|
|
667
|
+
send: (msg) => win.MiniAppAndroid?.call(JSON.stringify(msg)),
|
|
668
|
+
listen: (onMessage) => listenNative(win, onMessage)
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// src/transport/ios.ts
|
|
673
|
+
var isIos = (win) => typeof win.webkit?.messageHandlers?.miniapp?.postMessage === "function";
|
|
674
|
+
function createIosTransport(win) {
|
|
675
|
+
return {
|
|
676
|
+
name: "ios",
|
|
677
|
+
send: (msg) => win.webkit?.messageHandlers?.miniapp?.postMessage(JSON.stringify(msg)),
|
|
678
|
+
listen: (onMessage) => listenNative(win, onMessage)
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// src/transport/sha256.ts
|
|
683
|
+
var rotr = (x, n) => x >>> n | x << 32 - n;
|
|
684
|
+
var frac32 = (x) => (x - Math.floor(x)) * 2 ** 32 >>> 0;
|
|
685
|
+
var PRIMES = [];
|
|
686
|
+
for (let n = 2; PRIMES.length < 64; n++) if (PRIMES.every((p) => n % p !== 0)) PRIMES.push(n);
|
|
687
|
+
var K = Uint32Array.from(PRIMES, (p) => frac32(Math.cbrt(p)));
|
|
688
|
+
var H0 = Uint32Array.from(PRIMES.slice(0, 8), (p) => frac32(Math.sqrt(p)));
|
|
689
|
+
function sha256(data) {
|
|
690
|
+
const size = data.length + 72 & ~63;
|
|
691
|
+
const buf = new Uint8Array(size);
|
|
692
|
+
buf.set(data);
|
|
693
|
+
buf[data.length] = 128;
|
|
694
|
+
const view = new DataView(buf.buffer);
|
|
695
|
+
view.setUint32(size - 8, Math.floor(data.length / 2 ** 29));
|
|
696
|
+
view.setUint32(size - 4, data.length * 8 >>> 0);
|
|
697
|
+
const h = Uint32Array.from(H0);
|
|
698
|
+
const w = new Uint32Array(64);
|
|
699
|
+
const s = new Uint32Array(8);
|
|
700
|
+
for (let off = 0; off < size; off += 64) {
|
|
701
|
+
for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);
|
|
702
|
+
for (let i = 16; i < 64; i++) {
|
|
703
|
+
const a = w[i - 15];
|
|
704
|
+
const b = w[i - 2];
|
|
705
|
+
w[i] = w[i - 16] + (rotr(a, 7) ^ rotr(a, 18) ^ a >>> 3) + w[i - 7] + (rotr(b, 17) ^ rotr(b, 19) ^ b >>> 10);
|
|
706
|
+
}
|
|
707
|
+
s.set(h);
|
|
708
|
+
for (let i = 0; i < 64; i++) {
|
|
709
|
+
const [a, b, c, d, e, f, g, hh] = Array.from(s);
|
|
710
|
+
const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i];
|
|
711
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c);
|
|
712
|
+
s.set([t1 + t2, a, b, c, d + t1, e, f, g]);
|
|
713
|
+
}
|
|
714
|
+
for (let i = 0; i < 8; i++) h[i] = h[i] + s[i];
|
|
715
|
+
}
|
|
716
|
+
const out = new Uint8Array(32);
|
|
717
|
+
const outView = new DataView(out.buffer);
|
|
718
|
+
for (let i = 0; i < 8; i++) outView.setUint32(i * 4, h[i]);
|
|
719
|
+
return out;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/transport/mock.ts
|
|
723
|
+
var NS = "idcMiniApp:";
|
|
724
|
+
var utf8 = new TextEncoder();
|
|
725
|
+
var GESTURE_EVENTS = ["pointerup", "touchend", "keydown", "click"];
|
|
726
|
+
var MOCK_AVATAR = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGN46uELAAOQAXsmNkYKAAAAAElFTkSuQmCC";
|
|
727
|
+
var MOCK_USER = {
|
|
728
|
+
id: "mockUserId_00000000000",
|
|
729
|
+
displayName: "Mock User",
|
|
730
|
+
avatarUrl: MOCK_AVATAR,
|
|
731
|
+
locale: "en"
|
|
732
|
+
};
|
|
733
|
+
var MOCK_USER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
|
|
734
|
+
function mockUser(name) {
|
|
735
|
+
if (name === void 0) return MOCK_USER;
|
|
736
|
+
const digest = sha256(utf8.encode(name));
|
|
737
|
+
const id = btoa(String.fromCharCode(...digest)).replace(/\+/g, "-").replace(/\//g, "_").slice(0, 22);
|
|
738
|
+
return { ...MOCK_USER, id, displayName: `Mock User ${name}` };
|
|
739
|
+
}
|
|
740
|
+
var CLOSE_TIMEOUT_MS = 3e3;
|
|
741
|
+
function checkShare(p) {
|
|
742
|
+
startParam(p);
|
|
743
|
+
if (p.url !== void 0) webUrl(p);
|
|
744
|
+
if (p.image !== void 0) {
|
|
745
|
+
const c = checkShareImage(p.image);
|
|
746
|
+
if (!c.ok) invalid(c.reason);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
function memoryStorage() {
|
|
750
|
+
const m = /* @__PURE__ */ new Map();
|
|
751
|
+
return {
|
|
752
|
+
getItem: (k) => m.get(k) ?? null,
|
|
753
|
+
setItem: (k, v) => void m.set(k, v),
|
|
754
|
+
removeItem: (k) => void m.delete(k),
|
|
755
|
+
key: (i) => [...m.keys()][i] ?? null,
|
|
756
|
+
get length() {
|
|
757
|
+
return m.size;
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
function key(p) {
|
|
762
|
+
const k = p.key;
|
|
763
|
+
if (typeof k !== "string" || k.length === 0 || k.length > STORAGE_KEY_MAX)
|
|
764
|
+
invalid(`key must be a 1-${STORAGE_KEY_MAX} char string`);
|
|
765
|
+
return k;
|
|
766
|
+
}
|
|
767
|
+
var heading = (p) => {
|
|
768
|
+
const title = optionalString(p, "title");
|
|
769
|
+
const message = requiredString(p, "message");
|
|
770
|
+
return title === void 0 ? message : `${title}
|
|
771
|
+
|
|
772
|
+
${message}`;
|
|
773
|
+
};
|
|
774
|
+
function pickButton(buttons, answer) {
|
|
775
|
+
if (answer === null) return null;
|
|
776
|
+
const a = answer.trim().toLowerCase();
|
|
777
|
+
const b = buttons.find(
|
|
778
|
+
(x, i) => String(i + 1) === a || x.id.toLowerCase() === a || x.text.toLowerCase() === a
|
|
779
|
+
);
|
|
780
|
+
return b?.id ?? null;
|
|
781
|
+
}
|
|
782
|
+
function createMockTransport(opts = {}) {
|
|
783
|
+
const store = opts.storage ?? memoryStorage();
|
|
784
|
+
const limit = opts.limitBytes ?? STORAGE_LIMIT_BYTES;
|
|
785
|
+
const now = opts.now ?? Date.now;
|
|
786
|
+
const dialogs = opts.dialogs;
|
|
787
|
+
const userName = opts.userName !== void 0 && MOCK_USER_NAME_PATTERN.test(opts.userName) ? opts.userName : void 0;
|
|
788
|
+
const user = opts.user === void 0 ? mockUser(userName) : opts.user;
|
|
789
|
+
const profileUser = async () => {
|
|
790
|
+
const url = opts.user === void 0 ? await opts.avatar?.catch(() => null) : null;
|
|
791
|
+
return user && url ? { ...user, avatarUrl: url } : user;
|
|
792
|
+
};
|
|
793
|
+
let notifications = opts.notifications ?? "prompt";
|
|
794
|
+
const setNotifications = (state) => {
|
|
795
|
+
notifications = state;
|
|
796
|
+
opts.onNotificationsConsent?.(state, userName);
|
|
797
|
+
};
|
|
798
|
+
setNotifications(notifications);
|
|
799
|
+
let profile = user === null ? "denied" : opts.profile ?? "prompt";
|
|
800
|
+
let clipboard = "";
|
|
801
|
+
let colorScheme = opts.colorScheme ?? "light";
|
|
802
|
+
let backButton = false;
|
|
803
|
+
let seq = 0;
|
|
804
|
+
const replies = /* @__PURE__ */ new Map();
|
|
805
|
+
let scopes = null;
|
|
806
|
+
let reasons = {};
|
|
807
|
+
let mint = null;
|
|
808
|
+
const settled = Promise.all([
|
|
809
|
+
Promise.resolve(opts.scopes).then(
|
|
810
|
+
(s) => void (scopes = s ? new Set(s) : null),
|
|
811
|
+
() => void 0
|
|
812
|
+
),
|
|
813
|
+
Promise.resolve(opts.permissionReasons).then(
|
|
814
|
+
(r) => void (reasons = r ?? {}),
|
|
815
|
+
() => void 0
|
|
816
|
+
),
|
|
817
|
+
Promise.resolve(opts.launchTokens).then(
|
|
818
|
+
(m) => void (mint = user ? m ?? null : null),
|
|
819
|
+
() => void 0
|
|
820
|
+
)
|
|
821
|
+
]);
|
|
822
|
+
const withReason = (question, name) => reasons[name] ? `${question}
|
|
823
|
+
|
|
824
|
+
${reasons[name]}` : question;
|
|
825
|
+
const hasScope = (name) => scopes === null || scopes.has(name);
|
|
826
|
+
let lastGestureAt = Number.NEGATIVE_INFINITY;
|
|
827
|
+
const listeners2 = /* @__PURE__ */ new Set();
|
|
828
|
+
const deliver = (msg) => setTimeout(() => listeners2.forEach((l) => l(msg)), 0);
|
|
829
|
+
const emit = (name, data) => deliver({ v: 1, type: "event", name, data });
|
|
830
|
+
const ownKeys = () => {
|
|
831
|
+
const out = [];
|
|
832
|
+
for (let i = 0; i < store.length; i++) {
|
|
833
|
+
const k = store.key(i);
|
|
834
|
+
if (k?.startsWith(NS)) out.push(k.slice(NS.length));
|
|
835
|
+
}
|
|
836
|
+
return out;
|
|
837
|
+
};
|
|
838
|
+
const usedBytes = (except) => ownKeys().filter((k) => k !== except).reduce(
|
|
839
|
+
(n, k) => n + utf8.encode(k).length + utf8.encode(store.getItem(NS + k) ?? "").length,
|
|
840
|
+
0
|
|
841
|
+
);
|
|
842
|
+
const requestNotifications = () => {
|
|
843
|
+
if (notifications !== "prompt") return notifications;
|
|
844
|
+
const yes = dialogs ? dialogs.confirm(withReason("Allow this app to send you notifications?", "notifications")) : true;
|
|
845
|
+
setNotifications(yes ? "granted" : "denied");
|
|
846
|
+
emit("permissions.changed", { name: "notifications", state: notifications });
|
|
847
|
+
return notifications;
|
|
848
|
+
};
|
|
849
|
+
const requestProfile = () => {
|
|
850
|
+
if (profile !== "prompt") return profile;
|
|
851
|
+
const yes = dialogs ? dialogs.confirm(withReason("Allow this app to see your name and avatar?", "profile")) : true;
|
|
852
|
+
profile = yes ? "granted" : "denied";
|
|
853
|
+
emit("permissions.changed", { name: "profile", state: profile });
|
|
854
|
+
return profile;
|
|
855
|
+
};
|
|
856
|
+
const permissionState = (p, request) => {
|
|
857
|
+
const name = permissionName(p);
|
|
858
|
+
if (!hasScope(name)) return { state: "unavailable" };
|
|
859
|
+
if (name === "notifications")
|
|
860
|
+
return { state: request ? requestNotifications() : notifications };
|
|
861
|
+
if (name === "profile") return { state: request ? requestProfile() : profile };
|
|
862
|
+
return { state: "unavailable" };
|
|
863
|
+
};
|
|
864
|
+
const handlers = {
|
|
865
|
+
"app.ready": () => null,
|
|
866
|
+
"app.setLoadingProgress": (p) => (progress(p), null),
|
|
867
|
+
"app.close": () => null,
|
|
868
|
+
"ui.showToast": (p) => (requiredString(p, "message"), null),
|
|
869
|
+
"ui.showAlert": (p) => {
|
|
870
|
+
const text = heading(p);
|
|
871
|
+
dialogs?.alert(text);
|
|
872
|
+
return null;
|
|
873
|
+
},
|
|
874
|
+
"ui.showConfirm": (p) => {
|
|
875
|
+
const text = heading(p);
|
|
876
|
+
return { confirmed: dialogs ? dialogs.confirm(text) : true };
|
|
877
|
+
},
|
|
878
|
+
"ui.showPopup": (p) => {
|
|
879
|
+
const text = heading(p);
|
|
880
|
+
const buttons = popupButtons(p);
|
|
881
|
+
if (!dialogs) return { buttonId: buttons[0]?.id ?? null };
|
|
882
|
+
const list = buttons.map((b, i) => `${i + 1}. ${b.text}`).join("\n");
|
|
883
|
+
const hint = `
|
|
884
|
+
|
|
885
|
+
Pick 1-${buttons.length}, or Cancel to dismiss.`;
|
|
886
|
+
const unknown = (a) => pickButton(buttons, a) === null && !!a?.trim();
|
|
887
|
+
let answer = dialogs.prompt(`${text}
|
|
888
|
+
|
|
889
|
+
${list}`, "1");
|
|
890
|
+
if (unknown(answer)) answer = dialogs.prompt(`${text}
|
|
891
|
+
|
|
892
|
+
${list}${hint}`, "1");
|
|
893
|
+
if (unknown(answer))
|
|
894
|
+
console.warn(
|
|
895
|
+
`[miniapp-sdk] ui.showPopup: "${answer}" matches no button, treated as dismissed`
|
|
896
|
+
);
|
|
897
|
+
return { buttonId: pickButton(buttons, answer) };
|
|
898
|
+
},
|
|
899
|
+
"ui.setBackButtonVisible": (p) => {
|
|
900
|
+
if (typeof p.visible !== "boolean") invalid("visible must be a boolean");
|
|
901
|
+
backButton = p.visible;
|
|
902
|
+
return null;
|
|
903
|
+
},
|
|
904
|
+
"ui.setHeaderColor": (p) => (hexColor(p), null),
|
|
905
|
+
"ui.setBackgroundColor": (p) => (hexColor(p), null),
|
|
906
|
+
"ui.setOrientation": (p) => (oneOf(p, "orientation", ["portrait", "landscape", "auto"]), null),
|
|
907
|
+
"ui.getTheme": () => ({ colorScheme }),
|
|
908
|
+
"haptic.impact": (p) => (oneOf(p, "style", ["light", "medium", "heavy"]), null),
|
|
909
|
+
"haptic.notification": (p) => (oneOf(p, "type", ["success", "warning", "error"]), null),
|
|
910
|
+
"haptic.selection": () => null,
|
|
911
|
+
"storage.get": (p) => ({ value: store.getItem(NS + key(p)) }),
|
|
912
|
+
"storage.getMany": (p) => {
|
|
913
|
+
if (!Array.isArray(p.keys)) invalid("keys must be an array");
|
|
914
|
+
const values = {};
|
|
915
|
+
for (const k of p.keys) values[key({ key: k })] = store.getItem(NS + String(k));
|
|
916
|
+
return { values };
|
|
917
|
+
},
|
|
918
|
+
"storage.set": (p) => {
|
|
919
|
+
const k = key(p);
|
|
920
|
+
const value = requiredString(p, "value");
|
|
921
|
+
if (usedBytes(k) + utf8.encode(k).length + utf8.encode(value).length > limit)
|
|
922
|
+
throw new MiniAppError("QUOTA_EXCEEDED", `storage is limited to ${limit} bytes`);
|
|
923
|
+
store.setItem(NS + k, value);
|
|
924
|
+
return null;
|
|
925
|
+
},
|
|
926
|
+
"storage.remove": (p) => (store.removeItem(NS + key(p)), null),
|
|
927
|
+
"storage.keys": () => ({ keys: ownKeys() }),
|
|
928
|
+
"storage.clear": () => (ownKeys().forEach((k) => store.removeItem(NS + k)), null),
|
|
929
|
+
"link.open": (p) => {
|
|
930
|
+
const url = webUrl(p);
|
|
931
|
+
dialogs?.open(url, "_blank", "noopener,noreferrer");
|
|
932
|
+
return null;
|
|
933
|
+
},
|
|
934
|
+
// Simulated, as in Play: an app under test never reads or overwrites the real clipboard.
|
|
935
|
+
"clipboard.writeText": (p) => (clipboard = requiredString(p, "text"), null),
|
|
936
|
+
"clipboard.readText": () => ({ text: clipboard }),
|
|
937
|
+
"share.toChat": (p) => {
|
|
938
|
+
shareText(p, true);
|
|
939
|
+
checkShare(p);
|
|
940
|
+
opts.onShare?.("share.toChat", p);
|
|
941
|
+
return { shared: true };
|
|
942
|
+
},
|
|
943
|
+
// The user publishes or cancels in IdolChat's composer; a declined confirm is the cancel.
|
|
944
|
+
"share.toPost": (p) => {
|
|
945
|
+
shareText(p, false);
|
|
946
|
+
const text = optionalString(p, "text");
|
|
947
|
+
checkShare(p);
|
|
948
|
+
if (dialogs && !dialogs.confirm(`Share to your IdolChat feed?
|
|
949
|
+
|
|
950
|
+
${text ?? ""}`))
|
|
951
|
+
return { shared: false };
|
|
952
|
+
opts.onShare?.("share.toPost", p);
|
|
953
|
+
return { shared: true };
|
|
954
|
+
},
|
|
955
|
+
"share.toStory": (p) => {
|
|
956
|
+
const text = optionalString(p, "text");
|
|
957
|
+
storyContent(p);
|
|
958
|
+
checkShare(p);
|
|
959
|
+
if (dialogs && !dialogs.confirm(`Share to your IdolChat story?
|
|
960
|
+
|
|
961
|
+
${text ?? ""}`))
|
|
962
|
+
return { shared: false };
|
|
963
|
+
opts.onShare?.("share.toStory", p);
|
|
964
|
+
return { shared: true };
|
|
965
|
+
},
|
|
966
|
+
"share.system": (p) => {
|
|
967
|
+
optionalString(p, "text");
|
|
968
|
+
optionalString(p, "title");
|
|
969
|
+
checkShare(p);
|
|
970
|
+
opts.onShare?.("share.system", p);
|
|
971
|
+
return null;
|
|
972
|
+
},
|
|
973
|
+
"analytics.track": (p) => (analyticsEvent(p), null),
|
|
974
|
+
// No invoice is read and nothing is charged: the app's server still grants only from its webhook.
|
|
975
|
+
"payment.open": (p) => {
|
|
976
|
+
const invoiceId = requiredString(p, "invoiceId");
|
|
977
|
+
if (!/^inv_[A-Za-z0-9_-]{22}$/.test(invoiceId)) invalid("invoiceId is not an invoice id");
|
|
978
|
+
if (dialogs && !dialogs.confirm(`Pay invoice ${invoiceId}? (mock: no stars move)`))
|
|
979
|
+
return { status: "cancelled" };
|
|
980
|
+
return { status: opts.payment ?? "paid" };
|
|
981
|
+
},
|
|
982
|
+
"device.getInfo": () => ({
|
|
983
|
+
platform: "web",
|
|
984
|
+
hostVersion: "mock",
|
|
985
|
+
safeArea: { top: 0, bottom: 0, left: 0, right: 0 }
|
|
986
|
+
}),
|
|
987
|
+
"permissions.query": (p) => permissionState(p, false),
|
|
988
|
+
"permissions.request": (p) => permissionState(p, true),
|
|
989
|
+
"notifications.requestPermission": () => ({ state: requestNotifications() }),
|
|
990
|
+
"notifications.getPermission": () => ({
|
|
991
|
+
state: hasScope("notifications") ? notifications : "unavailable"
|
|
992
|
+
}),
|
|
993
|
+
"auth.requestProfile": async () => ({
|
|
994
|
+
user: requestProfile() === "granted" ? await profileUser() : null
|
|
995
|
+
})
|
|
996
|
+
};
|
|
997
|
+
const profileGranted = () => hasScope("profile") && profile === "granted";
|
|
998
|
+
const launchToken = async (p) => {
|
|
999
|
+
const nonce = optionalString(p, "nonce");
|
|
1000
|
+
if (nonce !== void 0 && !LAUNCH_NONCE_PATTERN.test(nonce))
|
|
1001
|
+
invalid("nonce must be 1-64 chars of [A-Za-z0-9_-]");
|
|
1002
|
+
if (!mint) throw new MiniAppError("METHOD_NOT_SUPPORTED", "no launch tokens here");
|
|
1003
|
+
try {
|
|
1004
|
+
return {
|
|
1005
|
+
token: await mint({
|
|
1006
|
+
...nonce === void 0 ? {} : { nonce },
|
|
1007
|
+
profile: profileGranted(),
|
|
1008
|
+
...userName === void 0 || opts.user !== void 0 ? {} : { user: userName }
|
|
1009
|
+
})
|
|
1010
|
+
};
|
|
1011
|
+
} catch (err) {
|
|
1012
|
+
throw new MiniAppError("INTERNAL_ERROR", `launch token: ${String(err)}`);
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
handlers["app.init"] = async () => ({
|
|
1016
|
+
protocol: 1,
|
|
1017
|
+
methods: [...Object.keys(handlers), ...mint ? ["auth.getLaunchToken"] : []].filter((m) => {
|
|
1018
|
+
const scope = scopeOf(m);
|
|
1019
|
+
return scope === void 0 || hasScope(scope);
|
|
1020
|
+
}),
|
|
1021
|
+
limits: { storageBytes: limit },
|
|
1022
|
+
// A host listing auth.requestProfile sends the name and avatar only once granted (ADR-0030).
|
|
1023
|
+
user: user && (profileGranted() ? await profileUser() : { id: user.id }),
|
|
1024
|
+
startParam: opts.startParam ?? null,
|
|
1025
|
+
launchToken: mint ? (await launchToken({}).catch(() => null))?.token ?? null : null
|
|
1026
|
+
});
|
|
1027
|
+
const known = new Set(METHODS);
|
|
1028
|
+
const handle = (msg) => {
|
|
1029
|
+
if (msg.method === "_reply") {
|
|
1030
|
+
const id = isRecord(msg.params) ? msg.params.id : void 0;
|
|
1031
|
+
if (typeof id === "string") replies.get(id)?.();
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
const fail = (err) => {
|
|
1035
|
+
const e = err instanceof MiniAppError ? err : new MiniAppError("INTERNAL_ERROR", String(err));
|
|
1036
|
+
deliver({ v: 1, type: "result", id: msg.id, ok: false, error: e.toWire() });
|
|
1037
|
+
};
|
|
1038
|
+
const gestured = now() - lastGestureAt <= GESTURE_WINDOW_MS;
|
|
1039
|
+
void settled.then(() => run(msg, gestured, fail));
|
|
1040
|
+
};
|
|
1041
|
+
const run = (msg, gestured, fail) => {
|
|
1042
|
+
try {
|
|
1043
|
+
const scope = scopeOf(msg.method);
|
|
1044
|
+
if (scope !== void 0 && !hasScope(scope))
|
|
1045
|
+
throw new MiniAppError("PERMISSION_DENIED", `no ${scope} scope`);
|
|
1046
|
+
const handler = msg.method === "auth.getLaunchToken" && mint ? launchToken : handlers[msg.method];
|
|
1047
|
+
if (handler === void 0)
|
|
1048
|
+
throw new MiniAppError(
|
|
1049
|
+
"METHOD_NOT_SUPPORTED",
|
|
1050
|
+
known.has(msg.method) ? `${msg.method} can only be tested inside IdolChat` : `unknown method ${msg.method}`
|
|
1051
|
+
);
|
|
1052
|
+
if (GESTURE_METHODS.has(msg.method) && !gestured)
|
|
1053
|
+
throw new MiniAppError("PERMISSION_DENIED", "gesture required");
|
|
1054
|
+
const data = handler(isRecord(msg.params) ? msg.params : {});
|
|
1055
|
+
void Promise.resolve(data).then(
|
|
1056
|
+
(d) => deliver({ v: 1, type: "result", id: msg.id, ok: true, data: d }),
|
|
1057
|
+
fail
|
|
1058
|
+
);
|
|
1059
|
+
} catch (err) {
|
|
1060
|
+
fail(err);
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
const mark = (e) => {
|
|
1064
|
+
if (e.isTrusted) lastGestureAt = now();
|
|
1065
|
+
};
|
|
1066
|
+
for (const type of GESTURE_EVENTS) opts.doc?.addEventListener(type, mark, { capture: true });
|
|
1067
|
+
opts.doc?.addEventListener("visibilitychange", () => {
|
|
1068
|
+
const name = opts.doc?.visibilityState === "hidden" ? "lifecycle.pause" : "lifecycle.resume";
|
|
1069
|
+
emit(name, { reason: "background" });
|
|
1070
|
+
});
|
|
1071
|
+
const events = new Set(EVENTS);
|
|
1072
|
+
const controls = {
|
|
1073
|
+
emit(name, data) {
|
|
1074
|
+
if (!events.has(name)) throw new TypeError(`${name} is not a host event`);
|
|
1075
|
+
if (isRecord(data) && name === "ui.themeChanged")
|
|
1076
|
+
colorScheme = data.colorScheme === "dark" ? "dark" : "light";
|
|
1077
|
+
if (isRecord(data) && name === "permissions.changed") {
|
|
1078
|
+
const state = data.state;
|
|
1079
|
+
if (state === "prompt" || state === "granted" || state === "denied") {
|
|
1080
|
+
if (data.name === "notifications") setNotifications(state);
|
|
1081
|
+
if (data.name === "profile" && user !== null) profile = state;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
emit(name, data);
|
|
1085
|
+
},
|
|
1086
|
+
async close() {
|
|
1087
|
+
if (backButton) {
|
|
1088
|
+
emit("ui.backButtonPressed", void 0);
|
|
1089
|
+
return "backButtonPressed";
|
|
1090
|
+
}
|
|
1091
|
+
const id = `mock_close_${++seq}`;
|
|
1092
|
+
await new Promise((done) => {
|
|
1093
|
+
const timer = setTimeout(done, CLOSE_TIMEOUT_MS);
|
|
1094
|
+
replies.set(id, () => (clearTimeout(timer), done()));
|
|
1095
|
+
deliver({
|
|
1096
|
+
v: 1,
|
|
1097
|
+
type: "request",
|
|
1098
|
+
id,
|
|
1099
|
+
name: "app.beforeClose",
|
|
1100
|
+
timeoutMs: CLOSE_TIMEOUT_MS
|
|
1101
|
+
});
|
|
1102
|
+
});
|
|
1103
|
+
replies.delete(id);
|
|
1104
|
+
emit("lifecycle.closing", void 0);
|
|
1105
|
+
return "closing";
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
return {
|
|
1109
|
+
name: "mock",
|
|
1110
|
+
send: handle,
|
|
1111
|
+
listen(onMessage) {
|
|
1112
|
+
listeners2.add(onMessage);
|
|
1113
|
+
return () => listeners2.delete(onMessage);
|
|
1114
|
+
},
|
|
1115
|
+
controls
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// src/transport/postmessage.ts
|
|
1120
|
+
var isFramed = (win) => win.parent !== win;
|
|
1121
|
+
function createPostMessageTransport(win) {
|
|
1122
|
+
return {
|
|
1123
|
+
name: "postmessage",
|
|
1124
|
+
send: (msg) => win.parent.postMessage(msg, "*"),
|
|
1125
|
+
listen(onMessage) {
|
|
1126
|
+
const handler = (e) => {
|
|
1127
|
+
if (e.source === win.parent) onMessage(e.data);
|
|
1128
|
+
};
|
|
1129
|
+
win.addEventListener("message", handler);
|
|
1130
|
+
return () => win.removeEventListener("message", handler);
|
|
1131
|
+
}
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// src/transport/detect.ts
|
|
1136
|
+
function detectTransport(win) {
|
|
1137
|
+
if (isIos(win)) return createIosTransport(win);
|
|
1138
|
+
if (isAndroid(win)) return createAndroidTransport(win);
|
|
1139
|
+
if (isFramed(win)) return createPostMessageTransport(win);
|
|
1140
|
+
const manifest = readManifest(win);
|
|
1141
|
+
const dev = devServer(win);
|
|
1142
|
+
const mock = createMockTransport({
|
|
1143
|
+
storage: safeLocalStorage(win),
|
|
1144
|
+
doc: win.document,
|
|
1145
|
+
dialogs: win,
|
|
1146
|
+
avatar: appIconAvatar(win, manifest),
|
|
1147
|
+
scopes: manifest.then(manifestScopes),
|
|
1148
|
+
permissionReasons: manifest.then(manifestReasons),
|
|
1149
|
+
launchTokens: dev.then((d) => d?.mint ?? null),
|
|
1150
|
+
onNotificationsConsent: (state, user) => void dev.then((d) => d?.consent(state, user)),
|
|
1151
|
+
...localSwitches(safeSearch(win))
|
|
1152
|
+
});
|
|
1153
|
+
Object.defineProperty(win, "__idolchatMock", { value: mock.controls, configurable: true });
|
|
1154
|
+
return mock;
|
|
1155
|
+
}
|
|
1156
|
+
async function readManifest(win) {
|
|
1157
|
+
try {
|
|
1158
|
+
const url = new URL("manifest.json", win.location.href);
|
|
1159
|
+
const res = await win.fetch(url);
|
|
1160
|
+
if (!res.ok) return null;
|
|
1161
|
+
const body = await res.json();
|
|
1162
|
+
return isRecord2(body) ? { url, body } : null;
|
|
1163
|
+
} catch {
|
|
1164
|
+
return null;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
function manifestScopes(manifest) {
|
|
1168
|
+
if (manifest === null) return null;
|
|
1169
|
+
const scopes = manifest.body.scopes ?? [];
|
|
1170
|
+
return Array.isArray(scopes) ? scopes.filter((s) => typeof s === "string") : [];
|
|
1171
|
+
}
|
|
1172
|
+
function manifestReasons(manifest) {
|
|
1173
|
+
const raw = manifest?.body.permissionReasons;
|
|
1174
|
+
if (!isRecord2(raw)) return {};
|
|
1175
|
+
return Object.fromEntries(
|
|
1176
|
+
Object.entries(raw).filter((e) => typeof e[1] === "string")
|
|
1177
|
+
);
|
|
1178
|
+
}
|
|
1179
|
+
var DEV_JWKS_PATH = "/__idolchat/jwks.json";
|
|
1180
|
+
var DEV_TOKEN_PATH = "/__idolchat/launch-token";
|
|
1181
|
+
var DEV_CONSENT_PATH = "/__idolchat/consent";
|
|
1182
|
+
var DEV_MARKER_HEADER = "x-idolchat-dev";
|
|
1183
|
+
async function devServer(win) {
|
|
1184
|
+
try {
|
|
1185
|
+
const probe = await win.fetch(new URL(DEV_JWKS_PATH, win.location.href), { cache: "no-store" });
|
|
1186
|
+
if (!probe.ok || probe.headers.get(DEV_MARKER_HEADER) !== "1") return null;
|
|
1187
|
+
} catch {
|
|
1188
|
+
return null;
|
|
1189
|
+
}
|
|
1190
|
+
const url = new URL(DEV_TOKEN_PATH, win.location.href);
|
|
1191
|
+
const consentUrl = new URL(DEV_CONSENT_PATH, win.location.href);
|
|
1192
|
+
let reported = Promise.resolve();
|
|
1193
|
+
const consent = (state, user) => reported = reported.then(
|
|
1194
|
+
() => win.fetch(consentUrl, {
|
|
1195
|
+
method: "POST",
|
|
1196
|
+
headers: { "content-type": "application/json" },
|
|
1197
|
+
body: JSON.stringify(user === void 0 ? { state } : { state, user })
|
|
1198
|
+
})
|
|
1199
|
+
).then(
|
|
1200
|
+
() => void 0,
|
|
1201
|
+
() => void 0
|
|
1202
|
+
);
|
|
1203
|
+
const mint = async (body) => {
|
|
1204
|
+
const res = await win.fetch(url, {
|
|
1205
|
+
method: "POST",
|
|
1206
|
+
headers: { "content-type": "application/json" },
|
|
1207
|
+
body: JSON.stringify(body)
|
|
1208
|
+
});
|
|
1209
|
+
const data = await res.json();
|
|
1210
|
+
const token = isRecord2(data) ? data.token : void 0;
|
|
1211
|
+
if (!res.ok || typeof token !== "string") throw new Error(`dev server answered ${res.status}`);
|
|
1212
|
+
return token;
|
|
1213
|
+
};
|
|
1214
|
+
return { mint, consent };
|
|
1215
|
+
}
|
|
1216
|
+
async function appIconAvatar(win, manifestRead) {
|
|
1217
|
+
try {
|
|
1218
|
+
const manifest = await manifestRead;
|
|
1219
|
+
const icon = manifest?.body.icon;
|
|
1220
|
+
if (manifest === null || typeof icon !== "string") return null;
|
|
1221
|
+
const img = win.document.createElement("img");
|
|
1222
|
+
img.src = new URL(icon, manifest.url).href;
|
|
1223
|
+
await img.decode();
|
|
1224
|
+
const size = Math.min(256, img.naturalWidth, img.naturalHeight);
|
|
1225
|
+
if (size === 0) return null;
|
|
1226
|
+
const canvas = win.document.createElement("canvas");
|
|
1227
|
+
canvas.width = canvas.height = size;
|
|
1228
|
+
canvas.getContext("2d")?.drawImage(img, 0, 0, size, size);
|
|
1229
|
+
return canvas.toDataURL("image/png");
|
|
1230
|
+
} catch {
|
|
1231
|
+
return null;
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1235
|
+
function localSwitches(search) {
|
|
1236
|
+
const q = new URLSearchParams(search);
|
|
1237
|
+
const out = {};
|
|
1238
|
+
const start = q.get("startapp");
|
|
1239
|
+
if (start !== null) {
|
|
1240
|
+
out.startParam = START_PARAM_PATTERN.test(start) ? start : null;
|
|
1241
|
+
if (out.startParam === null)
|
|
1242
|
+
console.warn(
|
|
1243
|
+
`[miniapp-sdk] ?startapp=${start} ignored: a startParam is 1-64 chars of [A-Za-z0-9_-], so IdolChat would never send it`
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
if (q.get("profile") === "0") out.profile = "denied";
|
|
1247
|
+
if (q.get("theme") === "dark") out.colorScheme = "dark";
|
|
1248
|
+
const user = q.get("user");
|
|
1249
|
+
if (user !== null) {
|
|
1250
|
+
if (MOCK_USER_NAME_PATTERN.test(user)) out.userName = user;
|
|
1251
|
+
else
|
|
1252
|
+
console.warn(
|
|
1253
|
+
`[miniapp-sdk] ?user=${user} ignored: a test user name is 1-32 chars of [A-Za-z0-9_-]`
|
|
1254
|
+
);
|
|
1255
|
+
}
|
|
1256
|
+
const n = q.get("notifications");
|
|
1257
|
+
if (n === "granted" || n === "denied" || n === "prompt") out.notifications = n;
|
|
1258
|
+
return out;
|
|
1259
|
+
}
|
|
1260
|
+
function safeSearch(win) {
|
|
1261
|
+
try {
|
|
1262
|
+
return win.location.search;
|
|
1263
|
+
} catch {
|
|
1264
|
+
return "";
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
function safeLocalStorage(win) {
|
|
1268
|
+
try {
|
|
1269
|
+
return win.localStorage;
|
|
1270
|
+
} catch {
|
|
1271
|
+
return void 0;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
// src/index.ts
|
|
1276
|
+
var miniApp = typeof window === "undefined" ? void 0 : window.MiniApp ?? (window.MiniApp = createMiniApp(detectTransport(window), {
|
|
1277
|
+
gestureTarget: window.document
|
|
1278
|
+
}));
|
|
1279
|
+
export {
|
|
1280
|
+
DEFAULT_TIMEOUT_MS,
|
|
1281
|
+
ERROR_CODES,
|
|
1282
|
+
EVENTS,
|
|
1283
|
+
GESTURE_WINDOW_MS,
|
|
1284
|
+
METHODS,
|
|
1285
|
+
MiniAppCore,
|
|
1286
|
+
MiniAppError,
|
|
1287
|
+
PROTOCOL_VERSION,
|
|
1288
|
+
REQUESTS,
|
|
1289
|
+
SDK_VERSION,
|
|
1290
|
+
SHARE_IMAGE_LIMITS,
|
|
1291
|
+
START_PARAM_PATTERN,
|
|
1292
|
+
STORAGE_LIMIT_BYTES,
|
|
1293
|
+
checkShareImage,
|
|
1294
|
+
createMiniApp,
|
|
1295
|
+
createMockTransport,
|
|
1296
|
+
detectTransport,
|
|
1297
|
+
isRecord,
|
|
1298
|
+
miniApp,
|
|
1299
|
+
parseCallMessage,
|
|
1300
|
+
parseError,
|
|
1301
|
+
parseHostMessage,
|
|
1302
|
+
parseInitResult,
|
|
1303
|
+
parseUser
|
|
1304
|
+
};
|