@native-sdk/cli 0.8.4 → 0.9.1
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/build/app.zig +1178 -74
- package/build.zig +715 -17
- package/build.zig.zon +1 -0
- package/native-sdk.d.ts +10 -0
- package/package.json +12 -11
- package/packages/core/compile-surface/core.ts +435 -3
- package/packages/core/package-lock.json +11 -11
- package/packages/core/package.json +2 -2
- package/packages/core/scripts/compiler_typecheck.mjs +116 -15
- package/packages/core/scripts/gen_service_surface.mjs +268 -0
- package/packages/core/scripts/merge_static_archives.mjs +78 -0
- package/packages/core/scripts/npm_static_spike.mjs +64 -0
- package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
- package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
- package/packages/core/scripts/stage_external_core.mjs +9 -1
- package/packages/core/scripts/stage_external_services.mjs +172 -0
- package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
- package/packages/core/scripts/vendor_service_packages.mjs +189 -0
- package/packages/core/sdk/core.d.ts +224 -0
- package/packages/core/sdk/core.ts +694 -22
- package/packages/core/sdk/events.d.ts +89 -0
- package/packages/core/sdk/events.ts +128 -0
- package/packages/core/src/checker.ts +936 -15
- package/packages/core/src/cli.ts +156 -3
- package/packages/core/src/contract.ts +28 -5
- package/packages/core/src/devhost.ts +1876 -16
- package/packages/core/src/devhost_journal.mjs +183 -0
- package/packages/core/src/devhost_resolver.mjs +17 -1
- package/packages/core/src/devhost_service_worker.mjs +90 -0
- package/packages/core/src/diagnostics.ts +179 -22
- package/packages/core/src/frontend.ts +210 -34
- package/packages/core/src/infer.ts +24 -0
- package/packages/core/src/modules.ts +129 -80
- package/packages/core/src/service_contract.ts +597 -0
- package/packages/core/src/sqlite_cli.ts +93 -0
- package/packages/core/src/sqlite_codegen.ts +806 -0
- package/packages/core/src/sqlite_runtime_policy.ts +364 -0
- package/packages/core/src/typed_ast.ts +36 -8
- package/skill-data/automation/SKILL.md +1 -1
- package/skill-data/core/references/project-anatomy.md +1 -1
- package/skill-data/native-ui/SKILL.md +58 -5
- package/skill-data/ts-core/SKILL.md +123 -41
- package/skill-data/ts-services/SKILL.md +126 -0
- package/skill-data/ts-services/references/service-surface.md +604 -0
- package/skill-data/zig/SKILL.md +1 -1
- package/skills/native-sdk/SKILL.md +1 -1
- package/src/app_runner/no_migrations.zig +3 -0
- package/src/app_runner/no_services.zig +20 -0
- package/src/app_runner/root.zig +133 -4
- package/src/app_runner/ts_core_main.zig +254 -8
- package/src/app_runner/ts_core_mobile.zig +241 -0
- package/src/automation/protocol.zig +5 -1
- package/src/automation/snapshot.zig +31 -11
- package/src/embed/app_exports.zig +12 -1
- package/src/embed/c_api.zig +48 -2
- package/src/embed/conversions.zig +4 -5
- package/src/embed/host.zig +109 -1
- package/src/embed/root.zig +8 -0
- package/src/embed/tests.zig +241 -0
- package/src/embed/types.zig +51 -0
- package/src/embed/ui_host.zig +185 -5
- package/src/platform/android/NativeSdkActivity.java +131 -0
- package/src/platform/android/android_host.c +182 -1
- package/src/platform/android/native_sdk_app.h +17 -0
- package/src/platform/ios/native_sdk_app.h +17 -0
- package/src/platform/ios/uikit_host.m +115 -0
- package/src/platform/linux/cef_host.cpp +8 -2
- package/src/platform/linux/gtk_host.c +289 -22
- package/src/platform/linux/gtk_host.h +5 -1
- package/src/platform/linux/root.zig +109 -22
- package/src/platform/macos/appkit_host.h +24 -7
- package/src/platform/macos/appkit_host.m +686 -64
- package/src/platform/macos/cef_host.mm +400 -66
- package/src/platform/macos/root.zig +304 -47
- package/src/platform/null_platform.zig +435 -48
- package/src/platform/null_platform_tests.zig +113 -0
- package/src/platform/root.zig +19 -0
- package/src/platform/types.zig +281 -28
- package/src/platform/windows/root.zig +207 -27
- package/src/platform/windows/webview2_host.cpp +334 -51
- package/src/primitives/app_manifest/comptime_scene.zig +2 -0
- package/src/primitives/app_manifest/root.zig +4 -0
- package/src/primitives/app_manifest/tests.zig +3 -0
- package/src/primitives/app_manifest/types.zig +32 -0
- package/src/primitives/app_manifest/validation.zig +19 -1
- package/src/root.zig +53 -0
- package/src/runtime/api.zig +19 -0
- package/src/runtime/automation_commands.zig +35 -2
- package/src/runtime/automation_snapshot.zig +32 -20
- package/src/runtime/bridge_permission_tests.zig +58 -3
- package/src/runtime/bridge_responses.zig +4 -2
- package/src/runtime/builtin_bridge.zig +11 -1
- package/src/runtime/canvas_frame.zig +18 -11
- package/src/runtime/canvas_frame_animation_tests.zig +4 -0
- package/src/runtime/clock.zig +13 -1
- package/src/runtime/core.zig +145 -7
- package/src/runtime/credentials_store.zig +115 -0
- package/src/runtime/effects.zig +3701 -231
- package/src/runtime/effects_credentials_tests.zig +332 -0
- package/src/runtime/effects_file_tests.zig +587 -0
- package/src/runtime/effects_host_tests.zig +208 -1
- package/src/runtime/effects_notification_tests.zig +11 -0
- package/src/runtime/effects_relational_tests.zig +314 -0
- package/src/runtime/effects_store_tests.zig +211 -0
- package/src/runtime/file_access.zig +400 -0
- package/src/runtime/file_effect_crash_helper.zig +28 -0
- package/src/runtime/file_effect_crash_tests.zig +37 -0
- package/src/runtime/flow.zig +35 -10
- package/src/runtime/gpu_surface_events.zig +6 -1
- package/src/runtime/native_command_event_tests.zig +86 -2
- package/src/runtime/persist_store.zig +666 -0
- package/src/runtime/pty.zig +5 -2
- package/src/runtime/record_store.zig +788 -0
- package/src/runtime/relational_store.zig +854 -0
- package/src/runtime/root.zig +54 -0
- package/src/runtime/runtime_event_tests.zig +70 -0
- package/src/runtime/service_host.zig +711 -0
- package/src/runtime/service_pool.zig +1314 -0
- package/src/runtime/session_blobs.zig +4 -1
- package/src/runtime/session_journal.zig +158 -5
- package/src/runtime/session_record.zig +215 -0
- package/src/runtime/session_replay.zig +206 -11
- package/src/runtime/session_tests.zig +81 -0
- package/src/runtime/shell_layout.zig +1 -0
- package/src/runtime/shell_layout_tests.zig +120 -0
- package/src/runtime/sqlite_engine.zig +474 -0
- package/src/runtime/state.zig +16 -0
- package/src/runtime/system_services.zig +170 -38
- package/src/runtime/tests.zig +4 -0
- package/src/runtime/ts_core_host.zig +1067 -95
- package/src/runtime/ts_core_host_tests.zig +325 -11
- package/src/runtime/ts_ui_app.zig +953 -2
- package/src/runtime/ui_app.zig +434 -96
- package/src/runtime/ui_app_tests.zig +287 -11
- package/src/runtime/ui_app_window_tests.zig +61 -7
- package/src/runtime/validation.zig +42 -0
- package/src/runtime/view.zig +9 -0
- package/src/runtime/window_storage.zig +1 -0
- package/src/runtime/window_view_runtime.zig +2 -3
- package/src/runtime/window_views.zig +19 -0
- package/src/tooling/android.zig +21 -16
- package/src/tooling/db.zig +160 -0
- package/src/tooling/ios.zig +7 -1
- package/src/tooling/manifest.zig +214 -2
- package/src/tooling/package.zig +116 -0
- package/src/tooling/raw_manifest.zig +30 -0
- package/src/tooling/root.zig +1 -0
- package/src/tooling/templates.zig +189 -4
- package/src/tooling/ts_core.zig +366 -17
- package/src/tooling/verbs.zig +7 -0
- package/third_party/sqlite/README.md +13 -0
- package/third_party/sqlite/sqlite3.c +269649 -0
- package/third_party/sqlite/sqlite3.h +14349 -0
- package/tools/corewire/core_abi.zig +14 -2
- package/tools/corewire/emit.zig +98 -29
- package/tools/corewire/emit_facade.zig +442 -27
- package/tools/corewire/emit_profile.zig +6 -2
- package/tools/corewire/emit_service.zig +924 -0
- package/tools/corewire/main.zig +122 -0
- package/tools/corewire/service_contract.zig +250 -0
- package/tools/corewire/sidecar.zig +26 -15
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
// services.contract.json — the only fact channel for the typed service
|
|
2
|
+
// seam. It is emitted from the same parsed program as the core contract; all
|
|
3
|
+
// downstream dispatch/host generation consumes this document rather than
|
|
4
|
+
// re-reading author source for declarations.
|
|
5
|
+
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { ts, hasExportModifier, exportListBindings, lineColumn, type TypedAst } from "./typed_ast.ts";
|
|
11
|
+
import { makeDiagnostic, type SubsetDiagnostic } from "./diagnostics.ts";
|
|
12
|
+
import { TypeTable, type ZType } from "./types.ts";
|
|
13
|
+
import type { IntInference } from "./infer.ts";
|
|
14
|
+
|
|
15
|
+
export const serviceContractFormat = 3;
|
|
16
|
+
export const serviceProtocolVersion = 3;
|
|
17
|
+
|
|
18
|
+
export type ServiceTypeRef =
|
|
19
|
+
| { readonly kind: "bool" | "f64" | "i64" | "bytes" }
|
|
20
|
+
| { readonly kind: "optional"; readonly inner: ServiceTypeRef }
|
|
21
|
+
| { readonly kind: "slice"; readonly elem: ServiceTypeRef }
|
|
22
|
+
| { readonly kind: "record" | "enum" | "union"; readonly name: string };
|
|
23
|
+
|
|
24
|
+
export interface ServiceRecordType {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly origin: string;
|
|
27
|
+
readonly fields: readonly { readonly name: string; readonly type: ServiceTypeRef }[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ServiceEnumType {
|
|
31
|
+
readonly name: string;
|
|
32
|
+
readonly origin: string;
|
|
33
|
+
readonly members: readonly string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ServiceUnionType {
|
|
37
|
+
readonly name: string;
|
|
38
|
+
readonly origin: string;
|
|
39
|
+
readonly arms: readonly {
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly fields: readonly { readonly name: string; readonly type: ServiceTypeRef }[];
|
|
42
|
+
}[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ServiceTypes {
|
|
46
|
+
readonly records: readonly ServiceRecordType[];
|
|
47
|
+
readonly enums: readonly ServiceEnumType[];
|
|
48
|
+
readonly unions: readonly ServiceUnionType[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ServicePackage {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
readonly version: string;
|
|
54
|
+
readonly content_hash: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ServiceOperation {
|
|
58
|
+
readonly name: string;
|
|
59
|
+
readonly client: string;
|
|
60
|
+
readonly module: string;
|
|
61
|
+
readonly export: string;
|
|
62
|
+
readonly request: { readonly kind: "none" } | ServiceTypeRef;
|
|
63
|
+
readonly result: ServiceTypeRef;
|
|
64
|
+
readonly deadline_ms: number | null;
|
|
65
|
+
readonly cancellable: boolean;
|
|
66
|
+
readonly stream: { readonly chunk: ServiceTypeRef; readonly in_flight: number } | null;
|
|
67
|
+
readonly source_hash: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ServiceSurfaceResult {
|
|
71
|
+
readonly operations: readonly ServiceOperation[];
|
|
72
|
+
readonly types: ServiceTypes;
|
|
73
|
+
readonly diagnostics: readonly SubsetDiagnostic[];
|
|
74
|
+
readonly contract: string | null;
|
|
75
|
+
readonly client: string | null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function report(site: string, node: ts.Node): SubsetDiagnostic {
|
|
79
|
+
const file = node.getSourceFile();
|
|
80
|
+
const where = lineColumn(file, node.getStart(file));
|
|
81
|
+
return makeDiagnostic("NS1067", site, file.fileName, where.line, where.column);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isBytesType(tast: TypedAst, node: ts.TypeNode | undefined, seen = new Set<ts.Node>()): boolean {
|
|
85
|
+
if (!node || !ts.isTypeReferenceNode(node)) return false;
|
|
86
|
+
const name = ts.isIdentifier(node.typeName) ? node.typeName : node.typeName.right;
|
|
87
|
+
const declaration = tast.declarationOf(name);
|
|
88
|
+
if (name.text === "Uint8Array") {
|
|
89
|
+
// Preserve the direct global spelling while still respecting a local
|
|
90
|
+
// type alias that shadows it.
|
|
91
|
+
if (!declaration || !ts.isTypeAliasDeclaration(declaration)) return true;
|
|
92
|
+
}
|
|
93
|
+
if (!declaration || !ts.isTypeAliasDeclaration(declaration) || seen.has(declaration)) return false;
|
|
94
|
+
seen.add(declaration);
|
|
95
|
+
return isBytesType(tast, declaration.type, seen);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isServiceCancellationType(tast: TypedAst, node: ts.TypeNode | undefined): boolean {
|
|
99
|
+
if (!node || !ts.isTypeReferenceNode(node) || node.typeArguments?.length) return false;
|
|
100
|
+
const name = ts.isIdentifier(node.typeName) ? node.typeName : node.typeName.right;
|
|
101
|
+
if (name.text !== "ServiceCancellation") return false;
|
|
102
|
+
const declaration = tast.declarationOf(name);
|
|
103
|
+
if (!declaration) return false;
|
|
104
|
+
const source = declaration.getSourceFile().fileName.split(path.sep).join("/");
|
|
105
|
+
return source.endsWith("/sdk/core.ts") || source.endsWith("/sdk/core.d.ts") || source.endsWith("/compile-surface/core.ts");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function unwrapExpression(expr: ts.Expression): ts.Expression {
|
|
109
|
+
while (ts.isAsExpression(expr) || ts.isTypeAssertionExpression(expr) || ts.isParenthesizedExpression(expr)) expr = expr.expression;
|
|
110
|
+
return expr;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function explicitThrowIsKindTagged(tast: TypedAst, expr: ts.Expression): boolean {
|
|
114
|
+
const value = unwrapExpression(expr);
|
|
115
|
+
if (!ts.isObjectLiteralExpression(value) || value.properties.length !== 2) return false;
|
|
116
|
+
const [kind, message] = value.properties;
|
|
117
|
+
const messageType = ts.isPropertyAssignment(message) ? tast.typeOf(message.initializer) : null;
|
|
118
|
+
const messageIsString = messageType !== null && (
|
|
119
|
+
(messageType.flags & (ts.TypeFlags.String | ts.TypeFlags.StringLiteral)) !== 0 ||
|
|
120
|
+
(messageType.isUnion() && messageType.types.every((member) => member.isStringLiteral())) ||
|
|
121
|
+
// The in-process checker deliberately has no Node declaration universe;
|
|
122
|
+
// defer an unresolved ambient expression to scriptc and stringify it in
|
|
123
|
+
// the scratch adapter rather than false-rejecting a real string result.
|
|
124
|
+
(messageType.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0
|
|
125
|
+
);
|
|
126
|
+
return ts.isPropertyAssignment(kind) && ts.isIdentifier(kind.name) && kind.name.text === "kind" &&
|
|
127
|
+
ts.isStringLiteral(kind.initializer) && kind.initializer.text.length > 0 &&
|
|
128
|
+
ts.isPropertyAssignment(message) && ts.isIdentifier(message.name) && message.name.text === "message" &&
|
|
129
|
+
messageIsString;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function throwIsLexicallyCaught(node: ts.ThrowStatement): boolean {
|
|
133
|
+
let child: ts.Node = node;
|
|
134
|
+
for (let parent = node.parent; parent; child = parent, parent = parent.parent) {
|
|
135
|
+
if (ts.isFunctionLike(parent)) return false;
|
|
136
|
+
if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) return true;
|
|
137
|
+
}
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function pinnedScriptcVersion(): string {
|
|
142
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
143
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")) as {
|
|
144
|
+
dependencies?: { scriptc?: unknown };
|
|
145
|
+
};
|
|
146
|
+
const pin = manifest.dependencies?.scriptc;
|
|
147
|
+
if (typeof pin !== "string" || !/^\d+\.\d+\.\d+$/.test(pin)) {
|
|
148
|
+
throw new Error("packages/core/package.json carries no exact scriptc pin");
|
|
149
|
+
}
|
|
150
|
+
return pin;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function sourceGraphHash(files: readonly ts.SourceFile[], srcRoot: string): string {
|
|
154
|
+
const facts = files.map((file) => ({
|
|
155
|
+
module: path.relative(srcRoot, file.fileName).split(path.sep).join("/"),
|
|
156
|
+
hash: crypto.createHash("sha256").update(fs.readFileSync(file.fileName)).digest("hex"),
|
|
157
|
+
})).sort((a, b) => a.module < b.module ? -1 : a.module > b.module ? 1 : 0);
|
|
158
|
+
const graph = crypto.createHash("sha256");
|
|
159
|
+
graph.update("native-sdk.services.sources.v1\0");
|
|
160
|
+
for (const fact of facts) {
|
|
161
|
+
graph.update(fact.module);
|
|
162
|
+
graph.update("\0");
|
|
163
|
+
graph.update(fact.hash);
|
|
164
|
+
graph.update("\0");
|
|
165
|
+
}
|
|
166
|
+
return graph.digest("hex");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function supportedOperationIdentifier(name: string): boolean {
|
|
170
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
class ServiceShapeError extends Error {
|
|
174
|
+
readonly node: ts.Node;
|
|
175
|
+
constructor(message: string, node: ts.Node) {
|
|
176
|
+
super(message);
|
|
177
|
+
this.node = node;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
class ServiceShapeTable {
|
|
182
|
+
readonly records: ServiceRecordType[] = [];
|
|
183
|
+
readonly enums: ServiceEnumType[] = [];
|
|
184
|
+
readonly unions: ServiceUnionType[] = [];
|
|
185
|
+
private readonly listed = new Set<string>();
|
|
186
|
+
private readonly tast: TypedAst;
|
|
187
|
+
private readonly table: TypeTable;
|
|
188
|
+
private readonly infer: IntInference;
|
|
189
|
+
private readonly srcRoot: string;
|
|
190
|
+
private readonly fallbackSite: ts.Node;
|
|
191
|
+
|
|
192
|
+
constructor(
|
|
193
|
+
tast: TypedAst,
|
|
194
|
+
table: TypeTable,
|
|
195
|
+
infer: IntInference,
|
|
196
|
+
srcRoot: string,
|
|
197
|
+
fallbackSite: ts.Node,
|
|
198
|
+
) {
|
|
199
|
+
this.tast = tast;
|
|
200
|
+
this.table = table;
|
|
201
|
+
this.infer = infer;
|
|
202
|
+
this.srcRoot = srcRoot;
|
|
203
|
+
this.fallbackSite = fallbackSite;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
ref(node: ts.TypeNode, site: ts.Node): ServiceTypeRef {
|
|
207
|
+
return this.reflect(this.table.resolveTypeNode(node), site);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private origin(decl: ts.Declaration, name: string): string {
|
|
211
|
+
const file = decl.getSourceFile();
|
|
212
|
+
const relative = path.relative(this.srcRoot, file.fileName).split(path.sep).join("/");
|
|
213
|
+
if (relative.startsWith("services/")) {
|
|
214
|
+
throw new ServiceShapeError(
|
|
215
|
+
`Service boundary type \`${name}\` is declared under src/services; declare and export the shared data shape from a core-class module so both sides read one authority`,
|
|
216
|
+
decl,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
const directlyExported = hasExportModifier(decl);
|
|
220
|
+
const listExported = exportListBindings(this.tast, file)
|
|
221
|
+
.some((binding) => binding.target === decl && !binding.renamed);
|
|
222
|
+
if (!directlyExported && !listExported) {
|
|
223
|
+
throw new ServiceShapeError(
|
|
224
|
+
`Service boundary type \`${name}\` is not exported from ${relative}; export the shared declaration so the generated client can import the same shape`,
|
|
225
|
+
decl,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
return relative;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private reflect(type: ZType, decl: ts.Node): ServiceTypeRef {
|
|
232
|
+
switch (type.k) {
|
|
233
|
+
case "bool": return { kind: "bool" };
|
|
234
|
+
case "f64": return { kind: "f64" };
|
|
235
|
+
case "i64": return { kind: "i64" };
|
|
236
|
+
case "number": return { kind: this.infer.classOfDecl(decl) === "i64" ? "i64" : "f64" };
|
|
237
|
+
case "bytes": return { kind: "bytes" };
|
|
238
|
+
case "numAlias": return { kind: "i64" };
|
|
239
|
+
case "optional": return { kind: "optional", inner: this.reflect(type.inner, decl) };
|
|
240
|
+
case "slice": return { kind: "slice", elem: this.reflect(type.elem, decl) };
|
|
241
|
+
case "struct":
|
|
242
|
+
this.collectRecord(type.name);
|
|
243
|
+
return { kind: "record", name: type.name };
|
|
244
|
+
case "enum":
|
|
245
|
+
this.collectEnum(type.name);
|
|
246
|
+
return { kind: "enum", name: type.name };
|
|
247
|
+
case "union":
|
|
248
|
+
this.collectUnion(type.name);
|
|
249
|
+
return { kind: "union", name: type.name };
|
|
250
|
+
case "string":
|
|
251
|
+
throw new ServiceShapeError("Dynamic string data has no core boundary representation; use Uint8Array byte text or a string-literal union", decl);
|
|
252
|
+
case "void":
|
|
253
|
+
throw new ServiceShapeError("A service boundary slot resolves to void", decl);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private collectRecord(name: string): void {
|
|
258
|
+
if (this.listed.has(name)) return;
|
|
259
|
+
const info = this.table.structs.get(name);
|
|
260
|
+
if (!info) throw new ServiceShapeError(`The shared type table has no record named \`${name}\``, this.fallbackSite);
|
|
261
|
+
this.listed.add(name);
|
|
262
|
+
const record: ServiceRecordType = {
|
|
263
|
+
name,
|
|
264
|
+
origin: this.origin(info.decl, name),
|
|
265
|
+
fields: info.fields.map((field) => ({ name: field.tsName, type: this.reflect(field.type, field.decl) })),
|
|
266
|
+
};
|
|
267
|
+
this.records.push(record);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private collectEnum(name: string): void {
|
|
271
|
+
if (this.listed.has(name)) return;
|
|
272
|
+
const info = this.table.enums.get(name);
|
|
273
|
+
if (!info) throw new ServiceShapeError(`The shared type table has no enum named \`${name}\``, this.fallbackSite);
|
|
274
|
+
this.listed.add(name);
|
|
275
|
+
this.enums.push({ name, origin: this.origin(info.decl, name), members: info.members });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private collectUnion(name: string): void {
|
|
279
|
+
if (this.listed.has(name)) return;
|
|
280
|
+
const info = this.table.unions.get(name);
|
|
281
|
+
if (!info) throw new ServiceShapeError(`The shared type table has no union named \`${name}\``, this.fallbackSite);
|
|
282
|
+
this.listed.add(name);
|
|
283
|
+
const union: ServiceUnionType = {
|
|
284
|
+
name,
|
|
285
|
+
origin: this.origin(info.decl, name),
|
|
286
|
+
arms: info.arms.map((arm) => ({
|
|
287
|
+
name: arm.tag,
|
|
288
|
+
fields: arm.fields.map((field) => ({ name: field.tsName, type: this.reflect(field.type, field.decl) })),
|
|
289
|
+
})),
|
|
290
|
+
};
|
|
291
|
+
this.unions.push(union);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
document(): ServiceTypes {
|
|
295
|
+
return { records: this.records, enums: this.enums, unions: this.unions };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function clientIdentifier(operation: Pick<ServiceOperation, "name" | "export">): string {
|
|
300
|
+
const stem = `${operation.name.slice(0, operation.name.lastIndexOf("."))}_${operation.export}`;
|
|
301
|
+
const words = stem.split(/[^A-Za-z0-9_$]+|_+/).filter(Boolean);
|
|
302
|
+
const joined = words.map((word, index) => index === 0 ? word : word[0].toUpperCase() + word.slice(1)).join("");
|
|
303
|
+
return supportedOperationIdentifier(joined) ? joined : `service_${operation.export}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function typeSpelling(ref: ServiceTypeRef): string {
|
|
307
|
+
switch (ref.kind) {
|
|
308
|
+
case "bool": return "boolean";
|
|
309
|
+
case "f64":
|
|
310
|
+
case "i64": return "number";
|
|
311
|
+
case "bytes": return "Uint8Array";
|
|
312
|
+
case "optional": return `${typeSpelling(ref.inner)} | null`;
|
|
313
|
+
case "slice": {
|
|
314
|
+
const elem = typeSpelling(ref.elem);
|
|
315
|
+
return `readonly ${ref.elem.kind === "optional" || ref.elem.kind === "slice" ? `(${elem})` : elem}[]`;
|
|
316
|
+
}
|
|
317
|
+
case "record":
|
|
318
|
+
case "enum":
|
|
319
|
+
case "union": return ref.name;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function emitServiceClientDocument(document: {
|
|
324
|
+
readonly operations: readonly ServiceOperation[];
|
|
325
|
+
readonly types: ServiceTypes;
|
|
326
|
+
}): string {
|
|
327
|
+
const imports = new Map<string, Set<string>>();
|
|
328
|
+
const addImport = (origin: string, name: string): void => {
|
|
329
|
+
const names = imports.get(origin) ?? new Set<string>();
|
|
330
|
+
names.add(name);
|
|
331
|
+
imports.set(origin, names);
|
|
332
|
+
};
|
|
333
|
+
addImport("core.ts", "Msg");
|
|
334
|
+
for (const type of [...document.types.records, ...document.types.enums, ...document.types.unions]) addImport(type.origin, type.name);
|
|
335
|
+
|
|
336
|
+
let out = "// Generated from services.contract.json. Do not edit.\n";
|
|
337
|
+
out += "import { Cmd, serviceBoolBytes, serviceBytes, serviceConcat, serviceEnumBytes, serviceF64Bytes, serviceI64Bytes, serviceOptionalBytes, serviceSliceBytes, serviceUnionBytes, type ServiceRoute, type ServiceStreamRoute } from \"@native-sdk/core\";\n";
|
|
338
|
+
for (const [origin, names] of [...imports].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
|
|
339
|
+
out += `import type { ${[...names].sort().join(", ")} } from \"./${origin}\";\n`;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const records = new Map(document.types.records.map((type) => [type.name, type]));
|
|
343
|
+
const enums = new Map(document.types.enums.map((type) => [type.name, type]));
|
|
344
|
+
const unions = new Map(document.types.unions.map((type) => [type.name, type]));
|
|
345
|
+
const encode = (ref: ServiceTypeRef, value: string): string => {
|
|
346
|
+
switch (ref.kind) {
|
|
347
|
+
case "bool": return `serviceBoolBytes(${value})`;
|
|
348
|
+
case "f64": return `serviceF64Bytes(${value})`;
|
|
349
|
+
case "i64": return `serviceI64Bytes(${value})`;
|
|
350
|
+
case "bytes": return `serviceBytes(${value})`;
|
|
351
|
+
case "optional": return `${value} === null ? serviceOptionalBytes(null) : serviceOptionalBytes(${encode(ref.inner, value)})`;
|
|
352
|
+
case "slice": return `serviceSliceBytes(${value}.map((item) => ${encode(ref.elem, "item")}))`;
|
|
353
|
+
case "record": return `__nativeSdkEncode${ref.name}(${value})`;
|
|
354
|
+
case "enum": {
|
|
355
|
+
const members = enums.get(ref.name)?.members ?? [];
|
|
356
|
+
const index = members.reduceRight((tail, member, i) => `${value} === ${JSON.stringify(member)} ? ${i} : (${tail})`, "0");
|
|
357
|
+
return `serviceEnumBytes(${index})`;
|
|
358
|
+
}
|
|
359
|
+
case "union": return `__nativeSdkEncode${ref.name}(${value})`;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
for (const record of records.values()) {
|
|
364
|
+
out += `\nfunction __nativeSdkEncode${record.name}(value: ${record.name}): Uint8Array {\n`;
|
|
365
|
+
out += ` return serviceConcat([${record.fields.map((field) => encode(field.type, `value.${field.name}`)).join(", ")}]);\n}\n`;
|
|
366
|
+
}
|
|
367
|
+
for (const union of unions.values()) {
|
|
368
|
+
out += `\nfunction __nativeSdkEncode${union.name}(value: ${union.name}): Uint8Array {\n switch (value.kind) {\n`;
|
|
369
|
+
union.arms.forEach((arm, index) => {
|
|
370
|
+
const fields = arm.fields.map((field) => encode(field.type, `value.${field.name}`));
|
|
371
|
+
out += ` case ${JSON.stringify(arm.name)}: return serviceConcat([serviceUnionBytes(${index})${fields.length ? `, ${fields.join(", ")}` : ""}]);\n`;
|
|
372
|
+
});
|
|
373
|
+
out += " }\n}\n";
|
|
374
|
+
}
|
|
375
|
+
for (const operation of document.operations) {
|
|
376
|
+
const fn = operation.client;
|
|
377
|
+
const request = operation.request.kind === "none" ? null : operation.request;
|
|
378
|
+
const requestParam = request ? `request: ${typeSpelling(request)}, ` : "";
|
|
379
|
+
const payload = request ? (request.kind === "bytes" ? "request" : encode(request, "request")) : "new Uint8Array(0)";
|
|
380
|
+
const routeType = operation.stream === null ? "ServiceRoute" : "ServiceStreamRoute";
|
|
381
|
+
out += `\nexport function ${fn}(${requestParam}route: ${routeType}<Msg, ${typeSpelling(operation.result)}>): Cmd<Msg> {\n`;
|
|
382
|
+
out += operation.stream === null
|
|
383
|
+
? ` return Cmd.serviceRequest(${JSON.stringify(operation.name)}, ${payload}, route);\n}\n`
|
|
384
|
+
: ` return Cmd.serviceStreamRequest(${JSON.stringify(operation.name)}, route.channelKey, ${payload}, route, ${operation.stream.in_flight});\n}\n`;
|
|
385
|
+
}
|
|
386
|
+
return out;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export function emitServiceContract(
|
|
390
|
+
tast: TypedAst,
|
|
391
|
+
table: TypeTable,
|
|
392
|
+
infer: IntInference,
|
|
393
|
+
files: readonly ts.SourceFile[],
|
|
394
|
+
hostFiles: readonly ts.SourceFile[],
|
|
395
|
+
srcRoot: string,
|
|
396
|
+
packages: readonly ServicePackage[] = [],
|
|
397
|
+
): ServiceSurfaceResult {
|
|
398
|
+
const emptyTypes: ServiceTypes = { records: [], enums: [], unions: [] };
|
|
399
|
+
if (files.length === 0) return { operations: [], types: emptyTypes, diagnostics: [], contract: null, client: null };
|
|
400
|
+
|
|
401
|
+
const diagnostics: SubsetDiagnostic[] = [];
|
|
402
|
+
const operations: ServiceOperation[] = [];
|
|
403
|
+
const shapes = new ServiceShapeTable(tast, table, infer, srcRoot, files[0]);
|
|
404
|
+
const names = new Set<string>();
|
|
405
|
+
const namespaceClaims = new Map<string, ts.Node>();
|
|
406
|
+
const sourceHash = sourceGraphHash(hostFiles, srcRoot);
|
|
407
|
+
for (const file of files) {
|
|
408
|
+
const relative = path.relative(srcRoot, file.fileName).split(path.sep).join("/");
|
|
409
|
+
const module = relative.replace(/^services\//, "").replace(/\.ts$/, "");
|
|
410
|
+
const moduleName = path.posix.basename(module);
|
|
411
|
+
for (const stmt of file.statements) {
|
|
412
|
+
const claim = (name: ts.Identifier): void => {
|
|
413
|
+
if (name.text.startsWith("__nativeSdk")) {
|
|
414
|
+
diagnostics.push(report("A service declaration uses the reserved `__nativeSdk` transport-adapter prefix.", name));
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
const prior = namespaceClaims.get(name.text);
|
|
418
|
+
if (prior && prior !== stmt) {
|
|
419
|
+
diagnostics.push(makeDiagnostic(
|
|
420
|
+
"NS1038",
|
|
421
|
+
`\`${name.text}\` is also declared in the service class; module-scope type and exported value names must be unique within a compiler class.`,
|
|
422
|
+
file.fileName,
|
|
423
|
+
lineColumn(file, name.getStart(file)).line,
|
|
424
|
+
lineColumn(file, name.getStart(file)).column,
|
|
425
|
+
));
|
|
426
|
+
} else namespaceClaims.set(name.text, stmt);
|
|
427
|
+
};
|
|
428
|
+
const declaredName = (ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt)) ? stmt.name : undefined;
|
|
429
|
+
if (declaredName && !hasExportModifier(stmt) && declaredName.text.startsWith("__nativeSdk")) {
|
|
430
|
+
diagnostics.push(report("A service declaration uses the reserved `__nativeSdk` transport-adapter prefix.", declaredName));
|
|
431
|
+
}
|
|
432
|
+
if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) claim(stmt.name);
|
|
433
|
+
else if ((ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt)) && stmt.name && hasExportModifier(stmt)) claim(stmt.name);
|
|
434
|
+
else if (ts.isVariableStatement(stmt)) {
|
|
435
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
436
|
+
if (!ts.isIdentifier(decl.name)) continue;
|
|
437
|
+
if (hasExportModifier(stmt)) claim(decl.name);
|
|
438
|
+
else if (decl.name.text.startsWith("__nativeSdk")) {
|
|
439
|
+
diagnostics.push(report("A service declaration uses the reserved `__nativeSdk` transport-lowering prefix.", decl.name));
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (ts.isExportDeclaration(stmt) && !stmt.isTypeOnly) {
|
|
445
|
+
diagnostics.push(report("A service value is exported through an export list or re-export, which has no direct operation declaration.", stmt));
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (!ts.isFunctionDeclaration(stmt) || !hasExportModifier(stmt)) continue;
|
|
449
|
+
if (stmt.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)) {
|
|
450
|
+
diagnostics.push(report("A service operation is default-exported, but generated dispatch imports operations by their named exports.", stmt));
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (!stmt.name) {
|
|
454
|
+
diagnostics.push(report("A service exports an unnamed function.", stmt));
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
if (!supportedOperationIdentifier(stmt.name.text)) {
|
|
458
|
+
diagnostics.push(report(
|
|
459
|
+
`\`${stmt.name.text}\` is outside the service contract's portable identifier set (ASCII letters, digits, \`_\`, and \`$\`).`,
|
|
460
|
+
stmt.name,
|
|
461
|
+
));
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const opName = `${moduleName}.${stmt.name.text}`;
|
|
465
|
+
if (names.has(opName)) {
|
|
466
|
+
diagnostics.push(report(`The operation name \`${opName}\` is declared more than once (module basenames form the public prefix).`, stmt.name));
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
names.add(opName);
|
|
470
|
+
|
|
471
|
+
const asyncModifier = stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;
|
|
472
|
+
if (asyncModifier || stmt.asteriskToken || !stmt.body) {
|
|
473
|
+
diagnostics.push(report(`\`${opName}\` is not a synchronous function with a body.`, stmt.name));
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (stmt.parameters.length > 3 || stmt.parameters.some((parameter) => !parameter.type)) {
|
|
477
|
+
diagnostics.push(report(`\`${opName}\` does not take an explicitly annotated request, optional generated emit capability, and optional ServiceCancellation capability.`, stmt.name));
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
if (!stmt.type) {
|
|
481
|
+
diagnostics.push(report(`\`${opName}\` does not declare an explicit contract-encodable return type.`, stmt.name));
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
try {
|
|
485
|
+
let requestParameter: ts.ParameterDeclaration | null = null;
|
|
486
|
+
let streamChunk: ServiceTypeRef | null = null;
|
|
487
|
+
let cancellable = false;
|
|
488
|
+
let boundaryParameters = [...stmt.parameters];
|
|
489
|
+
const cancellationParameter = boundaryParameters[boundaryParameters.length - 1];
|
|
490
|
+
if (cancellationParameter && isServiceCancellationType(tast, cancellationParameter.type)) {
|
|
491
|
+
cancellable = true;
|
|
492
|
+
boundaryParameters = boundaryParameters.slice(0, -1);
|
|
493
|
+
}
|
|
494
|
+
if (boundaryParameters.some((parameter) => isServiceCancellationType(tast, parameter.type))) {
|
|
495
|
+
diagnostics.push(report(`\`${opName}\` places ServiceCancellation before another parameter; the generated cancellation capability must be last.`, stmt.name));
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (boundaryParameters.length > 2) {
|
|
499
|
+
diagnostics.push(report(`\`${opName}\` has more than one data parameter; service operations take at most one request followed by the generated emit capability.`, stmt.name));
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
if (boundaryParameters.length > 0) {
|
|
503
|
+
const last = boundaryParameters[boundaryParameters.length - 1];
|
|
504
|
+
if (last.type && ts.isFunctionTypeNode(last.type)) {
|
|
505
|
+
const emitType = last.type;
|
|
506
|
+
if (emitType.parameters.length !== 1 || !emitType.parameters[0].type || emitType.type.kind !== ts.SyntaxKind.VoidKeyword) {
|
|
507
|
+
diagnostics.push(report(`\`${opName}\` has an invalid emit capability; spell the last parameter as \`emit: (chunk: SharedChunk) => void\`.`, last));
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
streamChunk = shapes.ref(emitType.parameters[0].type, emitType.parameters[0]);
|
|
511
|
+
requestParameter = boundaryParameters.length === 2 ? boundaryParameters[0] : null;
|
|
512
|
+
} else {
|
|
513
|
+
if (boundaryParameters.length > 1) {
|
|
514
|
+
diagnostics.push(report(`\`${opName}\` has two data parameters; the second parameter is reserved for \`emit: (chunk: SharedChunk) => void\`.`, last));
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
requestParameter = boundaryParameters[0];
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const deadlineTag = ts.getJSDocTags(stmt).find((tag) => tag.tagName.text === "deadlineMs");
|
|
521
|
+
const deadlineText = typeof deadlineTag?.comment === "string" ? deadlineTag.comment.trim() : "";
|
|
522
|
+
const deadline = deadlineText === "" ? null : Number(deadlineText);
|
|
523
|
+
if (deadline !== null && (!Number.isSafeInteger(deadline) || deadline < 1 || deadline > 86_400_000)) {
|
|
524
|
+
diagnostics.push(report(`\`${opName}\` has an invalid @deadlineMs value; use a whole 1..86400000 millisecond deadline.`, deadlineTag ?? stmt.name));
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
const streamTag = ts.getJSDocTags(stmt).find((tag) => tag.tagName.text === "streamBuffer");
|
|
528
|
+
const streamText = typeof streamTag?.comment === "string" ? streamTag.comment.trim() : "";
|
|
529
|
+
const streamBuffer = streamText === "" ? 8 : Number(streamText);
|
|
530
|
+
if (streamChunk !== null && (!Number.isSafeInteger(streamBuffer) || streamBuffer < 1 || streamBuffer > 64)) {
|
|
531
|
+
diagnostics.push(report(`\`${opName}\` has an invalid @streamBuffer value; use a whole 1..64 in-flight chunk cap.`, streamTag ?? stmt.name));
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
const client = clientIdentifier({ name: opName, export: stmt.name.text });
|
|
535
|
+
const priorClient = operations.find((operation) => operation.client === client);
|
|
536
|
+
if (priorClient) {
|
|
537
|
+
diagnostics.push(report(`\`${opName}\` and \`${priorClient.name}\` both generate the client name \`${client}\`; rename one service module or export.`, stmt.name));
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
operations.push({
|
|
541
|
+
name: opName,
|
|
542
|
+
client,
|
|
543
|
+
module: `src/${relative}`,
|
|
544
|
+
export: stmt.name.text,
|
|
545
|
+
request: requestParameter === null
|
|
546
|
+
? { kind: "none" }
|
|
547
|
+
: shapes.ref(requestParameter.type!, requestParameter),
|
|
548
|
+
result: shapes.ref(stmt.type, stmt),
|
|
549
|
+
deadline_ms: deadline,
|
|
550
|
+
cancellable,
|
|
551
|
+
stream: streamChunk === null ? null : { chunk: streamChunk, in_flight: streamBuffer },
|
|
552
|
+
source_hash: sourceHash,
|
|
553
|
+
});
|
|
554
|
+
} catch (error) {
|
|
555
|
+
if (error instanceof ServiceShapeError) {
|
|
556
|
+
diagnostics.push(report(`${error.message}.`, error.node));
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
throw error;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const visitThrows = (node: ts.Node): void => {
|
|
565
|
+
if (ts.isThrowStatement(node) && node.expression) {
|
|
566
|
+
if (!explicitThrowIsKindTagged(tast, node.expression)) {
|
|
567
|
+
diagnostics.push(report("An explicit service throw is not an inline `{ kind, message: string }` shape.", node));
|
|
568
|
+
} else if (throwIsLexicallyCaught(node)) {
|
|
569
|
+
diagnostics.push(report("A tagged service throw is caught inside the service instead of escaping through the operation boundary.", node));
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
ts.forEachChild(node, visitThrows);
|
|
573
|
+
};
|
|
574
|
+
for (const file of hostFiles) visitThrows(file);
|
|
575
|
+
|
|
576
|
+
if (operations.length === 0 && diagnostics.length === 0) {
|
|
577
|
+
diagnostics.push(report("The service tree exports no callable operations.", files[0]));
|
|
578
|
+
}
|
|
579
|
+
const types = shapes.document();
|
|
580
|
+
if (diagnostics.length > 0) return { operations, types, diagnostics, contract: null, client: null };
|
|
581
|
+
const document = {
|
|
582
|
+
format: serviceContractFormat,
|
|
583
|
+
protocol_version: serviceProtocolVersion,
|
|
584
|
+
compiler_version: pinnedScriptcVersion(),
|
|
585
|
+
deterministic: false,
|
|
586
|
+
packages,
|
|
587
|
+
types,
|
|
588
|
+
operations,
|
|
589
|
+
};
|
|
590
|
+
return {
|
|
591
|
+
operations,
|
|
592
|
+
types,
|
|
593
|
+
diagnostics,
|
|
594
|
+
contract: `${JSON.stringify(document, null, 2)}\n`,
|
|
595
|
+
client: emitServiceClientDocument(document),
|
|
596
|
+
};
|
|
597
|
+
}
|