@spellkave/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +89 -0
  2. package/README.md +155 -2
  3. package/package.json +63 -4
  4. package/src/binding_rows.ts +186 -0
  5. package/src/connection.ts +964 -0
  6. package/src/core/actor.ts +62 -0
  7. package/src/core/actor_control.ts +193 -0
  8. package/src/core/actor_control_query_methods.ts +101 -0
  9. package/src/core/actor_control_reaction_methods.ts +79 -0
  10. package/src/core/actor_control_sense_methods.ts +81 -0
  11. package/src/core/actor_control_source.ts +57 -0
  12. package/src/core/actor_session_methods.ts +226 -0
  13. package/src/core/binding_drift.ts +301 -0
  14. package/src/core/credential.ts +259 -0
  15. package/src/core/driver_control.ts +54 -0
  16. package/src/core/effective_environment_state.ts +71 -0
  17. package/src/core/factored_manipulation_attempt.ts +158 -0
  18. package/src/core/ids.ts +60 -0
  19. package/src/core/interaction/canonical.ts +15 -0
  20. package/src/core/interaction/fingerprint.ts +118 -0
  21. package/src/core/interaction/index.ts +31 -0
  22. package/src/core/interaction/intent.ts +284 -0
  23. package/src/core/interaction/outcome.ts +67 -0
  24. package/src/core/interaction/rejection_ledger.ts +108 -0
  25. package/src/core/kernel_contract.generated.ts +10 -0
  26. package/src/core/log.ts +23 -0
  27. package/src/core/movement.ts +111 -0
  28. package/src/core/node-io.ts +208 -0
  29. package/src/core/paths.ts +220 -0
  30. package/src/core/profile.ts +270 -0
  31. package/src/core/profiles.ts +9 -0
  32. package/src/core/provenance_buffer.ts +102 -0
  33. package/src/core/readers/_helpers.ts +273 -0
  34. package/src/core/readers/action_description.ts +17 -0
  35. package/src/core/readers/action_economy_events.ts +149 -0
  36. package/src/core/readers/actor_body_swaps.ts +62 -0
  37. package/src/core/readers/actor_snapshot.ts +197 -0
  38. package/src/core/readers/actor_states.ts +163 -0
  39. package/src/core/readers/actors_and_bodies.ts +179 -0
  40. package/src/core/readers/affordance_cue.ts +59 -0
  41. package/src/core/readers/affordance_defaults.ts +158 -0
  42. package/src/core/readers/affordance_group_membership.ts +67 -0
  43. package/src/core/readers/affordance_input.ts +129 -0
  44. package/src/core/readers/affordance_reference.ts +41 -0
  45. package/src/core/readers/apply_consequences.ts +54 -0
  46. package/src/core/readers/audience_trace_presentation.ts +62 -0
  47. package/src/core/readers/bounded_collection.ts +29 -0
  48. package/src/core/readers/bundle_definitions.ts +74 -0
  49. package/src/core/readers/bundle_entities.ts +62 -0
  50. package/src/core/readers/co_location.ts +71 -0
  51. package/src/core/readers/combat_session.ts +124 -0
  52. package/src/core/readers/combat_session_active.ts +44 -0
  53. package/src/core/readers/combat_session_feedback.ts +37 -0
  54. package/src/core/readers/combat_session_grid.ts +117 -0
  55. package/src/core/readers/combat_session_roster.ts +98 -0
  56. package/src/core/readers/combat_session_types.ts +51 -0
  57. package/src/core/readers/condition_deltas.ts +53 -0
  58. package/src/core/readers/container_contents.ts +92 -0
  59. package/src/core/readers/dialogue_guide.ts +99 -0
  60. package/src/core/readers/dialogue_prompt_presentation.ts +90 -0
  61. package/src/core/readers/driver_control.ts +64 -0
  62. package/src/core/readers/entity_art.ts +219 -0
  63. package/src/core/readers/entity_containment.ts +119 -0
  64. package/src/core/readers/equipment.ts +99 -0
  65. package/src/core/readers/intervention_windows.ts +136 -0
  66. package/src/core/readers/inventory_query.ts +145 -0
  67. package/src/core/readers/item_detail.ts +198 -0
  68. package/src/core/readers/location_snapshot.ts +216 -0
  69. package/src/core/readers/manifest_apply_provenance.ts +32 -0
  70. package/src/core/readers/manifest_export.ts +81 -0
  71. package/src/core/readers/manipulation_context.ts +475 -0
  72. package/src/core/readers/map_layers.ts +49 -0
  73. package/src/core/readers/metadata_rows.ts +56 -0
  74. package/src/core/readers/object_state.ts +124 -0
  75. package/src/core/readers/observer_knowledge.ts +41 -0
  76. package/src/core/readers/observer_place_knowledge.ts +37 -0
  77. package/src/core/readers/observer_trace_knowledge.ts +45 -0
  78. package/src/core/readers/outcome_template.ts +41 -0
  79. package/src/core/readers/place_topology.ts +109 -0
  80. package/src/core/readers/reaction_options.ts +156 -0
  81. package/src/core/readers/resource_deltas.ts +47 -0
  82. package/src/core/readers/scene.ts +275 -0
  83. package/src/core/readers/seats.ts +33 -0
  84. package/src/core/readers/self.ts +245 -0
  85. package/src/core/readers/self_capabilities.ts +159 -0
  86. package/src/core/readers/self_economy.ts +101 -0
  87. package/src/core/readers/self_economy_budget.ts +93 -0
  88. package/src/core/readers/self_evaluations.ts +128 -0
  89. package/src/core/readers/self_identity.ts +104 -0
  90. package/src/core/readers/sense_context.ts +112 -0
  91. package/src/core/readers/session.ts +207 -0
  92. package/src/core/readers/session_detail.ts +211 -0
  93. package/src/core/readers/session_status.ts +68 -0
  94. package/src/core/readers/spatial_environment_state.ts +74 -0
  95. package/src/core/readers/spatial_niche_attachments.ts +28 -0
  96. package/src/core/readers/substrate_definitions.ts +27 -0
  97. package/src/core/readers/suggest_next_action.ts +72 -0
  98. package/src/core/readers/surface_membership.ts +78 -0
  99. package/src/core/readers/tag_reads.ts +54 -0
  100. package/src/core/readers/trace_query.ts +120 -0
  101. package/src/core/readers/trace_response.ts +80 -0
  102. package/src/core/readers/traces.ts +124 -0
  103. package/src/core/readers/travel_session.ts +88 -0
  104. package/src/core/readers/turn_state.ts +34 -0
  105. package/src/core/readers/world_events.ts +43 -0
  106. package/src/core/readers/world_status.ts +63 -0
  107. package/src/core/reducers/manipulation_args.ts +239 -0
  108. package/src/core/reducers/manipulation_receipt.ts +66 -0
  109. package/src/core/reducers/r_actor_wake_up.ts +32 -0
  110. package/src/core/reducers/r_inscribe_trace.ts +109 -0
  111. package/src/core/reducers/r_manipulate.ts +163 -0
  112. package/src/core/reducers/r_move.ts +155 -0
  113. package/src/core/reducers/r_react.ts +143 -0
  114. package/src/core/reducers/r_release_claim.ts +81 -0
  115. package/src/core/reducers/r_sense.ts +84 -0
  116. package/src/core/reducers/r_session_close.ts +130 -0
  117. package/src/core/reducers/r_session_move.ts +116 -0
  118. package/src/core/reducers/r_session_open.ts +91 -0
  119. package/src/core/reducers/session_lookup.ts +64 -0
  120. package/src/core/reducers/tick.ts +65 -0
  121. package/src/core/reducers/trace_lookup.ts +29 -0
  122. package/src/core/reducers/transport.ts +84 -0
  123. package/src/core/resolve.ts +228 -0
  124. package/src/core/shape_telemetry.ts +146 -0
  125. package/src/core/snapshot_rows.ts +109 -0
  126. package/src/core/tick_cadence.ts +61 -0
  127. package/src/core/types.ts +501 -0
  128. package/src/core/watch_provenance.ts +113 -0
  129. package/src/core/world-contract/classify.ts +38 -0
  130. package/src/core/world-contract/index.ts +12 -0
  131. package/src/core/world-contract/normalise.ts +574 -0
  132. package/src/core/world-contract/runtime.ts +144 -0
  133. package/src/core/world-contract/served.ts +173 -0
  134. package/src/core/world-contract/strict-reducers.ts +14 -0
  135. package/src/core/world-contract/typetext.ts +94 -0
  136. package/src/core/world_time.ts +22 -0
  137. package/src/index.ts +262 -0
  138. package/src/manifest-apply.ts +497 -0
  139. package/src/provenance.ts +568 -0
  140. package/src/reader-manifest.ts +338 -0
  141. package/src/readers.ts +392 -0
  142. package/src/replay.ts +515 -0
  143. package/src/watch-buffer.ts +438 -0
  144. package/src/world-events/builder.ts +1042 -0
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The connect-time verdict (sk-jay0.7.389.3): can THIS built client decode the
3
+ * rows and call the reducers it uses on THAT served module? A different
4
+ * question from the publish verdict in `classify.ts` (can the database
5
+ * migrate?), so a different rule set:
6
+ *
7
+ * - Rows are decoded positionally and sequentially: the TypeScript SDK reads
8
+ * a row list as `while (reader.remaining > 0) deserializeRow(reader)`
9
+ * (spacetimedb 2.10.1 `#parseRowList`). ANY difference in a consumed
10
+ * column list — an appended defaulted column included, either side —
11
+ * mis-decodes every row after the first. Breaking.
12
+ * - A named type a consumed column or argument reaches: any change breaks
13
+ * decoding, except a sum type the CLIENT extends (variants appended only
14
+ * on the client side: client newer than server, the roll window between
15
+ * image apply and world load) — the server never sends them.
16
+ * - Reducers the client calls: removed, turned internal, changed arguments
17
+ * (types, order, arity) or return types break the call. Breaking.
18
+ * - Access: a consumed table or view the server made private refuses the
19
+ * subscription. Breaking. View parameters and return shape: breaking.
20
+ * - Everything that does not touch BSATN or the call — indexes, unique and
21
+ * primary keys, auto-inc, schedules, table kind or event flag, view
22
+ * anonymity, default values, private -> public — is a diagnostic.
23
+ *
24
+ * Inputs are the client contract and the served items it names, both with
25
+ * names folded (`normalise.ts` `foldNames`).
26
+ */
27
+ import type { SchemaSnapshot, SchemaTable, SchemaView } from "./classify.ts";
28
+
29
+ export interface RuntimeChange {
30
+ readonly verdict: "breaking" | "diagnostic";
31
+ readonly item: string;
32
+ /** Reads client -> server. */
33
+ readonly detail: string;
34
+ }
35
+
36
+ const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
37
+ const withoutDefault = (c: string) => c.replace(/ = 0x[0-9a-f]*$/, "");
38
+
39
+ function columns(item: string, client: readonly string[], server: readonly string[], out: RuntimeChange[]) {
40
+ const c = client.map(withoutDefault);
41
+ const s = server.map(withoutDefault);
42
+ const n = Math.max(c.length, s.length);
43
+ for (let i = 0; i < n; i++) {
44
+ if (c[i] === s[i]) continue;
45
+ const detail =
46
+ c[i] === undefined
47
+ ? `column ${s[i]} exists only on the server (rows are decoded positionally)`
48
+ : s[i] === undefined
49
+ ? `column ${c[i]} exists only on the client`
50
+ : `column ${i + 1} changed: ${c[i]} -> ${s[i]}`;
51
+ out.push({ verdict: "breaking", item, detail });
52
+ }
53
+ if (!same(client, server) && same(c, s)) out.push({ verdict: "diagnostic", item, detail: "column defaults differ" });
54
+ }
55
+
56
+ function table(name: string, client: SchemaTable, server: SchemaTable, out: RuntimeChange[]) {
57
+ const item = `table ${name}`;
58
+ if (client.access !== server.access) {
59
+ out.push({
60
+ verdict: server.access === "private" ? "breaking" : "diagnostic",
61
+ item,
62
+ detail: `access ${client.access} -> ${server.access}`,
63
+ });
64
+ }
65
+ columns(item, client.columns, server.columns, out);
66
+ const notes: [string, unknown, unknown][] = [
67
+ ["primary key", client.primaryKey, server.primaryKey],
68
+ ["unique constraints", client.unique, server.unique],
69
+ ["indexes", client.indexes, server.indexes],
70
+ ["auto-inc columns", client.autoInc, server.autoInc],
71
+ ["schedule", client.schedule ?? null, server.schedule ?? null],
72
+ ["table kind", [client.kind, client.event], [server.kind, server.event]],
73
+ ];
74
+ for (const [what, c, s] of notes) {
75
+ if (!same(c, s)) out.push({ verdict: "diagnostic", item, detail: `${what} differ: ${JSON.stringify(c)} -> ${JSON.stringify(s)}` });
76
+ }
77
+ }
78
+
79
+ function view(name: string, client: SchemaView, server: SchemaView, out: RuntimeChange[]) {
80
+ const item = `view ${name}`;
81
+ if (client.public !== server.public) {
82
+ out.push({ verdict: server.public ? "diagnostic" : "breaking", item, detail: `public ${client.public} -> ${server.public}` });
83
+ }
84
+ if (client.anonymous !== server.anonymous) {
85
+ out.push({ verdict: "diagnostic", item, detail: `anonymous ${client.anonymous} -> ${server.anonymous}` });
86
+ }
87
+ if (!same(client.params, server.params)) {
88
+ out.push({ verdict: "breaking", item, detail: `parameters (${client.params.join(", ")}) -> (${server.params.join(", ")})` });
89
+ }
90
+ if (client.returns !== server.returns) {
91
+ out.push({ verdict: "breaking", item, detail: `return shape ${client.returns} -> ${server.returns}` });
92
+ }
93
+ columns(item, client.columns ?? [], server.columns ?? [], out);
94
+ }
95
+
96
+ function namedType(name: string, client: unknown, server: unknown, out: RuntimeChange[]) {
97
+ if (same(client, server)) return;
98
+ const item = `type ${name}`;
99
+ const c = client as { sum?: string[] };
100
+ const s = server as { sum?: string[] };
101
+ if (c.sum && s.sum && s.sum.length < c.sum.length && same(c.sum.slice(0, s.sum.length), s.sum)) {
102
+ out.push({ verdict: "diagnostic", item, detail: `variants only on the client: ${c.sum.slice(s.sum.length).join(", ")}` });
103
+ return;
104
+ }
105
+ out.push({ verdict: "breaking", item, detail: `shape ${JSON.stringify(client)} -> ${JSON.stringify(server)}` });
106
+ }
107
+
108
+ /** Client contract vs served items, both folded. */
109
+ export function classifyRuntimeChange(client: SchemaSnapshot, server: SchemaSnapshot): RuntimeChange[] {
110
+ const out: RuntimeChange[] = [];
111
+ for (const [name, c] of Object.entries(client.tables)) {
112
+ const s = server.tables[name];
113
+ if (s) table(name, c, s, out);
114
+ else out.push({ verdict: "breaking", item: `table ${name}`, detail: server.views[name] ? "is a view on the server" : "absent on the server" });
115
+ }
116
+ for (const [name, c] of Object.entries(client.views)) {
117
+ const s = server.views[name];
118
+ if (s) view(name, c, s, out);
119
+ else out.push({ verdict: "breaking", item: `view ${name}`, detail: server.tables[name] ? "is a table on the server" : "absent on the server" });
120
+ }
121
+ for (const [name, c] of Object.entries(client.reducers)) {
122
+ const item = `reducer ${name}`;
123
+ const s = server.reducers[name];
124
+ if (!s) {
125
+ out.push({ verdict: "breaking", item, detail: "absent on the server" });
126
+ continue;
127
+ }
128
+ if (c.visibility !== s.visibility) {
129
+ out.push({ verdict: s.visibility === "client" ? "diagnostic" : "breaking", item, detail: `visibility ${c.visibility} -> ${s.visibility}` });
130
+ }
131
+ if (!same(c.params, s.params)) {
132
+ out.push({ verdict: "breaking", item, detail: `arguments (${c.params.join(", ")}) -> (${s.params.join(", ")})` });
133
+ }
134
+ if (c.ok !== s.ok || c.err !== s.err) {
135
+ out.push({ verdict: "breaking", item, detail: `return type ok ${c.ok}, err ${c.err} -> ok ${s.ok}, err ${s.err}` });
136
+ }
137
+ }
138
+ // A type the client reaches but the server does not name any more shows up
139
+ // as the column or argument that stopped mentioning it.
140
+ for (const [name, c] of Object.entries(client.types)) {
141
+ if (name in server.types) namedType(name, c, server.types[name], out);
142
+ }
143
+ return out;
144
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Encodes a kernel schema snapshot back into the served SATS-JSON shape of
3
+ * `/v1/database/<db>/schema?version=10` — the inverse of
4
+ * {@link normaliseModuleDef} for every field the snapshot keeps. For tests and
5
+ * fixtures: a connect test can serve exactly the module a client was built
6
+ * for, or a deliberately altered one, without a node.
7
+ */
8
+ import type { SchemaSnapshot } from "./classify.ts";
9
+ import { nameAndType, splitTop } from "./typetext.ts";
10
+
11
+ type Json = unknown;
12
+ const unit: Json = [];
13
+ const some = (v: Json) => ({ some: v });
14
+ const SPECIAL: Record<string, [string, string]> = {
15
+ Identity: ["__identity__", "U256"],
16
+ ConnectionId: ["__connection_id__", "U128"],
17
+ Timestamp: ["__timestamp_micros_since_unix_epoch__", "I64"],
18
+ TimeDuration: ["__time_duration_micros__", "I64"],
19
+ Uuid: ["__uuid__", "U128"],
20
+ };
21
+ const PRIMITIVES = new Set([
22
+ "Bool", "I8", "U8", "I16", "U16", "I32", "U32", "I64", "U64", "I128", "U128", "I256", "U256", "F32", "F64", "String",
23
+ ]);
24
+
25
+ const element = (name: string, ty: Json) => ({ name: some(name), algebraic_type: ty });
26
+ const product = (elements: Json[]) => ({ Product: { elements } });
27
+
28
+ export function servedSchemaFromSnapshot(snapshot: SchemaSnapshot): Json {
29
+ const typespace: Json[] = [];
30
+ const typeIndex = new Map<string, number>();
31
+ for (const name of Object.keys(snapshot.types)) {
32
+ typeIndex.set(name, typespace.length);
33
+ typespace.push(null);
34
+ }
35
+ const parse = (text: string): Json => {
36
+ const t = text.trim();
37
+ if (PRIMITIVES.has(t)) return { [t]: unit };
38
+ if (t === "()") return product([]);
39
+ const special = SPECIAL[t];
40
+ if (special) return product([element(special[0], { [special[1]]: unit })]);
41
+ if (t.startsWith("Array<")) return { Array: parse(t.slice(6, -1)) };
42
+ if (t.startsWith("Option<")) {
43
+ return { Sum: { variants: [element("some", parse(t.slice(7, -1))), element("none", product([]))] } };
44
+ }
45
+ if (t.startsWith("{")) {
46
+ return product(splitTop(t.slice(1, -1), ", ").map((f) => element(...withType(nameAndType(f)))));
47
+ }
48
+ if (t.startsWith("(")) {
49
+ return {
50
+ Sum: {
51
+ variants: splitTop(t.slice(1, -1), " | ").map((v) => {
52
+ const open = v.indexOf("(");
53
+ return open < 0 ? element(v, product([])) : element(v.slice(0, open), parse(v.slice(open + 1, -1)));
54
+ }),
55
+ },
56
+ };
57
+ }
58
+ const ref = typeIndex.get(t);
59
+ if (ref === undefined) throw new Error(`servedSchemaFromSnapshot: unknown type "${t}"`);
60
+ return { Ref: ref };
61
+ };
62
+ const withType = ([name, type]: [string, string]): [string, Json] => [name, parse(type)];
63
+ const columns = (cols: readonly string[]) =>
64
+ cols.map((c) => {
65
+ const [name, rest] = nameAndType(c);
66
+ const eq = rest.lastIndexOf(" = 0x");
67
+ return { name, type: eq >= 0 ? rest.slice(0, eq) : rest, def: eq >= 0 ? rest.slice(eq + 5) : undefined };
68
+ });
69
+ const row = (cols: readonly string[]) => {
70
+ typespace.push(product(columns(cols).map((c) => element(c.name, parse(c.type)))));
71
+ return typespace.length - 1;
72
+ };
73
+ for (const [name, def] of Object.entries(snapshot.types)) {
74
+ const d = def as { product?: string[]; sum?: string[]; alias?: string };
75
+ typespace[typeIndex.get(name) as number] = d.product
76
+ ? product(d.product.map((f) => element(...withType(nameAndType(f)))))
77
+ : d.sum
78
+ ? { Sum: { variants: d.sum.map((v) => element(...withType(nameAndType(v)))) } }
79
+ : parse(d.alias ?? "()");
80
+ }
81
+
82
+ const schedules: Json[] = [];
83
+ const tables = Object.entries(snapshot.tables).map(([name, t]) => {
84
+ const cols = columns(t.columns);
85
+ const id = (c: string) => cols.findIndex((x) => x.name === c);
86
+ if (t.schedule) {
87
+ const open = t.schedule.indexOf("(");
88
+ schedules.push({
89
+ source_name: some(`${name}_sched`),
90
+ table_name: name,
91
+ schedule_at_col: id(t.schedule.slice(open + 1, -1)),
92
+ function_name: t.schedule.slice(0, open),
93
+ });
94
+ }
95
+ return {
96
+ source_name: name,
97
+ product_type_ref: row(t.columns),
98
+ primary_key: t.primaryKey.map(id),
99
+ indexes: Object.entries(t.indexes).map(([ix, text]) => {
100
+ const [accessor, rest] = nameAndType(text);
101
+ const open = rest.indexOf("(");
102
+ const algorithm = rest.slice(0, open);
103
+ const ids = splitTop(rest.slice(open + 1, -1), ", ").map(id);
104
+ const tag = { btree: "BTree", hash: "Hash", direct: "Direct" }[algorithm] ?? algorithm;
105
+ return {
106
+ source_name: some(ix),
107
+ accessor_name: accessor ? some(accessor) : { none: unit },
108
+ algorithm: { [tag]: tag === "Direct" ? ids[0] : ids },
109
+ };
110
+ }),
111
+ constraints: t.unique.map((u) => ({ source_name: some(`${name}_unique`), data: { Unique: { columns: splitTop(u, ", ").map(id) } } })),
112
+ sequences: t.autoInc.map((c) => ({ source_name: some(`${name}_${c}_seq`), column: id(c) })),
113
+ table_type: { [t.kind === "system" ? "System" : "User"]: unit },
114
+ table_access: { [t.access === "public" ? "Public" : "Private"]: unit },
115
+ default_values: cols.flatMap((c, i) => (c.def === undefined ? [] : [{ col_id: i, value: c.def }])),
116
+ is_event: t.event,
117
+ };
118
+ });
119
+ const params = (ps: readonly string[]) => ({ elements: ps.map((p) => element(...withType(nameAndType(p)))) });
120
+ const views = Object.entries(snapshot.views).map(([name, v], index) => {
121
+ let ret: Json;
122
+ if (v.columns) {
123
+ const inner = { Ref: row(v.columns) };
124
+ ret =
125
+ v.returns === "Array"
126
+ ? { Array: inner }
127
+ : v.returns === "Option"
128
+ ? { Sum: { variants: [element("some", inner), element("none", product([]))] } }
129
+ : inner;
130
+ } else ret = parse(v.returns);
131
+ return { source_name: name, index, is_public: v.public, is_anonymous: v.anonymous, params: params(v.params), return_type: ret };
132
+ });
133
+ const visibility = (v: string) => ({ [v === "client" ? "ClientCallable" : "Internal"]: unit });
134
+ return {
135
+ sections: [
136
+ { CaseConversionPolicy: { None: [] } },
137
+ { Typespace: { types: typespace } },
138
+ {
139
+ Types: Object.keys(snapshot.types).map((name) => {
140
+ const parts = name.split(".");
141
+ return { source_name: { scope: parts.slice(0, -1), source_name: parts.at(-1) }, ty: typeIndex.get(name), custom_ordering: true };
142
+ }),
143
+ },
144
+ { Tables: tables },
145
+ {
146
+ Reducers: Object.entries(snapshot.reducers).map(([name, r]) => ({
147
+ source_name: name,
148
+ params: params(r.params),
149
+ visibility: visibility(r.visibility),
150
+ ok_return_type: parse(r.ok),
151
+ err_return_type: parse(r.err),
152
+ })),
153
+ },
154
+ {
155
+ Procedures: Object.entries(snapshot.procedures).map(([name, p]) => ({
156
+ source_name: name,
157
+ params: params(p.params),
158
+ return_type: parse(p.returns),
159
+ visibility: visibility(p.visibility),
160
+ })),
161
+ },
162
+ { Views: views },
163
+ { Schedules: schedules },
164
+ {
165
+ LifeCycleReducers: Object.entries(snapshot.lifecycle).map(([hook, fn]) => ({
166
+ lifecycle_spec: { [hook]: unit },
167
+ function_name: fn,
168
+ })),
169
+ },
170
+ { ExplicitNames: { entries: [] } },
171
+ ],
172
+ };
173
+ }
@@ -0,0 +1,14 @@
1
+ // Hand-edited. The strict table surface is derived from
2
+ // CONNECTION_BASELINE union READER_SCOPED_TABLES in @spellkave/sdk's
3
+ // connection.ts.
4
+ //
5
+ // Strict reducers are the SDK-helper reducer set; add a reducer here only
6
+ // when the SDK starts calling it through the generated bindings.
7
+ export const STRICT_REDUCERS: readonly string[] = [
8
+ "r_manipulate",
9
+ "r_move",
10
+ "r_sense",
11
+ "r_session_close",
12
+ "r_session_move",
13
+ "r_session_open",
14
+ ];
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The type text grammar of the kernel schema snapshot (rendered by
3
+ * `normalise.ts`): primitives (`U64`, `String`), special products
4
+ * (`Identity`, `Timestamp`, ...), `()`, `Array<T>`, `Option<T>`,
5
+ * products `{a: T, b: U}`, sums `(A | B(T))` and named types. Parsed
6
+ * structurally so a field or variant that happens to share a type's name is
7
+ * never mistaken for a reference to it.
8
+ */
9
+
10
+ export type TypeNode =
11
+ | { readonly kind: "name"; readonly name: string }
12
+ | { readonly kind: "unit" }
13
+ | { readonly kind: "array"; readonly of: TypeNode }
14
+ | { readonly kind: "option"; readonly of: TypeNode }
15
+ | { readonly kind: "product"; readonly fields: readonly (readonly [string, TypeNode])[] }
16
+ | { readonly kind: "sum"; readonly variants: readonly (readonly [string, TypeNode | null])[] };
17
+
18
+ /** Splits at top-level occurrences of `sep`, ignoring nested brackets. */
19
+ export function splitTop(text: string, sep: string): string[] {
20
+ const parts: string[] = [];
21
+ let depth = 0;
22
+ let start = 0;
23
+ for (let i = 0; i < text.length; i++) {
24
+ const c = text[i];
25
+ if (c === "<" || c === "{" || c === "(") depth++;
26
+ else if (c === ">" || c === "}" || c === ")") depth--;
27
+ else if (depth === 0 && text.startsWith(sep, i)) {
28
+ parts.push(text.slice(start, i));
29
+ start = i + sep.length;
30
+ i += sep.length - 1;
31
+ }
32
+ }
33
+ parts.push(text.slice(start));
34
+ return parts.map((p) => p.trim()).filter((p) => p.length > 0);
35
+ }
36
+
37
+ /** `name: Type` -> [name, Type]. */
38
+ export function nameAndType(text: string): [string, string] {
39
+ const i = text.indexOf(": ");
40
+ return [text.slice(0, i), text.slice(i + 2)];
41
+ }
42
+
43
+ export function parseType(text: string): TypeNode {
44
+ const t = text.trim();
45
+ if (t === "()") return { kind: "unit" };
46
+ if (t.startsWith("Array<") && t.endsWith(">")) return { kind: "array", of: parseType(t.slice(6, -1)) };
47
+ if (t.startsWith("Option<") && t.endsWith(">")) return { kind: "option", of: parseType(t.slice(7, -1)) };
48
+ if (t.startsWith("{") && t.endsWith("}")) {
49
+ return {
50
+ kind: "product",
51
+ fields: splitTop(t.slice(1, -1), ", ").map((f) => {
52
+ const [name, type] = nameAndType(f);
53
+ return [name, parseType(type)] as const;
54
+ }),
55
+ };
56
+ }
57
+ if (t.startsWith("(") && t.endsWith(")")) {
58
+ return {
59
+ kind: "sum",
60
+ variants: splitTop(t.slice(1, -1), " | ").map((v) => {
61
+ const open = v.indexOf("(");
62
+ return open < 0 ? ([v, null] as const) : ([v.slice(0, open), parseType(v.slice(open + 1, -1))] as const);
63
+ }),
64
+ };
65
+ }
66
+ return { kind: "name", name: t };
67
+ }
68
+
69
+ /** Every named type a type text refers to (primitives and special products included). */
70
+ export function typeNames(text: string): string[] {
71
+ const out: string[] = [];
72
+ const walk = (n: TypeNode | null) => {
73
+ if (n === null) return;
74
+ switch (n.kind) {
75
+ case "name":
76
+ out.push(n.name);
77
+ return;
78
+ case "array":
79
+ case "option":
80
+ walk(n.of);
81
+ return;
82
+ case "product":
83
+ for (const [, f] of n.fields) walk(f);
84
+ return;
85
+ case "sum":
86
+ for (const [, v] of n.variants) walk(v);
87
+ return;
88
+ default:
89
+ return;
90
+ }
91
+ };
92
+ walk(parseType(text));
93
+ return out;
94
+ }
@@ -0,0 +1,22 @@
1
+ import type { WorldTimeRow } from "../binding_rows";
2
+ import type { SnapshotDb } from "../connection";
3
+
4
+ function readTick(db: SnapshotDb): bigint | null {
5
+ const handle = db.world_time;
6
+ if (!handle) return null;
7
+ for (const row of handle.iter()) {
8
+ const r = row as unknown as WorldTimeRow;
9
+ return typeof r.tick === "bigint" ? r.tick : BigInt(String(r.tick ?? 0));
10
+ }
11
+ return null;
12
+ }
13
+
14
+ /** Returns the current world tick, or null when the world_time row is absent. */
15
+ export function currentWorldTick(db: SnapshotDb): bigint | null {
16
+ return readTick(db);
17
+ }
18
+
19
+ /** Returns the current world tick, or 0n when the world_time row is absent. */
20
+ export function currentWorldTickOrZero(db: SnapshotDb): bigint {
21
+ return readTick(db) ?? 0n;
22
+ }