Public
Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import type { ActionItem, Command } from "https://esm.town/v/pomdtr/cmdk_types";
import { callerRef } from "https://esm.town/v/pomdtr/refs";
export type {
Action,
ActionItem,
Command,
Context,
Detail,
Form,
List,
ListItem,
Page,
} from "https://esm.town/v/pomdtr/cmdk_types";
type Extension = {
title: string;
actions: ActionItem[];
};
export function defineExtension(manifest: {
title: string;
actions: ActionItem[];
}) {
const { slug } = callerRef() || {};
for (const action of manifest.actions) {
if (action.type == "run" && !action.run.extension) {
action.run.extension = slug;
}
if (action.type == "push" && !action.push.extension) {
action.push.extension = slug;
}
}
return manifest;
}
export function defineCommand(command: Command) {
return command;
}
export function cmdk(config: {
extensions?: Extension[];
actions?: ActionItem[];
}) {
const actions = [...config.extensions?.flatMap(ext => ext.actions), ...config.actions];
return async (req: Request) => {
const url = new URL(req.url);
if (req.method == "GET" && url.pathname == "/") {
return Response.json(actions);
}
const body = await req.json();
const commands = await import(`https://esm.town/v/${body.extension}`);
const command = commands[body.command];
if (!command) {
throw new Error(`Command not found: ${body.command}`);
}
const output = await command({ params: body.params, referer: body.referer });
return Response.json(output || null);
};
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 25, 2024