Refactor: Merging common/ into web/

This commit is contained in:
Zef Hemel
2025-06-04 14:01:59 +02:00
parent e5c137a505
commit bf2e0cdb87
122 changed files with 194 additions and 235 deletions
+74
View File
@@ -0,0 +1,74 @@
import type { SysCallMapping } from "$lib/plugos/system.ts";
import type { CommandDef } from "$lib/command.ts";
import { buildThreadLocalEnv, handleLuaError } from "../space_lua_api.ts";
import {
type ILuaFunction,
jsToLuaValue,
luaCall,
LuaStackFrame,
luaValueToJS,
} from "../space_lua/runtime.ts";
import type { ClientSystem } from "../client_system.ts";
export type CallbackCommandDef = CommandDef & {
run: ILuaFunction;
};
export function commandSyscalls(
clientSystem: ClientSystem,
): SysCallMapping {
return {
/**
* Define a Lua command
* @param def - The command definition
* @param luaCallback - The Lua callback
*/
"command.define": (
_ctx,
def: CallbackCommandDef,
) => {
console.log("Registering Lua command: ", def.name);
clientSystem.scriptEnv.registerCommand(
def,
async (...args: any[]) => {
const tl = await buildThreadLocalEnv(
clientSystem.system,
clientSystem.spaceLuaEnv.env,
);
const sf = new LuaStackFrame(tl, null);
try {
return luaValueToJS(
await luaCall(def.run, args.map(jsToLuaValue), {}, sf),
sf,
);
} catch (e: any) {
await handleLuaError(e, clientSystem.system);
}
},
);
},
"slashcommand.define": (
_ctx,
def: CallbackCommandDef,
) => {
clientSystem.scriptEnv.registerSlashCommand(
def,
async (...args: any[]) => {
const tl = await buildThreadLocalEnv(
clientSystem.system,
clientSystem.spaceLuaEnv.env,
);
const sf = new LuaStackFrame(tl, null);
try {
return luaValueToJS(
await luaCall(def.run, args.map(jsToLuaValue), {}, sf),
sf,
);
} catch (e: any) {
await handleLuaError(e, clientSystem.system);
}
},
);
},
};
}
+33
View File
@@ -0,0 +1,33 @@
import type { SysCallMapping } from "$lib/plugos/system.ts";
import type { Client } from "../client.ts";
export function configSyscalls(client: Client): SysCallMapping {
return {
"config.get": (_ctx, path: string, defaultValue: any) => {
return client.config.get(path, defaultValue);
},
"config.set": (
_ctx,
keyOrValues: string | Record<string, any>,
value?: any,
) => {
if (typeof keyOrValues === "string") {
client.config.set(keyOrValues, value);
} else {
client.config.set(keyOrValues);
}
},
"config.has": (_ctx, path: string) => {
return client.config.has(path);
},
"config.define": (_ctx, key: string, schema: any) => {
client.config.define(key, schema);
},
"config.getValues": () => {
return client.config.values;
},
"config.getSchemas": () => {
return client.config.schemas;
},
};
}
+88
View File
@@ -0,0 +1,88 @@
import {
type LuaCollectionQuery,
queryLua,
} from "../space_lua/query_collection.ts";
import type { KV, KvKey } from "../../plug-api/types.ts";
import type { DataStore } from "../../lib/data/datastore.ts";
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import {
jsToLuaValue,
LuaEnv,
LuaStackFrame,
luaValueToJS,
} from "../space_lua/runtime.ts";
import type { KvQueryOptions } from "$lib/data/kv_primitives.ts";
import type { ClientSystem } from "../client_system.ts";
/**
* Exposes the datastore API to plugs, but scoping everything to a prefix based on the plug's name
* @param ds the datastore to wrap
* @param prefix prefix to scope all keys to to which the plug name will be appended
*/
export function dataStoreReadSyscalls(
ds: DataStore,
clientSystem: ClientSystem,
): SysCallMapping {
return {
"datastore.batchGet": (
_ctx,
keys: KvKey[],
): Promise<(any | undefined)[]> => {
return ds.batchGet(keys);
},
"datastore.get": (_ctx, key: KvKey): Promise<any | null> => {
return ds.get(key);
},
"datastore.query": async (_ctx, options: KvQueryOptions): Promise<KV[]> => {
const results: KV[] = [];
for await (const item of ds.query(options)) {
results.push(item);
}
return results;
},
"datastore.queryLua": async (
_ctx,
prefix: string[],
query: LuaCollectionQuery,
scopeVariables?: Record<string, any>,
): Promise<any[]> => {
const sf = LuaStackFrame.createWithGlobalEnv(
clientSystem.spaceLuaEnv.env,
);
let env = clientSystem.spaceLuaEnv.env;
if (scopeVariables) {
env = new LuaEnv(clientSystem.spaceLuaEnv.env);
for (const [key, value] of Object.entries(scopeVariables)) {
env.setLocal(key, jsToLuaValue(value));
}
}
return (await queryLua<any>(ds.kv, prefix, query, env, sf)).map((item) =>
luaValueToJS(item, sf)
);
},
};
}
export function dataStoreWriteSyscalls(ds: DataStore): SysCallMapping {
return {
"datastore.delete": (_ctx, key: KvKey) => {
console.log("Deleting key", key);
return ds.delete(key);
},
"datastore.set": (_ctx, key: KvKey, value: any) => {
return ds.set(key, value);
},
"datastore.batchSet": (_ctx, kvs: KV[]) => {
return ds.batchSet(kvs);
},
"datastore.batchDelete": (_ctx, keys: KvKey[]) => {
return ds.batchDelete(keys);
},
};
}
+50
View File
@@ -0,0 +1,50 @@
import type { SysCallMapping } from "$lib/plugos/system.ts";
import type { EventListenerDef } from "../space_script.ts";
import { buildThreadLocalEnv, handleLuaError } from "../space_lua_api.ts";
import {
type ILuaFunction,
jsToLuaValue,
luaCall,
LuaStackFrame,
luaValueToJS,
} from "../space_lua/runtime.ts";
import type { ClientSystem } from "../client_system.ts";
export type CallbackEventListener = EventListenerDef & {
run: ILuaFunction;
};
export function eventListenerSyscalls(
clientSystem: ClientSystem,
): SysCallMapping {
return {
/**
* Define a Lua event listener
*/
"event.listen": (
_ctx,
def: CallbackEventListener,
) => {
console.log("Registering Lua event listener: ", def.name);
clientSystem.scriptEnv.registerEventListener(
def,
async (...args: any[]) => {
const tl = await buildThreadLocalEnv(
clientSystem.system,
clientSystem.spaceLuaEnv.env,
);
const sf = new LuaStackFrame(tl, null);
try {
const val = luaValueToJS(
await luaCall(def.run, args.map(jsToLuaValue), {}, sf),
sf,
);
return val;
} catch (e: any) {
await handleLuaError(e, clientSystem.system);
}
},
);
},
};
}
+49
View File
@@ -0,0 +1,49 @@
import type { SysCallMapping } from "$lib/plugos/system.ts";
import type {
LuaCollectionQuery,
LuaQueryCollection,
} from "../space_lua/query_collection.ts";
import {
jsToLuaValue,
type LuaEnv,
type LuaStackFrame,
} from "../space_lua/runtime.ts";
import type { Client } from "../client.ts";
import type { TagDef } from "../space_script.ts";
export function indexSyscalls(client: Client): SysCallMapping {
return {
"index.tag": (_ctx, tagName: string): LuaQueryCollection => {
return {
query: (
query: LuaCollectionQuery,
env: LuaEnv,
sf: LuaStackFrame,
): Promise<any[]> => {
return client.ds.luaQuery(
["idx", tagName],
query,
env,
sf,
(key, value: any) => {
const tag = key[1];
const tagDef = client.clientSystem.scriptEnv.tagDefs[tag];
if (!tagDef) {
// Return as is
return value;
}
// Convert to LuaTable
value = jsToLuaValue(value);
value.metatable = tagDef.metatable;
return value;
},
);
},
};
},
"index.defineTag": (_ctx, tagDef: TagDef) => {
client.clientSystem.scriptEnv.registerTag(tagDef);
},
};
}
+54
View File
@@ -0,0 +1,54 @@
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import Ajv from "ajv";
const ajv = new Ajv();
ajv.addFormat("email", {
validate: (data: string) => {
// TODO: Implement email validation
return data.includes("@");
},
async: false,
});
ajv.addFormat("page-ref", {
validate: (data: string) => {
return data.startsWith("[[") && data.endsWith("]]");
},
async: false,
});
export function jsonschemaSyscalls(): SysCallMapping {
return {
"jsonschema.validateObject": (
_ctx,
schema: any,
object: any,
): undefined | string => {
try {
const validate = ajv.compile(schema);
if (validate(object)) {
return;
} else {
let text = ajv.errorsText(validate.errors);
text = text.replaceAll("/", ".");
text = text.replace(/^data[\.\s]/, "");
return text;
}
} catch (e: any) {
return e.message;
}
},
"jsonschema.validateSchema": (
_ctx,
schema: any,
): undefined | string => {
const valid = ajv.validateSchema(schema);
if (valid) {
return;
} else {
return ajv.errorsText(ajv.errors);
}
},
};
}
+23
View File
@@ -0,0 +1,23 @@
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import { parse } from "../markdown_parser/parse_tree.ts";
import type { ParseTree } from "../../plug-api/lib/tree.ts";
import { builtinLanguages, languageFor } from "../languages.ts";
export function languageSyscalls(): SysCallMapping {
return {
"language.parseLanguage": (
_ctx,
language: string,
code: string,
): ParseTree => {
const lang = languageFor(language);
if (!lang) {
throw new Error(`Unknown language ${language}`);
}
return parse(lang, code);
},
"language.listLanguages": (): string[] => {
return Object.keys(builtinLanguages);
},
};
}
+58
View File
@@ -0,0 +1,58 @@
import type { SysCallMapping } from "$lib/plugos/system.ts";
import { evalExpression } from "../space_lua/eval.ts";
import { parse, parseExpressionString } from "../space_lua/parse.ts";
import {
LuaStackFrame,
luaToString,
luaValueToJS,
} from "../space_lua/runtime.ts";
import { buildThreadLocalEnv } from "../space_lua_api.ts";
import { isSendable } from "$lib/plugos/util.ts";
import type { LuaBlock, LuaExpression } from "../space_lua/ast.ts";
import type { ClientSystem } from "../client_system.ts";
export function luaSyscalls(clientSystem: ClientSystem): SysCallMapping {
return {
"lua.parse": (_ctx, code: string): LuaBlock => {
return parse(code);
},
"lua.parseExpression": (_ctx, expression: string): LuaExpression => {
return parseExpressionString(expression);
},
/**
* Evaluates a Lua expression and returns the result as a JavaScript value
* @param _ctx
* @param expression
* @returns
*/
"lua.evalExpression": async (_ctx, expression: string) => {
try {
const ast = parseExpressionString(expression);
const env = await buildThreadLocalEnv(
clientSystem.system,
clientSystem.spaceLuaEnv.env,
);
const sf = new LuaStackFrame(env, null);
const luaResult = await evalExpression(
ast,
clientSystem.spaceLuaEnv.env,
sf,
);
const jsResult = luaValueToJS(luaResult, sf);
if (isSendable(jsResult)) {
return jsResult;
} else {
// This may evaluate to e.g. a function, which is not sendable, in this case we'll console.warn and return a stringified version of the result
console.warn(
"Lua eval result is not sendable, returning stringified version",
jsResult,
);
return luaToString(luaResult);
}
} catch (e: any) {
console.error("Lua eval error: ", e.message, e.sf?.astCtx);
throw e;
}
},
};
}
+26
View File
@@ -0,0 +1,26 @@
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import { parse } from "../markdown_parser/parse_tree.ts";
import { type ParseTree, renderToText } from "../../plug-api/lib/tree.ts";
import { extendedMarkdownLanguage } from "../markdown_parser/parser.ts";
import { expandMarkdown } from "../markdown.ts";
import type { Client } from "../client.ts";
import { LuaStackFrame } from "../space_lua/runtime.ts";
export function markdownSyscalls(client: Client): SysCallMapping {
return {
"markdown.parseMarkdown": (_ctx, text: string): ParseTree => {
return parse(extendedMarkdownLanguage, text);
},
"markdown.renderParseTree": (_ctx, tree: ParseTree): string => {
return renderToText(tree);
},
"markdown.expandMarkdown": (_ctx, tree: ParseTree): Promise<ParseTree> => {
return expandMarkdown(
client,
tree,
client.clientSystem.spaceLuaEnv.env,
LuaStackFrame.lostFrame,
);
},
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import type { Client } from "../client.ts";
import { ShellStreamClient } from "../../common/shell_stream_client.ts";
import { ShellStreamClient } from "../shell_stream_client.ts";
/**
* Interface for the shell stream client
+190
View File
@@ -0,0 +1,190 @@
import type { SyscallMeta } from "../../plug-api/types.ts";
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import type { Client } from "../client.ts";
import type { CommandDef } from "$lib/command.ts";
import { version } from "../../version.ts";
import { deleteDB } from "idb";
export function systemSyscalls(
client: Client,
readOnlyMode: boolean,
): SysCallMapping {
const api: SysCallMapping = {
"system.invokeFunction": (
_ctx,
fullName: string, // plug.function
...args: any[]
) => {
const [plugName, functionName] = fullName.split(".");
if (!plugName || !functionName) {
throw Error(`Invalid function name ${fullName}`);
}
const plug = client.clientSystem.system.loadedPlugs.get(plugName);
if (!plug) {
throw Error(`Plug ${plugName} not found`);
}
const functionDef = plug.manifest!.functions[functionName];
if (!functionDef) {
throw Error(`Function ${functionName} not found`);
}
return plug.invoke(functionName, args);
},
"system.invokeFunctionOnServer": (
ctx,
fullName: string, // plug.function
...args: any[]
) => {
console.warn(
"Calling deprecated system.invokeFunctionOnServer, use system.invokeFunction instead",
);
return api["system.invokeFunction"](ctx, fullName, ...args);
},
"system.serverSyscall": (_ctx, name: string, ...args: any[]) => {
console.warn(
"Calling deprecated system.serverSyscall, use syscall instead",
);
return client.clientSystem.localSyscall(name, args);
},
"system.invokeCommand": (_ctx, name: string, args?: string[]) => {
if (!client) {
throw new Error("Not supported");
}
return client.runCommandByName(name, args);
},
"system.listCommands": (): { [key: string]: CommandDef } => {
const commandHook = client.clientSystem.commandHook;
const allCommands: { [key: string]: CommandDef } = {};
for (const [cmd, def] of commandHook.editorCommands) {
allCommands[cmd] = {
name: def.command.name,
contexts: def.command.contexts,
priority: def.command.priority,
key: def.command.key,
mac: def.command.mac,
hide: def.command.hide,
requireMode: def.command.requireMode,
};
}
return allCommands;
},
"system.listSyscalls": (): SyscallMeta[] => {
const syscalls: SyscallMeta[] = [];
for (
const [name, info] of client.clientSystem.system.registeredSyscalls
) {
syscalls.push({
name,
requiredPermissions: info.requiredPermissions,
argCount: Math.max(0, info.callback.length - 1),
});
}
return syscalls;
},
"system.reloadPlugs": () => {
if (!client) {
throw new Error("Not supported");
}
return client.loadPlugs();
},
"system.reloadConfig": (): Record<string, any> => {
console.warn("system.reloadConfig is deprecated, it's now a no-op");
return client.config.values;
},
"system.loadSpaceScripts": async () => {
await client.clientSystem.loadSpaceScripts();
},
"system.loadSpaceStyles": async () => {
if (!client) {
throw new Error("Not supported on server");
}
await client.loadCustomStyles();
},
"system.wipeClient": async (_ctx, logout = false) => {
// Two tracks:
// 1. Service worker unregister
// 2. IndexedDB cleaning
if (navigator.serviceWorker) {
const registration = await navigator.serviceWorker.ready;
if (registration?.active) {
// Disconnect the datastore in the service worker first
registration.active.postMessage({ type: "shutdown" });
// Then flush the cache
registration.active.postMessage({ type: "flushCache" });
await new Promise<void>((resolve) => {
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data.type === "cacheFlushed") {
console.log("Cache flushed");
navigator.serviceWorker.getRegistrations().then(
async (registrations) => {
for (const registration of registrations) {
await registration.unregister();
}
resolve();
},
);
}
});
});
} else {
console.info("No service worker active, so not unregistering");
}
} else {
console.info("Service workers not supported, so not unregistering");
}
console.log("Stop all the systems");
client.space.unwatch();
client.syncService.close();
client.ds.kv.close();
if (indexedDB.databases) {
// get a list of all existing IndexedDB databases
const databases = await indexedDB.databases();
// loop through the list and delete each database
for (const database of databases) {
console.log("Deleting database", database.name);
await deleteDB(database.name!);
}
} else {
// Firefox doesn't support indexedDB.databases :(
console.info(
"Cannot delete local database, so go to empty them instead",
);
const allKeys = [];
for await (
const { key } of client.ds.kv.query({})
) {
allKeys.push(key);
}
await client.ds.batchDelete(allKeys);
}
if (logout) {
location.href = "/.logout";
} else {
alert("Client wiped, feel free to navigate elsewhere");
}
},
// DEPRECATED
"system.getEnv": () => {
console.warn(
"system.getEnv is deprecated, you can assume the env to always be the client",
);
return null;
},
"system.getSpaceConfig": (_ctx, key, defaultValue?) => {
console.warn(
"system.getSpaceConfig is deprecated, use system.getConfig instead",
);
return client.config.get(key, defaultValue);
},
"system.getMode": () => {
return readOnlyMode ? "ro" : "rw";
},
"system.getVersion": () => {
return version;
},
"system.getConfig": (_ctx, key: string, defaultValue: any = undefined) => {
return client.config.get(key, defaultValue);
},
};
return api;
}
+57
View File
@@ -0,0 +1,57 @@
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import YAML from "js-yaml";
import { applyPatches, type SetKeyPatch } from "$lib/yaml.ts";
type YamlStringifyOptions = {
/** indentation width to use (in spaces). */
indent?: number;
/** when true, will not add an indentation level to array elements */
noArrayIndent?: boolean;
/** do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. */
skipInvalid?: boolean;
/** specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere */
flowLevel?: number;
/** if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) */
sortKeys?: boolean;
/** set max line width. (default: 80) */
lineWidth?: number;
/** if true, don't convert duplicate objects into references (default: false) */
noRefs?: boolean;
/** if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) */
noCompatMode?: boolean;
/**
* if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`.
* Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false).
*/
condenseFlow?: boolean;
/** strings will be quoted using this quoting style. If you specify single quotes, double quotes will still be used for non-printable characters. (default: `'`) */
quotingType?: "'" | '"';
/** if true, all non-key strings will be quoted even if they normally don't need to. (default: false) */
forceQuotes?: boolean;
};
export function yamlSyscalls(): SysCallMapping {
return {
"yaml.parse": (_ctx, text: string): any => {
return YAML.load(text);
},
"yaml.stringify": (
_ctx,
obj: any,
options: YamlStringifyOptions = {},
): string => {
return YAML.dump(obj, {
quotingType: '"',
noCompatMode: true,
...options,
});
},
"yaml.patch": (
_ctx,
yaml: string,
patches: SetKeyPatch[],
): string => {
return applyPatches(yaml, patches);
},
};
}