@indent-com/nexus-sdk 0.0.0-stage → 0.1.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.
- package/dist/analyze.d.ts +26 -0
- package/dist/analyze.js +190 -0
- package/dist/build.d.ts +32 -0
- package/dist/build.js +141 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +21 -0
- package/dist/client.d.ts +18 -0
- package/dist/client.js +4 -0
- package/dist/contract.d.ts +7 -0
- package/dist/contract.js +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +20 -0
- package/dist/helpers.d.ts +3 -0
- package/dist/helpers.js +43 -0
- package/dist/index.d.ts +199 -0
- package/dist/index.js +117 -0
- package/dist/manifest.d.ts +34 -0
- package/dist/react.d.ts +10 -0
- package/dist/react.js +7 -0
- package/dist/schema.d.ts +6 -0
- package/dist/schema.js +75 -0
- package/dist/store.d.ts +9 -0
- package/dist/store.js +118 -0
- package/dist/stubs.d.ts +1 -0
- package/dist/stubs.js +1 -0
- package/dist/vite.d.ts +7 -0
- package/dist/vite.js +56 -0
- package/package.json +72 -4
- package/README.md +0 -3
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { JsonSchema } from "@indent-com/nexus-sdk/manifest";
|
|
2
|
+
import type { Kind } from "./contract.ts";
|
|
3
|
+
export type Entrypoint = {
|
|
4
|
+
name: string;
|
|
5
|
+
kind: Kind;
|
|
6
|
+
input: JsonSchema;
|
|
7
|
+
output: JsonSchema;
|
|
8
|
+
description: string;
|
|
9
|
+
perViewer: boolean;
|
|
10
|
+
error?: string;
|
|
11
|
+
};
|
|
12
|
+
export type Installation = {
|
|
13
|
+
service: string;
|
|
14
|
+
alias: string;
|
|
15
|
+
};
|
|
16
|
+
export type TypedStatement = {
|
|
17
|
+
sql: string;
|
|
18
|
+
row: JsonSchema;
|
|
19
|
+
};
|
|
20
|
+
export type Analysis = {
|
|
21
|
+
entrypoints: Entrypoint[];
|
|
22
|
+
installations: Installation[];
|
|
23
|
+
env: string[];
|
|
24
|
+
statements: TypedStatement[];
|
|
25
|
+
};
|
|
26
|
+
export declare function analyze(root: string): Analysis;
|
package/dist/analyze.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import { BuildError, toSchema } from "./schema.js";
|
|
5
|
+
const defaults = {
|
|
6
|
+
strict: true,
|
|
7
|
+
target: ts.ScriptTarget.ES2023,
|
|
8
|
+
module: ts.ModuleKind.ESNext,
|
|
9
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
10
|
+
jsx: ts.JsxEmit.ReactJSX,
|
|
11
|
+
skipLibCheck: true,
|
|
12
|
+
};
|
|
13
|
+
export function analyze(root) {
|
|
14
|
+
const server = join(root, "server");
|
|
15
|
+
const sources = existsSync(server)
|
|
16
|
+
? readdirSync(server, { recursive: true, encoding: "utf8" })
|
|
17
|
+
.filter((file) => /\.tsx?$/.test(file) && !file.endsWith(".d.ts"))
|
|
18
|
+
.map((file) => join(server, file))
|
|
19
|
+
: [];
|
|
20
|
+
const ambient = readdirSync(root)
|
|
21
|
+
.filter((file) => file.endsWith(".d.ts"))
|
|
22
|
+
.map((file) => join(root, file));
|
|
23
|
+
const options = compilerOptions(root);
|
|
24
|
+
const program = ts.createProgram([...sources, ...ambient], options);
|
|
25
|
+
const checker = program.getTypeChecker();
|
|
26
|
+
const sdk = ts.resolveModuleName("@indent-com/nexus-sdk", join(server, "x.ts"), options, ts.sys)
|
|
27
|
+
.resolvedModule?.resolvedFileName;
|
|
28
|
+
const integrations = join(root, "integrations.d.ts");
|
|
29
|
+
const problems = [];
|
|
30
|
+
const entrypoints = [];
|
|
31
|
+
const installations = new Map();
|
|
32
|
+
const env = new Set();
|
|
33
|
+
const statements = new Map();
|
|
34
|
+
const where = (node) => {
|
|
35
|
+
const file = node.getSourceFile();
|
|
36
|
+
const { line } = file.getLineAndCharacterOfPosition(node.getStart());
|
|
37
|
+
return `${relative(root, file.fileName)}:${line + 1}`;
|
|
38
|
+
};
|
|
39
|
+
const problem = (node, message) => {
|
|
40
|
+
problems.push(`${where(node)}: ${message}`);
|
|
41
|
+
};
|
|
42
|
+
const exported = (callee) => {
|
|
43
|
+
const found = checker.getSymbolAtLocation(callee);
|
|
44
|
+
const symbol = found && found.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(found) : found;
|
|
45
|
+
const declared = symbol?.declarations?.[0]?.getSourceFile().fileName;
|
|
46
|
+
return declared === sdk ? symbol?.name : undefined;
|
|
47
|
+
};
|
|
48
|
+
const helper = (callee) => {
|
|
49
|
+
const name = exported(callee);
|
|
50
|
+
return name === "query" || name === "mutation" ? name : undefined;
|
|
51
|
+
};
|
|
52
|
+
const statement = (node) => {
|
|
53
|
+
const [row] = node.typeArguments ?? [];
|
|
54
|
+
if (row === undefined || exported(node.tag) !== "sql")
|
|
55
|
+
return;
|
|
56
|
+
const { template } = node;
|
|
57
|
+
const sql = ts.isNoSubstitutionTemplateLiteral(template)
|
|
58
|
+
? template.text
|
|
59
|
+
: template.head.text + template.templateSpans.map((span) => `?${span.literal.text}`).join("");
|
|
60
|
+
try {
|
|
61
|
+
const schema = toSchema(checker, checker.getTypeFromTypeNode(row), `sql<${row.getText()}>`);
|
|
62
|
+
if (schema.type !== "object") {
|
|
63
|
+
throw new BuildError(`sql<${row.getText()}> must be an object type`);
|
|
64
|
+
}
|
|
65
|
+
statements.set(JSON.stringify([sql, schema]), { sql, row: schema });
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (!(error instanceof BuildError))
|
|
69
|
+
throw error;
|
|
70
|
+
problem(node, error.message);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const entrypoint = (call, kind) => {
|
|
74
|
+
const declaration = call.parent;
|
|
75
|
+
const statement = declaration.parent?.parent;
|
|
76
|
+
const file = call.getSourceFile();
|
|
77
|
+
if (!ts.isVariableDeclaration(declaration) ||
|
|
78
|
+
!ts.isIdentifier(declaration.name) ||
|
|
79
|
+
declaration.initializer !== call ||
|
|
80
|
+
!(declaration.parent.flags & ts.NodeFlags.Const) ||
|
|
81
|
+
!ts.isVariableStatement(statement) ||
|
|
82
|
+
statement.parent !== file ||
|
|
83
|
+
!file.fileName.startsWith(`${server}/`) ||
|
|
84
|
+
!statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
85
|
+
return problem(call, `${kind} must make a top-level \`export const\` in server/`);
|
|
86
|
+
}
|
|
87
|
+
const module = relative(server, file.fileName).replace(/\.tsx?$/, "");
|
|
88
|
+
const name = `${module}/${declaration.name.text}`;
|
|
89
|
+
const doc = checker.getSymbolAtLocation(declaration.name)?.getDocumentationComment(checker);
|
|
90
|
+
const found = { name, kind, description: ts.displayPartsToString(doc) };
|
|
91
|
+
// A broken entrypoint fails only its own calls, so the rest of the app still runs.
|
|
92
|
+
const broken = (message) => entrypoints.push({
|
|
93
|
+
...found,
|
|
94
|
+
input: { type: "object" },
|
|
95
|
+
output: {},
|
|
96
|
+
perViewer: false,
|
|
97
|
+
error: `${where(call)}: ${message}`,
|
|
98
|
+
});
|
|
99
|
+
const [fn] = checker.getTypeAtLocation(call.arguments[0]).getCallSignatures();
|
|
100
|
+
if (fn === undefined)
|
|
101
|
+
return broken(`${name} must take a function`);
|
|
102
|
+
const [input, context] = fn.parameters;
|
|
103
|
+
try {
|
|
104
|
+
const schema = input
|
|
105
|
+
? toSchema(checker, checker.getTypeOfSymbol(input), `${name} input`)
|
|
106
|
+
: { type: "object", properties: {}, additionalProperties: false };
|
|
107
|
+
if (schema.type !== "object")
|
|
108
|
+
throw new BuildError(`${name} input must be an object type`);
|
|
109
|
+
const output = checker.getAwaitedType(fn.getReturnType()) ?? fn.getReturnType();
|
|
110
|
+
entrypoints.push({
|
|
111
|
+
...found,
|
|
112
|
+
input: schema,
|
|
113
|
+
output: toSchema(checker, output, `${name} output`),
|
|
114
|
+
perViewer: kind === "query" && context !== undefined,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
if (!(error instanceof BuildError))
|
|
119
|
+
throw error;
|
|
120
|
+
broken(error.message);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const staticName = (access, object) => {
|
|
124
|
+
if (ts.isPropertyAccessExpression(access) && access.expression === object) {
|
|
125
|
+
return access.name.text;
|
|
126
|
+
}
|
|
127
|
+
if (ts.isElementAccessExpression(access) &&
|
|
128
|
+
access.expression === object &&
|
|
129
|
+
ts.isStringLiteralLike(access.argumentExpression)) {
|
|
130
|
+
return access.argumentExpression.text;
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
};
|
|
134
|
+
const reference = (node) => {
|
|
135
|
+
const parent = node.parent;
|
|
136
|
+
if (node.text === "process" && staticName(parent, node) === "env") {
|
|
137
|
+
const variable = staticName(parent.parent, parent);
|
|
138
|
+
if (variable === undefined)
|
|
139
|
+
problem(parent, "read process.env by name, as in process.env.TOKEN");
|
|
140
|
+
else
|
|
141
|
+
env.add(variable);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const declared = checker.getSymbolAtLocation(node)?.valueDeclaration?.getSourceFile();
|
|
145
|
+
if (declared?.fileName !== integrations)
|
|
146
|
+
return;
|
|
147
|
+
const alias = staticName(parent, node);
|
|
148
|
+
if (alias === undefined && ts.isElementAccessExpression(parent)) {
|
|
149
|
+
problem(parent, `name the installation by its slug, as in ${node.text}["acme"]`);
|
|
150
|
+
}
|
|
151
|
+
else if (alias !== undefined && alias !== "me") {
|
|
152
|
+
installations.set(`${node.text}["${alias}"]`, { service: node.text, alias });
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const visit = (node) => {
|
|
156
|
+
if (ts.isCallExpression(node)) {
|
|
157
|
+
const kind = helper(node.expression);
|
|
158
|
+
if (kind !== undefined)
|
|
159
|
+
entrypoint(node, kind);
|
|
160
|
+
}
|
|
161
|
+
if (ts.isTaggedTemplateExpression(node))
|
|
162
|
+
statement(node);
|
|
163
|
+
if (ts.isIdentifier(node))
|
|
164
|
+
reference(node);
|
|
165
|
+
ts.forEachChild(node, visit);
|
|
166
|
+
};
|
|
167
|
+
for (const file of program.getSourceFiles()) {
|
|
168
|
+
if (!file.isDeclarationFile && !program.isSourceFileFromExternalLibrary(file))
|
|
169
|
+
visit(file);
|
|
170
|
+
}
|
|
171
|
+
if (problems.length > 0)
|
|
172
|
+
throw new BuildError(problems.join("\n"));
|
|
173
|
+
return {
|
|
174
|
+
entrypoints,
|
|
175
|
+
installations: [...installations]
|
|
176
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
177
|
+
.map(([, installation]) => installation),
|
|
178
|
+
env: [...env].sort(),
|
|
179
|
+
statements: [...statements]
|
|
180
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
181
|
+
.map(([, typed]) => typed),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function compilerOptions(root) {
|
|
185
|
+
const file = join(root, "tsconfig.json");
|
|
186
|
+
if (!existsSync(file))
|
|
187
|
+
return defaults;
|
|
188
|
+
const { config } = ts.readConfigFile(file, ts.sys.readFile);
|
|
189
|
+
return ts.parseJsonConfigFileContent(config, ts.sys, root).options;
|
|
190
|
+
}
|
package/dist/build.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { IncomingMessage, Server, ServerResponse } from "node:http";
|
|
2
|
+
import { type Entrypoint, type Installation, type TypedStatement } from "./analyze.ts";
|
|
3
|
+
import { BuildError } from "./schema.ts";
|
|
4
|
+
export type { DbBridge, DbGlobal, DbStatement, Kind } from "./contract.ts";
|
|
5
|
+
export type { Entrypoint, Installation, TypedStatement };
|
|
6
|
+
export { BuildError };
|
|
7
|
+
export type Migration = {
|
|
8
|
+
file: string;
|
|
9
|
+
sha256: string;
|
|
10
|
+
};
|
|
11
|
+
export type AppManifest = {
|
|
12
|
+
sdk: string;
|
|
13
|
+
installations: Installation[];
|
|
14
|
+
env: string[];
|
|
15
|
+
entrypoints: Entrypoint[];
|
|
16
|
+
migrations: Migration[];
|
|
17
|
+
statements: TypedStatement[];
|
|
18
|
+
};
|
|
19
|
+
export type BuildOptions = {
|
|
20
|
+
ui?: boolean;
|
|
21
|
+
};
|
|
22
|
+
export type ServeOptions = {
|
|
23
|
+
entrypoints: () => readonly Entrypoint[];
|
|
24
|
+
server: Server;
|
|
25
|
+
};
|
|
26
|
+
export type UiServer = {
|
|
27
|
+
handle(request: IncomingMessage, response: ServerResponse): void;
|
|
28
|
+
reload(): void;
|
|
29
|
+
close(): Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
export declare function build(dir: string, options?: BuildOptions): Promise<AppManifest>;
|
|
32
|
+
export declare function serve(dir: string, options: ServeOptions): Promise<UiServer>;
|
package/dist/build.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { builtinModules } from "node:module";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import esbuild from "esbuild";
|
|
6
|
+
import { build as buildUi, createServer } from "vite";
|
|
7
|
+
import { analyze } from "./analyze.js";
|
|
8
|
+
import { BuildError } from "./schema.js";
|
|
9
|
+
import { stubPrefix } from "./stubs.js";
|
|
10
|
+
import { nexus } from "./vite.js";
|
|
11
|
+
export { BuildError };
|
|
12
|
+
const sdk = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
13
|
+
export async function build(dir, options = {}) {
|
|
14
|
+
const root = realpathSync(dir);
|
|
15
|
+
const { entrypoints, installations, env, statements } = analyze(root);
|
|
16
|
+
const dist = join(root, "dist");
|
|
17
|
+
rmSync(dist, { recursive: true, force: true });
|
|
18
|
+
mkdirSync(dist);
|
|
19
|
+
for (const file of await bundle(root, entrypoints))
|
|
20
|
+
writeFileSync(file.path, file.contents);
|
|
21
|
+
const migrations = copyMigrations(root, dist);
|
|
22
|
+
if (options.ui !== false && existsSync(join(root, "ui", "index.html"))) {
|
|
23
|
+
await buildUi({
|
|
24
|
+
root: join(root, "ui"),
|
|
25
|
+
logLevel: "warn",
|
|
26
|
+
plugins: [nexus({ root, entrypoints: () => entrypoints })],
|
|
27
|
+
build: { outDir: join(dist, "ui"), emptyOutDir: true },
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
const manifest = { sdk, installations, env, entrypoints, migrations, statements };
|
|
31
|
+
writeFileSync(join(dist, "app_manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
32
|
+
return manifest;
|
|
33
|
+
}
|
|
34
|
+
export async function serve(dir, options) {
|
|
35
|
+
const root = realpathSync(dir);
|
|
36
|
+
const vite = await createServer({
|
|
37
|
+
root: join(root, "ui"),
|
|
38
|
+
appType: "spa",
|
|
39
|
+
plugins: [nexus({ root, entrypoints: options.entrypoints })],
|
|
40
|
+
server: { middlewareMode: true, hmr: { server: options.server } },
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
handle: (request, response) => vite.middlewares(request, response),
|
|
44
|
+
reload() {
|
|
45
|
+
for (const module of vite.moduleGraph.idToModuleMap.values()) {
|
|
46
|
+
if (module.id?.startsWith(stubPrefix))
|
|
47
|
+
vite.moduleGraph.invalidateModule(module);
|
|
48
|
+
}
|
|
49
|
+
vite.ws.send({ type: "full-reload" });
|
|
50
|
+
},
|
|
51
|
+
close: () => vite.close(),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
async function bundle(root, entrypoints) {
|
|
55
|
+
const contents = entrypoints
|
|
56
|
+
.map(({ name, kind, error }, index) => {
|
|
57
|
+
const at = name.lastIndexOf("/");
|
|
58
|
+
const as = JSON.stringify(name);
|
|
59
|
+
if (error !== undefined) {
|
|
60
|
+
const failure = JSON.stringify({ name: "BuildError", code: "build_failed" });
|
|
61
|
+
const fail = `throw Object.assign(new Error(${JSON.stringify(error)}), ${failure})`;
|
|
62
|
+
const fn = `Object.assign(async () => { ${fail}; }, { kind: ${JSON.stringify(kind)} })`;
|
|
63
|
+
return `const broken${index} = ${fn};\nexport { broken${index} as ${as} };`;
|
|
64
|
+
}
|
|
65
|
+
const from = JSON.stringify(`./server/${name.slice(0, at)}`);
|
|
66
|
+
return `export { ${name.slice(at + 1)} as ${as} } from ${from};`;
|
|
67
|
+
})
|
|
68
|
+
.join("\n");
|
|
69
|
+
const result = await esbuild.build({
|
|
70
|
+
stdin: { contents, resolveDir: root, sourcefile: "app.ts", loader: "ts" },
|
|
71
|
+
absWorkingDir: root,
|
|
72
|
+
bundle: true,
|
|
73
|
+
format: "esm",
|
|
74
|
+
platform: "neutral",
|
|
75
|
+
target: "es2023",
|
|
76
|
+
conditions: ["worker", "browser"],
|
|
77
|
+
mainFields: ["browser", "module", "main"],
|
|
78
|
+
plugins: [builtins],
|
|
79
|
+
metafile: true,
|
|
80
|
+
outfile: join(root, "dist", "app.mjs"),
|
|
81
|
+
sourcemap: "external",
|
|
82
|
+
sourcesContent: false,
|
|
83
|
+
write: false,
|
|
84
|
+
logLevel: "silent",
|
|
85
|
+
});
|
|
86
|
+
const missing = nodeImports(result.metafile);
|
|
87
|
+
if (missing.length > 0)
|
|
88
|
+
throw new BuildError(missing.join("\n"));
|
|
89
|
+
return result.outputFiles;
|
|
90
|
+
}
|
|
91
|
+
const builtins = {
|
|
92
|
+
name: "node-builtins",
|
|
93
|
+
setup(build) {
|
|
94
|
+
const filter = new RegExp(`^(node:.*|${builtinModules.join("|")})$`);
|
|
95
|
+
build.onResolve({ filter }, async ({ path, pluginData, ...args }) => {
|
|
96
|
+
if (pluginData === builtins)
|
|
97
|
+
return undefined;
|
|
98
|
+
const found = await build.resolve(path, { ...args, pluginData: builtins });
|
|
99
|
+
return found.errors.length === 0 ? found : { path, external: true };
|
|
100
|
+
});
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
function nodeImports({ inputs }) {
|
|
104
|
+
const imports = Object.values(inputs).flatMap(({ imports }) => imports);
|
|
105
|
+
const imported = new Set(imports.map(({ path }) => path));
|
|
106
|
+
const queue = Object.keys(inputs).filter((file) => !imported.has(file));
|
|
107
|
+
const parents = new Map();
|
|
108
|
+
for (const file of queue) {
|
|
109
|
+
for (const { path, external } of inputs[file]?.imports ?? []) {
|
|
110
|
+
if (external || parents.has(path))
|
|
111
|
+
continue;
|
|
112
|
+
parents.set(path, file);
|
|
113
|
+
queue.push(path);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return queue.flatMap((file) => (inputs[file]?.imports ?? [])
|
|
117
|
+
.filter(({ external }) => external)
|
|
118
|
+
.map(({ path }) => {
|
|
119
|
+
const chain = [path];
|
|
120
|
+
for (let at = file; at && parents.has(at); at = parents.get(at)) {
|
|
121
|
+
chain.unshift(at);
|
|
122
|
+
}
|
|
123
|
+
return `${path} is not in the server runtime, imported by ${chain.join(" → ")}`;
|
|
124
|
+
}));
|
|
125
|
+
}
|
|
126
|
+
function copyMigrations(root, dist) {
|
|
127
|
+
const from = join(root, "migrations");
|
|
128
|
+
if (!existsSync(from))
|
|
129
|
+
return [];
|
|
130
|
+
mkdirSync(join(dist, "migrations"));
|
|
131
|
+
return readdirSync(from)
|
|
132
|
+
.filter((file) => file.endsWith(".sql"))
|
|
133
|
+
.sort()
|
|
134
|
+
.map((file) => {
|
|
135
|
+
copyFileSync(join(from, file), join(dist, "migrations", file));
|
|
136
|
+
const sha256 = createHash("sha256")
|
|
137
|
+
.update(readFileSync(join(from, file)))
|
|
138
|
+
.digest("hex");
|
|
139
|
+
return { file, sha256 };
|
|
140
|
+
});
|
|
141
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { build } from "./build.js";
|
|
4
|
+
const [command, dir = "."] = process.argv.slice(2);
|
|
5
|
+
if (command !== "build") {
|
|
6
|
+
console.error("usage: nexus-sdk build [dir]");
|
|
7
|
+
process.exit(2);
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const manifest = await build(resolve(dir));
|
|
11
|
+
console.log(`built ${manifest.entrypoints.length} entrypoints into ${join(dir, "dist")}`);
|
|
12
|
+
const broken = manifest.entrypoints.flatMap(({ error }) => error ?? []);
|
|
13
|
+
for (const error of broken)
|
|
14
|
+
console.error(error);
|
|
15
|
+
if (broken.length > 0)
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
console.error(error instanceof Error ? error.message : error);
|
|
20
|
+
process.exitCode = 1;
|
|
21
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Query, ToolError } from "@indent-com/nexus-sdk";
|
|
2
|
+
|
|
3
|
+
export { ToolError } from "@indent-com/nexus-sdk";
|
|
4
|
+
|
|
5
|
+
/** Watches a query outside React. Call the result to stop watching. */
|
|
6
|
+
export function watch<I, O>(
|
|
7
|
+
query: Query<I, O>,
|
|
8
|
+
input: I,
|
|
9
|
+
listener: (reading: Reading<O>) => void,
|
|
10
|
+
): () => void;
|
|
11
|
+
|
|
12
|
+
/** A query's latest result, and whether it is being refreshed. */
|
|
13
|
+
export type Reading<O> = {
|
|
14
|
+
data: O | undefined; // the latest result
|
|
15
|
+
at: string | null; // when it was fetched
|
|
16
|
+
refreshing: boolean; // a live call is running
|
|
17
|
+
error: ToolError | undefined; // the last refresh failed; data is from before it
|
|
18
|
+
};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Result, Statement } from "@indent-com/nexus-sdk";
|
|
2
|
+
export type Kind = "query" | "mutation";
|
|
3
|
+
export type DbStatement = Statement<unknown>;
|
|
4
|
+
export type DbBridge = (statements: DbStatement[]) => Promise<Result<unknown>[]>;
|
|
5
|
+
export type DbGlobal = {
|
|
6
|
+
__nexusDb?: DbBridge;
|
|
7
|
+
};
|
package/dist/contract.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type * as Sdk from "@indent-com/nexus-sdk";
|
|
2
|
+
export declare class ToolError extends Error implements Sdk.ToolError {
|
|
3
|
+
readonly name = "ToolError";
|
|
4
|
+
readonly code: string;
|
|
5
|
+
readonly retryable: boolean;
|
|
6
|
+
readonly data: unknown;
|
|
7
|
+
readonly link: string | undefined;
|
|
8
|
+
constructor(code: string, message: string, options?: Sdk.ToolErrorOptions);
|
|
9
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
10
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export class ToolError extends Error {
|
|
2
|
+
name = "ToolError";
|
|
3
|
+
code;
|
|
4
|
+
retryable;
|
|
5
|
+
data;
|
|
6
|
+
link;
|
|
7
|
+
constructor(code, message, options = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.retryable = options.retryable ?? false;
|
|
11
|
+
this.data = options.data;
|
|
12
|
+
this.link = options.link;
|
|
13
|
+
}
|
|
14
|
+
// The runtime throws plain errors named ToolError, so they match too.
|
|
15
|
+
static [Symbol.hasInstance](value) {
|
|
16
|
+
return (value instanceof Error &&
|
|
17
|
+
value.name === "ToolError" &&
|
|
18
|
+
typeof value.code === "string");
|
|
19
|
+
}
|
|
20
|
+
}
|
package/dist/helpers.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export const paginate = async ({ page, items, next, limit }) => {
|
|
2
|
+
const found = [];
|
|
3
|
+
let cursor;
|
|
4
|
+
for (;;) {
|
|
5
|
+
const current = await page(cursor);
|
|
6
|
+
found.push(...items(current));
|
|
7
|
+
const following = next(current) || undefined;
|
|
8
|
+
if (limit !== undefined && found.length >= limit) {
|
|
9
|
+
if (following !== undefined || found.length > limit)
|
|
10
|
+
console.warn(`paginate stopped at ${limit} items, and more remain`);
|
|
11
|
+
return found.slice(0, limit);
|
|
12
|
+
}
|
|
13
|
+
if (following === undefined)
|
|
14
|
+
return found;
|
|
15
|
+
if (following === cursor)
|
|
16
|
+
throw new Error(`paginate got cursor ${cursor} twice`);
|
|
17
|
+
cursor = following;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
export const map = async (items, fn, options = {}) => {
|
|
21
|
+
const { concurrency = 5 } = options;
|
|
22
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
23
|
+
throw new RangeError(`concurrency must be a positive integer, not ${concurrency}`);
|
|
24
|
+
}
|
|
25
|
+
const results = new Array(items.length);
|
|
26
|
+
let next = 0;
|
|
27
|
+
let failed = false;
|
|
28
|
+
const worker = async () => {
|
|
29
|
+
while (!failed && next < items.length) {
|
|
30
|
+
const index = next++;
|
|
31
|
+
try {
|
|
32
|
+
results[index] = await fn(items[index], index);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
failed = true;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const workers = Math.min(concurrency, items.length);
|
|
41
|
+
await Promise.all(Array.from({ length: workers }, worker));
|
|
42
|
+
return results;
|
|
43
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/** A read: GET, with stored results. */
|
|
2
|
+
export function query<I extends object, O>(
|
|
3
|
+
fn: (input: I, context: Context) => Promise<O>,
|
|
4
|
+
): Query<I, O>;
|
|
5
|
+
|
|
6
|
+
/** A change: POST, always live. */
|
|
7
|
+
export function mutation<I extends object, O>(
|
|
8
|
+
fn: (input: I, context: Context) => Promise<O>,
|
|
9
|
+
): Mutation<I, O>;
|
|
10
|
+
|
|
11
|
+
/** What the UI imports: callable with the input alone, and branded by kind. */
|
|
12
|
+
export type Query<I, O> = ((input: I) => Promise<O>) & {
|
|
13
|
+
readonly kind: "query";
|
|
14
|
+
};
|
|
15
|
+
/** What the UI imports for a mutation: callable with the input alone. */
|
|
16
|
+
export type Mutation<I, O> = ((input: I) => Promise<O>) & {
|
|
17
|
+
readonly kind: "mutation";
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Who the call is for, and the app's cache. */
|
|
21
|
+
export type Context = { auth: Auth; cache: Cache };
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The app's cache. Nothing is cached unless a handler asks. Entries are shared by
|
|
25
|
+
* everyone who calls the app unless the handler scopes them with `forViewer()`.
|
|
26
|
+
*/
|
|
27
|
+
export type Cache = {
|
|
28
|
+
/**
|
|
29
|
+
* The value stored under `key` while it is younger than `freshFor`; otherwise what
|
|
30
|
+
* `load` returns, stored. Gets of one key in a call share one `load`, and when
|
|
31
|
+
* `load` throws, an older stored value is returned instead.
|
|
32
|
+
*/
|
|
33
|
+
get<T extends Json>(options: {
|
|
34
|
+
key: CacheKey;
|
|
35
|
+
freshFor: Duration;
|
|
36
|
+
load: () => Promise<T>;
|
|
37
|
+
}): Promise<T>;
|
|
38
|
+
/** Drops `key`, so the next `get` loads it. */
|
|
39
|
+
invalidate(key: CacheKey): Promise<void>;
|
|
40
|
+
/** The same cache, with entries only the caller sees. */
|
|
41
|
+
forViewer(): Cache;
|
|
42
|
+
};
|
|
43
|
+
/** Any JSON value; equal values name the same entry. */
|
|
44
|
+
export type CacheKey =
|
|
45
|
+
string | number | boolean | null | CacheKey[] | { [key: string]: CacheKey };
|
|
46
|
+
/** A value that comes back the same from JSON; `undefined` properties drop out. */
|
|
47
|
+
export type Json =
|
|
48
|
+
| string
|
|
49
|
+
| number
|
|
50
|
+
| boolean
|
|
51
|
+
| null
|
|
52
|
+
| readonly Json[]
|
|
53
|
+
| { readonly [key: string]: Json | undefined };
|
|
54
|
+
/** How long, as in `"1 minute"` or `"30 seconds"`. */
|
|
55
|
+
export type Duration = `${number} ${DurationUnit}`;
|
|
56
|
+
type DurationUnit =
|
|
57
|
+
| "second"
|
|
58
|
+
| "seconds"
|
|
59
|
+
| "minute"
|
|
60
|
+
| "minutes"
|
|
61
|
+
| "hour"
|
|
62
|
+
| "hours"
|
|
63
|
+
| "day"
|
|
64
|
+
| "days";
|
|
65
|
+
|
|
66
|
+
/** The actor a call or run is for. */
|
|
67
|
+
export type Auth = { actor: Actor };
|
|
68
|
+
|
|
69
|
+
/** A person, a bot, or Indent itself. */
|
|
70
|
+
export type Actor =
|
|
71
|
+
| { kind: "user"; id: string; name: string; email: string } // a person
|
|
72
|
+
| { kind: "bot"; id: string; name: string } // a program with its own credential
|
|
73
|
+
| { kind: "indent" }; // Indent itself, with no person or bot behind the call
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* What a call that cannot be made throws, and what the UI's calls reject with.
|
|
77
|
+
* `instanceof` matches every `ToolError`, including the ones the runtime throws.
|
|
78
|
+
*/
|
|
79
|
+
export class ToolError extends Error {
|
|
80
|
+
constructor(code: string, message: string, options?: ToolErrorOptions);
|
|
81
|
+
readonly name: "ToolError";
|
|
82
|
+
readonly code: string; // such as "invalid_arguments", "not_allowed" or "timeout"
|
|
83
|
+
readonly retryable: boolean; // the same call may work if tried again
|
|
84
|
+
readonly data: unknown; // details, such as the error body a provider sent
|
|
85
|
+
readonly link: string | undefined; // where the person connects or chooses
|
|
86
|
+
}
|
|
87
|
+
/** What a `ToolError` carries besides its code and message. */
|
|
88
|
+
export type ToolErrorOptions = {
|
|
89
|
+
retryable?: boolean;
|
|
90
|
+
data?: unknown;
|
|
91
|
+
link?: string;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** Every item of a paged list, following each page's cursor to the end. */
|
|
95
|
+
export function paginate<P, I>(options: {
|
|
96
|
+
page: (cursor: string | undefined) => Promise<P>; // the first has no cursor
|
|
97
|
+
items: (page: P) => readonly I[];
|
|
98
|
+
next: (page: P) => string | null | undefined; // the next cursor; none at the end
|
|
99
|
+
limit?: number; // stop at this many items, with a warning if more remain
|
|
100
|
+
}): Promise<I[]>;
|
|
101
|
+
|
|
102
|
+
/** `fn` on each item, a few at a time, with results in the items' order. */
|
|
103
|
+
export function map<T, R>(
|
|
104
|
+
items: readonly T[],
|
|
105
|
+
fn: (item: T, index: number) => Promise<R>,
|
|
106
|
+
options?: { concurrency?: number }, // at most this many at once; default 5
|
|
107
|
+
): Promise<R[]>;
|
|
108
|
+
|
|
109
|
+
/** The app's SQLite database. */
|
|
110
|
+
export const db: {
|
|
111
|
+
/** One statement, or several in one transaction; results come back in order. */
|
|
112
|
+
execute<S extends Statement<unknown>[]>(
|
|
113
|
+
...statements: S
|
|
114
|
+
): Promise<Results<S>>;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A statement. Each `${value}` is a bound parameter, never spliced into the SQL.
|
|
119
|
+
*/
|
|
120
|
+
export function sql<Row = never>(
|
|
121
|
+
strings: TemplateStringsArray,
|
|
122
|
+
...values: Value[]
|
|
123
|
+
): Statement<Row>;
|
|
124
|
+
|
|
125
|
+
/** SQL and its parameters. `Row` types its rows. */
|
|
126
|
+
export type Statement<Row> = { sql: string; params: Value[] };
|
|
127
|
+
/** The rows a statement returns, and how many rows it changed. */
|
|
128
|
+
export type Result<Row> = { rows: Row[]; changes: number };
|
|
129
|
+
/** One result per statement, in order. */
|
|
130
|
+
export type Results<S> = {
|
|
131
|
+
[K in keyof S]: S[K] extends Statement<infer Row> ? Result<Row> : never;
|
|
132
|
+
};
|
|
133
|
+
/** A value a statement binds. */
|
|
134
|
+
export type Value = string | number | boolean | null;
|
|
135
|
+
|
|
136
|
+
/** An event handler: called with each batch of the named event. */
|
|
137
|
+
export function onEvent<K extends keyof Events>(
|
|
138
|
+
name: K, // such as "linear.issue.updated"
|
|
139
|
+
fn: (events: Events[K][], context: HandlerContext) => Promise<void>,
|
|
140
|
+
): EventHandler;
|
|
141
|
+
|
|
142
|
+
/** A schedule handler: called on each tick of a cron schedule. */
|
|
143
|
+
export function onSchedule(
|
|
144
|
+
cron: string, // such as "0 3 * * *"; UTC unless it starts with CRON_TZ=
|
|
145
|
+
fn: (context: HandlerContext) => Promise<void>,
|
|
146
|
+
): ScheduleHandler;
|
|
147
|
+
|
|
148
|
+
/** Opaque: only Indent calls a handler. */
|
|
149
|
+
export interface EventHandler {}
|
|
150
|
+
/** Opaque: only Indent calls a handler. */
|
|
151
|
+
export interface ScheduleHandler {}
|
|
152
|
+
|
|
153
|
+
/** What a handler is called with. */
|
|
154
|
+
export type HandlerContext = {
|
|
155
|
+
auth: Auth; // always the indent actor
|
|
156
|
+
key: string; // the same on every delivery of one batch or tick
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/** Starts a session, waits for it to finish, and returns its final reply. */
|
|
160
|
+
export function session(input: SessionInput<string>): Promise<string>;
|
|
161
|
+
/** Starts a session, waits for it to finish, and returns its result as a `T`. */
|
|
162
|
+
export function session<T extends object>(input: SessionInput<T>): Promise<T>;
|
|
163
|
+
|
|
164
|
+
/** What a session works on, what it can call, and how its result is checked. */
|
|
165
|
+
export type SessionInput<T> = {
|
|
166
|
+
prompt: string;
|
|
167
|
+
allow?: readonly Allowed[]; // default: every installation the app names
|
|
168
|
+
check?: (result: T) => string | readonly string[] | undefined;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/** `MCP_Linear["acme"]`, one of its operations, or one of the app's functions. */
|
|
172
|
+
export type Allowed = { readonly [operation: string]: Operation } | Operation;
|
|
173
|
+
/** An operation, or one of the app's functions. */
|
|
174
|
+
export type Operation = (...args: never[]) => Promise<unknown>;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* What `session()` throws when a session fails, is stopped, or fails its checks.
|
|
178
|
+
*/
|
|
179
|
+
export class SessionError extends Error {
|
|
180
|
+
readonly name: "SessionError";
|
|
181
|
+
readonly sessionId: string; // to find the session's transcript
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Defines a workflow from its `run` function. */
|
|
185
|
+
export function workflow<I>(definition: {
|
|
186
|
+
oneAtATime?: (input: I) => string;
|
|
187
|
+
run(input: I, auth: Auth): Promise<void>;
|
|
188
|
+
}): Workflow<I>;
|
|
189
|
+
|
|
190
|
+
/** Opaque. `I` is the input it is started with. */
|
|
191
|
+
export interface Workflow<I> {}
|
|
192
|
+
|
|
193
|
+
/** Starts a run of a workflow with an input, a key, and the `auth` it acts for. */
|
|
194
|
+
export function start<I>(
|
|
195
|
+
workflow: Workflow<I>,
|
|
196
|
+
input: I,
|
|
197
|
+
key: string,
|
|
198
|
+
auth: Auth, // who the run is for
|
|
199
|
+
): Promise<void>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
function tag(kind) {
|
|
2
|
+
return (fn) => Object.assign((async (input, context) => fn(input, {
|
|
3
|
+
...context,
|
|
4
|
+
cache: appCache(context.auth.actor, null, new Map()),
|
|
5
|
+
})), { kind });
|
|
6
|
+
}
|
|
7
|
+
export { ToolError } from "./errors.js";
|
|
8
|
+
export { map, paginate } from "./helpers.js";
|
|
9
|
+
export const query = tag("query");
|
|
10
|
+
export const mutation = tag("mutation");
|
|
11
|
+
export const sql = (strings, ...values) => ({
|
|
12
|
+
sql: strings.join("?"),
|
|
13
|
+
params: values,
|
|
14
|
+
});
|
|
15
|
+
const onIndentOnly = (name) => async (..._args) => {
|
|
16
|
+
throw new Error(`${name} runs only on Indent`);
|
|
17
|
+
};
|
|
18
|
+
export const onEvent = () => ({});
|
|
19
|
+
export const onSchedule = () => ({});
|
|
20
|
+
export const workflow = () => ({});
|
|
21
|
+
export const session = onIndentOnly("session");
|
|
22
|
+
export const start = onIndentOnly("start");
|
|
23
|
+
function database() {
|
|
24
|
+
const bridge = globalThis.__nexusDb;
|
|
25
|
+
if (bridge === undefined)
|
|
26
|
+
throw new Error("db.execute runs only in an app's runtime");
|
|
27
|
+
return bridge;
|
|
28
|
+
}
|
|
29
|
+
export const db = {
|
|
30
|
+
async execute(...statements) {
|
|
31
|
+
const results = await database()(statements.map(({ sql, params }) => ({ sql, params })));
|
|
32
|
+
return results;
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
// The cache lives in the app's own database, so it is wherever the app's data is.
|
|
36
|
+
const CACHE_TABLE = "_indent_cache";
|
|
37
|
+
const CREATE_CACHE = {
|
|
38
|
+
sql: `CREATE TABLE IF NOT EXISTS ${CACHE_TABLE} (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL, stored_at INTEGER NOT NULL)`,
|
|
39
|
+
params: [],
|
|
40
|
+
};
|
|
41
|
+
const UNIT_MS = { day: 86_400_000, hour: 3_600_000, minute: 60_000, second: 1000 };
|
|
42
|
+
/** Entries nobody has stored for a week go, so the cache can't fill the database. */
|
|
43
|
+
const RETENTION_MS = 7 * UNIT_MS.day;
|
|
44
|
+
function milliseconds(duration) {
|
|
45
|
+
const [count, unit = ""] = duration.split(" ");
|
|
46
|
+
const ms = UNIT_MS[unit.replace(/s$/u, "")];
|
|
47
|
+
if (ms === undefined || !Number.isFinite(Number(count)))
|
|
48
|
+
throw new Error(`Not a duration: ${duration}`);
|
|
49
|
+
return Number(count) * ms;
|
|
50
|
+
}
|
|
51
|
+
/** Runs cache statements, creating the table the first time one finds it missing. */
|
|
52
|
+
async function cacheDb(statements) {
|
|
53
|
+
try {
|
|
54
|
+
return await database()(statements);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (!(error instanceof Error && /no such table/iu.test(error.message)))
|
|
58
|
+
throw error;
|
|
59
|
+
const [, ...results] = await database()([CREATE_CACHE, ...statements]);
|
|
60
|
+
return results;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function appCache(actor, viewer, loading) {
|
|
64
|
+
const name = (key) => JSON.stringify([viewer, key]);
|
|
65
|
+
async function lookup(id, options) {
|
|
66
|
+
const { key, freshFor, load } = options;
|
|
67
|
+
const [{ rows }] = (await cacheDb([
|
|
68
|
+
{ sql: `SELECT value, stored_at FROM ${CACHE_TABLE} WHERE key = ?`, params: [id] },
|
|
69
|
+
]));
|
|
70
|
+
const [hit] = rows;
|
|
71
|
+
if (hit !== undefined && Date.now() - hit.stored_at < milliseconds(freshFor))
|
|
72
|
+
return JSON.parse(hit.value);
|
|
73
|
+
let value;
|
|
74
|
+
try {
|
|
75
|
+
value = await load();
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (hit === undefined)
|
|
79
|
+
throw error;
|
|
80
|
+
const at = new Date(hit.stored_at).toISOString();
|
|
81
|
+
console.warn(`cache: loading ${JSON.stringify(key)} failed, so it returned the value stored ` +
|
|
82
|
+
`at ${at}: ${error instanceof Error ? error.message : String(error)}`);
|
|
83
|
+
return JSON.parse(hit.value);
|
|
84
|
+
}
|
|
85
|
+
const storedAt = Date.now();
|
|
86
|
+
await cacheDb([
|
|
87
|
+
{
|
|
88
|
+
sql: `INSERT OR REPLACE INTO ${CACHE_TABLE} (key, value, stored_at) VALUES (?, ?, ?)`,
|
|
89
|
+
params: [id, JSON.stringify(value) ?? "null", storedAt],
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
sql: `DELETE FROM ${CACHE_TABLE} WHERE stored_at < ?`,
|
|
93
|
+
params: [storedAt - RETENTION_MS],
|
|
94
|
+
},
|
|
95
|
+
]);
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
get(options) {
|
|
100
|
+
const id = name(options.key);
|
|
101
|
+
const running = loading.get(id);
|
|
102
|
+
if (running !== undefined)
|
|
103
|
+
return running;
|
|
104
|
+
const started = lookup(id, options).finally(() => loading.delete(id));
|
|
105
|
+
loading.set(id, started);
|
|
106
|
+
return started;
|
|
107
|
+
},
|
|
108
|
+
async invalidate(key) {
|
|
109
|
+
await cacheDb([{ sql: `DELETE FROM ${CACHE_TABLE} WHERE key = ?`, params: [name(key)] }]);
|
|
110
|
+
},
|
|
111
|
+
forViewer() {
|
|
112
|
+
if (actor.kind !== "user")
|
|
113
|
+
throw new Error("forViewer needs a person behind the call");
|
|
114
|
+
return appCache(actor, actor.id, loading);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** `dist/app_manifest.json`: what the build found in the code. */
|
|
2
|
+
export type BuiltManifest = {
|
|
3
|
+
app: string; // the repository's name
|
|
4
|
+
commit: string; // the commit it was built from
|
|
5
|
+
dirty: boolean; // true when the working tree had uncommitted changes
|
|
6
|
+
sdk: string; // the @indent-com/nexus-sdk version
|
|
7
|
+
installations: { service: string; alias: string }[]; // such as MCP_Linear, "acme"
|
|
8
|
+
me: string[]; // services it calls through me, such as "MCP_Linear"
|
|
9
|
+
env: string[]; // every environment variable the code reads
|
|
10
|
+
entrypoints: {
|
|
11
|
+
name: string; // file and export, such as "issues/assign"
|
|
12
|
+
kind: "query" | "mutation" | "event" | "schedule";
|
|
13
|
+
event?: string; // an event handler's event, such as "linear.issue.updated"
|
|
14
|
+
cron?: string; // a schedule handler's cron string
|
|
15
|
+
input: JsonSchema;
|
|
16
|
+
output: JsonSchema;
|
|
17
|
+
description: string; // the doc comment
|
|
18
|
+
perViewer: boolean; // a query that declares context or calls me
|
|
19
|
+
me: string[]; // services it calls through me
|
|
20
|
+
env: string[]; // variables it reads
|
|
21
|
+
error?: string; // why the build could not make it; calling it fails with this
|
|
22
|
+
}[];
|
|
23
|
+
workflows: { name: string; input: JsonSchema }[];
|
|
24
|
+
functions: {
|
|
25
|
+
name: string; // a query, mutation or function that a session allows
|
|
26
|
+
description: string; // the doc comment
|
|
27
|
+
input: JsonSchema;
|
|
28
|
+
result: JsonSchema;
|
|
29
|
+
}[];
|
|
30
|
+
files: { path: string; sha256: string; bytes: number }[]; // every file in dist/
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** A JSON Schema the build made from a TypeScript type. */
|
|
34
|
+
export type JsonSchema = { readonly [keyword: string]: unknown };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Query } from "@indent-com/nexus-sdk";
|
|
2
|
+
import type { Reading } from "@indent-com/nexus-sdk/client";
|
|
3
|
+
|
|
4
|
+
export type { Reading };
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reads a query in a component, as in `useCall(issues, { team: "ENG" })`.
|
|
8
|
+
* Passing a mutation is a type error.
|
|
9
|
+
*/
|
|
10
|
+
export function useCall<I, O>(query: Query<I, O>, input?: I): Reading<O>;
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
2
|
+
import { read, watch } from "./store.js";
|
|
3
|
+
export const useCall = (query, input) => {
|
|
4
|
+
const key = JSON.stringify(input ?? {});
|
|
5
|
+
const subscribe = useCallback((notify) => watch(query, input, notify), [query, key]);
|
|
6
|
+
return useSyncExternalStore(subscribe, () => read(query, input));
|
|
7
|
+
};
|
package/dist/schema.d.ts
ADDED
package/dist/schema.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
export class BuildError extends Error {
|
|
3
|
+
name = "BuildError";
|
|
4
|
+
}
|
|
5
|
+
export function toSchema(checker, type, path) {
|
|
6
|
+
const convert = (type, path, seen) => {
|
|
7
|
+
const fail = (reason) => {
|
|
8
|
+
throw new BuildError(`${path} is ${checker.typeToString(type)}, ${reason}`);
|
|
9
|
+
};
|
|
10
|
+
if (type.flags & ts.TypeFlags.Boolean)
|
|
11
|
+
return { type: "boolean" };
|
|
12
|
+
if (type.flags & ts.TypeFlags.String)
|
|
13
|
+
return { type: "string" };
|
|
14
|
+
if (type.flags & ts.TypeFlags.Number)
|
|
15
|
+
return { type: "number" };
|
|
16
|
+
if (type.flags & ts.TypeFlags.Null)
|
|
17
|
+
return { type: "null" };
|
|
18
|
+
if (type.isStringLiteral() || type.isNumberLiteral())
|
|
19
|
+
return { const: type.value };
|
|
20
|
+
if (type.flags & ts.TypeFlags.BooleanLiteral) {
|
|
21
|
+
return { const: checker.typeToString(type) === "true" };
|
|
22
|
+
}
|
|
23
|
+
if (type.isUnion())
|
|
24
|
+
return union(type, path, seen);
|
|
25
|
+
if (!(type.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection))) {
|
|
26
|
+
return fail("which is not a JSON type");
|
|
27
|
+
}
|
|
28
|
+
if (seen.includes(type))
|
|
29
|
+
return fail("which is recursive");
|
|
30
|
+
const inner = [...seen, type];
|
|
31
|
+
if (checker.isArrayType(type)) {
|
|
32
|
+
const [item] = checker.getTypeArguments(type);
|
|
33
|
+
return { type: "array", items: convert(item, `${path}[]`, inner) };
|
|
34
|
+
}
|
|
35
|
+
const callable = type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0;
|
|
36
|
+
const isClass = (type.getSymbol()?.flags ?? 0) & ts.SymbolFlags.Class;
|
|
37
|
+
if (callable || isClass || checker.isTupleType(type)) {
|
|
38
|
+
return fail("which is not a JSON type");
|
|
39
|
+
}
|
|
40
|
+
const index = checker.getIndexInfoOfType(type, ts.IndexKind.String);
|
|
41
|
+
const properties = checker.getPropertiesOfType(type);
|
|
42
|
+
const required = properties
|
|
43
|
+
.filter((property) => !(property.flags & ts.SymbolFlags.Optional))
|
|
44
|
+
.map((property) => property.name);
|
|
45
|
+
const entries = properties.map((property) => {
|
|
46
|
+
const schema = convert(checker.getTypeOfSymbol(property), `${path}.${property.name}`, inner);
|
|
47
|
+
const description = ts.displayPartsToString(property.getDocumentationComment(checker));
|
|
48
|
+
return [property.name, description ? { ...schema, description } : schema];
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
type: "object",
|
|
52
|
+
properties: Object.fromEntries(entries),
|
|
53
|
+
...(required.length > 0 ? { required } : {}),
|
|
54
|
+
additionalProperties: index ? convert(index.type, `${path}[string]`, inner) : false,
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const union = (type, path, seen) => {
|
|
58
|
+
const schemas = type.types
|
|
59
|
+
.filter((member) => !(member.flags & ts.TypeFlags.Undefined))
|
|
60
|
+
.map((member) => member.flags & ts.TypeFlags.BooleanLiteral
|
|
61
|
+
? { type: "boolean" }
|
|
62
|
+
: convert(member, path, seen));
|
|
63
|
+
const unique = [...new Map(schemas.map((s) => [JSON.stringify(s), s])).values()];
|
|
64
|
+
if (unique.length === 1)
|
|
65
|
+
return unique[0];
|
|
66
|
+
if (unique.every((schema) => "const" in schema)) {
|
|
67
|
+
return { enum: unique.map((schema) => schema.const) };
|
|
68
|
+
}
|
|
69
|
+
if (unique.every((schema) => Object.keys(schema).join() === "type")) {
|
|
70
|
+
return { type: unique.map((schema) => schema.type) };
|
|
71
|
+
}
|
|
72
|
+
return { anyOf: unique };
|
|
73
|
+
};
|
|
74
|
+
return convert(type, path, []);
|
|
75
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Query } from "@indent-com/nexus-sdk";
|
|
2
|
+
import type { Reading } from "@indent-com/nexus-sdk/client";
|
|
3
|
+
import type { Kind } from "./contract.ts";
|
|
4
|
+
export type Stub = ((input: unknown) => Promise<unknown>) & {
|
|
5
|
+
readonly kind: Kind;
|
|
6
|
+
};
|
|
7
|
+
export declare function stub(kind: Kind, path: string): Stub;
|
|
8
|
+
export declare function read<O>(query: Query<never, O>, input: unknown): Reading<O>;
|
|
9
|
+
export declare function watch<O>(query: Query<never, O>, input: unknown, listener: (reading: Reading<O>) => void): () => void;
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { ToolError } from "./errors.js";
|
|
2
|
+
const refreshEvery = 5 * 60_000;
|
|
3
|
+
const paths = new WeakMap();
|
|
4
|
+
const entries = new Map();
|
|
5
|
+
export function stub(kind, path) {
|
|
6
|
+
const call = async (input) => {
|
|
7
|
+
if (kind === "query")
|
|
8
|
+
return request("GET", path, input);
|
|
9
|
+
try {
|
|
10
|
+
return await request("POST", path, input);
|
|
11
|
+
}
|
|
12
|
+
finally {
|
|
13
|
+
for (const entry of entries.values()) {
|
|
14
|
+
if (entry.listeners.size > 0)
|
|
15
|
+
void refresh(entry, true);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const fn = Object.assign(call, { kind });
|
|
20
|
+
paths.set(fn, path);
|
|
21
|
+
return fn;
|
|
22
|
+
}
|
|
23
|
+
export function read(query, input) {
|
|
24
|
+
return entryFor(query, input).reading;
|
|
25
|
+
}
|
|
26
|
+
export function watch(query, input, listener) {
|
|
27
|
+
const entry = entryFor(query, input);
|
|
28
|
+
entry.listeners.add(listener);
|
|
29
|
+
if (entry.listeners.size === 1) {
|
|
30
|
+
const timer = setInterval(() => void refresh(entry), refreshEvery);
|
|
31
|
+
entry.stop = () => clearInterval(timer);
|
|
32
|
+
}
|
|
33
|
+
listener(entry.reading);
|
|
34
|
+
void refresh(entry);
|
|
35
|
+
return () => {
|
|
36
|
+
entry.listeners.delete(listener);
|
|
37
|
+
if (entry.listeners.size === 0)
|
|
38
|
+
entry.stop?.();
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function entryFor(query, input) {
|
|
42
|
+
const path = paths.get(query);
|
|
43
|
+
if (path === undefined)
|
|
44
|
+
throw new Error("Read only queries imported from server/");
|
|
45
|
+
const key = `${path}?${JSON.stringify(input ?? {})}`;
|
|
46
|
+
const found = entries.get(key);
|
|
47
|
+
if (found !== undefined)
|
|
48
|
+
return found;
|
|
49
|
+
const entry = {
|
|
50
|
+
path,
|
|
51
|
+
input,
|
|
52
|
+
reading: { data: undefined, at: null, refreshing: false, error: undefined },
|
|
53
|
+
listeners: new Set(),
|
|
54
|
+
running: false,
|
|
55
|
+
again: false,
|
|
56
|
+
};
|
|
57
|
+
entries.set(key, entry);
|
|
58
|
+
return entry;
|
|
59
|
+
}
|
|
60
|
+
async function refresh(entry, again = false) {
|
|
61
|
+
if (entry.running) {
|
|
62
|
+
entry.again ||= again;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
entry.running = true;
|
|
66
|
+
update(entry, { ...entry.reading, refreshing: true });
|
|
67
|
+
try {
|
|
68
|
+
const data = await request("GET", entry.path, entry.input);
|
|
69
|
+
update(entry, { data, at: new Date().toISOString(), refreshing: false, error: undefined });
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
update(entry, { ...entry.reading, refreshing: false, error: toolError(error) });
|
|
73
|
+
}
|
|
74
|
+
entry.running = false;
|
|
75
|
+
if (entry.again) {
|
|
76
|
+
entry.again = false;
|
|
77
|
+
await refresh(entry);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function update(entry, reading) {
|
|
81
|
+
entry.reading = reading;
|
|
82
|
+
for (const listener of entry.listeners)
|
|
83
|
+
listener(reading);
|
|
84
|
+
}
|
|
85
|
+
async function request(method, path, input) {
|
|
86
|
+
const body = JSON.stringify(input ?? {});
|
|
87
|
+
let response;
|
|
88
|
+
try {
|
|
89
|
+
response =
|
|
90
|
+
method === "GET"
|
|
91
|
+
? await fetch(`/api/${path}?input=${encodeURIComponent(body)}`)
|
|
92
|
+
: await fetch(`/api/${path}`, {
|
|
93
|
+
method,
|
|
94
|
+
headers: { "content-type": "application/json" },
|
|
95
|
+
body,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
throw toolError(error);
|
|
100
|
+
}
|
|
101
|
+
if (response.ok)
|
|
102
|
+
return (await response.json());
|
|
103
|
+
const failed = await response.json().catch(() => ({}));
|
|
104
|
+
const { error } = failed;
|
|
105
|
+
const message = error?.message ?? `${response.status} ${response.statusText}`;
|
|
106
|
+
throw new ToolError(error?.code ?? "call_failed", message, {
|
|
107
|
+
retryable: error?.retryable,
|
|
108
|
+
data: error?.data,
|
|
109
|
+
link: error?.link,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/** A failure that never reached the app, such as a dropped connection. */
|
|
113
|
+
function toolError(error) {
|
|
114
|
+
if (error instanceof ToolError)
|
|
115
|
+
return error;
|
|
116
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
117
|
+
return new ToolError("network", message, { retryable: true });
|
|
118
|
+
}
|
package/dist/stubs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const stubPrefix = "\0nexus-server:";
|
package/dist/stubs.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const stubPrefix = "\0nexus-server:";
|
package/dist/vite.d.ts
ADDED
package/dist/vite.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { parseSync } from "vite";
|
|
4
|
+
import { stubPrefix } from "./stubs.js";
|
|
5
|
+
export function nexus({ root: dir, entrypoints }) {
|
|
6
|
+
const root = realpathSync(dir);
|
|
7
|
+
const server = join(root, "server");
|
|
8
|
+
const module = (name) => name.slice(0, name.lastIndexOf("/"));
|
|
9
|
+
const exported = (name) => name.slice(name.lastIndexOf("/") + 1);
|
|
10
|
+
return {
|
|
11
|
+
name: "nexus-sdk",
|
|
12
|
+
resolveId: {
|
|
13
|
+
order: "pre",
|
|
14
|
+
async handler(source, importer, options) {
|
|
15
|
+
const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
|
|
16
|
+
if (!resolved?.id.startsWith(`${server}/`))
|
|
17
|
+
return resolved;
|
|
18
|
+
return stubPrefix + relative(server, resolved.id).replace(/\.[^./]+$/, "");
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
load(id) {
|
|
22
|
+
if (!id.startsWith(stubPrefix))
|
|
23
|
+
return null;
|
|
24
|
+
const file = id.slice(stubPrefix.length);
|
|
25
|
+
const stubs = entrypoints()
|
|
26
|
+
.filter(({ name }) => module(name) === file)
|
|
27
|
+
.map(({ name, kind }) => {
|
|
28
|
+
const call = `stub(${JSON.stringify(kind)}, ${JSON.stringify(name)})`;
|
|
29
|
+
return `export const ${exported(name)} = ${call};`;
|
|
30
|
+
});
|
|
31
|
+
return [`import { stub } from "@indent-com/nexus-sdk/client";`, ...stubs].join("\n");
|
|
32
|
+
},
|
|
33
|
+
transform: {
|
|
34
|
+
filter: { id: { include: /\.[cm]?[jt]sx?$/, exclude: /\/node_modules\// } },
|
|
35
|
+
async handler(code, id) {
|
|
36
|
+
const { staticImports } = parseSync(id, code, { lang: "js" }).module;
|
|
37
|
+
for (const { moduleRequest, entries } of staticImports) {
|
|
38
|
+
const resolved = await this.resolve(moduleRequest.value, id, { skipSelf: false });
|
|
39
|
+
if (!resolved?.id.startsWith(stubPrefix))
|
|
40
|
+
continue;
|
|
41
|
+
const file = resolved.id.slice(stubPrefix.length);
|
|
42
|
+
const names = new Set(entrypoints().map(({ name }) => name));
|
|
43
|
+
for (const { importName } of entries) {
|
|
44
|
+
const imported = importName.name ?? "default";
|
|
45
|
+
if (importName.kind === "NamespaceObject" || names.has(`${file}/${imported}`)) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
this.error(`${relative(root, id)} imports ${imported} from server/${file}, which is not ` +
|
|
49
|
+
"a query or mutation. The UI imports only queries, mutations and types.");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@indent-com/nexus-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Build Indent apps: server entrypoints, a database, and a React UI.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/indent-com/nexus-sdk.git",
|
|
9
|
+
"directory": "packages/sdk"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"bin": {
|
|
16
|
+
"nexus-sdk": "./dist/cli.js"
|
|
17
|
+
},
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./client": {
|
|
24
|
+
"types": "./dist/client.d.ts",
|
|
25
|
+
"default": "./dist/client.js"
|
|
26
|
+
},
|
|
27
|
+
"./react": {
|
|
28
|
+
"types": "./dist/react.d.ts",
|
|
29
|
+
"default": "./dist/react.js"
|
|
30
|
+
},
|
|
31
|
+
"./manifest": {
|
|
32
|
+
"types": "./dist/manifest.d.ts"
|
|
33
|
+
},
|
|
34
|
+
"./vite": {
|
|
35
|
+
"types": "./dist/vite.d.ts",
|
|
36
|
+
"default": "./dist/vite.js"
|
|
37
|
+
},
|
|
38
|
+
"./build": {
|
|
39
|
+
"types": "./dist/build.d.ts",
|
|
40
|
+
"default": "./dist/build.js"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && cp ../../sdk/index.d.ts ../../sdk/client.d.ts ../../sdk/react.d.ts ../../sdk/manifest.d.ts dist/",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
46
|
+
"test": "pnpm build && vitest run"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"esbuild": "^0.28.2",
|
|
50
|
+
"typescript": "^6.0.3"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"react": "^19.0.0",
|
|
54
|
+
"vite": "^8.0.0"
|
|
55
|
+
},
|
|
56
|
+
"peerDependenciesMeta": {
|
|
57
|
+
"react": {
|
|
58
|
+
"optional": true
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@happy-dom/global-registrator": "^20.14.5",
|
|
63
|
+
"@types/node": "^24.0.0",
|
|
64
|
+
"@types/react": "^19.3.0",
|
|
65
|
+
"@types/react-dom": "^19.3.0",
|
|
66
|
+
"react": "^19.3.0",
|
|
67
|
+
"react-dom": "^19.3.0",
|
|
68
|
+
"vite": "^8.3.3",
|
|
69
|
+
"vitest": "^5.0.3"
|
|
70
|
+
},
|
|
71
|
+
"prettier": {
|
|
72
|
+
"printWidth": 100
|
|
73
|
+
}
|
|
74
|
+
}
|
package/README.md
DELETED