@astrale-os/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +42 -0
  2. package/package.json +101 -0
  3. package/src/auth/authenticate.ts +51 -0
  4. package/src/auth/check.ts +73 -0
  5. package/src/auth/compose.ts +31 -0
  6. package/src/auth/errors.ts +32 -0
  7. package/src/auth/identity.ts +15 -0
  8. package/src/auth/index.ts +11 -0
  9. package/src/auth/kernel-client.ts +107 -0
  10. package/src/auth/resolve.ts +63 -0
  11. package/src/auth/sign.ts +36 -0
  12. package/src/auth/verify.ts +138 -0
  13. package/src/define/index.ts +9 -0
  14. package/src/define/remote-function.ts +96 -0
  15. package/src/define/view.ts +91 -0
  16. package/src/deploy/check.ts +124 -0
  17. package/src/deploy/hash-spec.ts +31 -0
  18. package/src/deploy/index.ts +3 -0
  19. package/src/deploy/meta.ts +25 -0
  20. package/src/dispatch/authorize.ts +29 -0
  21. package/src/dispatch/call-remote.ts +48 -0
  22. package/src/dispatch/dispatcher.ts +257 -0
  23. package/src/dispatch/errors.ts +94 -0
  24. package/src/dispatch/execute.ts +51 -0
  25. package/src/dispatch/identity.ts +148 -0
  26. package/src/dispatch/index.ts +17 -0
  27. package/src/dispatch/resolve.ts +78 -0
  28. package/src/dispatch/self.ts +32 -0
  29. package/src/dispatch/validate.ts +41 -0
  30. package/src/domain/build-spec.ts +127 -0
  31. package/src/domain/contract.ts +41 -0
  32. package/src/domain/define.ts +168 -0
  33. package/src/domain/extend-core.ts +287 -0
  34. package/src/domain/index.ts +4 -0
  35. package/src/index.ts +77 -0
  36. package/src/method/class.ts +148 -0
  37. package/src/method/context.ts +45 -0
  38. package/src/method/index.ts +5 -0
  39. package/src/method/single.ts +133 -0
  40. package/src/server/auxiliary-routes.ts +336 -0
  41. package/src/server/config.ts +85 -0
  42. package/src/server/create.ts +249 -0
  43. package/src/server/handle.ts +37 -0
  44. package/src/server/index.ts +10 -0
  45. package/src/server/jwks.ts +18 -0
  46. package/src/server/require-env.ts +19 -0
  47. package/src/server/serving-url.ts +28 -0
  48. package/src/server/start.ts +37 -0
  49. package/src/server/worker-entry.ts +122 -0
  50. package/src/server/worker-meta.ts +25 -0
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Param / result validation helpers — Zod `safeParse` wrappers returning a
3
+ * tagged result. Callers convert a `false` outcome into a typed error:
4
+ * `SdkValidationError` (input, → 422) or `SdkResultValidationError`
5
+ * (output, → 500).
6
+ */
7
+
8
+ import type { z } from 'zod'
9
+
10
+ export type ValidationResult =
11
+ | { ok: true; data: Record<string, unknown> }
12
+ | { ok: false; issues: unknown[] }
13
+
14
+ export function validateParams(inputSchema: z.ZodType, params: unknown): ValidationResult {
15
+ const result = inputSchema.safeParse(params)
16
+ if (result.success) {
17
+ return { ok: true, data: result.data as Record<string, unknown> }
18
+ }
19
+ return { ok: false, issues: result.error.issues }
20
+ }
21
+
22
+ /**
23
+ * Result of validating a handler's output against its `outputSchema`. Unlike
24
+ * params, an output may be any shape (object, primitive, array), so `data` is
25
+ * `unknown` rather than `Record<string, unknown>`.
26
+ */
27
+ export type ResultValidationResult = { ok: true; data: unknown } | { ok: false; issues: unknown[] }
28
+
29
+ /**
30
+ * Validate a handler's return value against its `outputSchema`. Mirrors the
31
+ * kernel's `validateOutput` (`runtime/.../validation/output.ts`) so deployed
32
+ * domains enforce the same output contract as in-process methods. Returns the
33
+ * parsed `data` (applies Zod `default`/`transform`/coercions) on success.
34
+ */
35
+ export function validateResult(outputSchema: z.ZodType, result: unknown): ResultValidationResult {
36
+ const parsed = outputSchema.safeParse(result)
37
+ if (parsed.success) {
38
+ return { ok: true, data: parsed.data }
39
+ }
40
+ return { ok: false, issues: parsed.error.issues }
41
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * SDK-side spec builder: CompiledDomain → serialize → Graph.
3
+ *
4
+ * Serializes BoundMethod[] into FunctionSchema[], generates entries for
5
+ * inherited methods not covered by the domain's handlers, then delegates
6
+ * to serialize() for graph blueprint generation.
7
+ *
8
+ * Domain-side Methods are remote-bound: dispatch routes through
9
+ * `binding.remoteUrl` and never reaches the kernel sandbox. We therefore
10
+ * do NOT stamp `code` on emitted FunctionSchema entries — there is no
11
+ * sandbox-eval'able body. Only the kernel domain (compiled in-process)
12
+ * carries `code` strings.
13
+ *
14
+ * The emitted graph is absolute — the Tree produced by `serialize()` is
15
+ * already mounted at `/<origin>`, so `tree.toGraph()` lifts every internal
16
+ * relative path into its host-graph absolute form. Wire serialization is the
17
+ * caller's responsibility (`graph.toWire()`).
18
+ */
19
+
20
+ import type { Graph, WireGraph } from '@astrale-os/kernel-core'
21
+ import type { BoundMethod, FunctionSchema } from '@astrale-os/kernel-core/domain'
22
+ import type { Schema } from '@astrale-os/kernel-dsl'
23
+
24
+ import { hashInstallGraph, serialize, zodToJsonSchema } from '@astrale-os/kernel-core/domain'
25
+
26
+ import type { AnyRemoteHandler } from '../method/single'
27
+ import type { RemoteDomain } from './define'
28
+
29
+ import { extractBinding } from './contract'
30
+ import { materializeRemoteDomain } from './define'
31
+
32
+ /**
33
+ * Build the install-ready wire graph for a domain served at `url`: materialize
34
+ * the domain at its real serving URL (so every binding carries the live URL —
35
+ * the define-time compile carries none), serialize, and emit the wire form.
36
+ * This is the graph the kernel installs and re-hashes to verify. There is no
37
+ * url-less variant: an install graph without bindings is uninstallable (the
38
+ * kernel install guard rejects it).
39
+ */
40
+ export function buildInstallGraph<S extends Schema>(
41
+ domain: RemoteDomain<S>,
42
+ url: string,
43
+ ): WireGraph {
44
+ const { compiled } = materializeRemoteDomain(domain, url)
45
+ return buildSpecInternal(compiled, domain.methods, url).toWire() as WireGraph
46
+ }
47
+
48
+ /**
49
+ * Content hash of the install graph. Delegates the canonical hash to kernel-core's
50
+ * `hashInstallGraph` — the same algorithm the kernel re-runs on install to verify
51
+ * the received graph against the signed hash.
52
+ */
53
+ export function buildInstallGraphHash<S extends Schema>(
54
+ domain: RemoteDomain<S>,
55
+ url: string,
56
+ ): Promise<string> {
57
+ return hashInstallGraph(buildInstallGraph(domain, url))
58
+ }
59
+
60
+ // ── Internal ────────────────────────────────────────────────
61
+
62
+ function buildSpecInternal(
63
+ compiled: RemoteDomain['compiled'],
64
+ methods: BoundMethod<AnyRemoteHandler>[],
65
+ url: string,
66
+ ): Graph {
67
+ const serialized = serializeMethodsWithStubs(compiled, methods, url)
68
+ const tree = serialize(compiled, serialized)
69
+ // Views / RemoteFunctions are auto-materialized into the Core BEFORE
70
+ // `compileDomain` runs (see `extend-core.ts`). By the time we reach
71
+ // `serialize` here the Tree already contains their nodes/edges.
72
+ return tree.toGraph()
73
+ }
74
+
75
+ /**
76
+ * Serialize BoundMethod[] and generate stubs for methods in compiled.$.methods
77
+ * that have no corresponding BoundMethod (inherited-sealed, inherited-default).
78
+ *
79
+ * Every Method's binding defaults its `remoteUrl` to the serving URL: domain
80
+ * methods are remote-bound — the kernel dispatches them by redirecting to the
81
+ * worker — so a method node without a remote binding is uninstallable (the
82
+ * kernel install guard rejects it). An explicit per-method `remoteUrl` wins.
83
+ */
84
+ function serializeMethodsWithStubs(
85
+ compiled: RemoteDomain['compiled'],
86
+ methods: BoundMethod<AnyRemoteHandler>[],
87
+ url: string,
88
+ ): FunctionSchema[] {
89
+ const bound = new Set(methods.map((m) => m.ref))
90
+ const result = methods.map((m) => serializeFromBoundMethod(m, url))
91
+
92
+ // Generate entries for unbound methods (replaces fillMissingCallables).
93
+ // No `code` is stamped — domain-side Methods are binding-only. The `ref` MUST
94
+ // be the QUALIFIED `ResolvedMethod.ref` (`<ns>.<Type>.method.<m>`) — the exact
95
+ // form `serialize`'s method-node lookup uses; re-deriving a bare `Type.method`
96
+ // is the F11 bug (interface methods then never resolve → MISSING_HANDLER).
97
+ for (const classMethods of Object.values(compiled.$.methods)) {
98
+ for (const rm of Object.values(classMethods)) {
99
+ const ref = rm.ref
100
+ if (bound.has(ref)) continue
101
+ result.push({
102
+ ref,
103
+ inputSchema: { type: 'object' },
104
+ outputSchema: {},
105
+ output: 'value',
106
+ binding: { remoteUrl: url },
107
+ })
108
+ }
109
+ }
110
+
111
+ return result
112
+ }
113
+
114
+ function serializeFromBoundMethod(
115
+ method: BoundMethod<AnyRemoteHandler>,
116
+ url: string,
117
+ ): FunctionSchema {
118
+ const binding = extractBinding(method.handler)
119
+ return {
120
+ ref: method.ref,
121
+ inputSchema: zodToJsonSchema(method.inputSchema),
122
+ outputSchema: zodToJsonSchema(method.outputSchema),
123
+ isStatic: method.isStatic || undefined,
124
+ output: method.output,
125
+ binding: binding?.remoteUrl ? binding : { ...binding, remoteUrl: url },
126
+ }
127
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * BoundMethod → MountableContract translator.
3
+ *
4
+ * The narrow view carries only what the server's mount planner reads —
5
+ * `ref` plus optional `binding` — because the SDK's SdkDispatcher
6
+ * handles dispatch via KernelAPI.call, not via runtime contract hooks.
7
+ */
8
+
9
+ import type {
10
+ AuthPolicy,
11
+ FunctionBinding,
12
+ MountableContract,
13
+ RouteBinding,
14
+ } from '@astrale-os/kernel-api/routed'
15
+ import type { BoundMethod } from '@astrale-os/kernel-core/domain'
16
+
17
+ import type { AnyRemoteHandler } from '../method/single'
18
+
19
+ export function toSdkContract(method: BoundMethod<AnyRemoteHandler>): MountableContract {
20
+ const handler = method.handler as {
21
+ route?: RouteBinding
22
+ remoteUrl?: string
23
+ auth?: AuthPolicy
24
+ }
25
+ const binding = extractBinding(handler)
26
+ return binding === undefined ? { ref: method.ref } : { ref: method.ref, binding }
27
+ }
28
+
29
+ export function extractBinding(handler: {
30
+ route?: RouteBinding
31
+ remoteUrl?: string
32
+ auth?: AuthPolicy
33
+ }): FunctionBinding | undefined {
34
+ const { route, remoteUrl, auth } = handler
35
+ if (route === undefined && remoteUrl === undefined && auth === undefined) return undefined
36
+ const binding: FunctionBinding = {}
37
+ if (remoteUrl !== undefined) binding.remoteUrl = remoteUrl
38
+ if (route !== undefined) binding.route = route
39
+ if (auth !== undefined) binding.auth = auth
40
+ return binding
41
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * `defineRemoteDomain` — turn a typed schema + methods map into a mountable domain.
3
+ *
4
+ * When `views` and/or `remoteFunctions` entries are provided, the SDK
5
+ * auto-materializes graph nodes
6
+ * under reserved folders (`viewsFolder` / `functionsFolder`, defaults `'views'`
7
+ * / `'functions'`). Views and standalone functions materialize as canonical
8
+ * kernel `View` / `Function` classes by default (no per-domain class to
9
+ * configure). The same entries'
10
+ * `render` / `execute` handlers are mounted as Hono routes by
11
+ * `createRemoteServer`. Slug = map key.
12
+ *
13
+ * The domain definition is deployment-agnostic: it carries NO serving url. The
14
+ * url is supplied late by the spec producer (`createRemoteServer({ url })` at
15
+ * runtime, the devkit CLI offline) and stamped onto every `binding.remoteUrl`
16
+ * by `materializeRemoteDomain`. There is exactly one notion of `url` in the SDK
17
+ * — the worker serving URL, which is also `iss` and the binding base.
18
+ */
19
+
20
+ import type { FunctionBinding } from '@astrale-os/kernel-api/routed'
21
+ import type { BoundMethod, CompiledDomain } from '@astrale-os/kernel-core/domain'
22
+ import type { AnyEdgeDef, AnyNodeDef, Core, Schema } from '@astrale-os/kernel-dsl'
23
+
24
+ import { bindMethods, compileDomain } from '@astrale-os/kernel-core/domain'
25
+
26
+ import type { AnyRemoteFunctionDef, ViewDef } from '../define'
27
+ import type { SchemaMethodsImpl } from '../method/class'
28
+ import type { AnyRemoteHandler } from '../method/single'
29
+
30
+ import { DEFAULT_FUNCTIONS_FOLDER, DEFAULT_VIEWS_FOLDER, extendCore } from './extend-core'
31
+
32
+ export type RemoteDomainConfig<S extends Schema, TDeps> = {
33
+ schema: S
34
+ methods: SchemaMethodsImpl<S, TDeps>
35
+ core?: Core<S>
36
+
37
+ views?: Record<string, ViewDef<TDeps>>
38
+ viewClass?: AnyNodeDef
39
+ viewForEdgeClass?: AnyEdgeDef
40
+ viewsFolder?: string
41
+
42
+ remoteFunctions?: Record<string, AnyRemoteFunctionDef>
43
+ functionsFolder?: string
44
+ }
45
+
46
+ /** Effective bindings + folder layout for auxiliary routes, resolved against `url`. */
47
+ export type AuxiliaryMetadata = {
48
+ url: string
49
+ viewsFolder: string
50
+ functionsFolder: string
51
+ viewBindings: Record<string, FunctionBinding>
52
+ remoteFunctionBindings: Record<string, FunctionBinding>
53
+ }
54
+
55
+ export type RemoteDomain<S extends Schema = Schema> = {
56
+ /**
57
+ * Define-time compile: full domain STRUCTURE (classes, methods, and the aux
58
+ * View/Function nodes' paths/names/refs — what identity, subs, and contract
59
+ * resolution need). It carries NO `binding` values: bindings derive from the
60
+ * serving url, which only the spec producers know — they call
61
+ * `materializeRemoteDomain(domain, url)` for the install-ready compile.
62
+ */
63
+ compiled: CompiledDomain<S>
64
+ methods: BoundMethod<AnyRemoteHandler>[]
65
+ // oxlint-disable-next-line no-explicit-any
66
+ views?: Record<string, ViewDef<any>>
67
+ remoteFunctions?: Record<string, AnyRemoteFunctionDef>
68
+ /** The original config, so `materializeRemoteDomain` re-extends from source. */
69
+ config: ExtendInputs
70
+ }
71
+
72
+ /** The defineRemoteDomain inputs `materializeRemoteDomain` needs to re-extend. */
73
+ type ExtendInputs = {
74
+ userCore?: Core
75
+ viewClass?: AnyNodeDef
76
+ viewForEdgeClass?: AnyEdgeDef
77
+ viewsFolder: string
78
+ functionsFolder: string
79
+ }
80
+
81
+ export function defineRemoteDomain<TDeps>() {
82
+ return function <S extends Schema>(config: RemoteDomainConfig<S, TDeps>): RemoteDomain<S> {
83
+ const hasAux = Boolean(config.views || config.remoteFunctions)
84
+ const viewsFolder = config.viewsFolder ?? DEFAULT_VIEWS_FOLDER
85
+ const functionsFolder = config.functionsFolder ?? DEFAULT_FUNCTIONS_FOLDER
86
+
87
+ // Structure-only extension (no url → no bindings stamped): the aux nodes
88
+ // exist with their paths so subs/identity/contract resolution see them.
89
+ const effectiveCore: Core | undefined = hasAux
90
+ ? extendCore({
91
+ schema: config.schema,
92
+ origin: config.schema.domain,
93
+ userCore: config.core,
94
+ viewClass: config.viewClass,
95
+ viewForEdgeClass: config.viewForEdgeClass,
96
+ viewsFolder,
97
+ views: config.views,
98
+ functionsFolder,
99
+ remoteFunctions: config.remoteFunctions,
100
+ }).core
101
+ : config.core
102
+
103
+ const compiled = compileDomain(config.schema, effectiveCore as Core<S> | undefined)
104
+ const methods = bindMethods<AnyRemoteHandler>(
105
+ compiled.$.schema,
106
+ compiled.$.methods,
107
+ // oxlint-disable-next-line no-explicit-any
108
+ config.methods as any,
109
+ )
110
+
111
+ return Object.freeze({
112
+ compiled,
113
+ methods,
114
+ ...(config.views ? { views: config.views } : {}),
115
+ ...(config.remoteFunctions ? { remoteFunctions: config.remoteFunctions } : {}),
116
+ config: {
117
+ userCore: config.core,
118
+ viewClass: config.viewClass,
119
+ viewForEdgeClass: config.viewForEdgeClass,
120
+ viewsFolder,
121
+ functionsFolder,
122
+ },
123
+ })
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Materialize a `RemoteDomain` at its real serving `url`: re-runs `extendCore`
129
+ * so every aux View/Function `binding.remoteUrl` points at the actual host,
130
+ * and returns the binding maps the auxiliary routes mount from. Called by the
131
+ * only two spec producers — `createRemoteServer` (`config.url`) and the devkit
132
+ * CLI. Returns the define-time `compiled` untouched when there is no aux to
133
+ * stamp. `extendCore`/`compileDomain` are pure, so this is safe to call
134
+ * repeatedly (and is memoized per cold isolate by the callers).
135
+ */
136
+ export function materializeRemoteDomain<S extends Schema>(
137
+ domain: RemoteDomain<S>,
138
+ url: string,
139
+ ): { compiled: CompiledDomain<S>; auxiliary: AuxiliaryMetadata | undefined } {
140
+ const hasAux = Boolean(domain.views || domain.remoteFunctions)
141
+ if (!hasAux) return { compiled: domain.compiled, auxiliary: undefined }
142
+
143
+ const { config } = domain
144
+ const schema = domain.compiled.$.schema as S
145
+ const result = extendCore({
146
+ schema,
147
+ origin: schema.domain,
148
+ userCore: config.userCore,
149
+ url,
150
+ viewClass: config.viewClass,
151
+ viewForEdgeClass: config.viewForEdgeClass,
152
+ viewsFolder: config.viewsFolder,
153
+ views: domain.views,
154
+ functionsFolder: config.functionsFolder,
155
+ remoteFunctions: domain.remoteFunctions,
156
+ })
157
+ const compiled = compileDomain(schema, result.core as Core<S>)
158
+ return {
159
+ compiled,
160
+ auxiliary: {
161
+ url,
162
+ viewsFolder: config.viewsFolder,
163
+ functionsFolder: config.functionsFolder,
164
+ viewBindings: result.viewBindings,
165
+ remoteFunctionBindings: result.remoteFunctionBindings,
166
+ },
167
+ }
168
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Build an augmented `Core<S>` that includes auto-materialized View and
3
+ * standalone-function nodes (one per entry in `defineRemoteDomain`'s `views` /
4
+ * `remoteFunctions` config), plus their parent Folder + optional `view_for`
5
+ * edges. Returns the resolved effective bindings alongside so callers don't
6
+ * recompute them.
7
+ *
8
+ * Standalone callables (the former `RemoteFunction` class) are materialized as
9
+ * the canonical kernel `Function` node class — "remote" is just a `binding`,
10
+ * not a distinct kind, so there is no per-domain class to configure.
11
+ *
12
+ * Conflicts: if the user core already declares a top-level node at
13
+ * `<viewsFolder>` or `<functionsFolder>`, throws — the auto-materialization
14
+ * reserves those slugs.
15
+ */
16
+
17
+ import type { FunctionBinding } from '@astrale-os/kernel-api/routed'
18
+ import type {
19
+ AnyEdgeDef,
20
+ AnyNodeDef,
21
+ Core,
22
+ CoreEdgeEntry,
23
+ CoreNodeEntry,
24
+ Schema,
25
+ } from '@astrale-os/kernel-dsl'
26
+
27
+ import { Folder, K, KernelSchema } from '@astrale-os/kernel-core'
28
+ import { buildCorePath } from '@astrale-os/kernel-dsl'
29
+
30
+ /** Canonical node class for standalone callables (the former `RemoteFunction`). */
31
+ const FUNCTION_CLASS = KernelSchema.classes.Function as unknown as AnyNodeDef
32
+ /** Canonical node class for GUI views. */
33
+ const VIEW_CLASS = KernelSchema.classes.View as unknown as AnyNodeDef
34
+ /** Canonical edge class linking a View to its target. */
35
+ const VIEW_FOR_EDGE_CLASS = KernelSchema.classes.view_for as unknown as AnyEdgeDef
36
+
37
+ import type { AnyRemoteFunctionDef } from '../define/remote-function'
38
+ import type { ViewDef } from '../define/view'
39
+
40
+ export const DEFAULT_VIEWS_FOLDER = 'views'
41
+ export const DEFAULT_FUNCTIONS_FOLDER = 'functions'
42
+ const SLUG_RE = /^[a-z][a-z0-9-]*$/
43
+
44
+ export type ExtendCoreConfig = {
45
+ schema: Schema
46
+ origin: string
47
+ userCore?: Core
48
+ /**
49
+ * The worker's serving URL — the base every auto-materialized binding
50
+ * resolves against. OMITTED at define time (the URL is known only to the
51
+ * spec producers): the aux nodes then materialize structure-only (paths,
52
+ * names, refs — what identity/subs resolution needs) with no `binding`
53
+ * stamped and empty binding maps. Every install graph comes from a
54
+ * `materializeRemoteDomain(domain, url)` call where it is present.
55
+ */
56
+ url?: string
57
+
58
+ viewClass?: AnyNodeDef
59
+ viewForEdgeClass?: AnyEdgeDef
60
+ viewsFolder?: string
61
+ // oxlint-disable-next-line no-explicit-any
62
+ views?: Record<string, ViewDef<any>>
63
+
64
+ functionsFolder?: string
65
+ remoteFunctions?: Record<string, AnyRemoteFunctionDef>
66
+ }
67
+
68
+ export type ExtendCoreResult = {
69
+ core: Core
70
+ viewBindings: Record<string, FunctionBinding>
71
+ remoteFunctionBindings: Record<string, FunctionBinding>
72
+ }
73
+
74
+ export function extendCore(config: ExtendCoreConfig): ExtendCoreResult {
75
+ const {
76
+ schema,
77
+ origin,
78
+ userCore,
79
+ url,
80
+ viewClass = VIEW_CLASS,
81
+ viewForEdgeClass = VIEW_FOR_EDGE_CLASS,
82
+ viewsFolder = DEFAULT_VIEWS_FOLDER,
83
+ views,
84
+ functionsFolder = DEFAULT_FUNCTIONS_FOLDER,
85
+ remoteFunctions,
86
+ } = config
87
+
88
+ validateInputs(config)
89
+
90
+ const nodes: CoreNodeEntry[] = userCore ? [...userCore.__nodes] : []
91
+ const edges: CoreEdgeEntry[] = userCore ? [...userCore.__edges] : []
92
+ const viewBindings: Record<string, FunctionBinding> = {}
93
+ const remoteFunctionBindings: Record<string, FunctionBinding> = {}
94
+
95
+ if (views && viewClass) {
96
+ // Enforce ViewDef's documented exclusivity: `mount` (SPA route) cannot be
97
+ // combined with `render` (inline HTML handler) or an explicit `binding` —
98
+ // silently ignoring one of them would deploy a view that behaves
99
+ // differently than its definition reads.
100
+ for (const [slug, def] of Object.entries(views)) {
101
+ if (def.mount && (def.render || def.binding)) {
102
+ throw new Error(
103
+ `defineRemoteDomain: view "${slug}" sets \`mount\` together with ` +
104
+ `${def.render ? '`render`' : '`binding`'} — they are mutually exclusive.`,
105
+ )
106
+ }
107
+ }
108
+ assertNoConflict(nodes, origin, viewsFolder)
109
+ addFolderAndEntries({
110
+ origin,
111
+ folderSlug: viewsFolder,
112
+ nodes,
113
+ entries: Object.entries(views).map(([slug, def]) => {
114
+ const binding = url
115
+ ? def.mount
116
+ ? { remoteUrl: joinWorkerPath(url, def.mount) }
117
+ : resolveBinding(def.binding, url, viewsFolder, slug)
118
+ : undefined
119
+ if (binding) viewBindings[slug] = binding
120
+ return {
121
+ slug,
122
+ nodeClass: viewClass,
123
+ data: buildFunctionData(slug, binding),
124
+ edges: buildViewForEdges(slug, def, viewForEdgeClass, viewsFolder, origin),
125
+ }
126
+ }),
127
+ edges,
128
+ })
129
+ }
130
+
131
+ if (remoteFunctions) {
132
+ assertNoConflict(nodes, origin, functionsFolder)
133
+ addFolderAndEntries({
134
+ origin,
135
+ folderSlug: functionsFolder,
136
+ nodes,
137
+ entries: Object.entries(remoteFunctions).map(([slug, def]) => {
138
+ const binding = url ? resolveBinding(def.binding, url, functionsFolder, slug) : undefined
139
+ if (binding) remoteFunctionBindings[slug] = binding
140
+ return {
141
+ slug,
142
+ // Standalone callables materialize as the canonical kernel Function class.
143
+ nodeClass: FUNCTION_CLASS,
144
+ data: {
145
+ ...buildFunctionData(slug, binding),
146
+ [K.$.i('Function').ref.key]: def.ref ?? `function.${slug}`,
147
+ },
148
+ edges: [],
149
+ }
150
+ }),
151
+ edges,
152
+ })
153
+ }
154
+
155
+ return {
156
+ core: { schema, domain: origin, __nodes: nodes, __edges: edges },
157
+ viewBindings,
158
+ remoteFunctionBindings,
159
+ }
160
+ }
161
+
162
+ /** Join a worker-relative mount path onto the serving url (single slash). */
163
+ function joinWorkerPath(url: string, mount: string): string {
164
+ const base = url.replace(/\/+$/, '')
165
+ return `${base}/${mount.replace(/^\/+/, '')}`
166
+ }
167
+
168
+ export function resolveBinding(
169
+ override: FunctionBinding | undefined,
170
+ url: string,
171
+ folderSlug: string,
172
+ slug: string,
173
+ ): FunctionBinding {
174
+ // Same trailing-slash discipline as `joinWorkerPath` — a `url` ending in `/`
175
+ // must not produce `//` in the binding (the kernel pins iss by exact string).
176
+ const base = url.replace(/\/+$/, '')
177
+ if (override) {
178
+ return {
179
+ ...override,
180
+ remoteUrl: override.remoteUrl ?? `${base}/${folderSlug}/${slug}`,
181
+ }
182
+ }
183
+ return { remoteUrl: `${base}/${folderSlug}/${slug}` }
184
+ }
185
+
186
+ // ── Internal ───────────────────────────────────────────────────────────────
187
+
188
+ function validateInputs(config: ExtendCoreConfig): void {
189
+ if (config.views) {
190
+ for (const slug of Object.keys(config.views)) {
191
+ if (!SLUG_RE.test(slug)) {
192
+ throw new Error(`defineRemoteDomain: invalid view slug "${slug}" — must match ${SLUG_RE}.`)
193
+ }
194
+ }
195
+ }
196
+ if (config.remoteFunctions) {
197
+ for (const slug of Object.keys(config.remoteFunctions)) {
198
+ if (!SLUG_RE.test(slug)) {
199
+ throw new Error(
200
+ `defineRemoteDomain: invalid remote-function slug "${slug}" — must match ${SLUG_RE}.`,
201
+ )
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ function assertNoConflict(
208
+ nodes: readonly CoreNodeEntry[],
209
+ origin: string,
210
+ folderSlug: string,
211
+ ): void {
212
+ const folderPath = buildCorePath(origin, [folderSlug])
213
+ if (nodes.some((n) => n.path === folderPath)) {
214
+ throw new Error(
215
+ `defineRemoteDomain: top-level core slug "${folderSlug}" is reserved by ` +
216
+ 'SDK auto-materialization. Move the conflicting node or rename the ' +
217
+ '`viewsFolder` / `functionsFolder` config.',
218
+ )
219
+ }
220
+ }
221
+
222
+ type EntryDescriptor = {
223
+ slug: string
224
+ nodeClass: AnyNodeDef
225
+ data: Record<string, unknown>
226
+ edges: CoreEdgeEntry[]
227
+ }
228
+
229
+ function addFolderAndEntries(args: {
230
+ origin: string
231
+ folderSlug: string
232
+ entries: EntryDescriptor[]
233
+ nodes: CoreNodeEntry[]
234
+ edges: CoreEdgeEntry[]
235
+ }): void {
236
+ const { origin, folderSlug, entries, nodes, edges } = args
237
+
238
+ const folderPath = buildCorePath(origin, [folderSlug])
239
+ nodes.push({
240
+ path: folderPath,
241
+ def: Folder as unknown as AnyNodeDef,
242
+ data: { [K.Named.name.key]: folderSlug },
243
+ })
244
+
245
+ for (const entry of entries) {
246
+ nodes.push({
247
+ path: buildCorePath(origin, [folderSlug, entry.slug]),
248
+ def: entry.nodeClass,
249
+ data: entry.data,
250
+ parent: folderPath,
251
+ })
252
+ for (const e of entry.edges) edges.push(e)
253
+ }
254
+ }
255
+
256
+ function buildFunctionData(
257
+ slug: string,
258
+ binding: FunctionBinding | undefined,
259
+ ): Record<string, unknown> {
260
+ // Match the kernel-core schema serializer which JSON-stringifies the
261
+ // `Function.binding` value on Function nodes (see
262
+ // kernel/core/domain/serialize/schema.ts). The kernel install validator
263
+ // checks `typeof binding === 'string'` then parses; storing a raw object
264
+ // trips the validator with "missing remote binding" even when the object IS
265
+ // the binding. No binding at all (define-time, no url) → no prop stamped.
266
+ return {
267
+ [K.Named.name.key]: slug,
268
+ ...(binding ? { [K.$.i('Function').binding.key]: JSON.stringify(binding) } : {}),
269
+ }
270
+ }
271
+
272
+ function buildViewForEdges(
273
+ slug: string,
274
+ def: ViewDef,
275
+ edgeClass: AnyEdgeDef | undefined,
276
+ viewsFolder: string,
277
+ origin: string,
278
+ ): CoreEdgeEntry[] {
279
+ if (!def.viewFor || !edgeClass) return []
280
+ const targets = Array.isArray(def.viewFor) ? def.viewFor : [def.viewFor]
281
+ const from = buildCorePath(origin, [viewsFolder, slug])
282
+ return targets.map((target) => ({
283
+ from,
284
+ edge: edgeClass,
285
+ to: target as CoreEdgeEntry['to'],
286
+ }))
287
+ }
@@ -0,0 +1,4 @@
1
+ export { defineRemoteDomain } from './define'
2
+ export type { RemoteDomain, RemoteDomainConfig } from './define'
3
+ export { buildInstallGraph, buildInstallGraphHash } from './build-spec'
4
+ export { toSdkContract } from './contract'