@tokamaq/sdk 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 +1403 -2
- package/build-internals.ts +25 -0
- package/caller/agent-launch.ts +60 -0
- package/client.tsx +498 -0
- package/component-actions.ts +327 -0
- package/component-alerts.ts +136 -0
- package/component-attributes.ts +340 -0
- package/component-parts.tsx +1177 -0
- package/core-contracts/auth.ts +40 -0
- package/package.json +98 -4
- package/quit.ts +58 -0
- package/regions.tsx +94 -0
- package/screen-search.ts +211 -0
- package/send-file.ts +175 -0
- package/server-build-internals.ts +11 -0
- package/solid.ts +132 -0
- package/src/agent-command.ts +48 -0
- package/src/agent-info-cache.ts +34 -0
- package/src/agent-reports.ts +140 -0
- package/src/agent-turn.ts +289 -0
- package/src/api.ts +174 -0
- package/src/auth.ts +39 -0
- package/src/call-error.ts +37 -0
- package/src/caller-storage.ts +32 -0
- package/src/client.ts +163 -0
- package/src/database.ts +322 -0
- package/src/functions.ts +726 -0
- package/src/hooks.ts +141 -0
- package/src/host.ts +211 -0
- package/src/http-action.ts +55 -0
- package/src/index.ts +126 -0
- package/src/internal/contracts.ts +260 -0
- package/src/internal/machine-scope.ts +21 -0
- package/src/local.ts +22 -0
- package/src/plugin.ts +162 -0
- package/src/points.ts +79 -0
- package/src/protocol.ts +64 -0
- package/src/schema.ts +136 -0
- package/src/storage.ts +193 -0
- package/src/thread-context.ts +42 -0
- package/src/transport.ts +421 -0
- package/src/triggers.ts +87 -0
- package/src/unstable.ts +66 -0
- package/src/validators.ts +248 -0
- package/src/values.ts +98 -0
- package/src/visibility.ts +8 -0
- package/src/websocket-transport.ts +91 -0
- package/src/window-state-protocol.ts +7 -0
- package/src/within.ts +24 -0
- package/src/worker-limits.ts +5 -0
- package/tools/bundle.mjs +490 -0
- package/tools/client-entry.mjs +10 -0
- package/tools/contracts.mjs +254 -0
- package/tools/http-actions.mjs +42 -0
- package/tools/placement.mjs +535 -0
- package/tools/plugin-boundary.mjs +592 -0
- package/tools/plugin-compiler.mjs +125 -0
- package/tools/plugin-descriptor.ts +75 -0
- package/tools/points.mjs +340 -0
- package/tools/result-validator.mjs +83 -0
- package/tools/server-builtins.mjs +82 -0
- package/tools/server-files.mjs +34 -0
- package/tools/table-references.mjs +98 -0
- package/tools/worker.mjs +110 -0
- package/tsconfig.plugin-server.json +12 -0
- package/tsconfig.plugin-window.json +15 -0
- package/view.ts +27 -0
- package/web.d.ts +6 -0
- package/window-state-host.ts +228 -0
- package/window-state.ts +43 -0
package/tools/bundle.mjs
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import { Visibility } from "../src/visibility.ts";
|
|
2
|
+
// Moon's feature build implementation, intentionally outside the portable SDK.
|
|
3
|
+
// Bun's parser scans module exports without executing feature code on the build
|
|
4
|
+
// machine. Namespace registration at runtime and mapped TS types use the same
|
|
5
|
+
// definition brand, so aliases/reexports/wrapped builders need no AST heuristics.
|
|
6
|
+
import { existsSync } from "node:fs";
|
|
7
|
+
import { mkdir, mkdtemp, realpath, rm, stat } from "node:fs/promises";
|
|
8
|
+
import { basename, join, resolve, relative, dirname, sep } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
|
|
11
|
+
import { httpActionEntry } from "./http-actions.mjs";
|
|
12
|
+
import { buildLocalBundle, transactionSources } from "./worker.mjs";
|
|
13
|
+
import { bunPluginBoundary, checkPluginImports, featurePluginRoot } from "./plugin-boundary.mjs";
|
|
14
|
+
import ts from "typescript";
|
|
15
|
+
import {
|
|
16
|
+
definitionInfo,
|
|
17
|
+
pluginCompilerOptions,
|
|
18
|
+
runtimeExportNames,
|
|
19
|
+
serverConfigPath,
|
|
20
|
+
} from "./plugin-compiler.mjs";
|
|
21
|
+
|
|
22
|
+
import { isServerRoot, isServerModule } from "./server-files.mjs";
|
|
23
|
+
import {
|
|
24
|
+
functionPlacement,
|
|
25
|
+
lanes,
|
|
26
|
+
placedModules,
|
|
27
|
+
placementTransform,
|
|
28
|
+
registrySource,
|
|
29
|
+
runnerFunction,
|
|
30
|
+
runnerActionFiles,
|
|
31
|
+
runnerProvider,
|
|
32
|
+
} from "./placement.mjs";
|
|
33
|
+
import { contractEntry, contractManifest } from "./contracts.mjs";
|
|
34
|
+
import { serverBuiltins } from "./server-builtins.mjs";
|
|
35
|
+
import { pointReferenceTypes } from "./points.mjs";
|
|
36
|
+
|
|
37
|
+
const sdkRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
38
|
+
const quote = JSON.stringify;
|
|
39
|
+
const useLocal = 'Move access to processes and files into an action with on: "caller".';
|
|
40
|
+
const useServer = "Call a server function for database access.";
|
|
41
|
+
const header = "// Generated by the sdk:bundle moon task. Do not edit.\n";
|
|
42
|
+
|
|
43
|
+
function apiType(modules, typeAt) {
|
|
44
|
+
const tree = new Map();
|
|
45
|
+
for (const [moduleIndex, module] of modules.entries()) {
|
|
46
|
+
let node = tree;
|
|
47
|
+
const parts = module.split("/");
|
|
48
|
+
for (const [index, part] of parts.entries()) {
|
|
49
|
+
const last = index === parts.length - 1;
|
|
50
|
+
const existing = node.get(part);
|
|
51
|
+
if ((last && existing !== undefined) || typeof existing === "string") {
|
|
52
|
+
throw new Error(`API module path collision at ${module}; rename the file or folder`);
|
|
53
|
+
}
|
|
54
|
+
if (last) node.set(part, typeAt(moduleIndex));
|
|
55
|
+
else {
|
|
56
|
+
if (existing === undefined) node.set(part, new Map());
|
|
57
|
+
node = node.get(part);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function render(node, depth = 0) {
|
|
63
|
+
if (!node.size) return "{}";
|
|
64
|
+
const indent = " ".repeat(depth + 1);
|
|
65
|
+
const fields = [...node].map(([key, value]) => {
|
|
66
|
+
const type =
|
|
67
|
+
typeof value === "string" ? value.replaceAll("\n", "\n" + indent) : render(value, depth + 1);
|
|
68
|
+
return `${indent}readonly ${quote(key)}: ${type};`;
|
|
69
|
+
});
|
|
70
|
+
return `{\n${fields.join("\n")}\n${" ".repeat(depth)}}`;
|
|
71
|
+
}
|
|
72
|
+
return render(tree);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function discoverReferences(root, pluginRoot, sources, virtual) {
|
|
76
|
+
const config = ts.getParsedCommandLineOfConfigFile(
|
|
77
|
+
serverConfigPath(root, pluginRoot),
|
|
78
|
+
{},
|
|
79
|
+
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic() {} },
|
|
80
|
+
);
|
|
81
|
+
const options = pluginCompilerOptions(pluginRoot, config?.options ?? {});
|
|
82
|
+
const host = ts.createCompilerHost(options);
|
|
83
|
+
// Discover definitions from source types without loading plugin code or
|
|
84
|
+
// depending on the last build's references. The virtual types bootstrap
|
|
85
|
+
// plugins that already refer to their generated API from a handler.
|
|
86
|
+
const { getSourceFile, fileExists } = host;
|
|
87
|
+
host.fileExists = (path) => virtual.has(path) || fileExists(path);
|
|
88
|
+
host.getSourceFile = (path, language, ...rest) =>
|
|
89
|
+
virtual.has(path)
|
|
90
|
+
? ts.createSourceFile(path, virtual.get(path), language, true)
|
|
91
|
+
: getSourceFile(path, language, ...rest);
|
|
92
|
+
const program = ts.createProgram(sources, options, host);
|
|
93
|
+
const checker = program.getTypeChecker();
|
|
94
|
+
return sources.map((path) => {
|
|
95
|
+
const source = program.getSourceFile(path);
|
|
96
|
+
const symbol = checker.getSymbolAtLocation(source);
|
|
97
|
+
if (!symbol) return [];
|
|
98
|
+
const runtime = runtimeExportNames(checker, symbol);
|
|
99
|
+
return checker
|
|
100
|
+
.getExportsOfModule(symbol)
|
|
101
|
+
.filter((entry) => runtime.has(entry.name))
|
|
102
|
+
.flatMap((entry) => {
|
|
103
|
+
const info = definitionInfo(checker, entry, source);
|
|
104
|
+
if (!info || info.kind === "httpAction") return [];
|
|
105
|
+
if (info.visibility === undefined)
|
|
106
|
+
throw new Error(
|
|
107
|
+
`Cannot determine visibility of ${path}:${entry.name}; preserve the function builder's inferred type`,
|
|
108
|
+
);
|
|
109
|
+
return [{ name: entry.name, visibility: info.visibility }];
|
|
110
|
+
})
|
|
111
|
+
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function generateReferences(root, pluginRoot, files, modules, namespace, placement) {
|
|
116
|
+
const generated = join(root, "_generated");
|
|
117
|
+
const variants = [
|
|
118
|
+
{ name: "api", mapping: "ApiFromModule", visibility: Visibility.Public },
|
|
119
|
+
{ name: "internal", mapping: "InternalFromModule", visibility: Visibility.Internal },
|
|
120
|
+
{ name: "plugin", mapping: "PluginFunctionsFromModule", visibility: Visibility.PluginOnly },
|
|
121
|
+
];
|
|
122
|
+
const pathFor = (variant) => join(generated, variant.name + ".ts");
|
|
123
|
+
function render(name, mapping, type, names, kinds, points, aliases = []) {
|
|
124
|
+
const list = names?.length ? `[\n${names.map((name) => " " + quote(name) + ",").join("\n")}\n]` : "[]";
|
|
125
|
+
return (
|
|
126
|
+
header +
|
|
127
|
+
`import { createApi${mapping ? ", type " + mapping : ""} } from "@tokamaq/sdk";\n` +
|
|
128
|
+
aliases.join("") +
|
|
129
|
+
`type References = ${type};\n` +
|
|
130
|
+
`export const ${name}: References = createApi(${quote(namespace) ?? "undefined"}${names ? ", " + list : ""}${points && Object.keys(points).length ? `, ${quote(kinds)}, ${quote(points)}` : ""});\n`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
const importType = (index) => `typeof import(${quote("../" + files[index].replace(/\.tsx?$/, ""))})`;
|
|
134
|
+
const virtual = new Map(
|
|
135
|
+
variants.map((variant) => [
|
|
136
|
+
pathFor(variant),
|
|
137
|
+
render(
|
|
138
|
+
variant.name,
|
|
139
|
+
variant.mapping,
|
|
140
|
+
apiType(modules, (i) => `${variant.mapping}<${importType(i)}>`),
|
|
141
|
+
),
|
|
142
|
+
]),
|
|
143
|
+
);
|
|
144
|
+
const exports = discoverReferences(
|
|
145
|
+
root,
|
|
146
|
+
pluginRoot,
|
|
147
|
+
files.map((file) => join(root, file)),
|
|
148
|
+
virtual,
|
|
149
|
+
);
|
|
150
|
+
await mkdir(generated, { recursive: true });
|
|
151
|
+
for (const variant of variants) {
|
|
152
|
+
const groups = exports.map((entries) =>
|
|
153
|
+
entries.filter((entry) => entry.visibility === variant.visibility),
|
|
154
|
+
);
|
|
155
|
+
const included = modules.flatMap((_, i) => (groups[i].length ? [i] : []));
|
|
156
|
+
const names = groups.flatMap((group, i) => group.map((entry) => `${modules[i]}:${entry.name}`));
|
|
157
|
+
const points = {};
|
|
158
|
+
const kinds = {};
|
|
159
|
+
const aliases = [];
|
|
160
|
+
const type = apiType(
|
|
161
|
+
included.map((i) => modules[i]),
|
|
162
|
+
(index) => {
|
|
163
|
+
const i = included[index];
|
|
164
|
+
return (
|
|
165
|
+
"{\n" +
|
|
166
|
+
groups[i]
|
|
167
|
+
.map(({ name }) => {
|
|
168
|
+
const key = `${modules[i]}:${name}`;
|
|
169
|
+
const definition = placement?.modules.get(join(root, files[i]))?.get(name);
|
|
170
|
+
if (definition?.points?.size) {
|
|
171
|
+
points[key] = [...definition.points.keys()];
|
|
172
|
+
kinds[key] = definition.kind;
|
|
173
|
+
}
|
|
174
|
+
const named = pointReferenceTypes(
|
|
175
|
+
definition?.points,
|
|
176
|
+
definition?.kind,
|
|
177
|
+
namespace,
|
|
178
|
+
namespace ? `${namespace}/${key}` : key,
|
|
179
|
+
aliases,
|
|
180
|
+
);
|
|
181
|
+
return ` readonly ${quote(name)}: ReferenceFromDefinition<${importType(i)}[${quote(name)}]>${named};`;
|
|
182
|
+
})
|
|
183
|
+
.join("\n") +
|
|
184
|
+
"\n}"
|
|
185
|
+
);
|
|
186
|
+
},
|
|
187
|
+
);
|
|
188
|
+
const output = render(
|
|
189
|
+
variant.name,
|
|
190
|
+
names.length ? "ReferenceFromDefinition" : null,
|
|
191
|
+
type,
|
|
192
|
+
names,
|
|
193
|
+
kinds,
|
|
194
|
+
points,
|
|
195
|
+
aliases,
|
|
196
|
+
);
|
|
197
|
+
const destination = Bun.file(pathFor(variant));
|
|
198
|
+
const existed = await destination.exists();
|
|
199
|
+
if (variant.visibility === Visibility.PluginOnly && !names.length && !existed) continue;
|
|
200
|
+
if (!existed || (await destination.text()) !== output) await Bun.write(destination, output);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Called only by moon; there is no installable binary or SDK CLI. */
|
|
205
|
+
export async function bundleFeature(folder, namespace, splitActions = namespace !== undefined, depends) {
|
|
206
|
+
const root = await realpath(folder);
|
|
207
|
+
if (!(await stat(root)).isDirectory()) throw new Error(`Feature root is not a directory: ${root}`);
|
|
208
|
+
// A flat plugin has its server entry at src/, even without a plugin.ts descriptor.
|
|
209
|
+
const pluginRoot =
|
|
210
|
+
namespace !== undefined && basename(root) === "src" ? dirname(root) : featurePluginRoot(root);
|
|
211
|
+
checkPluginImports(pluginRoot, depends);
|
|
212
|
+
// An explicit empty plugin server part is valid; a missing root still fails.
|
|
213
|
+
const organized = isServerRoot(root);
|
|
214
|
+
const flat = root === join(pluginRoot, "src");
|
|
215
|
+
const pluginSource = organized || flat;
|
|
216
|
+
const placement = pluginSource ? functionPlacement(pluginRoot, undefined, namespace) : undefined;
|
|
217
|
+
const providers = placement?.providers ?? [];
|
|
218
|
+
const http = placement ? httpActionEntry(placement, root, organized) : undefined;
|
|
219
|
+
const local = placement ? placedModules(placement, root, organized, runnerFunction) : [];
|
|
220
|
+
const split =
|
|
221
|
+
!!placement &&
|
|
222
|
+
(http !== undefined ||
|
|
223
|
+
local.length > 0 ||
|
|
224
|
+
flat ||
|
|
225
|
+
(organized && [...placement.modules.keys()].some((path) => !path.startsWith(root + sep))));
|
|
226
|
+
const server = split ? placedModules(placement, root, organized, lanes.server.keep) : [];
|
|
227
|
+
const files = split
|
|
228
|
+
? [
|
|
229
|
+
...new Set(
|
|
230
|
+
[...server, ...local, ...(http?.modules ?? [])].map(([path]) =>
|
|
231
|
+
relative(root, path).split(sep).join("/"),
|
|
232
|
+
),
|
|
233
|
+
),
|
|
234
|
+
]
|
|
235
|
+
: await scanFiles(root);
|
|
236
|
+
const modules = split
|
|
237
|
+
? files.map(
|
|
238
|
+
(file) =>
|
|
239
|
+
[...server, ...local, ...(http?.modules ?? [])].find(([path]) => path === resolve(root, file))[1],
|
|
240
|
+
)
|
|
241
|
+
: files.map((file) => (organized ? file.split("/").at(-1).slice(0, -3) : file.slice(0, -3)));
|
|
242
|
+
if (new Set(modules).size !== modules.length)
|
|
243
|
+
throw new Error("Duplicate server module name; module basenames must be unique");
|
|
244
|
+
const generated = join(root, "_generated");
|
|
245
|
+
await generateReferences(root, pluginRoot, files, modules, namespace, placement);
|
|
246
|
+
|
|
247
|
+
// Temporary entry/config live together and are always removed. They must
|
|
248
|
+
// never be mistaken for author modules on the next build.
|
|
249
|
+
const temporary = await mkdtemp(join(generated, "build-"));
|
|
250
|
+
try {
|
|
251
|
+
const hasSchema = await Bun.file(join(root, "schema.ts")).exists();
|
|
252
|
+
const entry = join(temporary, "entry.ts");
|
|
253
|
+
const source = registrySource({
|
|
254
|
+
root,
|
|
255
|
+
modules: split ? server : files.map((file, i) => [join(root, file), modules[i]]),
|
|
256
|
+
hasSchema,
|
|
257
|
+
placement,
|
|
258
|
+
results: placement?.results(root, organized),
|
|
259
|
+
points: placement?.points(root, organized),
|
|
260
|
+
providers,
|
|
261
|
+
header,
|
|
262
|
+
});
|
|
263
|
+
await Bun.write(entry, source);
|
|
264
|
+
|
|
265
|
+
const hasLocal = local.length > 0 || providers.some(runnerProvider);
|
|
266
|
+
if (hasLocal) {
|
|
267
|
+
await buildLocalBundle({
|
|
268
|
+
root,
|
|
269
|
+
sdkRoot,
|
|
270
|
+
pluginRoot,
|
|
271
|
+
source: registrySource({
|
|
272
|
+
root,
|
|
273
|
+
modules: local,
|
|
274
|
+
providers,
|
|
275
|
+
placement,
|
|
276
|
+
points: placement?.points(root, organized),
|
|
277
|
+
lane: lanes.local,
|
|
278
|
+
worker: true,
|
|
279
|
+
header,
|
|
280
|
+
}),
|
|
281
|
+
plugins: [placementTransform(placement, lanes.local)],
|
|
282
|
+
actionModules: runnerActionFiles(placement.modules, providers),
|
|
283
|
+
});
|
|
284
|
+
// Preserve the installed-artifact and socket entryHash contract. No
|
|
285
|
+
// executable entry is needed: the plugin process loads local.js.
|
|
286
|
+
await Bun.write(join(root, "dist/local-entry.js"), "");
|
|
287
|
+
}
|
|
288
|
+
async function buildServer(naming, contents, plugins) {
|
|
289
|
+
const built = await Bun.build({
|
|
290
|
+
entrypoints: ["tokamaq-feature:entry"],
|
|
291
|
+
target: "browser",
|
|
292
|
+
format: "esm",
|
|
293
|
+
splitting: false,
|
|
294
|
+
sourcemap: "linked",
|
|
295
|
+
naming,
|
|
296
|
+
outdir: join(root, "dist"),
|
|
297
|
+
packages: "bundle",
|
|
298
|
+
env: "disable",
|
|
299
|
+
allowUnresolved: [],
|
|
300
|
+
plugins: [
|
|
301
|
+
bunPluginBoundary(pluginRoot),
|
|
302
|
+
...plugins,
|
|
303
|
+
{
|
|
304
|
+
name: "stable-feature-entry",
|
|
305
|
+
setup(build) {
|
|
306
|
+
build.onResolve({ filter: /^tokamaq-feature:entry$/ }, () => ({
|
|
307
|
+
path: "entry",
|
|
308
|
+
namespace: "tokamaq-feature",
|
|
309
|
+
}));
|
|
310
|
+
build.onLoad({ filter: /.*/, namespace: "tokamaq-feature" }, () => ({
|
|
311
|
+
contents,
|
|
312
|
+
loader: "ts",
|
|
313
|
+
resolveDir: root,
|
|
314
|
+
}));
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
name: "portable-sdk",
|
|
319
|
+
setup(build) {
|
|
320
|
+
build.onResolve({ filter: /^@tokamaq\/sdk$/ }, () => ({
|
|
321
|
+
path: join(sdkRoot, "src/index.ts"),
|
|
322
|
+
}));
|
|
323
|
+
},
|
|
324
|
+
},
|
|
325
|
+
],
|
|
326
|
+
});
|
|
327
|
+
if (!built.success) throw new AggregateError(built.logs, "Feature bundle failed");
|
|
328
|
+
return built;
|
|
329
|
+
}
|
|
330
|
+
const stubImporters = new Set();
|
|
331
|
+
const built = await buildServer("bundle.js", source, [
|
|
332
|
+
...(placement ? [placementTransform(placement, lanes.server)] : []),
|
|
333
|
+
serverBuiltins("server-local-boundary", pluginRoot, "queries, mutations and server actions", {
|
|
334
|
+
callerFiles: placement?.callerFiles,
|
|
335
|
+
onStub: (path) => stubImporters.add(relative(pluginRoot, path)),
|
|
336
|
+
}),
|
|
337
|
+
]);
|
|
338
|
+
if (stubImporters.size) {
|
|
339
|
+
try {
|
|
340
|
+
await import(join(root, "dist/bundle.js"));
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (!(error instanceof Error) || error.kind !== "noMachine") throw error;
|
|
343
|
+
throw new Error(
|
|
344
|
+
`Plugin import boundary: a Runner binding from ${[...stubImporters].join(", ")} was used at module load. Move it inside the handler.\n${error.stack}`,
|
|
345
|
+
{ cause: error },
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (http) {
|
|
350
|
+
await buildServer("http-actions.js", http.source, [
|
|
351
|
+
placementTransform(placement, lanes.http),
|
|
352
|
+
serverBuiltins("http-action-builtins", pluginRoot, "HTTP actions"),
|
|
353
|
+
]);
|
|
354
|
+
}
|
|
355
|
+
if (splitActions) {
|
|
356
|
+
const descriptor = transactionSources({
|
|
357
|
+
root,
|
|
358
|
+
files,
|
|
359
|
+
modules,
|
|
360
|
+
hasSchema,
|
|
361
|
+
header,
|
|
362
|
+
pluginRoot,
|
|
363
|
+
placement: split ? placement : undefined,
|
|
364
|
+
namespace,
|
|
365
|
+
});
|
|
366
|
+
await buildServer("transactions.js", descriptor.source, descriptor.plugins);
|
|
367
|
+
}
|
|
368
|
+
// Report unsupported imports before TypeScript reports missing Node declarations.
|
|
369
|
+
await checkFeature(root, pluginRoot, temporary, generated, files, entry, hasLocal, providers);
|
|
370
|
+
if (namespace !== undefined)
|
|
371
|
+
await Bun.write(
|
|
372
|
+
join(root, "dist/contracts.json"),
|
|
373
|
+
JSON.stringify(contractManifest(pluginRoot, namespace, providers)),
|
|
374
|
+
);
|
|
375
|
+
const chunks = built.outputs.filter((output) => output.kind !== "sourcemap");
|
|
376
|
+
if (chunks.length !== 1 || !built.outputs.some((output) => output.kind === "sourcemap"))
|
|
377
|
+
throw new Error("Feature build must produce exactly one ESM file and its source map");
|
|
378
|
+
const scan = new Bun.Transpiler({ loader: "js" }).scan(await chunks[0].text());
|
|
379
|
+
if (scan.imports.length !== 0)
|
|
380
|
+
throw new Error("Feature bundle retains imports; the runtime loads only one module");
|
|
381
|
+
console.log(
|
|
382
|
+
`${relative(process.cwd(), root)} -> dist/bundle.js + source map, _generated/{api,internal}.ts`,
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
return {
|
|
386
|
+
bundle: join(root, "dist/bundle.js"),
|
|
387
|
+
api: join(generated, "api.ts"),
|
|
388
|
+
};
|
|
389
|
+
} finally {
|
|
390
|
+
await rm(temporary, { recursive: true, force: true });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (import.meta.main) {
|
|
395
|
+
const [, , folder, flag, namespace, dependsFlag, depends] = process.argv;
|
|
396
|
+
if (
|
|
397
|
+
!folder ||
|
|
398
|
+
(flag !== undefined && (flag !== "--plugin" || !namespace)) ||
|
|
399
|
+
(dependsFlag !== undefined && (dependsFlag !== "--depends" || !depends)) ||
|
|
400
|
+
process.argv.length > 7
|
|
401
|
+
) {
|
|
402
|
+
throw new Error("sdk:bundle expects a feature folder and optional --plugin <id> [--depends <json>]");
|
|
403
|
+
}
|
|
404
|
+
// Moon runs in packages/sdk/ and also accepts workspace-relative arguments.
|
|
405
|
+
const fromCwd = resolve(folder);
|
|
406
|
+
const feature = existsSync(fromCwd) ? fromCwd : resolve(sdkRoot, "../..", folder);
|
|
407
|
+
// Bun's generated module comments/debug IDs must not depend on caller cwd.
|
|
408
|
+
process.chdir(feature);
|
|
409
|
+
await bundleFeature(feature, namespace, true, depends && JSON.parse(depends));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function scanFiles(root) {
|
|
413
|
+
const files = [];
|
|
414
|
+
const scanner = new Bun.Transpiler({ loader: "ts" });
|
|
415
|
+
for await (const scanned of new Bun.Glob("**/*.ts").scan({
|
|
416
|
+
cwd: root,
|
|
417
|
+
onlyFiles: true,
|
|
418
|
+
})) {
|
|
419
|
+
const file = scanned.split(sep).join("/");
|
|
420
|
+
if (!isServerModule(root, file)) continue;
|
|
421
|
+
// scan is a real parser, not a regexp. We do not interpret initializer
|
|
422
|
+
// syntax: exported definitions are recognized by their runtime brand.
|
|
423
|
+
scanner.scan(await Bun.file(join(root, file)).text());
|
|
424
|
+
files.push(file);
|
|
425
|
+
}
|
|
426
|
+
files.sort();
|
|
427
|
+
return files;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function checkFeature(root, pluginRoot, temporary, generated, files, entry, hasLocal, providers) {
|
|
431
|
+
const config = join(temporary, "tsconfig.json");
|
|
432
|
+
// Inherit resolution options unchanged, including paths relative to the
|
|
433
|
+
// config that declared them. A build-only SDK alias or TS-extension opt-in
|
|
434
|
+
// would accept code that generated-reference consumers cannot type-check.
|
|
435
|
+
const parentConfig = serverConfigPath(root, pluginRoot);
|
|
436
|
+
const inherited = ts.getParsedCommandLineOfConfigFile(
|
|
437
|
+
parentConfig,
|
|
438
|
+
{},
|
|
439
|
+
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic() {} },
|
|
440
|
+
);
|
|
441
|
+
const paths = pluginCompilerOptions(pluginRoot, inherited?.options ?? {}).paths;
|
|
442
|
+
await Bun.write(
|
|
443
|
+
config,
|
|
444
|
+
JSON.stringify({
|
|
445
|
+
extends: parentConfig,
|
|
446
|
+
compilerOptions: {
|
|
447
|
+
lib: hasLocal ? ["ES2022", "DOM"] : ["ES2022"],
|
|
448
|
+
types: hasLocal ? ["node"] : [],
|
|
449
|
+
paths,
|
|
450
|
+
noEmit: true,
|
|
451
|
+
strict: true,
|
|
452
|
+
},
|
|
453
|
+
files: [
|
|
454
|
+
entry,
|
|
455
|
+
join(generated, "api.ts"),
|
|
456
|
+
join(generated, "internal.ts"),
|
|
457
|
+
...new Set([
|
|
458
|
+
...files.map((file) => join(root, file)),
|
|
459
|
+
...providers.map((p) => p.path),
|
|
460
|
+
...[contractEntry(pluginRoot)].filter(ts.sys.fileExists),
|
|
461
|
+
]),
|
|
462
|
+
],
|
|
463
|
+
include: [],
|
|
464
|
+
exclude: [],
|
|
465
|
+
}),
|
|
466
|
+
);
|
|
467
|
+
const check = Bun.spawnSync([process.execPath, "check", "--no-script", "--project", config]);
|
|
468
|
+
const stdout = check.stdout.toString();
|
|
469
|
+
const stderr = check.stderr.toString();
|
|
470
|
+
if (stdout) process.stdout.write(stdout);
|
|
471
|
+
if (stderr) process.stderr.write(stderr);
|
|
472
|
+
if (check.exitCode !== 0) {
|
|
473
|
+
const diagnostics = (stdout + stderr).replace(/\x1b\[[0-9;]*m/g, "");
|
|
474
|
+
const advice = [];
|
|
475
|
+
if (/Property 'local' does not exist on type .*TokamaqClient/.test(diagnostics))
|
|
476
|
+
advice.push("Use client.action(...)");
|
|
477
|
+
if (/Property 'hasLocal' does not exist on type .*TokamaqClient/.test(diagnostics))
|
|
478
|
+
advice.push("Call the action and handle the noMachine failure");
|
|
479
|
+
if (
|
|
480
|
+
/Property 'proc' does not exist on type .*?(?:Query|Mutation|Action)Context/.test(diagnostics) ||
|
|
481
|
+
[...diagnostics.matchAll(/Cannot find module '([^']+)'/g)].some(([, path]) =>
|
|
482
|
+
/^(?:node:)?fs\/promises$/.test(path),
|
|
483
|
+
)
|
|
484
|
+
)
|
|
485
|
+
advice.push(useLocal);
|
|
486
|
+
if (/Property 'db' does not exist on type 'CallerActionContext'/.test(diagnostics))
|
|
487
|
+
advice.push(useServer);
|
|
488
|
+
throw new Error(["Feature type check failed.", ...advice].join(" "));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
export function clientEntry(root) {
|
|
5
|
+
for (const entry of ["src/client/api.ts", "src/client/api.tsx", "src/client/main.tsx", "src/main.tsx"]) {
|
|
6
|
+
const file = resolve(root, entry);
|
|
7
|
+
if (existsSync(file)) return file;
|
|
8
|
+
}
|
|
9
|
+
return resolve(root, existsSync(resolve(root, "src/client")) ? "src/client/main.tsx" : "src/main.tsx");
|
|
10
|
+
}
|