@tokamaq/build 0.0.0-stage → 0.1.0-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +346 -2
- package/package.json +71 -4
- package/src/artifact-bundle.ts +86 -0
- package/src/auth-dependencies.ts +65 -0
- package/src/build.ts +73 -0
- package/src/client-surface.ts +179 -0
- package/src/compiler.ts +47 -0
- package/src/component-parts.ts +928 -0
- package/src/contributions.ts +534 -0
- package/src/css.ts +25 -0
- package/src/descriptor.ts +8 -0
- package/src/exports.ts +79 -0
- package/src/hook-targets.ts +46 -0
- package/src/part-props.ts +172 -0
- package/src/plugin-boundary.ts +48 -0
- package/src/ui-build-config.ts +48 -0
- package/src/vite.ts +284 -0
- package/src/window-state.ts +230 -0
- package/src/window-test-config.ts +48 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
export function warnMissingHookTargets(
|
|
5
|
+
root: string,
|
|
6
|
+
plugin: string,
|
|
7
|
+
targets: Set<string>,
|
|
8
|
+
catalog: string | undefined,
|
|
9
|
+
warn: (message: string) => void,
|
|
10
|
+
) {
|
|
11
|
+
// Match the complete key: plugin/module:fn, or plugin/module:fn#point for points.
|
|
12
|
+
const reported = new Set<string>();
|
|
13
|
+
for (const directory of new Set([
|
|
14
|
+
dirname(root),
|
|
15
|
+
process.env.TOKAMAQ_PLUGIN_DIR,
|
|
16
|
+
catalog && resolve(root, catalog),
|
|
17
|
+
])) {
|
|
18
|
+
if (!directory || !existsSync(directory)) continue;
|
|
19
|
+
const folders = readdirSync(directory, { withFileTypes: true })
|
|
20
|
+
.filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
|
|
21
|
+
.map((entry) => resolve(directory, entry.name));
|
|
22
|
+
for (const folder of [directory, ...folders]) {
|
|
23
|
+
const path = ["manifest.json", "dist/manifest.json"]
|
|
24
|
+
.map((file) => resolve(folder, file))
|
|
25
|
+
.find(existsSync);
|
|
26
|
+
if (!path) continue;
|
|
27
|
+
|
|
28
|
+
let manifest: { plugin?: { id?: string }; hookTargets?: unknown };
|
|
29
|
+
try {
|
|
30
|
+
manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
31
|
+
} catch {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const owner = manifest?.plugin?.id;
|
|
35
|
+
if (!owner || !Array.isArray(manifest.hookTargets)) continue;
|
|
36
|
+
for (const target of manifest.hookTargets) {
|
|
37
|
+
if (typeof target !== "string" || !target.startsWith(`${plugin}/`) || targets.has(target)) continue;
|
|
38
|
+
const message = `Plugin "${owner}" hooks ${target}, which no longer exists`;
|
|
39
|
+
if (reported.has(message)) continue;
|
|
40
|
+
|
|
41
|
+
reported.add(message);
|
|
42
|
+
warn(message);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { dirname, isAbsolute, join, relative } from "node:path";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import { importModule, inSource, unalias } from "./compiler.ts";
|
|
4
|
+
|
|
5
|
+
export function partProps(
|
|
6
|
+
entry: ts.SourceFile,
|
|
7
|
+
checker: ts.TypeChecker,
|
|
8
|
+
root: string,
|
|
9
|
+
sources: ts.SourceFile[],
|
|
10
|
+
) {
|
|
11
|
+
const typeNames = new Map<string, string>();
|
|
12
|
+
const modules = new Set<ts.Symbol>();
|
|
13
|
+
const modulePath = (file: string) => file.replace(/(?:\.d)?\.[cm]?tsx?$/, "");
|
|
14
|
+
for (const source of sources) {
|
|
15
|
+
for (const statement of source.statements) {
|
|
16
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
17
|
+
const specifier = statement.moduleSpecifier.text;
|
|
18
|
+
if (specifier.startsWith(".") || isAbsolute(specifier)) continue;
|
|
19
|
+
const imported = checker.getSymbolAtLocation(statement.moduleSpecifier);
|
|
20
|
+
if (!imported || modules.has(imported)) continue;
|
|
21
|
+
modules.add(imported);
|
|
22
|
+
for (const member of checker.getExportsOfModule(imported)) {
|
|
23
|
+
const original = unalias(checker, member);
|
|
24
|
+
for (const declaration of original.declarations ?? []) {
|
|
25
|
+
const file = declaration.getSourceFile().fileName;
|
|
26
|
+
typeNames.set(
|
|
27
|
+
`${modulePath(file)}:${original.name}`,
|
|
28
|
+
`import(${JSON.stringify(specifier)}).${member.name}`,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const privateTypes = new Map<ts.Declaration, string>();
|
|
36
|
+
const privateShapes = new Map<string, string>();
|
|
37
|
+
const localImport = (file: string) => {
|
|
38
|
+
const path = relative(join(dirname(entry.fileName), "_generated"), modulePath(file)).replaceAll(
|
|
39
|
+
"\\",
|
|
40
|
+
"/",
|
|
41
|
+
);
|
|
42
|
+
return `import(${JSON.stringify(path.startsWith(".") ? path : "./" + path)})`;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function exportedType(symbol: ts.Symbol, declaration: ts.Declaration) {
|
|
46
|
+
const file = declaration.getSourceFile();
|
|
47
|
+
const imported = typeNames.get(`${modulePath(file.fileName)}:${symbol.name}`);
|
|
48
|
+
if (imported) return imported;
|
|
49
|
+
const module = checker.getSymbolAtLocation(file);
|
|
50
|
+
const exported =
|
|
51
|
+
module && checker.getExportsOfModule(module).find((member) => unalias(checker, member) === symbol);
|
|
52
|
+
if (exported && inSource(root, file.fileName)) return `${localImport(file.fileName)}.${exported.name}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function annotation(node: ts.Node) {
|
|
56
|
+
const source = node.getSourceFile();
|
|
57
|
+
const offset = node.getStart(source);
|
|
58
|
+
let text = node.getText(source);
|
|
59
|
+
const edits: [number, number, string][] = [];
|
|
60
|
+
function visit(child: ts.Node) {
|
|
61
|
+
const name = ts.isTypeReferenceNode(child)
|
|
62
|
+
? child.typeName
|
|
63
|
+
: ts.isTypeQueryNode(child)
|
|
64
|
+
? child.exprName
|
|
65
|
+
: ts.isExpressionWithTypeArguments(child)
|
|
66
|
+
? child.expression
|
|
67
|
+
: undefined;
|
|
68
|
+
if (name) {
|
|
69
|
+
// A type query may select a property of an imported value (typeof api.foo).
|
|
70
|
+
let base = name;
|
|
71
|
+
while (ts.isQualifiedName(base) || ts.isPropertyAccessExpression(base))
|
|
72
|
+
base = ts.isQualifiedName(base) ? base.left : base.expression;
|
|
73
|
+
const alias = checker.getSymbolAtLocation(base);
|
|
74
|
+
const symbol = alias && unalias(checker, alias);
|
|
75
|
+
const declaration = symbol?.declarations?.[0];
|
|
76
|
+
if (symbol && declaration) {
|
|
77
|
+
const namespace = alias?.declarations?.find(ts.isNamespaceImport);
|
|
78
|
+
const specifier = importModule(namespace);
|
|
79
|
+
let reference =
|
|
80
|
+
specifier && !specifier.startsWith(".") && !isAbsolute(specifier)
|
|
81
|
+
? `import(${JSON.stringify(specifier)})`
|
|
82
|
+
: exportedType(symbol, declaration);
|
|
83
|
+
if (
|
|
84
|
+
!reference &&
|
|
85
|
+
(ts.isTypeAliasDeclaration(declaration) || ts.isInterfaceDeclaration(declaration)) &&
|
|
86
|
+
inSource(root, declaration.getSourceFile().fileName)
|
|
87
|
+
) {
|
|
88
|
+
reference = privateTypes.get(declaration);
|
|
89
|
+
if (!reference) {
|
|
90
|
+
reference = `Local${privateTypes.size + 1}`;
|
|
91
|
+
privateTypes.set(declaration, reference);
|
|
92
|
+
const params = declaration.typeParameters?.map(annotation).join(", ");
|
|
93
|
+
const definition = ts.isTypeAliasDeclaration(declaration)
|
|
94
|
+
? annotation(declaration.type)
|
|
95
|
+
: [
|
|
96
|
+
...(declaration.heritageClauses?.flatMap((clause) => clause.types.map(annotation)) ?? []),
|
|
97
|
+
`{ ${declaration.members.map((member) => annotation(member).replace(/[;,]$/, "")).join("; ")} }`,
|
|
98
|
+
].join(" & ");
|
|
99
|
+
privateShapes.set(
|
|
100
|
+
reference,
|
|
101
|
+
`type ${reference}${params ? `<${params}>` : ""} = ${definition};\n`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (reference) edits.push([base.getStart(source) - offset, base.end - offset, reference]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
ts.forEachChild(child, visit);
|
|
109
|
+
}
|
|
110
|
+
visit(node);
|
|
111
|
+
for (const [start, end, replacement] of edits.sort(([a], [b]) => b - a))
|
|
112
|
+
text = text.slice(0, start) + replacement + text.slice(end);
|
|
113
|
+
return text;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function propsType(parameter: ts.ParameterDeclaration) {
|
|
117
|
+
if (parameter.type) return annotation(parameter.type);
|
|
118
|
+
return typeShape(checker.getTypeAtLocation(parameter));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function componentValue(tag: ts.JsxTagNameExpression): string | undefined {
|
|
122
|
+
if (ts.isJsxNamespacedName(tag)) return;
|
|
123
|
+
let base = tag;
|
|
124
|
+
while (ts.isPropertyAccessExpression(base)) {
|
|
125
|
+
if (!ts.isIdentifier(base.expression) && !ts.isPropertyAccessExpression(base.expression)) return;
|
|
126
|
+
base = base.expression;
|
|
127
|
+
}
|
|
128
|
+
if (!ts.isIdentifier(base)) return;
|
|
129
|
+
const binding = checker.getSymbolAtLocation(base);
|
|
130
|
+
if (!binding) return;
|
|
131
|
+
const declaration = binding.declarations?.[0];
|
|
132
|
+
const module = importModule(declaration);
|
|
133
|
+
if (module && !module.startsWith(".") && !isAbsolute(module)) {
|
|
134
|
+
const from = `import(${JSON.stringify(module)})`;
|
|
135
|
+
const name =
|
|
136
|
+
declaration && ts.isImportSpecifier(declaration)
|
|
137
|
+
? (declaration.propertyName ?? declaration.name).text
|
|
138
|
+
: declaration && ts.isImportClause(declaration)
|
|
139
|
+
? "default"
|
|
140
|
+
: undefined;
|
|
141
|
+
return (name ? `${from}.${name}` : from) + tag.getText().slice(base.getText().length);
|
|
142
|
+
}
|
|
143
|
+
const original = unalias(checker, binding);
|
|
144
|
+
const value = original.valueDeclaration;
|
|
145
|
+
const reference = value && exportedType(original, value);
|
|
146
|
+
return reference && reference + tag.getText().slice(base.getText().length);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function typeShape(type: ts.Type) {
|
|
150
|
+
const flags =
|
|
151
|
+
ts.TypeFormatFlags.NoTruncation |
|
|
152
|
+
ts.TypeFormatFlags.InTypeAlias |
|
|
153
|
+
ts.TypeFormatFlags.UseFullyQualifiedType;
|
|
154
|
+
return checker
|
|
155
|
+
.typeToString(type, undefined, flags)
|
|
156
|
+
.replace(/import\("([^"]+)"\)\.([\w$]+)/g, (reference, path: string, name: string) => {
|
|
157
|
+
if (!isAbsolute(path)) return reference;
|
|
158
|
+
const exported = typeNames.get(`${path}:${name}`);
|
|
159
|
+
if (exported) return exported;
|
|
160
|
+
if (inSource(root, path)) return `${localImport(path)}.${name}`;
|
|
161
|
+
return "unknown";
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
propsType,
|
|
167
|
+
typeShape,
|
|
168
|
+
componentValue,
|
|
169
|
+
annotation,
|
|
170
|
+
privateDeclarations: () => [...privateShapes.values()].join(""),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { isInternalReferenceModule, serverDirectory } from "@tokamaq/sdk/internal/build";
|
|
2
|
+
import { assertPluginResolution, pluginReferenceSource } from "@tokamaq/sdk/internal/server-build";
|
|
3
|
+
import type { Plugin } from "vite";
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { isAbsolute, resolve, sep } from "node:path";
|
|
6
|
+
|
|
7
|
+
export function pluginBoundary(root: () => string): Plugin {
|
|
8
|
+
return {
|
|
9
|
+
name: "tokamaq-plugin-boundary",
|
|
10
|
+
enforce: "pre",
|
|
11
|
+
async resolveId(id, importer) {
|
|
12
|
+
if (id.startsWith("plugin:")) {
|
|
13
|
+
const client = /^plugin:([^/]+)\/client$/.exec(id);
|
|
14
|
+
if (client) return { id: `@plugins/${client[1]}/ui`, external: true };
|
|
15
|
+
return `\0tokamaq-reference:${id}`;
|
|
16
|
+
}
|
|
17
|
+
if (importer?.startsWith("\0")) return;
|
|
18
|
+
const resolved = await this.resolve(id, importer, { skipSelf: true });
|
|
19
|
+
if (resolved && !resolved.external && isAbsolute(resolved.id)) {
|
|
20
|
+
const target = resolved.id.split("?")[0]!;
|
|
21
|
+
assertPluginResolution(
|
|
22
|
+
root(),
|
|
23
|
+
importer?.split("?")[0] ?? root(),
|
|
24
|
+
id,
|
|
25
|
+
target,
|
|
26
|
+
!id.startsWith(".") && !isAbsolute(id) && /\/node_modules\//.test(resolved.id),
|
|
27
|
+
);
|
|
28
|
+
const directory = realpathSync(root());
|
|
29
|
+
const server = serverDirectory(directory);
|
|
30
|
+
const file = realpathSync(target);
|
|
31
|
+
if (
|
|
32
|
+
isInternalReferenceModule(file) ||
|
|
33
|
+
(server !== resolve(directory, "src") &&
|
|
34
|
+
file.startsWith(server + sep) &&
|
|
35
|
+
file !== resolve(server, "_generated/api.ts"))
|
|
36
|
+
)
|
|
37
|
+
throw new Error(
|
|
38
|
+
`Server code cannot be imported by the window: ${id}. Import the generated public api instead.`,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
return resolved;
|
|
42
|
+
},
|
|
43
|
+
load(id) {
|
|
44
|
+
if (id.startsWith("\0tokamaq-reference:"))
|
|
45
|
+
return pluginReferenceSource(root(), id.slice("\0tokamaq-reference:".length), { publicOnly: true });
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { windowStateModule } from "@tokamaq/sdk/internal/build";
|
|
2
|
+
import { normalizePath, type UserConfig } from "vite";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { dirname, resolve } from "node:path";
|
|
5
|
+
import { compileCss } from "./css.ts";
|
|
6
|
+
import { clientEntry } from "./descriptor.ts";
|
|
7
|
+
|
|
8
|
+
export const hostModule = (id: string) =>
|
|
9
|
+
id === windowStateModule ||
|
|
10
|
+
/^(solid-js(?:$|\/)|@solidjs\/web(?:$|\/)|@tokamaq\/(?:sdk(?:$|\/)|ui(?:$|\/)|runtime\/router$)|@ui-sdk\/(?:solid|core)(?:$|\/)|@plugins\/)/.test(
|
|
11
|
+
id,
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
export function uiBuildConfig(root: string): UserConfig {
|
|
15
|
+
return {
|
|
16
|
+
root,
|
|
17
|
+
build: {
|
|
18
|
+
target: "es2022",
|
|
19
|
+
emptyOutDir: false,
|
|
20
|
+
outDir: "dist",
|
|
21
|
+
sourcemap: true,
|
|
22
|
+
lib: {
|
|
23
|
+
entry: clientEntry(root),
|
|
24
|
+
formats: ["es"],
|
|
25
|
+
fileName: () => "ui.js",
|
|
26
|
+
cssFileName: "styles",
|
|
27
|
+
},
|
|
28
|
+
rollupOptions: { external: hostModule, output: { codeSplitting: false } },
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function clientAssets(root: () => string): import("vite").Plugin {
|
|
34
|
+
return {
|
|
35
|
+
name: "tokamaq-client-entry",
|
|
36
|
+
enforce: "post",
|
|
37
|
+
async load(id) {
|
|
38
|
+
const css = resolve(dirname(clientEntry(root())), "styles.css");
|
|
39
|
+
if (normalizePath(id) === normalizePath(css)) return compileCss(css);
|
|
40
|
+
},
|
|
41
|
+
transform(code, id) {
|
|
42
|
+
const entry = clientEntry(root());
|
|
43
|
+
const css = resolve(dirname(entry), "styles.css");
|
|
44
|
+
if (normalizePath(id) === normalizePath(entry) && existsSync(css))
|
|
45
|
+
return { code: `${code}\nimport ${JSON.stringify(normalizePath(css))};`, map: null };
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
package/src/vite.ts
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { serverDirectory } from "@tokamaq/sdk/internal/build";
|
|
2
|
+
import {
|
|
3
|
+
checkPluginImports,
|
|
4
|
+
contractDeclarations,
|
|
5
|
+
contractEntry,
|
|
6
|
+
declaresAccessTo,
|
|
7
|
+
functionPlacement,
|
|
8
|
+
httpActionEntry,
|
|
9
|
+
lanes,
|
|
10
|
+
moduleName,
|
|
11
|
+
runnerFunction,
|
|
12
|
+
runnerProvider,
|
|
13
|
+
} from "@tokamaq/sdk/internal/server-build";
|
|
14
|
+
import { normalizePath, type InlineConfig, type PluginOption } from "vite";
|
|
15
|
+
import { definePlugin, type PluginDefinition } from "@tokamaq/sdk";
|
|
16
|
+
import { dirname, relative, resolve, sep } from "node:path";
|
|
17
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
18
|
+
import { readFile, rm } from "node:fs/promises";
|
|
19
|
+
import { spawnSync } from "node:child_process";
|
|
20
|
+
import { createRequire } from "node:module";
|
|
21
|
+
import { pluginBoundary } from "./plugin-boundary.ts";
|
|
22
|
+
import { uiContributions } from "./contributions.ts";
|
|
23
|
+
import { artifactBundle, stripSourcesContent } from "./artifact-bundle.ts";
|
|
24
|
+
import solid from "@solidjs/vite-plugin";
|
|
25
|
+
import { clientSurface } from "./client-surface.ts";
|
|
26
|
+
import { uiBuildConfig, clientAssets } from "./ui-build-config.ts";
|
|
27
|
+
import { exportedFunctions } from "./exports.ts";
|
|
28
|
+
import { readDescriptor, clientEntry } from "./descriptor.ts";
|
|
29
|
+
import { warnMissingHookTargets } from "./hook-targets.ts";
|
|
30
|
+
import { signInDependency } from "./auth-dependencies.ts";
|
|
31
|
+
|
|
32
|
+
export const PLUGIN_UI_BUILD_ENABLED = true;
|
|
33
|
+
|
|
34
|
+
export function tokamaq(
|
|
35
|
+
options: { backend?: false; ui?: false; plugin?: PluginDefinition; pluginCatalog?: string } = {},
|
|
36
|
+
): PluginOption {
|
|
37
|
+
let root: string;
|
|
38
|
+
let plugin: Readonly<PluginDefinition>;
|
|
39
|
+
let placement: ReturnType<typeof functionPlacement>;
|
|
40
|
+
let ui: ReturnType<typeof uiContributions> | undefined;
|
|
41
|
+
let hasLocal = false;
|
|
42
|
+
let stripClientSources = false;
|
|
43
|
+
return [
|
|
44
|
+
pluginBoundary(() => root),
|
|
45
|
+
{
|
|
46
|
+
name: "tokamaq-application",
|
|
47
|
+
config(config, environment) {
|
|
48
|
+
if (environment.command !== "build") {
|
|
49
|
+
throw new Error("Plugin artifacts require a build");
|
|
50
|
+
}
|
|
51
|
+
// Explicit --config must work from the workspace root as well as Moon's
|
|
52
|
+
// app cwd. For implicit discovery Vite already searches the project cwd.
|
|
53
|
+
const configFile = (config as InlineConfig).configFile;
|
|
54
|
+
root =
|
|
55
|
+
typeof configFile === "string"
|
|
56
|
+
? dirname(resolve(configFile))
|
|
57
|
+
: resolve(config.root ?? process.cwd());
|
|
58
|
+
root = realpathSync(root);
|
|
59
|
+
checkPluginImports(root, (options.plugin ?? readDescriptor(root))?.depends ?? {});
|
|
60
|
+
placement = functionPlacement(root);
|
|
61
|
+
stripClientSources = false;
|
|
62
|
+
const server = serverDirectory(root);
|
|
63
|
+
// A flat src/ may contain only window code. Enable function bundling
|
|
64
|
+
// there only when placement finds definitions or a schema needs a server entry.
|
|
65
|
+
if (
|
|
66
|
+
existsSync(resolve(root, "plugin.ts")) &&
|
|
67
|
+
(!existsSync(server) ||
|
|
68
|
+
(server === resolve(root, "src") &&
|
|
69
|
+
!placement?.modules.size &&
|
|
70
|
+
!placement?.providers.length &&
|
|
71
|
+
!contractDeclarations(contractEntry(root)).length &&
|
|
72
|
+
!existsSync(resolve(server, "schema.ts"))))
|
|
73
|
+
)
|
|
74
|
+
options.backend = false;
|
|
75
|
+
if (!existsSync(clientEntry(root))) options.ui = false;
|
|
76
|
+
if (options.ui !== false) return uiBuildConfig(root);
|
|
77
|
+
if (options.backend === false) throw new Error("Plugin has no enabled targets");
|
|
78
|
+
return {
|
|
79
|
+
root,
|
|
80
|
+
build: {
|
|
81
|
+
target: "es2022",
|
|
82
|
+
emptyOutDir: false,
|
|
83
|
+
outDir: "dist",
|
|
84
|
+
lib: {
|
|
85
|
+
entry: resolve(root, ".tokamaq-backend-entry.js"),
|
|
86
|
+
formats: ["es"],
|
|
87
|
+
fileName: () => ".tokamaq-backend-entry.js",
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
resolveId(id) {
|
|
93
|
+
if (normalizePath(id) === normalizePath(resolve(root, ".tokamaq-backend-entry.js")))
|
|
94
|
+
return "\0tokamaq-backend-entry";
|
|
95
|
+
},
|
|
96
|
+
load(id) {
|
|
97
|
+
if (id === "\0tokamaq-backend-entry") return "export {};";
|
|
98
|
+
},
|
|
99
|
+
async buildStart() {
|
|
100
|
+
hasLocal =
|
|
101
|
+
!!placement &&
|
|
102
|
+
([...placement.modules.values()].some((exports) =>
|
|
103
|
+
[...exports.values()].some((definition) => runnerFunction(definition.kind)),
|
|
104
|
+
) ||
|
|
105
|
+
placement.providers.some(runnerProvider));
|
|
106
|
+
const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
|
|
107
|
+
plugin = definePlugin(
|
|
108
|
+
options.plugin ??
|
|
109
|
+
readDescriptor(root) ?? {
|
|
110
|
+
id: String(manifest.name).replace(/^@/, "").replaceAll("/", "."),
|
|
111
|
+
version: manifest.version ?? "0.1.0",
|
|
112
|
+
},
|
|
113
|
+
);
|
|
114
|
+
if (options.ui !== false) ui = uiContributions(root, plugin.id, (message) => this.warn(message));
|
|
115
|
+
const signIn = signInDependency(root, plugin, options.pluginCatalog);
|
|
116
|
+
if (signIn)
|
|
117
|
+
throw new Error(`Plugin ${plugin.id} lists ${signIn} as a dependency; depend on auth instead`);
|
|
118
|
+
const server = serverDirectory(root);
|
|
119
|
+
if (existsSync(resolve(root, "plugin.ts"))) {
|
|
120
|
+
plugin = definePlugin({
|
|
121
|
+
...plugin,
|
|
122
|
+
...(existsSync(resolve(server, "api.ts"))
|
|
123
|
+
? { exports: "./" + relative(root, resolve(server, "api.ts")).split(sep).join("/") }
|
|
124
|
+
: {}),
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const entries: Record<string, unknown> = {};
|
|
128
|
+
let contracts: object = {};
|
|
129
|
+
for (const provider of placement?.providers ?? []) {
|
|
130
|
+
const owner = provider.owner;
|
|
131
|
+
if (owner && !declaresAccessTo(plugin, owner)) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`Provider for ${owner}/${provider.name}: declare ${owner} in depends or optional`,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (options.backend === false && hasLocal)
|
|
138
|
+
throw new Error("Caller actions require the function build");
|
|
139
|
+
if (options.backend === false && plugin.exports !== undefined)
|
|
140
|
+
throw new Error("Plugin exports require a backend");
|
|
141
|
+
if (options.backend !== false) {
|
|
142
|
+
// Reuse the builder's Bun from any cwd. The checkout pins Bun for Node's Vite CLI.
|
|
143
|
+
const transactions = resolve(server, "dist/transactions.js");
|
|
144
|
+
await rm(transactions, { force: true });
|
|
145
|
+
await rm(`${transactions}.map`, { force: true });
|
|
146
|
+
const usingBun = !!process.versions.bun;
|
|
147
|
+
const bundled = spawnSync(
|
|
148
|
+
usingBun ? process.execPath : "proto",
|
|
149
|
+
[
|
|
150
|
+
...(usingBun ? [] : ["run", "bun", "--"]),
|
|
151
|
+
createRequire(import.meta.url).resolve("@tokamaq/sdk/internal/bundle"),
|
|
152
|
+
server,
|
|
153
|
+
"--plugin",
|
|
154
|
+
plugin.id,
|
|
155
|
+
...(options.plugin ? ["--depends", JSON.stringify(plugin.depends ?? {})] : []),
|
|
156
|
+
],
|
|
157
|
+
{ stdio: "inherit", ...(usingBun ? {} : { cwd: import.meta.dirname }) },
|
|
158
|
+
);
|
|
159
|
+
if (bundled.error) throw bundled.error;
|
|
160
|
+
if (bundled.status !== 0) throw new Error("SDK backend bundling failed");
|
|
161
|
+
contracts = JSON.parse(await readFile(resolve(server, "dist/contracts.json"), "utf8"));
|
|
162
|
+
// The bundle's describe() carries the schema/index registry evaluated
|
|
163
|
+
// in QuickJS. Keep that source authoritative instead of importing user
|
|
164
|
+
// schema modules into the build host or duplicating them in manifests.
|
|
165
|
+
const bundle = resolve(server, "dist/bundle.js");
|
|
166
|
+
const source = await readFile(bundle, "utf8");
|
|
167
|
+
const map = JSON.parse(await readFile(`${bundle}.map`, "utf8"));
|
|
168
|
+
if (hasLocal) stripSourcesContent(map);
|
|
169
|
+
// SDK maps are relative to the server half’s dist/. Rebase source names when the
|
|
170
|
+
// unchanged bundle is packaged into app/dist; retain original contents.
|
|
171
|
+
map.sources = map.sources.map((source: string) =>
|
|
172
|
+
relative(resolve(root, "dist"), resolve(dirname(bundle), source))
|
|
173
|
+
.split(sep)
|
|
174
|
+
.join("/"),
|
|
175
|
+
);
|
|
176
|
+
this.emitFile({ type: "asset", fileName: "bundle.js", source });
|
|
177
|
+
this.emitFile({ type: "asset", fileName: "bundle.js.map", source: JSON.stringify(map) });
|
|
178
|
+
// References are source-aware, matching the existing SDK contract.
|
|
179
|
+
// Rebase only its generated type-import specifiers, not user code.
|
|
180
|
+
const api = (await readFile(resolve(server, "_generated/api.ts"), "utf8")).replaceAll(
|
|
181
|
+
'import("../',
|
|
182
|
+
`import("../${relative(root, server).split(sep).join("/")}/`,
|
|
183
|
+
);
|
|
184
|
+
this.emitFile({ type: "asset", fileName: "api.ts", source: api });
|
|
185
|
+
entries.server = { code: "bundle.js", map: "bundle.js.map", api: "api.ts" };
|
|
186
|
+
if (existsSync(transactions)) {
|
|
187
|
+
for (const name of ["transactions.js", "transactions.js.map"]) {
|
|
188
|
+
let source = await readFile(resolve(server, "dist", name), "utf8");
|
|
189
|
+
if (hasLocal && name.endsWith(".map")) {
|
|
190
|
+
const map = JSON.parse(source);
|
|
191
|
+
stripSourcesContent(map);
|
|
192
|
+
source = JSON.stringify(map);
|
|
193
|
+
}
|
|
194
|
+
this.emitFile({ type: "asset", fileName: name, source });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const http = placement && httpActionEntry(placement, server, server !== resolve(root, "src"));
|
|
198
|
+
if (http) {
|
|
199
|
+
const code = "http-actions.js";
|
|
200
|
+
const map = code + ".map";
|
|
201
|
+
for (const name of [code, map])
|
|
202
|
+
this.emitFile({
|
|
203
|
+
type: "asset",
|
|
204
|
+
fileName: name,
|
|
205
|
+
source: await readFile(resolve(server, "dist", name), "utf8"),
|
|
206
|
+
});
|
|
207
|
+
entries.http = { code, map, paths: http.paths };
|
|
208
|
+
}
|
|
209
|
+
if (hasLocal) {
|
|
210
|
+
for (const name of ["local.js", "local.js.map", "local-entry.js"]) {
|
|
211
|
+
let source = await readFile(resolve(server, "dist", name), "utf8");
|
|
212
|
+
if (name.endsWith(".map")) {
|
|
213
|
+
// Original mixed modules can contain handlers from the other lanes.
|
|
214
|
+
const map = JSON.parse(source);
|
|
215
|
+
stripSourcesContent(map);
|
|
216
|
+
source = JSON.stringify(map);
|
|
217
|
+
}
|
|
218
|
+
this.emitFile({ type: "asset", fileName: name, source });
|
|
219
|
+
}
|
|
220
|
+
entries.local = { entry: "local-entry.js", code: "local.js", map: "local.js.map" };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const functions = exportedFunctions(root, plugin.exports);
|
|
224
|
+
const hookTargets = new Set<string>();
|
|
225
|
+
const hookable = new Set<string>();
|
|
226
|
+
for (const [path, definitions] of placement?.modules ?? []) {
|
|
227
|
+
const module = moduleName(server, path, server === resolve(root, "src/server"));
|
|
228
|
+
for (const [name, definition] of definitions) {
|
|
229
|
+
if (definition.target) hookTargets.add(definition.target);
|
|
230
|
+
if (["query", "mutation", "action"].includes(definition.kind)) {
|
|
231
|
+
const key = `${plugin.id}/${module}:${name}`;
|
|
232
|
+
hookable.add(key);
|
|
233
|
+
for (const point of definition.points?.keys() ?? []) hookable.add(`${key}#${point}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
warnMissingHookTargets(root, plugin.id, hookable, options.pluginCatalog, (message) =>
|
|
238
|
+
this.warn(message),
|
|
239
|
+
);
|
|
240
|
+
this.emitFile({
|
|
241
|
+
type: "asset",
|
|
242
|
+
fileName: "manifest.json",
|
|
243
|
+
source:
|
|
244
|
+
JSON.stringify(
|
|
245
|
+
{
|
|
246
|
+
formatVersion: 1,
|
|
247
|
+
plugin,
|
|
248
|
+
entries,
|
|
249
|
+
publicFunctions: functions.publicFunctions,
|
|
250
|
+
...(functions.pluginFunctions.length ? { pluginFunctions: functions.pluginFunctions } : {}),
|
|
251
|
+
...(hookTargets.size ? { hookTargets: [...hookTargets].sort() } : {}),
|
|
252
|
+
...contracts,
|
|
253
|
+
},
|
|
254
|
+
null,
|
|
255
|
+
2,
|
|
256
|
+
) + "\n",
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
generateBundle: {
|
|
260
|
+
order: "post",
|
|
261
|
+
handler(_options, bundle, isWrite) {
|
|
262
|
+
return artifactBundle(ui?.contributes ?? {}, plugin, { ...options, stripClientSources }).call(
|
|
263
|
+
this,
|
|
264
|
+
_options,
|
|
265
|
+
bundle,
|
|
266
|
+
isWrite,
|
|
267
|
+
);
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
clientAssets(() => root),
|
|
272
|
+
clientSurface(
|
|
273
|
+
() => root,
|
|
274
|
+
() => plugin.id,
|
|
275
|
+
(id) => {
|
|
276
|
+
const edits = placement?.edits(id, lanes.window) ?? [];
|
|
277
|
+
if (edits.length) stripClientSources = true;
|
|
278
|
+
return [...edits, ...(ui?.edits.get(id) ?? [])];
|
|
279
|
+
},
|
|
280
|
+
options.pluginCatalog,
|
|
281
|
+
),
|
|
282
|
+
solid(),
|
|
283
|
+
];
|
|
284
|
+
}
|