@assistant-ui/appos 0.0.0-stage → 0.0.1
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/dist/chunks/ai-call.js +71 -0
- package/dist/chunks/ai-sdk.js +66 -0
- package/dist/chunks/src.js +1174 -0
- package/dist/index.js +1618 -0
- package/dist/next-page.js +150 -0
- package/dist/next-runtime.js +102 -0
- package/dist/next-server.js +50 -0
- package/dist/next.js +215 -0
- package/dist/pack.js +107 -0
- package/dist/server.js +77 -0
- package/dist/types/packages/appos-client/src/ai-sdk.d.ts +7 -0
- package/dist/types/packages/appos-client/src/index.d.ts +467 -0
- package/dist/types/packages/appos-client/src/theme.d.ts +16 -0
- package/dist/types/packages/appos-client/src/update-text.d.ts +13 -0
- package/dist/types/packages/appos-host/src/AppOSApp.d.ts +20 -0
- package/dist/types/packages/appos-host/src/ai-call.d.ts +31 -0
- package/dist/types/packages/appos-host/src/ai.d.ts +61 -0
- package/dist/types/packages/appos-host/src/embed.d.ts +119 -0
- package/dist/types/packages/appos-host/src/index.d.ts +6 -0
- package/dist/types/packages/appos-host/src/next/adapter.d.ts +43 -0
- package/dist/types/packages/appos-host/src/next/page.d.ts +1 -0
- package/dist/types/packages/appos-host/src/next/routes.d.ts +2 -0
- package/dist/types/packages/appos-host/src/next/runtime.d.ts +11 -0
- package/dist/types/packages/appos-host/src/next/server.d.ts +22 -0
- package/dist/types/packages/appos-host/src/pack.d.ts +16 -0
- package/dist/types/packages/appos-host/src/server.d.ts +23 -0
- package/dist/types/src/lib/ai-spend.d.ts +51 -0
- package/dist/types/src/lib/bundle-meta.d.ts +13 -0
- package/dist/types/src/lib/color-scheme.d.ts +17 -0
- package/dist/types/src/lib/external-link.d.ts +5 -0
- package/dist/types/src/lib/frame-pinch.d.ts +6 -0
- package/dist/types/src/lib/pack.d.ts +17 -0
- package/dist/types/src/lib/swbn/cbor.d.ts +16 -0
- package/dist/types/src/lib/swbn/identity.d.ts +121 -0
- package/dist/types/src/lib/swbn/integrity.d.ts +51 -0
- package/dist/types/src/lib/swbn/keys.d.ts +25 -0
- package/dist/types/src/lib/swbn/manifest.d.ts +106 -0
- package/dist/types/src/lib/swbn/release.d.ts +39 -0
- package/package.json +43 -4
- package/README.md +0 -3
|
@@ -0,0 +1,1174 @@
|
|
|
1
|
+
// packages/appos-client/src/update-text.ts
|
|
2
|
+
/** "0.0.1 (3)", "build 3", "1.0.0", or undefined when nothing usable came. */
|
|
3
|
+
function releaseText(details) {
|
|
4
|
+
const version = typeof details.version === "string" && details.version.trim() ? details.version.trim() : void 0;
|
|
5
|
+
const build = typeof details.build === "number" && Number.isInteger(details.build) && details.build > 0 ? details.build : void 0;
|
|
6
|
+
if (build === void 0) return version;
|
|
7
|
+
return version ? `${version} (${build})` : `build ${build}`;
|
|
8
|
+
}
|
|
9
|
+
/** The sheet's text for update-required. Never prints a missing version. */
|
|
10
|
+
function updateRequiredText(appName, details) {
|
|
11
|
+
const runs = releaseText(details);
|
|
12
|
+
return runs ? `This actor runs ${appName} ${runs}. Update to join.` : `This actor needs a newer ${appName}. Update to join.`;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The sheet for upgrade-pending / upgrade-denied. The owner (`canApprove`) gets
|
|
16
|
+
* Approve (and Deny while it is pending); anyone else gets the server's words.
|
|
17
|
+
*/
|
|
18
|
+
function upgradeSheet(appName, code, message, details) {
|
|
19
|
+
if (details.canApprove !== true) return {
|
|
20
|
+
title: code === "upgrade-pending" ? "Waiting for the owner" : "Update declined",
|
|
21
|
+
text: message,
|
|
22
|
+
actions: []
|
|
23
|
+
};
|
|
24
|
+
const runs = releaseText({
|
|
25
|
+
version: details.running,
|
|
26
|
+
build: details.runningBuild
|
|
27
|
+
});
|
|
28
|
+
const wants = releaseText({
|
|
29
|
+
version: details.requested,
|
|
30
|
+
build: details.requestedBuild
|
|
31
|
+
}) ?? "the newer version";
|
|
32
|
+
return {
|
|
33
|
+
title: `Update ${appName}?`,
|
|
34
|
+
text: `${runs ? `This file runs ${appName} ${runs}. ` : ""}Approve ${wants} to update it for everyone.`,
|
|
35
|
+
actions: code === "upgrade-pending" ? ["deny", "approve"] : ["approve"]
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
// packages/appos-client/src/theme.ts
|
|
39
|
+
var EVENT = "appos:color-scheme";
|
|
40
|
+
var DARK_QUERY = "(prefers-color-scheme: dark)";
|
|
41
|
+
var hasDom = typeof document !== "undefined" && !!document.documentElement && typeof window !== "undefined" && typeof window.addEventListener === "function";
|
|
42
|
+
function isScheme(v) {
|
|
43
|
+
return v === "light" || v === "dark";
|
|
44
|
+
}
|
|
45
|
+
/** The shell's scheme, if the sandbox has set one on this page. */
|
|
46
|
+
function fromShell() {
|
|
47
|
+
const v = hasDom ? document.documentElement.dataset.apposColorScheme : void 0;
|
|
48
|
+
return isScheme(v) ? v : void 0;
|
|
49
|
+
}
|
|
50
|
+
function fromSystem() {
|
|
51
|
+
return hasDom && typeof matchMedia === "function" && matchMedia(DARK_QUERY).matches ? "dark" : "light";
|
|
52
|
+
}
|
|
53
|
+
function get() {
|
|
54
|
+
return fromShell() ?? fromSystem();
|
|
55
|
+
}
|
|
56
|
+
var manual = () => document.documentElement.dataset.apposTheme === "manual";
|
|
57
|
+
function apply(scheme) {
|
|
58
|
+
if (!hasDom || manual()) return;
|
|
59
|
+
const root = document.documentElement;
|
|
60
|
+
root.classList.toggle("dark", scheme === "dark");
|
|
61
|
+
root.style.colorScheme = scheme;
|
|
62
|
+
}
|
|
63
|
+
/** Calls `fn` with the new scheme on every change. Returns an unsubscribe. */
|
|
64
|
+
function onChange(fn) {
|
|
65
|
+
if (!hasDom) return () => {};
|
|
66
|
+
let last = get();
|
|
67
|
+
const check = () => {
|
|
68
|
+
const now = get();
|
|
69
|
+
if (now === last) return;
|
|
70
|
+
last = now;
|
|
71
|
+
fn(now);
|
|
72
|
+
};
|
|
73
|
+
window.addEventListener(EVENT, check);
|
|
74
|
+
const query = typeof matchMedia === "function" ? matchMedia(DARK_QUERY) : void 0;
|
|
75
|
+
query?.addEventListener("change", check);
|
|
76
|
+
return () => {
|
|
77
|
+
window.removeEventListener(EVENT, check);
|
|
78
|
+
query?.removeEventListener("change", check);
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Whether the SDK keeps <html>'s "dark" class and color-scheme in step
|
|
83
|
+
* (default true). false leaves them as they are: style from get() and
|
|
84
|
+
* onChange() yourself. Same as <html data-appos-theme="manual">.
|
|
85
|
+
*/
|
|
86
|
+
function autoApply(on) {
|
|
87
|
+
if (!hasDom) return;
|
|
88
|
+
if (on) {
|
|
89
|
+
delete document.documentElement.dataset.apposTheme;
|
|
90
|
+
apply(get());
|
|
91
|
+
} else document.documentElement.dataset.apposTheme = "manual";
|
|
92
|
+
}
|
|
93
|
+
if (hasDom && !fromShell()) {
|
|
94
|
+
apply(get());
|
|
95
|
+
onChange(apply);
|
|
96
|
+
}
|
|
97
|
+
var theme = {
|
|
98
|
+
get,
|
|
99
|
+
onChange,
|
|
100
|
+
autoApply
|
|
101
|
+
};
|
|
102
|
+
// packages/appos-client/src/index.ts
|
|
103
|
+
var VERSION_KEY = "appos:version";
|
|
104
|
+
/** Request bodies through the handle, like the cloud's own cap. */
|
|
105
|
+
var MAX_BODY = 1048576;
|
|
106
|
+
var CloudError = class extends Error {
|
|
107
|
+
code;
|
|
108
|
+
status;
|
|
109
|
+
details;
|
|
110
|
+
constructor(code, message, status = 0, details = {}) {
|
|
111
|
+
super(message);
|
|
112
|
+
this.code = code;
|
|
113
|
+
this.status = status;
|
|
114
|
+
this.details = details;
|
|
115
|
+
this.name = "CloudError";
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
function parentOrigin() {
|
|
119
|
+
if (window.parent === window) return void 0;
|
|
120
|
+
try {
|
|
121
|
+
const a = location.ancestorOrigins?.[0];
|
|
122
|
+
if (a) return a;
|
|
123
|
+
} catch {}
|
|
124
|
+
try {
|
|
125
|
+
return document.referrer ? new URL(document.referrer).origin : void 0;
|
|
126
|
+
} catch {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
var seq = 0;
|
|
131
|
+
/** Asks the appOS shell; it answers only frames it opened, on their own origin. */
|
|
132
|
+
function ask(type, data = {}, timeoutMs = 2e4, transfer = []) {
|
|
133
|
+
if (window.parent === window) return Promise.reject(new CloudError("no-shell", "Open this app from appOS."));
|
|
134
|
+
const id = `${Date.now()}-${++seq}`;
|
|
135
|
+
const origin = parentOrigin();
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
const timer = setTimeout(() => {
|
|
138
|
+
removeEventListener("message", onMessage);
|
|
139
|
+
reject(new CloudError("timeout", `appOS did not answer ${type}.`));
|
|
140
|
+
}, timeoutMs);
|
|
141
|
+
const onMessage = (e) => {
|
|
142
|
+
if (e.source !== window.parent || origin && e.origin !== origin) return;
|
|
143
|
+
const d = e.data;
|
|
144
|
+
if (d?.type !== `${type}:reply` || d.id !== id) return;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
removeEventListener("message", onMessage);
|
|
147
|
+
if (d.error) reject(new CloudError(d.error, d.message ?? d.error, 0, d));
|
|
148
|
+
else resolve(d);
|
|
149
|
+
};
|
|
150
|
+
addEventListener("message", onMessage);
|
|
151
|
+
window.parent.postMessage({
|
|
152
|
+
type,
|
|
153
|
+
id,
|
|
154
|
+
...data
|
|
155
|
+
}, origin ?? "*", transfer);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** Tells the shell something it doesn't answer (appos:badge). Outside a shell, nothing. */
|
|
159
|
+
function tell(type, data) {
|
|
160
|
+
if (window.parent === window) return;
|
|
161
|
+
try {
|
|
162
|
+
window.parent.postMessage({
|
|
163
|
+
type,
|
|
164
|
+
...data
|
|
165
|
+
}, parentOrigin() ?? "*");
|
|
166
|
+
} catch {}
|
|
167
|
+
}
|
|
168
|
+
var hello;
|
|
169
|
+
var getHello = () => hello ??= ask("appos:hello").then((h) => {
|
|
170
|
+
if (h.removed?.length) for (const fn of removedListeners) fn(h.removed);
|
|
171
|
+
removedSeen = h.removed ?? [];
|
|
172
|
+
return h;
|
|
173
|
+
}, (e) => (hello = void 0, Promise.reject(e)));
|
|
174
|
+
var removedListeners = [];
|
|
175
|
+
var removedSeen;
|
|
176
|
+
/** "0.0.1 (12)" for apps with builds, else the version. */
|
|
177
|
+
var labelOf = (h) => h.build === void 0 ? h.version : `${h.version} (${h.build})`;
|
|
178
|
+
var current;
|
|
179
|
+
var upgradeListeners = [];
|
|
180
|
+
async function ready() {
|
|
181
|
+
if (current) return current;
|
|
182
|
+
const h = await getHello();
|
|
183
|
+
const label = labelOf(h);
|
|
184
|
+
let stored = null;
|
|
185
|
+
try {
|
|
186
|
+
stored = localStorage.getItem(VERSION_KEY);
|
|
187
|
+
localStorage.setItem(VERSION_KEY, label);
|
|
188
|
+
} catch {}
|
|
189
|
+
current = {
|
|
190
|
+
version: h.version,
|
|
191
|
+
...h.build !== void 0 ? { build: h.build } : {},
|
|
192
|
+
...stored && stored !== label ? {
|
|
193
|
+
previousVersion: stored,
|
|
194
|
+
upgrade: {
|
|
195
|
+
from: stored,
|
|
196
|
+
to: label
|
|
197
|
+
}
|
|
198
|
+
} : {}
|
|
199
|
+
};
|
|
200
|
+
if (current.upgrade) for (const fn of upgradeListeners) fn(current.upgrade.from, current.upgrade.to);
|
|
201
|
+
return current;
|
|
202
|
+
}
|
|
203
|
+
var sheetHost;
|
|
204
|
+
function closeSheet() {
|
|
205
|
+
sheetHost?.remove();
|
|
206
|
+
sheetHost = void 0;
|
|
207
|
+
}
|
|
208
|
+
/** A small modal sheet inside the app's frame. */
|
|
209
|
+
function showSheet(opts) {
|
|
210
|
+
closeSheet();
|
|
211
|
+
const host = document.createElement("div");
|
|
212
|
+
host.setAttribute("data-appos-sheet", "");
|
|
213
|
+
const root = host.attachShadow({ mode: "open" });
|
|
214
|
+
root.innerHTML = `<style>
|
|
215
|
+
:host { all: initial; }
|
|
216
|
+
.scrim { position: fixed; inset: 0; z-index: 2147483647; display: grid; place-items: end center;
|
|
217
|
+
background: rgb(0 0 0 / .35); font: 14px/1.4 ui-sans-serif, system-ui, sans-serif; }
|
|
218
|
+
.sheet { box-sizing: border-box; width: min(420px, calc(100vw - 24px)); margin: 12px; padding: 18px;
|
|
219
|
+
border-radius: 14px; background: #fff; color: #111; box-shadow: 0 10px 40px rgb(0 0 0 / .25); }
|
|
220
|
+
h2 { margin: 0 0 6px; font-size: 16px; } p { margin: 0 0 14px; color: #555; }
|
|
221
|
+
.row { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
|
|
222
|
+
button { font: inherit; padding: 8px 14px; border-radius: 9px; border: 1px solid #ccc; background: transparent; color: inherit; cursor: pointer; }
|
|
223
|
+
button.primary { background: #111; color: #fff; border-color: #111; }
|
|
224
|
+
@media (prefers-color-scheme: dark) { .sheet { background: #1b1b1b; color: #eee; } p { color: #aaa; }
|
|
225
|
+
button { border-color: #444; } button.primary { background: #eee; color: #111; border-color: #eee; } }
|
|
226
|
+
</style><div class="scrim" role="dialog" aria-modal="true"><div class="sheet"><h2></h2><p></p><div class="row"></div></div></div>`;
|
|
227
|
+
root.querySelector("h2").textContent = opts.title;
|
|
228
|
+
root.querySelector("p").textContent = opts.text;
|
|
229
|
+
const row = root.querySelector(".row");
|
|
230
|
+
const actions = [...opts.actions ?? []];
|
|
231
|
+
if (opts.dismissable !== false) actions.unshift({
|
|
232
|
+
label: "Not now",
|
|
233
|
+
run: () => {}
|
|
234
|
+
});
|
|
235
|
+
for (const a of actions) {
|
|
236
|
+
const b = document.createElement("button");
|
|
237
|
+
b.textContent = a.label;
|
|
238
|
+
if (a.primary) b.className = "primary";
|
|
239
|
+
b.onclick = async () => {
|
|
240
|
+
b.disabled = true;
|
|
241
|
+
try {
|
|
242
|
+
await a.run();
|
|
243
|
+
} finally {
|
|
244
|
+
closeSheet();
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
row.append(b);
|
|
248
|
+
}
|
|
249
|
+
document.body.append(host);
|
|
250
|
+
sheetHost = host;
|
|
251
|
+
}
|
|
252
|
+
var appName = document.title || "this app";
|
|
253
|
+
/** The actor a backend path belongs to ("/actor/<id>"), if any. */
|
|
254
|
+
var actorPathOf = (path) => /^\/actor\/[^/?#]+/.exec(path)?.[0];
|
|
255
|
+
/** Shows the built-in sheet for a cloud problem the user can act on (`actorPath`: the actor the call went to). */
|
|
256
|
+
function explain(error, actorPath) {
|
|
257
|
+
switch (error.code) {
|
|
258
|
+
case "signed-out":
|
|
259
|
+
showSheet({
|
|
260
|
+
title: "Sign in to continue",
|
|
261
|
+
text: `Sign in with assistant-ui to use ${appName}'s shared data.`,
|
|
262
|
+
actions: [{
|
|
263
|
+
label: "Sign in with assistant-ui",
|
|
264
|
+
primary: true,
|
|
265
|
+
run: () => void ask("appos:sign-in").catch(() => {})
|
|
266
|
+
}]
|
|
267
|
+
});
|
|
268
|
+
break;
|
|
269
|
+
case "update-required":
|
|
270
|
+
showSheet({
|
|
271
|
+
title: "Update to join",
|
|
272
|
+
text: updateRequiredText(appName, error.details),
|
|
273
|
+
dismissable: false,
|
|
274
|
+
actions: [{
|
|
275
|
+
label: "Update",
|
|
276
|
+
primary: true,
|
|
277
|
+
run: () => void ask("appos:update-from-cloud", typeof error.details.hash === "string" ? { hash: error.details.hash } : {}, 12e4).catch((e) => showSheet({
|
|
278
|
+
title: "Couldn't update",
|
|
279
|
+
text: e instanceof Error && e.message ? e.message : `${appName} did not update.`
|
|
280
|
+
}))
|
|
281
|
+
}]
|
|
282
|
+
});
|
|
283
|
+
break;
|
|
284
|
+
case "upgrade-pending":
|
|
285
|
+
case "upgrade-denied": {
|
|
286
|
+
const sheet = upgradeSheet(appName, error.code, error.message, error.details);
|
|
287
|
+
const decide = async (approve) => {
|
|
288
|
+
try {
|
|
289
|
+
await actorJson(`${actorPath}/_upgrade`, {
|
|
290
|
+
method: "POST",
|
|
291
|
+
json: { approve }
|
|
292
|
+
});
|
|
293
|
+
if (approve) location.reload();
|
|
294
|
+
} catch {}
|
|
295
|
+
};
|
|
296
|
+
showSheet({
|
|
297
|
+
title: sheet.title,
|
|
298
|
+
text: sheet.text,
|
|
299
|
+
actions: actorPath ? sheet.actions.map((a) => a === "approve" ? {
|
|
300
|
+
label: "Approve",
|
|
301
|
+
primary: true,
|
|
302
|
+
run: () => decide(true)
|
|
303
|
+
} : {
|
|
304
|
+
label: "Deny",
|
|
305
|
+
run: () => decide(false)
|
|
306
|
+
}) : []
|
|
307
|
+
});
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
var port;
|
|
313
|
+
var nextId = 0;
|
|
314
|
+
var pending = /* @__PURE__ */ new Map();
|
|
315
|
+
function onWire(e) {
|
|
316
|
+
const m = e.data;
|
|
317
|
+
const p = pending.get(m?.id);
|
|
318
|
+
if (!p) return;
|
|
319
|
+
switch (m.op) {
|
|
320
|
+
case "head": {
|
|
321
|
+
const stream = new ReadableStream({
|
|
322
|
+
start: (c) => void (p.stream = c),
|
|
323
|
+
cancel: () => {
|
|
324
|
+
pending.delete(m.id);
|
|
325
|
+
port?.then((pt) => pt.postMessage({
|
|
326
|
+
op: "abort",
|
|
327
|
+
id: m.id
|
|
328
|
+
}));
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
const nullBody = m.status === 204 || m.status === 205 || m.status === 304;
|
|
332
|
+
p.head?.(new Response(nullBody ? null : stream, {
|
|
333
|
+
status: m.status,
|
|
334
|
+
statusText: m.statusText,
|
|
335
|
+
headers: m.headers
|
|
336
|
+
}));
|
|
337
|
+
p.head = p.fail = void 0;
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
case "chunk":
|
|
341
|
+
p.stream?.enqueue(m.data);
|
|
342
|
+
break;
|
|
343
|
+
case "end":
|
|
344
|
+
pending.delete(m.id);
|
|
345
|
+
try {
|
|
346
|
+
p.stream?.close();
|
|
347
|
+
} catch {}
|
|
348
|
+
break;
|
|
349
|
+
case "error": {
|
|
350
|
+
pending.delete(m.id);
|
|
351
|
+
const err = new CloudError(m.code, m.message);
|
|
352
|
+
if (p.fail) p.fail(err);
|
|
353
|
+
else p.stream?.error(err);
|
|
354
|
+
p.socket?._closed(1006, m.message, false);
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
case "ws-open":
|
|
358
|
+
p.socket?._opened(m.protocol);
|
|
359
|
+
break;
|
|
360
|
+
case "ws-message":
|
|
361
|
+
p.socket?._message(m.data);
|
|
362
|
+
break;
|
|
363
|
+
case "ws-close":
|
|
364
|
+
pending.delete(m.id);
|
|
365
|
+
p.socket?._closed(m.code, m.reason, m.clean);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** The port to the shell, set up on first use. */
|
|
369
|
+
function bridge() {
|
|
370
|
+
port ??= (async () => {
|
|
371
|
+
const channel = new MessageChannel();
|
|
372
|
+
channel.port1.onmessage = onWire;
|
|
373
|
+
await ask("appos:backend", {}, 2e4, [channel.port2]);
|
|
374
|
+
return channel.port1;
|
|
375
|
+
})().catch((e) => {
|
|
376
|
+
port = void 0;
|
|
377
|
+
throw e;
|
|
378
|
+
});
|
|
379
|
+
return port;
|
|
380
|
+
}
|
|
381
|
+
/** A backend path: "/actors", "/actor/cloud-Board-x/sw". Never a URL. */
|
|
382
|
+
function backendPath(input) {
|
|
383
|
+
let path;
|
|
384
|
+
if (typeof input === "string") path = input;
|
|
385
|
+
else {
|
|
386
|
+
const u = new URL(input.url);
|
|
387
|
+
if (u.origin !== location.origin) throw new TypeError("backend.fetch takes a backend path, not another site's URL.");
|
|
388
|
+
path = u.pathname + u.search;
|
|
389
|
+
}
|
|
390
|
+
if (!path.startsWith("/") || path.startsWith("//")) throw new TypeError(`backend.fetch takes a path like "/actor/<id>/x", not ${JSON.stringify(path)}.`);
|
|
391
|
+
return path;
|
|
392
|
+
}
|
|
393
|
+
async function bodyBytes(body) {
|
|
394
|
+
if (body === null || body === void 0) return void 0;
|
|
395
|
+
const buf = await new Response(body).arrayBuffer();
|
|
396
|
+
if (buf.byteLength > MAX_BODY) throw new CloudError("too-big", "Request bodies are capped at 1 MB.", 413);
|
|
397
|
+
return buf;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* The app's backend. It has no URL: `fetch()` can't reach it, so a URL that
|
|
401
|
+
* came from anywhere (a link, a message, another site) never becomes a call
|
|
402
|
+
* to it. Paths name an actor and what to send it:
|
|
403
|
+
*
|
|
404
|
+
* /whoami
|
|
405
|
+
* /actors GET: the user's actors; POST /actors/<Class>: a new one
|
|
406
|
+
* /actor/<id>/<path> one actor
|
|
407
|
+
*/
|
|
408
|
+
var backend = {
|
|
409
|
+
/** Sends a request to the backend; resolves to its streamed response. */
|
|
410
|
+
async fetch(input, init = {}) {
|
|
411
|
+
const path = backendPath(input);
|
|
412
|
+
const req = typeof input === "string" ? void 0 : input;
|
|
413
|
+
const method = (init.method ?? req?.method ?? "GET").toUpperCase();
|
|
414
|
+
const headers = new Headers(init.headers ?? req?.headers);
|
|
415
|
+
const body = await bodyBytes(init.body !== void 0 ? init.body : req && !["GET", "HEAD"].includes(method) ? await req.arrayBuffer() : void 0);
|
|
416
|
+
const signal = init.signal ?? req?.signal;
|
|
417
|
+
signal?.throwIfAborted();
|
|
418
|
+
const pt = await bridge();
|
|
419
|
+
const id = ++nextId;
|
|
420
|
+
return new Promise((resolve, reject) => {
|
|
421
|
+
pending.set(id, {
|
|
422
|
+
head: resolve,
|
|
423
|
+
fail: reject
|
|
424
|
+
});
|
|
425
|
+
signal?.addEventListener("abort", () => {
|
|
426
|
+
const p = pending.get(id);
|
|
427
|
+
pending.delete(id);
|
|
428
|
+
pt.postMessage({
|
|
429
|
+
op: "abort",
|
|
430
|
+
id
|
|
431
|
+
});
|
|
432
|
+
const reason = signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
433
|
+
if (p?.fail) p.fail(reason);
|
|
434
|
+
else try {
|
|
435
|
+
p?.stream?.error(reason);
|
|
436
|
+
} catch {}
|
|
437
|
+
}, { once: true });
|
|
438
|
+
pt.postMessage({
|
|
439
|
+
op: "fetch",
|
|
440
|
+
id,
|
|
441
|
+
method,
|
|
442
|
+
path,
|
|
443
|
+
headers: [...headers],
|
|
444
|
+
body
|
|
445
|
+
}, body ? [body] : []);
|
|
446
|
+
});
|
|
447
|
+
},
|
|
448
|
+
/** A WebSocket to the backend, relayed by the shell. */
|
|
449
|
+
async connect(path, protocols = []) {
|
|
450
|
+
const p = backendPath(path);
|
|
451
|
+
const pt = await bridge();
|
|
452
|
+
const id = ++nextId;
|
|
453
|
+
const socket = new BackendSocket(pt, id);
|
|
454
|
+
pending.set(id, { socket });
|
|
455
|
+
pt.postMessage({
|
|
456
|
+
op: "ws",
|
|
457
|
+
id,
|
|
458
|
+
path: p,
|
|
459
|
+
protocols: typeof protocols === "string" ? [protocols] : protocols
|
|
460
|
+
});
|
|
461
|
+
return socket;
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
/** A WebSocket-like socket over the handle: send, close, open/message/close/error events. */
|
|
465
|
+
var BackendSocket = class extends EventTarget {
|
|
466
|
+
port;
|
|
467
|
+
id;
|
|
468
|
+
static CONNECTING = 0;
|
|
469
|
+
static OPEN = 1;
|
|
470
|
+
static CLOSING = 2;
|
|
471
|
+
static CLOSED = 3;
|
|
472
|
+
readyState = 0;
|
|
473
|
+
protocol = "";
|
|
474
|
+
binaryType = "arraybuffer";
|
|
475
|
+
onopen = null;
|
|
476
|
+
onmessage = null;
|
|
477
|
+
onclose = null;
|
|
478
|
+
onerror = null;
|
|
479
|
+
constructor(port, id) {
|
|
480
|
+
super();
|
|
481
|
+
this.port = port;
|
|
482
|
+
this.id = id;
|
|
483
|
+
}
|
|
484
|
+
send(data) {
|
|
485
|
+
if (this.readyState !== 1) throw new DOMException("The socket is not open.", "InvalidStateError");
|
|
486
|
+
const out = typeof data === "string" || data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
|
|
487
|
+
this.port.postMessage({
|
|
488
|
+
op: "ws-send",
|
|
489
|
+
id: this.id,
|
|
490
|
+
data: out
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
close(code, reason) {
|
|
494
|
+
if (this.readyState >= 2) return;
|
|
495
|
+
this.readyState = 2;
|
|
496
|
+
this.port.postMessage({
|
|
497
|
+
op: "ws-close",
|
|
498
|
+
id: this.id,
|
|
499
|
+
code,
|
|
500
|
+
reason
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
#emit(e) {
|
|
504
|
+
this.dispatchEvent(e);
|
|
505
|
+
this[`on${e.type}`]?.call(this, e);
|
|
506
|
+
}
|
|
507
|
+
/** @internal */
|
|
508
|
+
_opened(protocol) {
|
|
509
|
+
this.readyState = 1;
|
|
510
|
+
this.protocol = protocol;
|
|
511
|
+
this.#emit(new Event("open"));
|
|
512
|
+
}
|
|
513
|
+
/** @internal */
|
|
514
|
+
_message(data) {
|
|
515
|
+
this.#emit(new MessageEvent("message", { data }));
|
|
516
|
+
}
|
|
517
|
+
/** @internal */
|
|
518
|
+
_closed(code, reason, clean) {
|
|
519
|
+
if (this.readyState === 3) return;
|
|
520
|
+
const wasOpen = this.readyState === 1 || this.readyState === 2;
|
|
521
|
+
this.readyState = 3;
|
|
522
|
+
pending.delete(this.id);
|
|
523
|
+
if (!clean && !wasOpen) this.#emit(new Event("error"));
|
|
524
|
+
this.#emit(new CloseEvent("close", {
|
|
525
|
+
code,
|
|
526
|
+
reason,
|
|
527
|
+
wasClean: clean
|
|
528
|
+
}));
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
async function errorOf(res) {
|
|
532
|
+
try {
|
|
533
|
+
const b = await res.json();
|
|
534
|
+
if (typeof b.error === "string") return new CloudError(b.error, b.message ?? b.error, res.status, b);
|
|
535
|
+
} catch {}
|
|
536
|
+
}
|
|
537
|
+
/** A file link's data (/a/<did>/<name>#d=<data>), as the shell passes it: base64url text. */
|
|
538
|
+
function launchDataOnce() {
|
|
539
|
+
const m = /^#appos-data=([A-Za-z0-9_-]+)$/.exec(location.hash);
|
|
540
|
+
if (!m) return void 0;
|
|
541
|
+
history.replaceState(history.state, "", location.pathname + location.search);
|
|
542
|
+
return m[1];
|
|
543
|
+
}
|
|
544
|
+
/** The actor a share link opened this app on, and the link's key, as the shell passes them. */
|
|
545
|
+
function launchLinkOnce() {
|
|
546
|
+
const m = /^#appos-actor=([^&]+)&k=([A-Za-z0-9_-]+)$/.exec(location.hash);
|
|
547
|
+
if (!m) return void 0;
|
|
548
|
+
history.replaceState(history.state, "", location.pathname + location.search);
|
|
549
|
+
return {
|
|
550
|
+
actor: decodeURIComponent(m[1]),
|
|
551
|
+
key: m[2]
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
async function actorJson(path, init = {}) {
|
|
555
|
+
const headers = new Headers(init.headers);
|
|
556
|
+
let body = init.body;
|
|
557
|
+
if (init.json !== void 0) {
|
|
558
|
+
body = JSON.stringify(init.json);
|
|
559
|
+
headers.set("content-type", "application/json");
|
|
560
|
+
}
|
|
561
|
+
const { json: _, ...rest } = init;
|
|
562
|
+
const res = await backend.fetch(path, {
|
|
563
|
+
...rest,
|
|
564
|
+
headers,
|
|
565
|
+
body
|
|
566
|
+
});
|
|
567
|
+
if (!res.ok) {
|
|
568
|
+
const err = await errorOf(res) ?? new CloudError("error", `${path} failed (${res.status})`, res.status);
|
|
569
|
+
explain(err, actorPathOf(path));
|
|
570
|
+
throw err;
|
|
571
|
+
}
|
|
572
|
+
return await res.json();
|
|
573
|
+
}
|
|
574
|
+
/** A connection to one actor: RPC, fetch and a live socket, each with the user's claims. */
|
|
575
|
+
var Actor = class {
|
|
576
|
+
id;
|
|
577
|
+
path;
|
|
578
|
+
/** The signed-in user's roles, as of open(). */
|
|
579
|
+
roles = [];
|
|
580
|
+
constructor(id) {
|
|
581
|
+
this.id = id;
|
|
582
|
+
this.path = `/actor/${encodeURIComponent(id)}`;
|
|
583
|
+
}
|
|
584
|
+
/** backend.fetch() to the actor's own fetch handler, at `sub` under it. Problems the user can act on get the SDK's sheets. */
|
|
585
|
+
async fetch(sub = "/", init = {}) {
|
|
586
|
+
const res = await backend.fetch(this.path + (sub.startsWith("/") ? sub : `/${sub}`).replace(/^\/$/, ""), init);
|
|
587
|
+
if (!res.ok) {
|
|
588
|
+
const err = await errorOf(res.clone());
|
|
589
|
+
if (err) explain(err, this.path);
|
|
590
|
+
}
|
|
591
|
+
return res;
|
|
592
|
+
}
|
|
593
|
+
/** Calls a method of the actor's class. Throws CloudError on failure. */
|
|
594
|
+
async call(method, ...args) {
|
|
595
|
+
return (await actorJson(`${this.path}/_rpc`, {
|
|
596
|
+
method: "POST",
|
|
597
|
+
json: {
|
|
598
|
+
method,
|
|
599
|
+
args
|
|
600
|
+
}
|
|
601
|
+
})).result;
|
|
602
|
+
}
|
|
603
|
+
/** A WebSocket to the actor's fetch handler. */
|
|
604
|
+
websocket(sub = "/", protocols = []) {
|
|
605
|
+
return backend.connect(this.path + (sub.startsWith("/") ? sub : `/${sub}`), protocols);
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* The owner and members to show: [{ id, role, name?, image? }]. `name` and
|
|
609
|
+
* `image` (an https avatar URL) come from each person's assistant-ui
|
|
610
|
+
* account; someone who never signed in to appOS has only id and role.
|
|
611
|
+
* The backend reads the same list with env.appos.profiles(). Cloud actors only.
|
|
612
|
+
*/
|
|
613
|
+
async profiles() {
|
|
614
|
+
return (await actorJson(`${this.path}/_profiles`)).profiles;
|
|
615
|
+
}
|
|
616
|
+
/** Owner, roles, the build it runs. Shows the owner a newer build a member asked for (Approve / Deny). */
|
|
617
|
+
async info() {
|
|
618
|
+
const info = await actorJson(`${this.path}/_info`);
|
|
619
|
+
this.roles = info.roles;
|
|
620
|
+
const p = info.pending;
|
|
621
|
+
if (info.isOwner && p && !p.denied) {
|
|
622
|
+
const decide = (approve) => void actorJson(`${this.path}/_upgrade`, {
|
|
623
|
+
method: "POST",
|
|
624
|
+
json: { approve }
|
|
625
|
+
}).catch(() => {});
|
|
626
|
+
showSheet({
|
|
627
|
+
title: "Update this board?",
|
|
628
|
+
text: `Someone wants to update ${appName} to ${p.version}. It runs ${info.running?.version ?? "?"} now.`,
|
|
629
|
+
dismissable: false,
|
|
630
|
+
actions: [{
|
|
631
|
+
label: "Deny",
|
|
632
|
+
run: () => decide(false)
|
|
633
|
+
}, {
|
|
634
|
+
label: "Approve",
|
|
635
|
+
primary: true,
|
|
636
|
+
run: () => decide(true)
|
|
637
|
+
}]
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
return info;
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
var actors = {
|
|
644
|
+
/**
|
|
645
|
+
* A new actor of class `name`, owned by the user, on their default host.
|
|
646
|
+
* `host` says where it went: "cloud" or the host's name.
|
|
647
|
+
*/
|
|
648
|
+
create(name) {
|
|
649
|
+
return actorJson(`/actors/${encodeURIComponent(name)}`, { method: "POST" });
|
|
650
|
+
},
|
|
651
|
+
/** A connection to an actor the user holds a role in. Rejects with "not-member" otherwise. */
|
|
652
|
+
async open(id) {
|
|
653
|
+
const a = new Actor(id);
|
|
654
|
+
await a.info();
|
|
655
|
+
return a;
|
|
656
|
+
},
|
|
657
|
+
/** The actors the user owns or holds a role in, on every host. */
|
|
658
|
+
async list() {
|
|
659
|
+
return (await actorJson("/actors")).actors;
|
|
660
|
+
},
|
|
661
|
+
/** Owner only: gives `user` a role in actor `id`. */
|
|
662
|
+
/** Owner only: gives `user` (their appOS ID) a role in actor `id`. */
|
|
663
|
+
async grant(id, user, role) {
|
|
664
|
+
await actorJson(`${new Actor(id).path}/_members`, {
|
|
665
|
+
method: "POST",
|
|
666
|
+
json: {
|
|
667
|
+
user,
|
|
668
|
+
role
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
},
|
|
672
|
+
/** Owner only: takes `user`'s role in actor `id` away. */
|
|
673
|
+
async revoke(id, user) {
|
|
674
|
+
await actorJson(`${new Actor(id).path}/_members`, {
|
|
675
|
+
method: "DELETE",
|
|
676
|
+
json: { user }
|
|
677
|
+
});
|
|
678
|
+
},
|
|
679
|
+
/**
|
|
680
|
+
* The actor a share link opened this app on, joined with the link's key
|
|
681
|
+
* (once per launch). Undefined when the app was not opened from one.
|
|
682
|
+
*/
|
|
683
|
+
async launched() {
|
|
684
|
+
const l = launchLink;
|
|
685
|
+
launchLink = void 0;
|
|
686
|
+
if (!l) return void 0;
|
|
687
|
+
const a = new Actor(l.actor);
|
|
688
|
+
await actorJson(`${a.path}/_join`, {
|
|
689
|
+
method: "POST",
|
|
690
|
+
json: { key: l.key }
|
|
691
|
+
});
|
|
692
|
+
await a.info();
|
|
693
|
+
return a;
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
/**
|
|
697
|
+
* A link that opens this app on actor `id` and gives whoever opens it `role`
|
|
698
|
+
* (editor by default; viewers can share only as viewers). The app shows it
|
|
699
|
+
* in its own share sheet.
|
|
700
|
+
*/
|
|
701
|
+
async function share(id, role = "editor") {
|
|
702
|
+
const { key } = await actorJson(`${new Actor(id).path}/_invite?role=${role}`);
|
|
703
|
+
return (await ask("appos:share-link", {
|
|
704
|
+
actor: id,
|
|
705
|
+
key
|
|
706
|
+
})).url;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Opens appOS's Share sheet for actor `id`: the people on it with their role
|
|
710
|
+
* and the link each joined by, and, for its owner, the share links (new,
|
|
711
|
+
* copy, revoke). The same sheet for every app; resolves once it is shown.
|
|
712
|
+
*/
|
|
713
|
+
async function openShare(id) {
|
|
714
|
+
await ask("appos:share-sheet", { actor: id });
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Calls `fn` when appOS finds the signed-in person's access to an actor
|
|
718
|
+
* changed (revoked, or they left on another device). Returns an unsubscribe.
|
|
719
|
+
*/
|
|
720
|
+
function onAccess(fn) {
|
|
721
|
+
const origin = parentOrigin();
|
|
722
|
+
const listener = (e) => {
|
|
723
|
+
if (e.source !== window.parent || origin && e.origin !== origin) return;
|
|
724
|
+
const d = e.data;
|
|
725
|
+
if (d?.type !== "appos:access" || typeof d.actor !== "string") return;
|
|
726
|
+
fn({
|
|
727
|
+
actor: d.actor,
|
|
728
|
+
role: d.role === "owner" || d.role === "editor" || d.role === "viewer" ? d.role : null
|
|
729
|
+
});
|
|
730
|
+
};
|
|
731
|
+
addEventListener("message", listener);
|
|
732
|
+
return () => removeEventListener("message", listener);
|
|
733
|
+
}
|
|
734
|
+
/** The live file this frame runs (appos.liveFile()). */
|
|
735
|
+
var LiveFile = class {
|
|
736
|
+
/** The link that opens this file, to copy and send. */
|
|
737
|
+
url;
|
|
738
|
+
#port;
|
|
739
|
+
#data;
|
|
740
|
+
#rev = 0;
|
|
741
|
+
/** The newest local write the cloud hasn't confirmed. */
|
|
742
|
+
#pending;
|
|
743
|
+
#sent = 0;
|
|
744
|
+
#acked = 0;
|
|
745
|
+
#first;
|
|
746
|
+
#resolveFirst;
|
|
747
|
+
#changeFns = /* @__PURE__ */ new Set();
|
|
748
|
+
#statusFns = /* @__PURE__ */ new Set();
|
|
749
|
+
#status = { state: "connecting" };
|
|
750
|
+
/** @internal */
|
|
751
|
+
constructor(port, url) {
|
|
752
|
+
this.url = url;
|
|
753
|
+
this.#port = port;
|
|
754
|
+
this.#first = new Promise((r) => this.#resolveFirst = r);
|
|
755
|
+
port.onmessage = (e) => this.#onMessage(e.data);
|
|
756
|
+
port.start();
|
|
757
|
+
}
|
|
758
|
+
/** The file's text as this frame last saw it; undefined until loaded(). */
|
|
759
|
+
get data() {
|
|
760
|
+
return this.#data;
|
|
761
|
+
}
|
|
762
|
+
get rev() {
|
|
763
|
+
return this.#rev;
|
|
764
|
+
}
|
|
765
|
+
get status() {
|
|
766
|
+
return this.#status;
|
|
767
|
+
}
|
|
768
|
+
/** Resolves with the file's text once the cloud has sent it. */
|
|
769
|
+
loaded() {
|
|
770
|
+
return this.#first;
|
|
771
|
+
}
|
|
772
|
+
/** Runs `fn` with the text whenever someone else changed the file. */
|
|
773
|
+
onChange(fn) {
|
|
774
|
+
this.#changeFns.add(fn);
|
|
775
|
+
return () => void this.#changeFns.delete(fn);
|
|
776
|
+
}
|
|
777
|
+
/** Runs `fn` when the connection changes (connecting, live with N people, offline). */
|
|
778
|
+
onStatus(fn) {
|
|
779
|
+
this.#statusFns.add(fn);
|
|
780
|
+
return () => void this.#statusFns.delete(fn);
|
|
781
|
+
}
|
|
782
|
+
/** Replaces the file's text for everyone. Resent after a reconnect until the cloud confirms it. */
|
|
783
|
+
save(data) {
|
|
784
|
+
this.#data = data;
|
|
785
|
+
this.#pending = data;
|
|
786
|
+
this.#put(data);
|
|
787
|
+
}
|
|
788
|
+
/** True while a local write is not yet in the cloud. */
|
|
789
|
+
get saving() {
|
|
790
|
+
return this.#pending !== void 0;
|
|
791
|
+
}
|
|
792
|
+
close() {
|
|
793
|
+
this.#port.postMessage({ t: "close" });
|
|
794
|
+
this.#port.close();
|
|
795
|
+
}
|
|
796
|
+
#put(data) {
|
|
797
|
+
this.#sent++;
|
|
798
|
+
this.#port.postMessage({
|
|
799
|
+
t: "put",
|
|
800
|
+
data
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
#setStatus(s) {
|
|
804
|
+
this.#status = s;
|
|
805
|
+
for (const fn of this.#statusFns) fn(s);
|
|
806
|
+
}
|
|
807
|
+
#changed(data) {
|
|
808
|
+
if (data === this.#data) return;
|
|
809
|
+
this.#data = data;
|
|
810
|
+
for (const fn of this.#changeFns) fn(data);
|
|
811
|
+
}
|
|
812
|
+
#onMessage(m) {
|
|
813
|
+
switch (m.t) {
|
|
814
|
+
case "welcome": {
|
|
815
|
+
this.#sent = this.#acked = 0;
|
|
816
|
+
this.#rev = m.rev;
|
|
817
|
+
const data = m.data;
|
|
818
|
+
const first = this.#data === void 0;
|
|
819
|
+
if (this.#pending !== void 0 && this.#pending !== data) this.#put(this.#pending);
|
|
820
|
+
else {
|
|
821
|
+
this.#pending = void 0;
|
|
822
|
+
if (first) this.#data = data;
|
|
823
|
+
else this.#changed(data);
|
|
824
|
+
}
|
|
825
|
+
this.#setStatus({
|
|
826
|
+
state: "live",
|
|
827
|
+
peers: m.peers
|
|
828
|
+
});
|
|
829
|
+
if (first) this.#resolveFirst(this.#data ?? data);
|
|
830
|
+
break;
|
|
831
|
+
}
|
|
832
|
+
case "ack":
|
|
833
|
+
this.#rev = m.rev;
|
|
834
|
+
if (++this.#acked >= this.#sent) this.#pending = void 0;
|
|
835
|
+
break;
|
|
836
|
+
case "data":
|
|
837
|
+
this.#rev = m.rev;
|
|
838
|
+
if (this.#pending === void 0) this.#changed(m.data);
|
|
839
|
+
break;
|
|
840
|
+
case "peers":
|
|
841
|
+
if (this.#status.state === "live") this.#setStatus({
|
|
842
|
+
state: "live",
|
|
843
|
+
peers: m.peers
|
|
844
|
+
});
|
|
845
|
+
break;
|
|
846
|
+
case "error": if (m.code === "offline") this.#setStatus({
|
|
847
|
+
state: "offline",
|
|
848
|
+
message: String(m.message)
|
|
849
|
+
});
|
|
850
|
+
else this.#setStatus({
|
|
851
|
+
state: "error",
|
|
852
|
+
code: String(m.code),
|
|
853
|
+
message: String(m.message)
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
async function liveFile() {
|
|
859
|
+
const channel = new MessageChannel();
|
|
860
|
+
try {
|
|
861
|
+
const r = await ask("appos:live-file", {}, 2e4, [channel.port2]);
|
|
862
|
+
return new LiveFile(channel.port1, r.url);
|
|
863
|
+
} catch (e) {
|
|
864
|
+
channel.port1.close();
|
|
865
|
+
if (e instanceof CloudError && e.code === "not-live") return void 0;
|
|
866
|
+
throw e;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Moves the file this frame runs to the appOS cloud as a live file holding
|
|
871
|
+
* `data` (text, at most 512 KB), and returns its link. Anyone with the link
|
|
872
|
+
* opens the file and edits it live; no sign-in. Already live: its link.
|
|
873
|
+
* Afterwards appos.liveFile() connects to it.
|
|
874
|
+
*/
|
|
875
|
+
async function shareFile(data) {
|
|
876
|
+
return ask("appos:share-file", { data }, 3e4);
|
|
877
|
+
}
|
|
878
|
+
/** A port to the shell for one AI call or voice session. */
|
|
879
|
+
function shellPort(type) {
|
|
880
|
+
if (window.parent === window) throw new CloudError("no-shell", "Open this app from appOS.");
|
|
881
|
+
const ch = new MessageChannel();
|
|
882
|
+
window.parent.postMessage({ type }, parentOrigin() ?? "*", [ch.port2]);
|
|
883
|
+
ch.port1.start();
|
|
884
|
+
return ch.port1;
|
|
885
|
+
}
|
|
886
|
+
function postPlain(port, msg) {
|
|
887
|
+
try {
|
|
888
|
+
port.postMessage(msg);
|
|
889
|
+
} catch {
|
|
890
|
+
port.postMessage(JSON.parse(JSON.stringify(msg)));
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
var capError = (e) => new CloudError(e.code ?? "error", e.message ?? "The call failed.");
|
|
894
|
+
/**
|
|
895
|
+
* One AI call to the shell (the "appos:ai" port): AI SDK LanguageModelV4
|
|
896
|
+
* call options in (prompt, tools, maxOutputTokens…; no headers or signal),
|
|
897
|
+
* its stream parts out. `model` is a hint: the provider the user set up
|
|
898
|
+
* decides. Errors with code "not-configured" mean no AI is set up; offer
|
|
899
|
+
* appos.openSettings(). The AI SDK model on top is appos-client/ai-sdk.
|
|
900
|
+
*/
|
|
901
|
+
function aiCall(options, model, signal) {
|
|
902
|
+
const port = shellPort("appos:ai");
|
|
903
|
+
const abort = () => {
|
|
904
|
+
postPlain(port, { op: "abort" });
|
|
905
|
+
port.close();
|
|
906
|
+
};
|
|
907
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
908
|
+
return new ReadableStream({
|
|
909
|
+
start(controller) {
|
|
910
|
+
port.onmessage = (e) => {
|
|
911
|
+
const d = e.data;
|
|
912
|
+
if (d.part) {
|
|
913
|
+
const p = d.part;
|
|
914
|
+
controller.enqueue(p.type === "error" ? {
|
|
915
|
+
type: "error",
|
|
916
|
+
error: capError(p.error)
|
|
917
|
+
} : p);
|
|
918
|
+
} else if (d.done) {
|
|
919
|
+
controller.close();
|
|
920
|
+
port.close();
|
|
921
|
+
} else if (d.error) {
|
|
922
|
+
controller.error(capError(d.error));
|
|
923
|
+
port.close();
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
postPlain(port, {
|
|
927
|
+
op: "stream",
|
|
928
|
+
model,
|
|
929
|
+
options
|
|
930
|
+
});
|
|
931
|
+
},
|
|
932
|
+
cancel: abort
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
/** Text deltas for one prompt: `for await (const t of appos.ai.stream({ prompt: "Hi" }))`. */
|
|
936
|
+
async function* aiStream(opts) {
|
|
937
|
+
const reader = aiCall({
|
|
938
|
+
prompt: [...opts.system ? [{
|
|
939
|
+
role: "system",
|
|
940
|
+
content: opts.system
|
|
941
|
+
}] : [], {
|
|
942
|
+
role: "user",
|
|
943
|
+
content: [{
|
|
944
|
+
type: "text",
|
|
945
|
+
text: opts.prompt
|
|
946
|
+
}]
|
|
947
|
+
}],
|
|
948
|
+
maxOutputTokens: opts.maxOutputTokens ?? 4096
|
|
949
|
+
}, opts.model).getReader();
|
|
950
|
+
for (;;) {
|
|
951
|
+
const { done, value } = await reader.read();
|
|
952
|
+
if (done) return;
|
|
953
|
+
if (value.type === "text-delta") yield value.delta;
|
|
954
|
+
else if (value.type === "error") throw value.error;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Live transcription. The shell holds the mic and the provider; the app gets
|
|
959
|
+
* text. Times are seconds since listening started. Ends with an "end" event
|
|
960
|
+
* (after an "error" one when it failed).
|
|
961
|
+
*/
|
|
962
|
+
function transcribe(options, onEvent) {
|
|
963
|
+
let port;
|
|
964
|
+
try {
|
|
965
|
+
port = shellPort("appos:voice");
|
|
966
|
+
} catch (e) {
|
|
967
|
+
const err = e;
|
|
968
|
+
queueMicrotask(() => {
|
|
969
|
+
onEvent({
|
|
970
|
+
event: "error",
|
|
971
|
+
code: err.code,
|
|
972
|
+
message: err.message
|
|
973
|
+
});
|
|
974
|
+
onEvent({ event: "end" });
|
|
975
|
+
});
|
|
976
|
+
return {
|
|
977
|
+
stop() {},
|
|
978
|
+
ended: Promise.resolve()
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
const ended = new Promise((resolve) => {
|
|
982
|
+
port.onmessage = (e) => {
|
|
983
|
+
const ev = e.data;
|
|
984
|
+
onEvent(ev);
|
|
985
|
+
if (ev.event === "end") {
|
|
986
|
+
port.close();
|
|
987
|
+
resolve();
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
});
|
|
991
|
+
postPlain(port, {
|
|
992
|
+
op: "start",
|
|
993
|
+
options
|
|
994
|
+
});
|
|
995
|
+
return {
|
|
996
|
+
stop: () => postPlain(port, { op: "stop" }),
|
|
997
|
+
ended
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
var permissions = {
|
|
1001
|
+
/** The grant now: "prompt" until the user has answered. */
|
|
1002
|
+
async query(cap) {
|
|
1003
|
+
return (await ask("appos:permission", { cap })).state;
|
|
1004
|
+
},
|
|
1005
|
+
/** Asks the user (the shell's prompt) if they never have; the answer is remembered per app. */
|
|
1006
|
+
async request(cap) {
|
|
1007
|
+
return (await ask("appos:permission", {
|
|
1008
|
+
cap,
|
|
1009
|
+
request: true
|
|
1010
|
+
}, 6e5)).state;
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
var launchLink = launchLinkOnce();
|
|
1014
|
+
var launchedData = launchDataOnce();
|
|
1015
|
+
var appos = {
|
|
1016
|
+
/** The app's backend: backend.fetch(path), backend.connect(path). No URL reaches it. */
|
|
1017
|
+
backend,
|
|
1018
|
+
/** The app's actors: create, open, list, grant, revoke, launched (appos.actors in the manifest). */
|
|
1019
|
+
actors,
|
|
1020
|
+
/** A share link to an actor for a role: share(id, "viewer"). */
|
|
1021
|
+
share,
|
|
1022
|
+
/** appOS's Share sheet for an actor: openShare(id). */
|
|
1023
|
+
openShare,
|
|
1024
|
+
/** Hears when the person's access to an actor changed: onAccess(({ actor, role }) => …). */
|
|
1025
|
+
onAccess,
|
|
1026
|
+
/** { version, previousVersion }: previousVersion only on the first launch after an update. */
|
|
1027
|
+
ready,
|
|
1028
|
+
/** This build's manifest version (after ready()). */
|
|
1029
|
+
get version() {
|
|
1030
|
+
return current?.version;
|
|
1031
|
+
},
|
|
1032
|
+
/** This build's appos.build, if the app has builds (after ready()). */
|
|
1033
|
+
get build() {
|
|
1034
|
+
return current?.build;
|
|
1035
|
+
},
|
|
1036
|
+
/**
|
|
1037
|
+
* Asks the shell for this app's newest build now (the app's server said it
|
|
1038
|
+
* is too old, or the app came back into view): the shell checks the app's
|
|
1039
|
+
* update feed and applies what it lists at once, relaunching this frame.
|
|
1040
|
+
* Answers when there was nothing to apply ("none"), or the check failed.
|
|
1041
|
+
*/
|
|
1042
|
+
checkForUpdate() {
|
|
1043
|
+
return ask("appos:check-update", {}, 12e4);
|
|
1044
|
+
},
|
|
1045
|
+
/**
|
|
1046
|
+
* What this origin ran before, on the first launch after an update (after
|
|
1047
|
+
* ready()): the version, or "0.0.1 (12)" for apps with builds.
|
|
1048
|
+
*/
|
|
1049
|
+
get previousVersion() {
|
|
1050
|
+
return current?.previousVersion;
|
|
1051
|
+
},
|
|
1052
|
+
/** Runs once, on the first launch after an update: migrate local data here. */
|
|
1053
|
+
onUpgrade(fn) {
|
|
1054
|
+
upgradeListeners.push(fn);
|
|
1055
|
+
if (current?.upgrade) fn(current.upgrade.from, current.upgrade.to);
|
|
1056
|
+
else ready().catch(() => {});
|
|
1057
|
+
},
|
|
1058
|
+
/**
|
|
1059
|
+
* The data a file link opened this app with (/a/<did>/<name>#d=<data>),
|
|
1060
|
+
* the first time it is asked: base64url text in the app's own format. The
|
|
1061
|
+
* file is local and the link reopens it, so fill the file only when it is
|
|
1062
|
+
* new. It came from a link: treat it as untrusted input.
|
|
1063
|
+
*/
|
|
1064
|
+
launchData() {
|
|
1065
|
+
const d = launchedData;
|
|
1066
|
+
launchedData = void 0;
|
|
1067
|
+
return d;
|
|
1068
|
+
},
|
|
1069
|
+
/**
|
|
1070
|
+
* The live file this frame runs, connected: load with loaded(), write with
|
|
1071
|
+
* save(), hear others with onChange(). Undefined when the file is not live
|
|
1072
|
+
* (see shareFile()).
|
|
1073
|
+
*/
|
|
1074
|
+
liveFile,
|
|
1075
|
+
/** Moves this frame's file to the cloud as a live file; resolves to its link. */
|
|
1076
|
+
shareFile,
|
|
1077
|
+
/** The file (grain) this frame runs; undefined in appOS from before grains. */
|
|
1078
|
+
async grain() {
|
|
1079
|
+
return (await getHello()).grain;
|
|
1080
|
+
},
|
|
1081
|
+
/**
|
|
1082
|
+
* The shell's file picker: this app's files on every host the user is
|
|
1083
|
+
* signed in to, and New (on the host the user picks). Resolves to what the
|
|
1084
|
+
* user picked or made, or null when they cancelled. Apps with
|
|
1085
|
+
* appos.multiple may ask for several; the shell saves them as a workspace.
|
|
1086
|
+
*/
|
|
1087
|
+
files: {
|
|
1088
|
+
async open({ multiple = false } = {}) {
|
|
1089
|
+
try {
|
|
1090
|
+
return await ask("appos:files-open", { multiple }, 864e5);
|
|
1091
|
+
} catch (e) {
|
|
1092
|
+
if (e instanceof CloudError && e.code === "cancelled") return null;
|
|
1093
|
+
throw e;
|
|
1094
|
+
}
|
|
1095
|
+
},
|
|
1096
|
+
/**
|
|
1097
|
+
* The Files app only (did:web:appos.assistant-ui.workers.dev:apps:files):
|
|
1098
|
+
* every file of every app, on this device and every host, read-only:
|
|
1099
|
+
* where each is, never its data. Other apps get CloudError "forbidden".
|
|
1100
|
+
*/
|
|
1101
|
+
all() {
|
|
1102
|
+
return ask("appos:files-all", {}, 6e4);
|
|
1103
|
+
},
|
|
1104
|
+
/** The Files app only: opens a file all() listed in its own app, in a tab. */
|
|
1105
|
+
openInApp(key) {
|
|
1106
|
+
return ask("appos:files-open-in", { key }, 6e4);
|
|
1107
|
+
}
|
|
1108
|
+
},
|
|
1109
|
+
/** Makes a new file of this app (an actor when it has them) and opens it in its own tab. */
|
|
1110
|
+
newGrain() {
|
|
1111
|
+
return ask("appos:new-grain");
|
|
1112
|
+
},
|
|
1113
|
+
/**
|
|
1114
|
+
* Local grains the user deleted since the app last ran: delete their data
|
|
1115
|
+
* (it shares this origin). Called once per launch with the ids.
|
|
1116
|
+
*/
|
|
1117
|
+
onGrainRemoved(fn) {
|
|
1118
|
+
removedListeners.push(fn);
|
|
1119
|
+
if (removedSeen?.length) fn(removedSeen);
|
|
1120
|
+
else getHello().catch(() => {});
|
|
1121
|
+
},
|
|
1122
|
+
/** Names the app in the SDK's sheets. */
|
|
1123
|
+
setName(name) {
|
|
1124
|
+
appName = name;
|
|
1125
|
+
},
|
|
1126
|
+
/** Names the file this frame runs, as Home and the tab show it. */
|
|
1127
|
+
async setTitle(title) {
|
|
1128
|
+
await ask("appos:set-title", { title });
|
|
1129
|
+
},
|
|
1130
|
+
/**
|
|
1131
|
+
* A count for the shell to show on this app's tile or tab (unread items, say); 0 clears it. A whole number,
|
|
1132
|
+
* 0 or more. Nothing comes back, and a shell may show it or ignore it (appOS itself doesn't show it yet).
|
|
1133
|
+
* Outside a shell it does nothing.
|
|
1134
|
+
*/
|
|
1135
|
+
setBadge(count) {
|
|
1136
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("appos.setBadge takes a whole number, 0 or more.");
|
|
1137
|
+
tell("appos:badge", { count });
|
|
1138
|
+
},
|
|
1139
|
+
/**
|
|
1140
|
+
* How many CSS px of the shell's own chrome (a host page's mark, say) cover the start of the app's header, from
|
|
1141
|
+
* the shell's hello: pad the header's start by it. 0 when the shell says nothing (appOS itself) or outside a shell.
|
|
1142
|
+
*/
|
|
1143
|
+
async markSpace() {
|
|
1144
|
+
if (window.parent === window) return 0;
|
|
1145
|
+
const m = (await getHello()).markSpace;
|
|
1146
|
+
return typeof m === "number" && Number.isFinite(m) && m > 0 ? m : 0;
|
|
1147
|
+
},
|
|
1148
|
+
/**
|
|
1149
|
+
* Opens a web page (https) as a new top-level page with no opener: sign-in pages, docs, anything outside the
|
|
1150
|
+
* app. Call it from the tap or click itself. A popup the app's sandboxed frame opens inherits the sandbox,
|
|
1151
|
+
* and browsers won't show pages that send Cross-Origin-Opener-Policy there; the shell opens it instead.
|
|
1152
|
+
* Outside appOS it opens the page itself.
|
|
1153
|
+
*/
|
|
1154
|
+
async openExternal(url) {
|
|
1155
|
+
if (window.parent === window) {
|
|
1156
|
+
window.open(url, "_blank", "noopener,noreferrer");
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
await ask("appos:open-external", { url });
|
|
1160
|
+
},
|
|
1161
|
+
/** Opens appOS Settings (AI & voice, permissions), e.g. after a "not-configured" error. */
|
|
1162
|
+
async openSettings() {
|
|
1163
|
+
await ask("appos:open-settings");
|
|
1164
|
+
},
|
|
1165
|
+
permissions,
|
|
1166
|
+
/** Language models through the shell (the "ai" capability). */
|
|
1167
|
+
/** Text deltas for one prompt. For the AI SDK, use apposModel() from appos-client/ai-sdk. */
|
|
1168
|
+
ai: { stream: aiStream },
|
|
1169
|
+
/** Live transcription through the shell (the "microphone" capability). */
|
|
1170
|
+
voice: { transcribe },
|
|
1171
|
+
/** Light or dark, from the shell: get(), onChange(fn), autoApply(false). Applied to <html> by default. */
|
|
1172
|
+
theme
|
|
1173
|
+
};
|
|
1174
|
+
export { Actor, BackendSocket, CloudError, LiveFile, aiCall, appos, appos as default, backend, explain, showSheet, theme };
|