orvyn-lang 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +744 -27
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +186 -10
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +428 -57
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +69 -8
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +518 -44
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +266 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -34
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +406 -56
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +792 -10
  39. package/src/lang/runtime.js +362 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/vite-plugin.js +82 -3
  48. package/src/lang/web-overlay.js +578 -0
  49. package/src/lang/widgets.js +94 -0
  50. package/src/lang/words.js +38 -0
  51. package/src/runtime/mount.js +116 -27
  52. package/src/runtime/patch.js +90 -11
  53. package/src/runtime/style.js +11 -1
  54. package/src/styling/fluid.js +91 -4
  55. package/src/styling/spec.js +306 -0
@@ -0,0 +1,409 @@
1
+ import { createHash, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { words } from "./words.js";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { CALLABLE, fromLibrary, parseApi, Refused, runApi } from "./server-code.js";
6
+ const RESERVED_TABLES = ["signup", "login", "logout", "refresh", "me", "health"];
7
+ const RESERVED_FIELDS = ["id", "owner", "created"];
8
+ const MAX_BODY = 5 * 1024 * 1024;
9
+ const HOUR = 36e5;
10
+ const braces = (line) => {
11
+ const code = line.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, "").replace(/\/\/.*$/, "");
12
+ return code.split("{").length - code.split("}").length;
13
+ };
14
+ function parseServer(source) {
15
+ const tables = [];
16
+ const apis = [];
17
+ const uses = [];
18
+ let open = null;
19
+ let api = null;
20
+ source.split(/\r?\n/).forEach((raw, index) => {
21
+ if (api) {
22
+ api.lines.push(raw);
23
+ api.depth += braces(raw);
24
+ if (api.depth <= 0) {
25
+ const block = parseApi(api.header, api.lines, api.line);
26
+ if (apis.some((a) => a.method === block.method && a.path === block.path)) throw new Error(`line ${api.line}: ${block.method} "${block.path}" is written twice`);
27
+ apis.push(block);
28
+ api = null;
29
+ }
30
+ return;
31
+ }
32
+ const line = raw.replace(/("(?:[^"\\]|\\.)*")|\/\/.*$/g, "$1").trim();
33
+ if (!line) return;
34
+ const fail = (message) => {
35
+ throw new Error(`line ${index + 1}: ${message}`);
36
+ };
37
+ if (!open && /^use\b/.test(line)) {
38
+ const used = line.match(/^use\s+([A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*)\s+from\s+"([^"]+)"$/);
39
+ if (!used) fail(`Write it like: use sendEmail from "./email.js"`);
40
+ uses.push({ names: used[1].split(",").map((n) => n.trim()), path: used[2], line: index + 1 });
41
+ return;
42
+ }
43
+ if (!open && /^api\b/.test(line)) {
44
+ api = { header: line, lines: [], line: index + 1, depth: 1 };
45
+ return;
46
+ }
47
+ if (!open) {
48
+ const start = line.match(/^table\s+([a-z][a-z0-9_]*)((?:\s+[a-z]+)*)\s*\{$/i);
49
+ if (!start) fail(`Expected a table, like: table notes {`);
50
+ const [, name2, words2] = start;
51
+ const flags = words2.trim().split(/\s+/).filter(Boolean);
52
+ const unknown = flags.find((f) => !["public", "admin", "locked"].includes(f));
53
+ if (unknown) fail(`A table can be "public", "admin" or "locked", not "${unknown}"`);
54
+ if (RESERVED_TABLES.includes(name2.toLowerCase()) || /^(sqlite_|_)/i.test(name2)) fail(`A table can't be called "${name2}"`);
55
+ if (tables.some((t) => t.name.toLowerCase() === name2.toLowerCase())) fail(`There are two tables called "${name2}"`);
56
+ open = { name: name2, public: flags.includes("public"), admin: flags.includes("admin"), locked: flags.includes("locked"), fields: [] };
57
+ return;
58
+ }
59
+ if (line === "}") {
60
+ if (!open.fields.length) fail(`Table "${open.name}" has no fields`);
61
+ tables.push(open);
62
+ open = null;
63
+ return;
64
+ }
65
+ const field = line.match(/^([a-z][a-z0-9_]*)\s*:\s*(text|number|yesno)(\s+required)?$/i);
66
+ if (!field) fail(`Write a field like: title: text required (types: text, number, yesno)`);
67
+ const name = field[1];
68
+ if (RESERVED_FIELDS.includes(name.toLowerCase())) fail(`"${name}" is added for you; choose another name`);
69
+ if (open.fields.some((f) => f.name.toLowerCase() === name.toLowerCase())) fail(`"${name}" is listed twice`);
70
+ open.fields.push({ name, type: field[2].toLowerCase(), required: Boolean(field[3]) });
71
+ });
72
+ if (open) throw new Error(`Table "${open.name}" is missing its closing }`);
73
+ if (api) throw new Error(`line ${api.line}: this api is missing its closing }`);
74
+ if (!tables.length && !apis.length) throw new Error("No tables. Add one, like: table notes { text: text }");
75
+ for (const block of apis) {
76
+ const first = block.path.split("/")[1] ?? "";
77
+ if (!first || RESERVED_TABLES.includes(first) || tables.some((t) => t.name === first)) {
78
+ throw new Error(`api "${block.path}" uses an address Orvyn already has. Choose another`);
79
+ }
80
+ }
81
+ for (const use of uses) {
82
+ const taken = use.names.find((n) => tables.some((t) => t.name === n) || ["body", "query", "user", "fail", "secret", "get", "post"].includes(n));
83
+ if (taken) throw new Error(`line ${use.line}: "${taken}" already means something in server code. Use another name`);
84
+ }
85
+ tables.apis = apis;
86
+ tables.uses = uses;
87
+ return tables;
88
+ }
89
+ class HttpError extends Error {
90
+ status;
91
+ constructor(status, message) {
92
+ super(message);
93
+ this.status = status;
94
+ }
95
+ }
96
+ const hashPassword = (password, salt) => new Promise((resolve, reject) => scrypt(password, salt, 64, (error, key) => error ? reject(error) : resolve(key)));
97
+ const digest = (token) => createHash("sha256").update(token).digest("hex");
98
+ const quote = (name) => `"${name}"`;
99
+ function openDatabase(file, tables) {
100
+ const db = new DatabaseSync(file);
101
+ db.exec(`
102
+ CREATE TABLE IF NOT EXISTS _users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, salt TEXT NOT NULL, hash TEXT NOT NULL, admin INTEGER NOT NULL DEFAULT 0);
103
+ CREATE TABLE IF NOT EXISTS _tokens (hash TEXT PRIMARY KEY, user INTEGER NOT NULL, kind TEXT NOT NULL, expires INTEGER NOT NULL);
104
+ `);
105
+ const sqlType = { text: "TEXT", number: "REAL", yesno: "INTEGER" };
106
+ for (const table of tables) {
107
+ db.exec(`CREATE TABLE IF NOT EXISTS ${quote(table.name)} (id INTEGER PRIMARY KEY AUTOINCREMENT, owner INTEGER NOT NULL, created TEXT NOT NULL)`);
108
+ const have = db.prepare(`PRAGMA table_info(${quote(table.name)})`).all().map((c) => String(c.name).toLowerCase());
109
+ for (const field of table.fields) {
110
+ if (!have.includes(field.name.toLowerCase())) db.exec(`ALTER TABLE ${quote(table.name)} ADD COLUMN ${quote(field.name)} ${sqlType[field.type]}`);
111
+ }
112
+ }
113
+ return db;
114
+ }
115
+ function makeAdmin(db, email) {
116
+ return Number(db.prepare("UPDATE _users SET admin = 1 WHERE email = ?").run(email.trim().toLowerCase()).changes) > 0;
117
+ }
118
+ function createApi(tables, db, options = {}) {
119
+ const tries = /* @__PURE__ */ new Map();
120
+ const limit = (key) => {
121
+ const now = Date.now();
122
+ if (tries.size > 1e4) tries.clear();
123
+ const entry = tries.get(key);
124
+ if (!entry || entry.until < now) return void tries.set(key, { count: 1, until: now + HOUR / 4 });
125
+ if (++entry.count > 10) throw new HttpError(429, "Too many tries. Wait 15 minutes");
126
+ };
127
+ const session = (user) => {
128
+ db.prepare("DELETE FROM _tokens WHERE expires < ?").run(Date.now());
129
+ const make = (kind, life) => {
130
+ const token = randomBytes(32).toString("base64url");
131
+ db.prepare("INSERT INTO _tokens (hash, user, kind, expires) VALUES (?, ?, ?, ?)").run(digest(token), user.id, kind, Date.now() + life);
132
+ return token;
133
+ };
134
+ return { token: make("access", HOUR), refresh: make("refresh", 30 * 24 * HOUR), user: { id: user.id, email: user.email, admin: Boolean(user.admin) } };
135
+ };
136
+ const userFor = (token, kind) => db.prepare("SELECT u.id, u.email, u.admin FROM _tokens t JOIN _users u ON u.id = t.user WHERE t.hash = ? AND t.kind = ? AND t.expires > ?").get(digest(token), kind, Date.now()) ?? null;
137
+ const credentials = (body) => {
138
+ const email = String(body.email ?? "").trim().toLowerCase();
139
+ const password = String(body.password ?? "");
140
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) || email.length > 200) throw new HttpError(400, "Enter a valid email");
141
+ if (password.length < 8 || password.length > 200) throw new HttpError(400, "The password needs 8 or more characters");
142
+ return { email, password };
143
+ };
144
+ const values = (table, body, creating) => {
145
+ const out = [];
146
+ for (const key of Object.keys(body)) {
147
+ if (!table.fields.some((f) => f.name === key)) throw new HttpError(400, `${table.name} has no field "${key}"`);
148
+ }
149
+ for (const field of table.fields) {
150
+ const given = Object.hasOwn(body, field.name);
151
+ const value = given ? body[field.name] : null;
152
+ if (field.required && (creating || given) && (value === null || value === "")) throw new HttpError(400, `"${field.name}" is required`);
153
+ if (!given) continue;
154
+ if (value === null) {
155
+ out.push([field.name, null]);
156
+ continue;
157
+ }
158
+ const right = field.type === "text" ? typeof value === "string" : field.type === "number" ? typeof value === "number" && Number.isFinite(value) : typeof value === "boolean";
159
+ if (!right) throw new HttpError(400, `"${field.name}" must be ${field.type === "yesno" ? "true or false" : `a ${field.type === "text" ? "text" : "number"}`}`);
160
+ out.push([field.name, typeof value === "boolean" ? Number(value) : value]);
161
+ }
162
+ return out;
163
+ };
164
+ const shown = (table, row) => ({
165
+ id: row.id,
166
+ ...Object.fromEntries(table.fields.map((f) => [f.name, f.type === "yesno" && row[f.name] !== null ? Boolean(row[f.name]) : row[f.name]])),
167
+ created: row.created
168
+ });
169
+ let queue = Promise.resolve();
170
+ const oneAtATime = (work) => {
171
+ const next = queue.then(work, work);
172
+ queue = next.catch(() => {
173
+ });
174
+ return next;
175
+ };
176
+ const outside = async (url, init) => {
177
+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(1e4) });
178
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
179
+ return (res.headers.get("content-type") ?? "").includes("json") ? res.json() : res.text();
180
+ };
181
+ const handle = (table, user) => {
182
+ const everyone = table.admin;
183
+ const ownRows = !table.admin && !table.public;
184
+ const need = () => {
185
+ if (!user) throw new Refused("Please log in");
186
+ };
187
+ const select = (onlyMine, id) => {
188
+ if (onlyMine) need();
189
+ const where = [...onlyMine ? ["owner = ?"] : [], ...id === void 0 ? [] : ["id = ?"]];
190
+ const args = [...onlyMine ? [user.id] : [], ...id === void 0 ? [] : [Number(id) || 0]];
191
+ return db.prepare(`SELECT * FROM ${quote(table.name)}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY id DESC LIMIT 1000`).all(...args).map((row) => shown(table, row));
192
+ };
193
+ const changeable = (id) => {
194
+ if (!everyone) need();
195
+ if (!select(!everyone, id).length) throw new Refused(`That ${table.name} row was not found`);
196
+ };
197
+ const object = {
198
+ all: () => select(ownRows),
199
+ where: (wanted) => words(select(ownRows), "where", [wanted]),
200
+ first: (wanted) => words(select(ownRows), "first", [wanted]),
201
+ count: (wanted) => words(select(ownRows), "count", [wanted]),
202
+ add: (given) => {
203
+ need();
204
+ const fields = values(table, given ?? {}, true);
205
+ const columns = ["owner", "created", ...fields.map(([key]) => key)];
206
+ const made = db.prepare(`INSERT INTO ${quote(table.name)} (${columns.map(quote).join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`).run(user.id, (/* @__PURE__ */ new Date()).toISOString(), ...fields.map(([, value]) => value));
207
+ return shown(table, db.prepare(`SELECT * FROM ${quote(table.name)} WHERE id = ?`).get(made.lastInsertRowid));
208
+ },
209
+ update: (id, given) => {
210
+ changeable(id);
211
+ const fields = values(table, given ?? {}, false);
212
+ if (fields.length) db.prepare(`UPDATE ${quote(table.name)} SET ${fields.map(([key]) => `${quote(key)} = ?`).join(", ")} WHERE id = ?`).run(...fields.map(([, value]) => value), Number(id));
213
+ return select(false, id)[0];
214
+ },
215
+ remove: (id) => {
216
+ changeable(id);
217
+ db.prepare(`DELETE FROM ${quote(table.name)} WHERE id = ?`).run(Number(id));
218
+ return true;
219
+ }
220
+ };
221
+ CALLABLE.add(object);
222
+ return object;
223
+ };
224
+ const custom = (block, body, user, url) => {
225
+ if (block.requires && !user) throw new HttpError(401, "Please log in");
226
+ if (block.requires === "admin" && !user.admin) throw new HttpError(403, "Only an admin can do this");
227
+ return oneAtATime(async () => {
228
+ const names = {
229
+ ...Object.fromEntries(Object.entries(tables.libraries ?? {}).map(([name, value]) => [name, fromLibrary(value)])),
230
+ ...Object.fromEntries(tables.map((t) => [t.name, handle(t, user)])),
231
+ body,
232
+ query: Object.fromEntries(url.searchParams),
233
+ user: user ? { id: user.id, email: user.email, admin: Boolean(user.admin) } : null,
234
+ fail: (message) => {
235
+ throw new Refused(String(message));
236
+ },
237
+ // secrets stay on the server: set them as environment variables
238
+ secret: (name) => process.env[String(name)] ?? "",
239
+ get: (address, headers) => outside(address, { headers }),
240
+ post: (address, data, headers) => outside(address, { method: "POST", body: JSON.stringify(data ?? {}), headers: { "Content-Type": "application/json", ...headers } })
241
+ };
242
+ db.exec("BEGIN");
243
+ try {
244
+ const result = await runApi(block, { names });
245
+ db.exec("COMMIT");
246
+ return result;
247
+ } catch (error) {
248
+ db.exec("ROLLBACK");
249
+ if (error instanceof Refused) throw new HttpError(error.message === "Please log in" ? 401 : 400, error.message);
250
+ if (error instanceof HttpError) throw error;
251
+ console.error(`[Orvyn] api ${block.method} "${block.path}": ${error.message}`);
252
+ throw new HttpError(500, "Something went wrong");
253
+ }
254
+ });
255
+ };
256
+ async function route(method, url, body, token, from) {
257
+ const [api, name, id, extra] = url.pathname.split("/").filter(Boolean);
258
+ if (api !== "api" || !name) throw new HttpError(404, "Not found");
259
+ const user = token ? userFor(token, "access") : null;
260
+ if (name === "health" && !id && method === "GET") return [200, { ok: true }];
261
+ if (token && !user) throw new HttpError(401, "Please log in again");
262
+ const path = url.pathname.replace(/^\/api/, "").replace(/\/+$/, "");
263
+ const block = tables.apis?.find((a) => a.path === path && a.method === method);
264
+ if (block) return [200, await custom(block, body, user, url)];
265
+ if (extra !== void 0) throw new HttpError(404, "Not found");
266
+ if (RESERVED_TABLES.includes(name) && !id) {
267
+ if (name === "me" && method === "GET") {
268
+ if (!user) throw new HttpError(401, "Please log in");
269
+ return [200, { id: user.id, email: user.email, admin: Boolean(user.admin) }];
270
+ }
271
+ if (method !== "POST") throw new HttpError(405, "Use POST");
272
+ if (name === "signup") {
273
+ limit(`signup|${from}`);
274
+ const { email, password } = credentials(body);
275
+ const salt = randomBytes(16).toString("hex");
276
+ const hash = (await hashPassword(password, salt)).toString("hex");
277
+ if (db.prepare("SELECT 1 FROM _users WHERE email = ?").get(email)) throw new HttpError(409, "That email already has an account");
278
+ const made = db.prepare("INSERT INTO _users (email, salt, hash) VALUES (?, ?, ?)").run(email, salt, hash);
279
+ return [201, session({ id: Number(made.lastInsertRowid), email, admin: 0 })];
280
+ }
281
+ if (name === "login") {
282
+ const email = String(body.email ?? "").trim().toLowerCase();
283
+ limit(`login|${from}|${email}`);
284
+ const found = db.prepare("SELECT * FROM _users WHERE email = ?").get(email);
285
+ const hash = await hashPassword(String(body.password ?? "").slice(0, 200), found?.salt ?? "nobody");
286
+ if (!found || !timingSafeEqual(hash, Buffer.from(found.hash, "hex"))) throw new HttpError(401, "Wrong email or password");
287
+ tries.delete(`login|${from}|${email}`);
288
+ return [200, session(found)];
289
+ }
290
+ if (name === "refresh") {
291
+ const old = String(body.refresh ?? "");
292
+ const owner = userFor(old, "refresh");
293
+ if (!owner) throw new HttpError(401, "Please log in again");
294
+ db.prepare("DELETE FROM _tokens WHERE hash = ?").run(digest(old));
295
+ return [200, session(owner)];
296
+ }
297
+ if (name === "logout") {
298
+ if (user) db.prepare("DELETE FROM _tokens WHERE user = ?").run(user.id);
299
+ return [200, { ok: true }];
300
+ }
301
+ throw new HttpError(404, "Not found");
302
+ }
303
+ const table = tables.find((t) => t.name === name);
304
+ if (!table) throw new HttpError(404, "Not found");
305
+ const reading = method === "GET";
306
+ if (!user && !(reading && table.public)) throw new HttpError(401, "Please log in");
307
+ if (!reading && table.admin && !user.admin) throw new HttpError(403, "Only an admin can change this");
308
+ const mine = reading ? !table.public : !(table.admin && user.admin);
309
+ const where = [];
310
+ const args = [];
311
+ if (mine) {
312
+ where.push("owner = ?");
313
+ args.push(user.id);
314
+ }
315
+ if (id !== void 0) {
316
+ if (!/^\d+$/.test(id)) throw new HttpError(404, "Not found");
317
+ where.push("id = ?");
318
+ args.push(Number(id));
319
+ }
320
+ const filter = () => where.length ? ` WHERE ${where.join(" AND ")}` : "";
321
+ const one = () => db.prepare(`SELECT * FROM ${quote(table.name)}${filter()}`).get(...args);
322
+ if (reading) {
323
+ if (id !== void 0) {
324
+ const row = one();
325
+ if (!row) throw new HttpError(404, "Not found");
326
+ return [200, shown(table, row)];
327
+ }
328
+ for (const field of table.fields) {
329
+ const wanted = url.searchParams.get(field.name);
330
+ if (wanted === null) continue;
331
+ where.push(`${quote(field.name)} = ?`);
332
+ args.push(field.type === "number" ? Number(wanted) : field.type === "yesno" ? Number(wanted === "true") : wanted);
333
+ }
334
+ const page = Math.max(1, Math.floor(Number(url.searchParams.get("page"))) || 1);
335
+ const rows = db.prepare(`SELECT * FROM ${quote(table.name)}${filter()} ORDER BY id DESC LIMIT 100 OFFSET ?`).all(...args, (page - 1) * 100);
336
+ return [200, rows.map((row) => shown(table, row))];
337
+ }
338
+ if (table.locked) throw new HttpError(403, "This can only be changed by the server");
339
+ if (method === "POST" && id === void 0) {
340
+ const fields = values(table, body, true);
341
+ const columns = ["owner", "created", ...fields.map(([key]) => key)];
342
+ const made = db.prepare(`INSERT INTO ${quote(table.name)} (${columns.map(quote).join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`).run(user.id, (/* @__PURE__ */ new Date()).toISOString(), ...fields.map(([, value]) => value));
343
+ return [201, shown(table, db.prepare(`SELECT * FROM ${quote(table.name)} WHERE id = ?`).get(made.lastInsertRowid))];
344
+ }
345
+ if (id !== void 0 && (method === "PATCH" || method === "PUT" || method === "DELETE")) {
346
+ if (!one()) throw new HttpError(404, "Not found");
347
+ if (method === "DELETE") {
348
+ db.prepare(`DELETE FROM ${quote(table.name)}${filter()}`).run(...args);
349
+ return [200, { ok: true }];
350
+ }
351
+ const fields = values(table, body, false);
352
+ if (fields.length) {
353
+ db.prepare(`UPDATE ${quote(table.name)} SET ${fields.map(([key]) => `${quote(key)} = ?`).join(", ")}${filter()}`).run(...fields.map(([, value]) => value), ...args);
354
+ }
355
+ return [200, shown(table, one())];
356
+ }
357
+ throw new HttpError(405, "That isn't possible here");
358
+ }
359
+ const allowed = (origin) => (options.origins ?? []).includes(origin) || /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin);
360
+ return createServer(async (req, res) => {
361
+ const origin = String(req.headers.origin ?? "");
362
+ const headers = { "Content-Type": "application/json", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", Vary: "Origin" };
363
+ if (origin && allowed(origin)) {
364
+ headers["Access-Control-Allow-Origin"] = origin;
365
+ headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization";
366
+ headers["Access-Control-Allow-Methods"] = "GET, POST, PATCH, PUT, DELETE";
367
+ }
368
+ const send = (status, value) => {
369
+ res.writeHead(status, headers);
370
+ res.end(value === void 0 ? "" : JSON.stringify(value));
371
+ };
372
+ if (req.method === "OPTIONS") return send(204, void 0);
373
+ try {
374
+ const chunks = [];
375
+ let size = 0;
376
+ for await (const chunk of req) {
377
+ size += chunk.length;
378
+ if (size > MAX_BODY) throw new HttpError(413, "That is too large (over 5 MB)");
379
+ chunks.push(chunk);
380
+ }
381
+ let body = {};
382
+ if (size) {
383
+ try {
384
+ body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
385
+ } catch {
386
+ throw new HttpError(400, "Send JSON");
387
+ }
388
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new HttpError(400, "Send a JSON object");
389
+ }
390
+ const token = String(req.headers.authorization ?? "").replace(/^Bearer(\s+|$)/i, "");
391
+ const forwarded = options.proxy ? String(req.headers["x-forwarded-for"] ?? "").split(",").pop().trim() : "";
392
+ const from = forwarded || req.socket.remoteAddress || "";
393
+ const run = () => route(req.method ?? "GET", new URL(req.url ?? "/", "http://x"), body, token, from);
394
+ const changes = req.method !== "GET" && !tables.apis?.some((a) => `/api${a.path}` === req.url.split("?")[0]);
395
+ const [status, value] = await (changes ? oneAtATime(run) : run());
396
+ send(status, value);
397
+ } catch (error) {
398
+ if (error instanceof HttpError) return send(error.status, { error: error.message });
399
+ console.error("[Orvyn] server error:", error);
400
+ send(500, { error: "Something went wrong" });
401
+ }
402
+ });
403
+ }
404
+ export {
405
+ createApi,
406
+ makeAdmin,
407
+ openDatabase,
408
+ parseServer
409
+ };
@@ -0,0 +1,134 @@
1
+ import { runInNewContext } from "node:vm";
2
+ import { bundleNative } from "./bundle-native.js";
3
+ const settle = async () => {
4
+ for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0));
5
+ };
6
+ const nodes = (node) => node ? [node, ...(node.c ?? []).flatMap(nodes)] : [];
7
+ const words = (tree) => nodes(tree).map((n) => n.x).filter(Boolean);
8
+ async function runOne(code, index) {
9
+ let tree;
10
+ const errors = [];
11
+ const mocks = [];
12
+ const store = /* @__PURE__ */ new Map();
13
+ const secrets = /* @__PURE__ */ new Map();
14
+ const memory = (map, name2) => ({
15
+ [`__orvyn${name2}Get`]: (key) => map.get(key) ?? null,
16
+ [`__orvyn${name2}Set`]: (key, value) => {
17
+ map.set(key, value);
18
+ },
19
+ [`__orvyn${name2}Remove`]: (key) => {
20
+ map.delete(key);
21
+ }
22
+ });
23
+ const host = {
24
+ queueMicrotask,
25
+ setTimeout,
26
+ clearTimeout,
27
+ URL,
28
+ console: { log() {
29
+ }, warn() {
30
+ }, error: (...args) => errors.push(args.join(" ")) },
31
+ ...memory(store, "Storage"),
32
+ ...memory(secrets, "Secure"),
33
+ __orvynSecureClear: () => secrets.clear(),
34
+ __orvynRender: (json) => {
35
+ tree = JSON.parse(json);
36
+ },
37
+ // mock("photo", {...}), mock("location", {...}): what the "person" chooses
38
+ __orvynDevice: (id, kind) => setTimeout(() => {
39
+ const mock = mocks.findLast((m) => m.url === kind);
40
+ if (!mock) host.__orvynDeviceDone(id, "", `no mock for the ${kind}. Add: mock("${kind}", ...)`);
41
+ else host.__orvynDeviceDone(id, JSON.stringify(mock.body ?? null), "");
42
+ }, 0),
43
+ // answered on the next tick, so a test's mock() lines are in place first
44
+ __orvynFetch: (id, url) => setTimeout(() => {
45
+ const mock = mocks.findLast((m) => url === m.url || url.split("?")[0].endsWith(m.url));
46
+ if (!mock) host.__orvynFetchDone(id, 0, `no mock for this address. Add: mock("${url}", ...)`, "");
47
+ else host.__orvynFetchDone(id, mock.status, JSON.stringify(mock.body ?? null), "application/json");
48
+ }, 0)
49
+ };
50
+ let name = `test ${index + 1}`;
51
+ try {
52
+ runInNewContext(code, host);
53
+ const test = host.OrvynApp.__tests[index];
54
+ name = test.name;
55
+ const find = (kind, label) => {
56
+ const found = nodes(tree).filter((n) => kind.includes(n.t)).find((n) => n.x === label || n.a === label || n.ph === label);
57
+ if (!found) {
58
+ const shown = nodes(tree).filter((n) => kind.includes(n.t)).map((n) => n.a || n.x || n.ph).filter(Boolean);
59
+ throw new Error(`No ${kind[0]} called "${label}". On screen: ${shown.join(", ") || "none"}`);
60
+ }
61
+ return found;
62
+ };
63
+ await test.run({
64
+ async tap(label) {
65
+ await settle();
66
+ const button = find(["button", "link", "toggle"], String(label));
67
+ if (button.t === "toggle") {
68
+ if (button.e?.change === void 0) throw new Error(`"${label}" is disabled`);
69
+ host.__orvynEvent(button.e.change, button.v === "true" ? "false" : "true");
70
+ await settle();
71
+ return;
72
+ }
73
+ if (button.e?.tap === void 0) throw new Error(`"${label}" can't be tapped right now (disabled or loading)`);
74
+ host.__orvynEvent(button.e.tap);
75
+ await settle();
76
+ },
77
+ async type(field, value) {
78
+ await settle();
79
+ const input = find(["input", "select"], String(field));
80
+ if (input.t === "select" && !input.o.includes(String(value))) {
81
+ throw new Error(`"${value}" is not a choice of "${field}". Choices: ${input.o.join(", ")}`);
82
+ }
83
+ host.__orvynEvent(input.e.change, String(value));
84
+ await settle();
85
+ },
86
+ async settle() {
87
+ await settle();
88
+ },
89
+ text(value) {
90
+ return words(tree).some((word) => word.includes(String(value)));
91
+ },
92
+ expect(condition, line) {
93
+ if (!condition) throw new Error(`expect failed on line ${line}. On screen: ${words(tree).join(" | ") || "nothing"}`);
94
+ },
95
+ mock(url, body, status = 200) {
96
+ mocks.push({ url, body, status });
97
+ }
98
+ });
99
+ await settle();
100
+ return { name, ok: true };
101
+ } catch (error) {
102
+ const reported = errors.length ? `
103
+ The app reported: ${errors[0].split("\n")[0]}` : "";
104
+ return { name, ok: false, error: `${error.message}${reported}` };
105
+ } finally {
106
+ host.__orvynStop?.();
107
+ }
108
+ }
109
+ async function runTests(entry, env) {
110
+ const code = await bundleNative(entry, { env, tests: true });
111
+ const probe = {
112
+ queueMicrotask,
113
+ setTimeout: () => 0,
114
+ clearTimeout,
115
+ URL,
116
+ console: { log() {
117
+ }, warn() {
118
+ }, error() {
119
+ } },
120
+ __orvynRender() {
121
+ },
122
+ __orvynFetch() {
123
+ }
124
+ };
125
+ runInNewContext(code, probe);
126
+ const count = probe.OrvynApp.__tests?.length ?? 0;
127
+ probe.__orvynStop?.();
128
+ const results = [];
129
+ for (let i = 0; i < count; i++) results.push(await runOne(code, i));
130
+ return results;
131
+ }
132
+ export {
133
+ runTests
134
+ };