@assistant-ui/appos 0.0.0-stage → 0.0.2
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 +1468 -0
- package/dist/index.js +1662 -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 +112 -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 +661 -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 +144 -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,150 @@
|
|
|
1
|
+
// packages/appos-host/src/next/page.ts
|
|
2
|
+
var client = () => import("./chunks/src.js");
|
|
3
|
+
var aiSdk = () => import("./chunks/ai-sdk.js");
|
|
4
|
+
var GATEWAY_HOST = "ai-gateway.vercel.sh";
|
|
5
|
+
/** Platform answers that mean "no cloud here"; anything else is the app's own answer. */
|
|
6
|
+
var NO_CLOUD = /* @__PURE__ */ new Set([
|
|
7
|
+
"signed-out",
|
|
8
|
+
"unavailable",
|
|
9
|
+
"sign-in-not-configured",
|
|
10
|
+
"no-cloud",
|
|
11
|
+
"no-shell"
|
|
12
|
+
]);
|
|
13
|
+
var SERVER_URL = "/_appos/server.js";
|
|
14
|
+
var server;
|
|
15
|
+
var local = () => server ??= import(SERVER_URL).then((m) => m.default);
|
|
16
|
+
/** Set once this page has no cloud at all (outside appOS, or an embed); signed out is checked again each time. */
|
|
17
|
+
var noCloud = false;
|
|
18
|
+
/** A route handler request: the app's server Worker in the cloud, else the module in this page. */
|
|
19
|
+
async function serverFetch(request, signal) {
|
|
20
|
+
if (!noCloud) {
|
|
21
|
+
const url = new URL(request.url);
|
|
22
|
+
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.clone().arrayBuffer();
|
|
23
|
+
const { CloudError, backend } = await client();
|
|
24
|
+
try {
|
|
25
|
+
const res = await backend.fetch(`/server${url.pathname}${url.search}`, {
|
|
26
|
+
method: request.method,
|
|
27
|
+
headers: request.headers,
|
|
28
|
+
body,
|
|
29
|
+
signal
|
|
30
|
+
});
|
|
31
|
+
const type = res.headers.get("content-type") ?? "";
|
|
32
|
+
if (res.status < 400 || !type.includes("json")) return res;
|
|
33
|
+
const code = (await res.clone().json().catch(() => null))?.error;
|
|
34
|
+
if (typeof code !== "string" || !NO_CLOUD.has(code)) return res;
|
|
35
|
+
} catch (e) {
|
|
36
|
+
if (signal.aborted) throw e;
|
|
37
|
+
if (!(e instanceof CloudError)) throw e;
|
|
38
|
+
noCloud = true;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return (await local()).fetch(request);
|
|
42
|
+
}
|
|
43
|
+
function gatewayError(status, type, message) {
|
|
44
|
+
return Response.json({ error: {
|
|
45
|
+
message,
|
|
46
|
+
type
|
|
47
|
+
} }, { status });
|
|
48
|
+
}
|
|
49
|
+
/** appOS's AI gateway in the page: the Vercel gateway protocol (cloud/ai.ts), served by the shell's AI. */
|
|
50
|
+
async function gatewayFetch(request) {
|
|
51
|
+
if (request.headers.get("authorization") !== "Bearer appos") return gatewayError(401, "authentication_error", "appOS answers AI gateway calls made with its own key only.");
|
|
52
|
+
if (request.method !== "POST" || !/\/language-model$/.test(new URL(request.url).pathname)) return gatewayError(404, "not_found", "appOS's AI gateway serves language models only.");
|
|
53
|
+
const { apposModel } = await aiSdk();
|
|
54
|
+
const model = apposModel((request.headers.get("ai-language-model-id") ?? "default").replace(/^anthropic\//, ""));
|
|
55
|
+
const options = await request.json();
|
|
56
|
+
if (request.headers.get("ai-language-model-streaming") !== "true") try {
|
|
57
|
+
const { content, finishReason, usage, providerMetadata, warnings } = await model.doGenerate(options);
|
|
58
|
+
return Response.json({
|
|
59
|
+
content,
|
|
60
|
+
finishReason,
|
|
61
|
+
usage,
|
|
62
|
+
providerMetadata,
|
|
63
|
+
warnings
|
|
64
|
+
});
|
|
65
|
+
} catch (e) {
|
|
66
|
+
const err = e;
|
|
67
|
+
const type = err.code === "rate-limited" ? "rate_limit_exceeded" : err.code === "bad-request" ? "invalid_request_error" : "failed_dependency";
|
|
68
|
+
return gatewayError(err.code === "rate-limited" ? 429 : err.code === "bad-request" ? 400 : 424, type, err.message ?? String(e));
|
|
69
|
+
}
|
|
70
|
+
const { stream } = await model.doStream(options);
|
|
71
|
+
const enc = new TextEncoder();
|
|
72
|
+
const body = stream.pipeThrough(new TransformStream({ transform(part, controller) {
|
|
73
|
+
const out = part.type === "error" ? {
|
|
74
|
+
type: "error",
|
|
75
|
+
error: part.error?.message ?? String(part.error)
|
|
76
|
+
} : part;
|
|
77
|
+
controller.enqueue(enc.encode(`data: ${JSON.stringify(out)}\n\n`));
|
|
78
|
+
} }));
|
|
79
|
+
return new Response(body, { headers: { "content-type": "text/event-stream" } });
|
|
80
|
+
}
|
|
81
|
+
/** Answers one request the service worker relayed, streaming the response back on its port. */
|
|
82
|
+
async function answer(m, port) {
|
|
83
|
+
const abort = new AbortController();
|
|
84
|
+
port.onmessage = (e) => {
|
|
85
|
+
if (e.data?.op === "abort") abort.abort();
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
const request = new Request(m.url, {
|
|
89
|
+
method: m.method,
|
|
90
|
+
headers: m.headers,
|
|
91
|
+
body: m.body,
|
|
92
|
+
signal: abort.signal
|
|
93
|
+
});
|
|
94
|
+
const res = new URL(m.url).hostname === GATEWAY_HOST ? await gatewayFetch(request) : await serverFetch(request, abort.signal);
|
|
95
|
+
port.postMessage({
|
|
96
|
+
op: "head",
|
|
97
|
+
status: res.status,
|
|
98
|
+
statusText: res.statusText,
|
|
99
|
+
headers: [...res.headers]
|
|
100
|
+
});
|
|
101
|
+
if (res.body) {
|
|
102
|
+
const reader = res.body.getReader();
|
|
103
|
+
abort.signal.addEventListener("abort", () => void reader.cancel().catch(() => {}), { once: true });
|
|
104
|
+
for (;;) {
|
|
105
|
+
const { done, value } = await reader.read();
|
|
106
|
+
if (done) break;
|
|
107
|
+
const copy = value.slice();
|
|
108
|
+
port.postMessage({
|
|
109
|
+
op: "chunk",
|
|
110
|
+
data: copy.buffer
|
|
111
|
+
}, [copy.buffer]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
port.postMessage({ op: "end" });
|
|
115
|
+
} catch (e) {
|
|
116
|
+
if (!abort.signal.aborted) port.postMessage({
|
|
117
|
+
op: "error",
|
|
118
|
+
message: e instanceof Error ? e.message : String(e)
|
|
119
|
+
});
|
|
120
|
+
} finally {
|
|
121
|
+
port.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function install() {
|
|
125
|
+
const sw = navigator.serviceWorker;
|
|
126
|
+
sw?.addEventListener("message", (e) => {
|
|
127
|
+
const m = e.data;
|
|
128
|
+
if (m?.type === "appos:server-fetch" && e.ports[0]) answer(m, e.ports[0]);
|
|
129
|
+
});
|
|
130
|
+
sw?.startMessages();
|
|
131
|
+
const original = window.fetch.bind(window);
|
|
132
|
+
window.fetch = async (input, init) => {
|
|
133
|
+
const url = new URL(input instanceof Request ? input.url : String(input), location.href);
|
|
134
|
+
if (url.origin !== location.origin) return original(input, init);
|
|
135
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
|
|
136
|
+
const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
137
|
+
if (headers.get("rsc") === "1" && method === "GET") {
|
|
138
|
+
const base = url.pathname === "/" ? "/index" : url.pathname.replace(/\/$/, "");
|
|
139
|
+
const segment = headers.get("next-router-segment-prefetch");
|
|
140
|
+
const res = await original(segment ? `${base}.segments${segment}.segment.rsc` : `${base}.rsc`);
|
|
141
|
+
if (!res.ok) return res;
|
|
142
|
+
return new Response(res.body, {
|
|
143
|
+
status: 200,
|
|
144
|
+
headers: { "content-type": "text/x-component" }
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return original(input, init);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export { install };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { NextRequest } from "./next-server.js";
|
|
2
|
+
// packages/appos-host/src/next/routes.ts
|
|
3
|
+
function compile(pathname) {
|
|
4
|
+
const names = [];
|
|
5
|
+
let source = "";
|
|
6
|
+
for (const seg of pathname.split("/").filter(Boolean)) {
|
|
7
|
+
const optional = /^\[\[\.\.\.(.+)\]\]$/.exec(seg);
|
|
8
|
+
const many = /^\[\.\.\.(.+)\]$/.exec(seg);
|
|
9
|
+
const one = /^\[(.+)\]$/.exec(seg);
|
|
10
|
+
if (optional) {
|
|
11
|
+
names.push({
|
|
12
|
+
name: optional[1],
|
|
13
|
+
many: true
|
|
14
|
+
});
|
|
15
|
+
source += "(?:/(.*))?";
|
|
16
|
+
} else if (many) {
|
|
17
|
+
names.push({
|
|
18
|
+
name: many[1],
|
|
19
|
+
many: true
|
|
20
|
+
});
|
|
21
|
+
source += "/(.+)";
|
|
22
|
+
} else if (one) {
|
|
23
|
+
names.push({
|
|
24
|
+
name: one[1],
|
|
25
|
+
many: false
|
|
26
|
+
});
|
|
27
|
+
source += "/([^/]+)";
|
|
28
|
+
} else source += "/" + seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
29
|
+
}
|
|
30
|
+
const re = new RegExp(`^${source || "/"}/?$`);
|
|
31
|
+
return (path) => {
|
|
32
|
+
const m = re.exec(path);
|
|
33
|
+
if (!m) return void 0;
|
|
34
|
+
const params = {};
|
|
35
|
+
names.forEach(({ name, many }, i) => {
|
|
36
|
+
const v = m[i + 1];
|
|
37
|
+
if (v === void 0) return;
|
|
38
|
+
params[name] = many ? v.split("/").map(decodeURIComponent) : decodeURIComponent(v);
|
|
39
|
+
});
|
|
40
|
+
return params;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
// packages/appos-host/src/next/runtime.ts
|
|
44
|
+
var METHODS = [
|
|
45
|
+
"GET",
|
|
46
|
+
"HEAD",
|
|
47
|
+
"POST",
|
|
48
|
+
"PUT",
|
|
49
|
+
"PATCH",
|
|
50
|
+
"DELETE",
|
|
51
|
+
"OPTIONS"
|
|
52
|
+
];
|
|
53
|
+
/** The AI_GATEWAY_API_KEY that sends the gateway provider to appOS (cloud/ai.ts). */
|
|
54
|
+
var APPOS_GATEWAY_KEY = "appos";
|
|
55
|
+
function serve(table, env = {}) {
|
|
56
|
+
const g = globalThis;
|
|
57
|
+
g.process ??= {};
|
|
58
|
+
g.process.env = {
|
|
59
|
+
AI_GATEWAY_API_KEY: APPOS_GATEWAY_KEY,
|
|
60
|
+
...g.process.env,
|
|
61
|
+
...env
|
|
62
|
+
};
|
|
63
|
+
const routes = table.map((r) => ({
|
|
64
|
+
match: compile(r.pathname),
|
|
65
|
+
mod: r.mod
|
|
66
|
+
}));
|
|
67
|
+
return {
|
|
68
|
+
/** `secrets`: the cloud's env for this app (its server secrets); none in the page. */
|
|
69
|
+
async fetch(request, secrets) {
|
|
70
|
+
if (secrets) {
|
|
71
|
+
for (const [k, v] of Object.entries(secrets)) if (typeof v === "string") g.process.env[k] = v;
|
|
72
|
+
}
|
|
73
|
+
const path = new URL(request.url).pathname;
|
|
74
|
+
for (const { match, mod } of routes) {
|
|
75
|
+
const params = match(path);
|
|
76
|
+
if (!params) continue;
|
|
77
|
+
const method = request.method.toUpperCase();
|
|
78
|
+
const handler = mod[method] ?? (method === "HEAD" ? mod.GET : void 0);
|
|
79
|
+
const allow = METHODS.filter((m) => typeof mod[m] === "function").join(", ");
|
|
80
|
+
if (typeof handler !== "function") {
|
|
81
|
+
if (method === "OPTIONS") return new Response(null, {
|
|
82
|
+
status: 204,
|
|
83
|
+
headers: { allow }
|
|
84
|
+
});
|
|
85
|
+
return new Response(null, {
|
|
86
|
+
status: 405,
|
|
87
|
+
headers: { allow }
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
const response = await handler(new NextRequest(request), { params: Promise.resolve(params) });
|
|
92
|
+
if (response instanceof Response) return response;
|
|
93
|
+
console.error(`The ${method} handler for ${path} returned no Response.`);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
console.error(error);
|
|
96
|
+
}
|
|
97
|
+
return new Response("Internal Server Error", { status: 500 });
|
|
98
|
+
}
|
|
99
|
+
return new Response("Not Found", { status: 404 });
|
|
100
|
+
} };
|
|
101
|
+
}
|
|
102
|
+
export { APPOS_GATEWAY_KEY, serve };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// packages/appos-host/src/next/server.ts
|
|
2
|
+
var NextRequest = class extends Request {
|
|
3
|
+
get nextUrl() {
|
|
4
|
+
return new URL(this.url);
|
|
5
|
+
}
|
|
6
|
+
get cookies() {
|
|
7
|
+
const jar = /* @__PURE__ */ new Map();
|
|
8
|
+
for (const pair of (this.headers.get("cookie") ?? "").split(/;\s*/)) {
|
|
9
|
+
const i = pair.indexOf("=");
|
|
10
|
+
if (i > 0) jar.set(pair.slice(0, i), decodeURIComponent(pair.slice(i + 1)));
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
get: (name) => jar.has(name) ? {
|
|
14
|
+
name,
|
|
15
|
+
value: jar.get(name)
|
|
16
|
+
} : void 0,
|
|
17
|
+
getAll: () => [...jar].map(([name, value]) => ({
|
|
18
|
+
name,
|
|
19
|
+
value
|
|
20
|
+
})),
|
|
21
|
+
has: (name) => jar.has(name)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
function unsupported(what) {
|
|
26
|
+
throw new Error(`NextResponse.${what}() is middleware-only, and appOS doesn't run middleware yet.`);
|
|
27
|
+
}
|
|
28
|
+
var NextResponse = class NextResponse extends Response {
|
|
29
|
+
static json(body, init) {
|
|
30
|
+
return Response.json(body, init);
|
|
31
|
+
}
|
|
32
|
+
static redirect(url, init) {
|
|
33
|
+
const status = typeof init === "number" ? init : init?.status ?? 307;
|
|
34
|
+
return new NextResponse(null, {
|
|
35
|
+
status,
|
|
36
|
+
headers: { location: String(url) }
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
static next() {
|
|
40
|
+
return unsupported("next");
|
|
41
|
+
}
|
|
42
|
+
static rewrite() {
|
|
43
|
+
return unsupported("rewrite");
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/** Runs `task` after the response, as Next's `after()` does. */
|
|
47
|
+
function after(task) {
|
|
48
|
+
Promise.resolve().then(() => typeof task === "function" ? task() : task).catch((error) => console.error(error));
|
|
49
|
+
}
|
|
50
|
+
export { NextRequest, NextResponse, after };
|
package/dist/next.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative } from "node:path";
|
|
3
|
+
import { build } from "esbuild";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
// packages/appos-host/src/next/adapter.ts
|
|
6
|
+
var fromSource = import.meta.url.endsWith(".ts");
|
|
7
|
+
var sibling = (name) => fileURLToPath(new URL(fromSource ? `./${name}.ts` : `./next-${name}.js`, import.meta.url));
|
|
8
|
+
var SCRIPT = `<script src="/_appos/next.js"><\/script>`;
|
|
9
|
+
/** Where a built file is served in the bundle. HTML pages become `<path>/index.html`. */
|
|
10
|
+
function bundlePath(pathname, file) {
|
|
11
|
+
if (!file.endsWith(".html")) return pathname;
|
|
12
|
+
if (pathname === "/") return "/index.html";
|
|
13
|
+
if (pathname === "/_not-found" || pathname === "/404") return "/404.html";
|
|
14
|
+
return `${pathname}/index.html`;
|
|
15
|
+
}
|
|
16
|
+
function routeSource(projectDir, sourcePage, extensions) {
|
|
17
|
+
for (const dir of ["app", "src/app"]) for (const ext of extensions) {
|
|
18
|
+
const file = join(projectDir, dir, `${sourcePage}.${ext}`);
|
|
19
|
+
if (existsSync(file)) return file;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function htmlFiles(dir) {
|
|
23
|
+
return readdirSync(dir, {
|
|
24
|
+
recursive: true,
|
|
25
|
+
withFileTypes: true
|
|
26
|
+
}).filter((e) => e.isFile() && e.name.endsWith(".html")).map((e) => join(e.parentPath, e.name));
|
|
27
|
+
}
|
|
28
|
+
/** Resolves next/server to appOS's shim and server-only to nothing. */
|
|
29
|
+
var nextShims = {
|
|
30
|
+
name: "appos-next-shims",
|
|
31
|
+
setup(b) {
|
|
32
|
+
b.onResolve({ filter: /^next\/server(\.js)?$/ }, () => ({ path: sibling("server") }));
|
|
33
|
+
b.onResolve({ filter: /^(server-only|client-only)$/ }, () => ({
|
|
34
|
+
path: "empty",
|
|
35
|
+
namespace: "appos-empty"
|
|
36
|
+
}));
|
|
37
|
+
b.onLoad({
|
|
38
|
+
filter: /.*/,
|
|
39
|
+
namespace: "appos-empty"
|
|
40
|
+
}, () => ({
|
|
41
|
+
contents: "",
|
|
42
|
+
loader: "js"
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var ENV_FILES = [
|
|
47
|
+
".env.production.local",
|
|
48
|
+
".env.local",
|
|
49
|
+
".env.production",
|
|
50
|
+
".env"
|
|
51
|
+
];
|
|
52
|
+
/** Names in the project's .env files that aren't NEXT_PUBLIC_: server secrets. */
|
|
53
|
+
function serverEnvNames(projectDir) {
|
|
54
|
+
const names = /* @__PURE__ */ new Set();
|
|
55
|
+
for (const f of ENV_FILES) {
|
|
56
|
+
const file = join(projectDir, f);
|
|
57
|
+
if (!existsSync(file)) continue;
|
|
58
|
+
for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
|
|
59
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
|
|
60
|
+
if (m && !m[1].startsWith("NEXT_PUBLIC_")) names.add(m[1]);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return [...names];
|
|
64
|
+
}
|
|
65
|
+
/** Adds appos.server to the app's manifest, keeping what it declares. */
|
|
66
|
+
function declareServer(out, routes) {
|
|
67
|
+
const file = ["manifest.webmanifest", "manifest.json"].map((f) => join(out, f)).find(existsSync);
|
|
68
|
+
const manifest = JSON.parse(readFileSync(file, "utf8"));
|
|
69
|
+
manifest.appos = {
|
|
70
|
+
...manifest.appos,
|
|
71
|
+
server: {
|
|
72
|
+
main: "_appos/server.js",
|
|
73
|
+
routes
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
writeFileSync(file, JSON.stringify(manifest));
|
|
77
|
+
}
|
|
78
|
+
async function writeApp(ctx) {
|
|
79
|
+
const { outputs, projectDir } = ctx;
|
|
80
|
+
const out = join(ctx.distDir, "appos");
|
|
81
|
+
rmSync(out, {
|
|
82
|
+
recursive: true,
|
|
83
|
+
force: true
|
|
84
|
+
});
|
|
85
|
+
mkdirSync(out, { recursive: true });
|
|
86
|
+
const put = (path, from) => {
|
|
87
|
+
const target = join(out, path);
|
|
88
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
89
|
+
copyFileSync(from, target);
|
|
90
|
+
};
|
|
91
|
+
const served = /* @__PURE__ */ new Set();
|
|
92
|
+
for (const f of outputs.staticFiles) {
|
|
93
|
+
if (!f.filePath || f.pathname === "/500") continue;
|
|
94
|
+
put(bundlePath(f.pathname, f.filePath), f.filePath);
|
|
95
|
+
served.add(f.pathname);
|
|
96
|
+
}
|
|
97
|
+
for (const p of outputs.prerenders) {
|
|
98
|
+
const file = p.fallback?.filePath;
|
|
99
|
+
if (!file || p.pathname.startsWith("/_global-error")) continue;
|
|
100
|
+
put(bundlePath(p.pathname, file), file);
|
|
101
|
+
served.add(p.pathname);
|
|
102
|
+
if (p.parentOutputId) served.add(p.parentOutputId);
|
|
103
|
+
}
|
|
104
|
+
const isServed = (o) => served.has(o.pathname) || served.has(o.id);
|
|
105
|
+
const extensions = ctx.config.pageExtensions ?? [
|
|
106
|
+
"tsx",
|
|
107
|
+
"ts",
|
|
108
|
+
"jsx",
|
|
109
|
+
"js"
|
|
110
|
+
];
|
|
111
|
+
const warnings = [];
|
|
112
|
+
const routes = [];
|
|
113
|
+
for (const r of outputs.appRoutes) {
|
|
114
|
+
if (r.pathname.endsWith(".rsc") || isServed(r) || routes.some((x) => x.pathname === r.pathname)) continue;
|
|
115
|
+
const file = r.sourcePage && routeSource(projectDir, r.sourcePage, extensions);
|
|
116
|
+
if (file) routes.push({
|
|
117
|
+
pathname: r.pathname,
|
|
118
|
+
file
|
|
119
|
+
});
|
|
120
|
+
else warnings.push(`${r.pathname}: no source for this route handler (metadata routes must be static).`);
|
|
121
|
+
}
|
|
122
|
+
for (const p of outputs.appPages) {
|
|
123
|
+
if (p.pathname.endsWith(".rsc") || p.pathname.startsWith("/_") || isServed(p)) continue;
|
|
124
|
+
warnings.push(`${p.pathname}: a dynamic page. appOS serves prerendered pages only; make it static.`);
|
|
125
|
+
}
|
|
126
|
+
for (const p of [...outputs.pages, ...outputs.pagesApi]) if (!isServed(p) && !p.pathname.startsWith("/_")) warnings.push(`${p.pathname}: pages/ routes that run on a server aren't supported.`);
|
|
127
|
+
if (outputs.middleware) warnings.push("middleware (proxy) doesn't run in appOS yet; it is skipped.");
|
|
128
|
+
if (routes.length) {
|
|
129
|
+
const secrets = serverEnvNames(projectDir);
|
|
130
|
+
if (secrets.length) warnings.push(`server env ${secrets.join(", ")} is not in the bundle. Set it for the app's cloud server with \`appos secrets <dir> --key <keyfile>\`; without the cloud, route handlers run in the page without it.`);
|
|
131
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => k.startsWith("NEXT_PUBLIC_")));
|
|
132
|
+
const entry = [
|
|
133
|
+
`import { serve } from ${JSON.stringify(sibling("runtime"))};`,
|
|
134
|
+
...routes.map((r, i) => `import * as r${i} from ${JSON.stringify(r.file)};`),
|
|
135
|
+
`export default serve([${routes.map((r, i) => `{ pathname: ${JSON.stringify(r.pathname)}, mod: r${i} }`).join(", ")}], ${JSON.stringify(env)});`
|
|
136
|
+
].join("\n");
|
|
137
|
+
const tsconfig = join(projectDir, "tsconfig.json");
|
|
138
|
+
await build({
|
|
139
|
+
stdin: {
|
|
140
|
+
contents: entry,
|
|
141
|
+
resolveDir: projectDir,
|
|
142
|
+
sourcefile: "appos-server.js",
|
|
143
|
+
loader: "js"
|
|
144
|
+
},
|
|
145
|
+
bundle: true,
|
|
146
|
+
format: "esm",
|
|
147
|
+
platform: "browser",
|
|
148
|
+
target: "es2022",
|
|
149
|
+
minify: true,
|
|
150
|
+
legalComments: "none",
|
|
151
|
+
jsx: "automatic",
|
|
152
|
+
outfile: join(out, "_appos/server.js"),
|
|
153
|
+
tsconfig: existsSync(tsconfig) ? tsconfig : void 0,
|
|
154
|
+
banner: { js: `globalThis.process??={env:{NODE_ENV:"production"}};` },
|
|
155
|
+
define: { "process.env.NODE_ENV": "\"production\"" },
|
|
156
|
+
plugins: [nextShims],
|
|
157
|
+
logLevel: "warning"
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
await build({
|
|
161
|
+
stdin: {
|
|
162
|
+
contents: `import { install } from ${JSON.stringify(sibling("page"))};\ninstall();`,
|
|
163
|
+
resolveDir: projectDir,
|
|
164
|
+
sourcefile: "appos-page.js",
|
|
165
|
+
loader: "js"
|
|
166
|
+
},
|
|
167
|
+
bundle: true,
|
|
168
|
+
format: "iife",
|
|
169
|
+
target: "es2022",
|
|
170
|
+
minify: true,
|
|
171
|
+
outfile: join(out, "_appos/next.js"),
|
|
172
|
+
logLevel: "warning"
|
|
173
|
+
});
|
|
174
|
+
for (const file of htmlFiles(out)) {
|
|
175
|
+
const html = readFileSync(file, "utf8");
|
|
176
|
+
const head = /<head[^>]*>/i.exec(html);
|
|
177
|
+
writeFileSync(file, head ? html.replace(head[0], head[0] + SCRIPT) : SCRIPT + html);
|
|
178
|
+
}
|
|
179
|
+
if (!existsSync(join(out, "manifest.webmanifest")) && !existsSync(join(out, "manifest.json"))) {
|
|
180
|
+
const index = existsSync(join(out, "index.html")) ? readFileSync(join(out, "index.html"), "utf8") : "";
|
|
181
|
+
const title = /<title>([^<]*)<\/title>/i.exec(index)?.[1];
|
|
182
|
+
const pkg = join(projectDir, "package.json");
|
|
183
|
+
const name = title || (existsSync(pkg) ? JSON.parse(readFileSync(pkg, "utf8")).name : void 0) || "Next.js app";
|
|
184
|
+
writeFileSync(join(out, "manifest.webmanifest"), JSON.stringify({
|
|
185
|
+
name,
|
|
186
|
+
start_url: "/"
|
|
187
|
+
}, null, 2) + "\n");
|
|
188
|
+
}
|
|
189
|
+
if (routes.length) declareServer(out, routes.map((r) => r.pathname));
|
|
190
|
+
return {
|
|
191
|
+
out,
|
|
192
|
+
routes: routes.map((r) => r.pathname),
|
|
193
|
+
warnings
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
var adapter = {
|
|
197
|
+
name: "appOS",
|
|
198
|
+
modifyConfig(config, { phase }) {
|
|
199
|
+
if (phase !== "phase-production-build") return config;
|
|
200
|
+
return {
|
|
201
|
+
...config,
|
|
202
|
+
images: {
|
|
203
|
+
...config.images,
|
|
204
|
+
unoptimized: true
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
async onBuildComplete(ctx) {
|
|
209
|
+
const { out, routes, warnings } = await writeApp(ctx);
|
|
210
|
+
for (const w of warnings) console.warn(`appOS: ${w}`);
|
|
211
|
+
const where = relative(process.cwd(), out) || out;
|
|
212
|
+
console.log(`appOS: wrote ${where}${routes.length ? ` with route handlers ${routes.join(", ")}` : ""}`);
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
export { adapter as default, serverEnvNames, writeApp };
|
package/dist/pack.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { BundleBuilder } from "wbn";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
// src/lib/pack.ts
|
|
6
|
+
var MIME = {
|
|
7
|
+
".html": "text/html; charset=utf-8",
|
|
8
|
+
".htm": "text/html; charset=utf-8",
|
|
9
|
+
".js": "text/javascript; charset=utf-8",
|
|
10
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
11
|
+
".css": "text/css; charset=utf-8",
|
|
12
|
+
".json": "application/json",
|
|
13
|
+
".map": "application/json",
|
|
14
|
+
".svg": "image/svg+xml",
|
|
15
|
+
".png": "image/png",
|
|
16
|
+
".jpg": "image/jpeg",
|
|
17
|
+
".jpeg": "image/jpeg",
|
|
18
|
+
".gif": "image/gif",
|
|
19
|
+
".webp": "image/webp",
|
|
20
|
+
".avif": "image/avif",
|
|
21
|
+
".ico": "image/x-icon",
|
|
22
|
+
".wasm": "application/wasm",
|
|
23
|
+
".woff": "font/woff",
|
|
24
|
+
".woff2": "font/woff2",
|
|
25
|
+
".ttf": "font/ttf",
|
|
26
|
+
".otf": "font/otf",
|
|
27
|
+
".mp3": "audio/mpeg",
|
|
28
|
+
".mp4": "video/mp4",
|
|
29
|
+
".webm": "video/webm",
|
|
30
|
+
".txt": "text/plain; charset=utf-8",
|
|
31
|
+
".md": "text/markdown; charset=utf-8",
|
|
32
|
+
".xml": "application/xml",
|
|
33
|
+
".webmanifest": "application/manifest+json",
|
|
34
|
+
".rsc": "text/x-component"
|
|
35
|
+
};
|
|
36
|
+
function mimeFor(path) {
|
|
37
|
+
const dot = path.lastIndexOf(".");
|
|
38
|
+
return MIME[dot > path.lastIndexOf("/") ? path.slice(dot).toLowerCase() : ""] ?? "application/octet-stream";
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Normalizes a file path to "/a/b.js". Rejects empty paths, `..`, and
|
|
42
|
+
* paths reserved by the sandbox.
|
|
43
|
+
*/
|
|
44
|
+
function normalizePath(input) {
|
|
45
|
+
const parts = input.replace(/\\/g, "/").split("/").filter((p) => p && p !== ".");
|
|
46
|
+
if (parts.length === 0) throw new Error(`Invalid path: "${input}"`);
|
|
47
|
+
if (parts.some((p) => p === "..")) throw new Error(`Path may not contain "..": ${input}`);
|
|
48
|
+
const path = "/" + parts.join("/");
|
|
49
|
+
if (path.startsWith("/__appos/") || path === "/__appos") throw new Error("Paths under /__appos/ are reserved");
|
|
50
|
+
return path;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* TypeScript declarations and their maps, which a library build (aui-build)
|
|
54
|
+
* writes beside its JavaScript. An app has no use for them, so a pack skips them.
|
|
55
|
+
*/
|
|
56
|
+
var DECLARATION = /\.d\.[cm]?ts(\.map)?$/;
|
|
57
|
+
/**
|
|
58
|
+
* Builds a .wbn. `/index.html` is also served at `/`, the primary URL, and
|
|
59
|
+
* `/a/index.html` at `/a`. Declaration files (.d.ts, .d.ts.map) stay out.
|
|
60
|
+
*/
|
|
61
|
+
function packFiles(files) {
|
|
62
|
+
const sorted = files.map((f) => ({
|
|
63
|
+
...f,
|
|
64
|
+
path: normalizePath(f.path)
|
|
65
|
+
})).filter((f) => !DECLARATION.test(f.path)).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
66
|
+
if (!sorted.find((f) => f.path === "/index.html")) throw new Error("An app needs an index.html at its root");
|
|
67
|
+
const builder = new BundleBuilder("b2");
|
|
68
|
+
for (const file of sorted) {
|
|
69
|
+
const headers = { "content-type": mimeFor(file.path) };
|
|
70
|
+
builder.addExchange(file.path, 200, headers, file.body);
|
|
71
|
+
if (file.path.endsWith("/index.html")) {
|
|
72
|
+
const dir = file.path.slice(0, -10);
|
|
73
|
+
const alias = dir === "/" ? "/" : dir.slice(0, -1);
|
|
74
|
+
if (!sorted.some((f) => f.path === alias)) builder.addExchange(alias, 200, headers, file.body);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
builder.setPrimaryURL("/");
|
|
78
|
+
return builder.createBundle();
|
|
79
|
+
}
|
|
80
|
+
// packages/appos-host/src/pack.ts
|
|
81
|
+
var SKIP = /* @__PURE__ */ new Set([
|
|
82
|
+
".DS_Store",
|
|
83
|
+
".git",
|
|
84
|
+
"node_modules"
|
|
85
|
+
]);
|
|
86
|
+
function walk(dir) {
|
|
87
|
+
return readdirSync(dir).flatMap((name) => {
|
|
88
|
+
if (SKIP.has(name)) return [];
|
|
89
|
+
const path = join(dir, name);
|
|
90
|
+
return statSync(path).isDirectory() ? walk(path) : [path];
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/** Packs `dir` into a .wbn at `out`. `/index.html` is also served at `/`, the primary URL. */
|
|
94
|
+
async function pack({ dir, out }) {
|
|
95
|
+
const root = resolve(dir);
|
|
96
|
+
const files = walk(root).map((f) => ({
|
|
97
|
+
path: "/" + relative(root, f).split(sep).join("/"),
|
|
98
|
+
body: new Uint8Array(readFileSync(f))
|
|
99
|
+
}));
|
|
100
|
+
const wbn = packFiles(files);
|
|
101
|
+
const hash = createHash("sha256").update(wbn).digest("hex");
|
|
102
|
+
const target = resolve(out.replaceAll("[hash]", hash.slice(0, 12)));
|
|
103
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
104
|
+
writeFileSync(target, wbn);
|
|
105
|
+
return {
|
|
106
|
+
out: target,
|
|
107
|
+
hash,
|
|
108
|
+
size: wbn.length,
|
|
109
|
+
files: files.length
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export { pack };
|