@draht/chord 2026.10.31 → 2026.11.5

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 (70) hide show
  1. package/dist/cell.d.ts +7 -7
  2. package/dist/cell.d.ts.map +1 -1
  3. package/dist/cell.js.map +1 -1
  4. package/dist/context/index.d.ts +1 -1
  5. package/dist/context/index.d.ts.map +1 -1
  6. package/dist/context/index.js +1 -1
  7. package/dist/context/index.js.map +1 -1
  8. package/dist/contract.d.ts +51 -52
  9. package/dist/contract.d.ts.map +1 -1
  10. package/dist/contract.js +19 -24
  11. package/dist/contract.js.map +1 -1
  12. package/dist/delta/apply-immutable-trusted.js +3 -4
  13. package/dist/delta/apply-immutable-trusted.js.map +1 -1
  14. package/dist/delta/diff.d.ts.map +1 -1
  15. package/dist/delta/diff.js +5 -3
  16. package/dist/delta/diff.js.map +1 -1
  17. package/dist/delta/index.d.ts +9 -1
  18. package/dist/delta/index.d.ts.map +1 -1
  19. package/dist/delta/index.js +15 -11
  20. package/dist/delta/index.js.map +1 -1
  21. package/dist/delta/pending.d.ts +36 -0
  22. package/dist/delta/pending.d.ts.map +1 -0
  23. package/dist/delta/pending.js +143 -0
  24. package/dist/delta/pending.js.map +1 -0
  25. package/dist/delta/tracker.d.ts +12 -0
  26. package/dist/delta/tracker.d.ts.map +1 -1
  27. package/dist/delta/tracker.js +109 -39
  28. package/dist/delta/tracker.js.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/object.d.ts +4 -4
  34. package/dist/object.d.ts.map +1 -1
  35. package/dist/object.js +3 -4
  36. package/dist/object.js.map +1 -1
  37. package/dist/output.d.ts +1 -1
  38. package/dist/output.d.ts.map +1 -1
  39. package/dist/output.js +4 -2
  40. package/dist/output.js.map +1 -1
  41. package/dist/remote.d.ts.map +1 -1
  42. package/dist/remote.js +2 -2
  43. package/dist/remote.js.map +1 -1
  44. package/dist/schema.d.ts +8 -4
  45. package/dist/schema.d.ts.map +1 -1
  46. package/dist/schema.js +180 -5
  47. package/dist/schema.js.map +1 -1
  48. package/dist/sqlite/cloudflare.d.ts +2 -0
  49. package/dist/sqlite/cloudflare.d.ts.map +1 -1
  50. package/dist/sqlite/cloudflare.js +10 -0
  51. package/dist/sqlite/cloudflare.js.map +1 -1
  52. package/dist/sqlite/database.d.ts +5 -2
  53. package/dist/sqlite/database.d.ts.map +1 -1
  54. package/dist/sqlite/database.js.map +1 -1
  55. package/dist/sqlite/node.d.ts +4 -1
  56. package/dist/sqlite/node.d.ts.map +1 -1
  57. package/dist/sqlite/node.js +22 -5
  58. package/dist/sqlite/node.js.map +1 -1
  59. package/dist/watch.d.ts +194 -0
  60. package/dist/watch.d.ts.map +1 -0
  61. package/dist/watch.js +383 -0
  62. package/dist/watch.js.map +1 -0
  63. package/dist/wire.d.ts +174 -193
  64. package/dist/wire.d.ts.map +1 -1
  65. package/dist/wire.js +81 -80
  66. package/dist/wire.js.map +1 -1
  67. package/docs/guide.md +15 -15
  68. package/docs/spec.md +8 -8
  69. package/docs/tutorial.md +26 -25
  70. package/package.json +4 -5
package/dist/wire.js CHANGED
@@ -1,5 +1,4 @@
1
- import { Type } from "typebox";
2
- import { Value } from "typebox/value";
1
+ import { arr, bool, compile, int, lit, map, num, obj, oneOf, opt, str, union, unknown, } from "@draht/schema";
3
2
  import { DescriptionSchema } from "./contract.js";
4
3
  import { CHORD_ERROR_CODES, ChordError } from "./errors.js";
5
4
  // JSON frames between two hosts (or a host and a client). Ids are chosen by the side that creates the hold, call or
@@ -20,46 +19,48 @@ import { CHORD_ERROR_CODES, ChordError } from "./errors.js";
20
19
  * (`LinkOptions.onProtocolMismatch`).
21
20
  */
22
21
  export const PROTOCOL_VERSION = 4;
23
- const Id = Type.Integer({ minimum: 1 });
24
- const Name = Type.String({ minLength: 1 });
25
- const Reload = Type.Integer({ minimum: 1 });
26
- /** Arrays a sender may pass as readonly. */
27
- const List = (item) => Type.Immutable(Type.Array(item));
28
- const RootRefSchema = Type.Object({ rootId: Name, codeVersion: Type.Integer({ minimum: 1 }) });
29
- const WireErrorSchema = Type.Object({
30
- code: Type.Enum(CHORD_ERROR_CODES),
31
- message: Type.String(),
32
- reason: Type.Optional(Type.String()),
22
+ const Id = int({ minimum: 1 });
23
+ const Name = str({ minLength: 1 });
24
+ const Reload = int({ minimum: 1 });
25
+ /** Arrays a sender may pass as readonly: the same schema, a readonly type. */
26
+ const List = (item) => arr(item);
27
+ /** An object that admits fields it does not name (a newer peer's), as every frame does. */
28
+ const Open = (properties) => obj(properties, { open: true });
29
+ const RootRefSchema = Open({ rootId: Name, codeVersion: int({ minimum: 1 }) });
30
+ const WireErrorSchema = Open({
31
+ code: oneOf(CHORD_ERROR_CODES),
32
+ message: str(),
33
+ reason: opt(str()),
33
34
  });
34
- const WireReloadOptionsSchema = Type.Object({
35
- remove: Type.Optional(List(Type.String())),
36
- gateDeadline: Type.Optional(Type.Number()),
37
- retireDeadline: Type.Optional(Type.Number()),
35
+ const WireReloadOptionsSchema = Open({
36
+ remove: opt(List(str())),
37
+ gateDeadline: opt(num()),
38
+ retireDeadline: opt(num()),
38
39
  });
39
40
  /** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */
40
- const WireReloadReportSchema = Type.Object({
41
- codeVersion: Type.Integer(),
42
- previous: Type.Integer(),
43
- changed: List(Type.String()),
44
- removed: List(Type.String()),
45
- prepared: List(Type.String()),
46
- gated: List(Type.String()),
41
+ const WireReloadReportSchema = Open({
42
+ codeVersion: int(),
43
+ previous: int(),
44
+ changed: List(str()),
45
+ removed: List(str()),
46
+ prepared: List(str()),
47
+ gated: List(str()),
47
48
  });
48
- const FrameSchema = Type.Union([
49
- Type.Object({
50
- t: Type.Literal("hello"),
49
+ const FrameSchema = union([
50
+ Open({
51
+ t: lit("hello"),
51
52
  /** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */
52
- protocol: Type.Optional(Type.Integer({ minimum: 1 })),
53
+ protocol: opt(int({ minimum: 1 })),
53
54
  name: Name,
54
- kind: Type.Union([Type.Literal("host"), Type.Literal("client")]),
55
- codeVersion: Type.Integer({ minimum: 0 }),
55
+ kind: union([lit("host"), lit("client")]),
56
+ codeVersion: int({ minimum: 0 }),
56
57
  /** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */
57
- acks: Type.Optional(Type.Boolean()),
58
+ acks: opt(bool()),
58
59
  }),
59
60
  /** Every frame received so far except `ack` frames, counted from the link's start, once processed. */
60
- Type.Object({ t: Type.Literal("ack"), n: Type.Integer({ minimum: 1 }) }),
61
- Type.Object({
62
- t: Type.Literal("hold"),
61
+ Open({ t: lit("ack"), n: int({ minimum: 1 }) }),
62
+ Open({
63
+ t: lit("hold"),
63
64
  id: Id,
64
65
  /**
65
66
  * Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after
@@ -69,90 +70,90 @@ const FrameSchema = Type.Union([
69
70
  /** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */
70
71
  token: DescriptionSchema,
71
72
  /** Normalized with the consumer's contract. */
72
- input: Type.Unknown(),
73
+ input: unknown(),
73
74
  /** A forwarded principal. Honored only on frames from the parent link. */
74
- principal: Type.Optional(Type.Unknown()),
75
+ principal: opt(unknown()),
75
76
  /**
76
77
  * The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored
77
78
  * only on frames from the parent link; present means the hold is a client's (not a reload participant).
78
79
  */
79
- origin: Type.Optional(Name),
80
+ origin: opt(Name),
80
81
  /** False: no state for this hold until `sub` (a method-only binding). */
81
- state: Type.Optional(Type.Literal(false)),
82
+ state: opt(lit(false)),
82
83
  /** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */
83
- again: Type.Optional(Type.Literal(true)),
84
+ again: opt(lit(true)),
84
85
  }),
85
- Type.Object({ t: Type.Literal("release"), id: Id }),
86
- Type.Object({
87
- t: Type.Literal("shape"),
86
+ Open({ t: lit("release"), id: Id }),
87
+ Open({
88
+ t: lit("shape"),
88
89
  id: Id,
89
- variant: Type.Optional(Type.String()),
90
- members: List(Type.String()),
91
- contract: Type.String(),
90
+ variant: opt(str()),
91
+ members: List(str()),
92
+ contract: str(),
92
93
  /** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */
93
94
  state: List(Name),
94
95
  }),
95
- Type.Object({ t: Type.Literal("gone"), id: Id, error: WireErrorSchema }),
96
- Type.Object({
97
- t: Type.Literal("call"),
96
+ Open({ t: lit("gone"), id: Id, error: WireErrorSchema }),
97
+ Open({
98
+ t: lit("call"),
98
99
  id: Id,
99
100
  hold: Id,
100
101
  member: Name,
101
- args: Type.Optional(Type.Unknown()),
102
+ args: opt(unknown()),
102
103
  /** Absent: the receiving host starts a root (browsers never carry roots). */
103
- root: Type.Optional(RootRefSchema),
104
+ root: opt(RootRefSchema),
104
105
  }),
105
- Type.Object({
106
- t: Type.Literal("result"),
106
+ Open({
107
+ t: lit("result"),
107
108
  id: Id,
108
- value: Type.Optional(Type.Unknown()),
109
- error: Type.Optional(WireErrorSchema),
109
+ value: opt(unknown()),
110
+ error: opt(WireErrorSchema),
110
111
  }),
111
- Type.Object({ t: Type.Literal("cancel"), id: Id }),
112
+ Open({ t: lit("cancel"), id: Id }),
112
113
  /** Starts the state of a hold opened with `state: false` (answered with a unit). */
113
- Type.Object({ t: Type.Literal("sub"), hold: Id }),
114
+ Open({ t: lit("sub"), hold: Id }),
114
115
  /** Stops the state of a hold. */
115
- Type.Object({ t: Type.Literal("unsub"), hold: Id }),
116
+ Open({ t: lit("unsub"), hold: Id }),
116
117
  /** Sends member `m` again as a reset (a relay that had to drop what waited for it). */
117
- Type.Object({ t: Type.Literal("resync"), hold: Id, m: Name }),
118
- Type.Object({
119
- t: Type.Literal("state"),
118
+ Open({ t: lit("resync"), hold: Id, m: Name }),
119
+ Open({
120
+ t: lit("state"),
120
121
  hold: Id,
121
122
  m: Name,
122
123
  /** `snap`/`reset` without `value`: the value is `undefined`. */
123
- as: Type.Union([Type.Literal("snap"), Type.Literal("reset"), Type.Literal("ops"), Type.Literal("error")]),
124
- value: Type.Optional(Type.Unknown()),
124
+ as: union([lit("snap"), lit("reset"), lit("ops"), lit("error")]),
125
+ value: opt(unknown()),
125
126
  /** Encoded with the stream's delta encoder; the decoder validates each op. */
126
- ops: Type.Optional(List(List(Type.Unknown()))),
127
- error: Type.Optional(WireErrorSchema),
127
+ ops: opt(List(List(unknown()))),
128
+ error: opt(WireErrorSchema),
128
129
  }),
129
- Type.Object({ t: Type.Literal("ping"), n: Type.Integer() }),
130
- Type.Object({ t: Type.Literal("pong"), n: Type.Integer() }),
130
+ Open({ t: lit("ping"), n: int() }),
131
+ Open({ t: lit("pong"), n: int() }),
131
132
  /** Ends the link (consumed by the link itself). `reason: "protocol-version <n>"`: the sender speaks version n. */
132
- Type.Object({ t: Type.Literal("bye"), reason: Type.Optional(Type.String()) }),
133
+ Open({ t: lit("bye"), reason: opt(str()) }),
133
134
  /** The root ended at its origin: its leases on objects end (sent on every link the root's calls used). */
134
- Type.Object({ t: Type.Literal("root_end"), rootId: Name }),
135
- Type.Object({ t: Type.Literal("invalidate"), pattern: Type.Record(Type.String(), Type.Unknown()) }),
136
- Type.Object({
137
- t: Type.Literal("prepare"),
135
+ Open({ t: lit("root_end"), rootId: Name }),
136
+ Open({ t: lit("invalidate"), pattern: map(unknown()) }),
137
+ Open({
138
+ t: lit("prepare"),
138
139
  reload: Reload,
139
- codeVersion: Type.Integer({ minimum: 1 }),
140
- plugins: List(Type.String()),
140
+ codeVersion: int({ minimum: 1 }),
141
+ plugins: List(str()),
141
142
  options: WireReloadOptionsSchema,
142
143
  }),
143
- Type.Object({
144
- t: Type.Literal("vote"),
144
+ Open({
145
+ t: lit("vote"),
145
146
  reload: Reload,
146
- error: Type.Optional(WireErrorSchema),
147
- report: Type.Optional(WireReloadReportSchema),
147
+ error: opt(WireErrorSchema),
148
+ report: opt(WireReloadReportSchema),
148
149
  }),
149
- Type.Object({ t: Type.Literal("commit"), reload: Reload }),
150
+ Open({ t: lit("commit"), reload: Reload }),
150
151
  /** The parent dropped `codeVersion`: roots of it may still come from there no longer. */
151
- Type.Object({ t: Type.Literal("retire"), codeVersion: Type.Integer({ minimum: 1 }) }),
152
- Type.Object({ t: Type.Literal("abort"), reload: Reload }),
152
+ Open({ t: lit("retire"), codeVersion: int({ minimum: 1 }) }),
153
+ Open({ t: lit("abort"), reload: Reload }),
153
154
  ]);
154
155
  /** A frame that passes validation; anything else is a protocol violation. */
155
- export const isFrame = (value) => Value.Check(FrameSchema, value);
156
+ export const isFrame = compile(FrameSchema).check;
156
157
  export function toWireError(error) {
157
158
  if (error instanceof ChordError) {
158
159
  return error.reason === undefined
package/dist/wire.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,IAAI,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE5D,oHAAoH;AACpH,0EAA0E;AAC1E,yEAAyE;AACzE,oDAAoD;AACpD,uHAAuH;AACvH,iEAAiE;AACjE,6GAA6G;AAC7G,yBAAyB;AACzB,EAAE;AACF,wHAAwH;AACxH,mHAAmH;AACnH,mFAAmF;AAEnF;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAElC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;AACxC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC;AAC3C,MAAM,MAAM,GAAG,IAAI,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,EAAE,aAAa,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACjG,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAAgB,EAAc,EAAE,CAC7D,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC","sourcesContent":["import { type Static, type TSchema, Type } from \"typebox\";\nimport { Value } from \"typebox/value\";\nimport { DescriptionSchema } from \"./contract.ts\";\nimport { CHORD_ERROR_CODES, ChordError } from \"./errors.ts\";\n\n// JSON frames between two hosts (or a host and a client). Ids are chosen by the side that creates the hold, call or\n// subscription; every frame type has one direction, so ids never collide:\n// consumer → provider: hold, release, call, cancel, sub, unsub, resync\n// provider → consumer: shape, gone, result, state\n// State is addressed by (hold id, member): a hold implies the state of its variant, sent as units (a shape followed by\n// a snapshot of each member the consumer lacks; see Connection).\n// both: hello, ping, pong, bye, root_end, ack; parent → child: invalidate, prepare, commit, abort, retire;\n// child → parent: vote\n//\n// Each frame is declared once, as the schema every received frame is checked against (`isFrame`); the types are derived\n// from it. Payloads (hold inputs, call args, results, snapshots) stay `unknown`: they are validated where they are\n// used, against the contract. State ops are checked op by op by the delta decoder.\n\n/**\n * The link protocol version, announced in `hello`. Peers of different versions do not talk: the side that notices\n * closes the link with reason `protocol-version <its version>`, so the other side learns it too\n * (`LinkOptions.onProtocolMismatch`).\n */\nexport const PROTOCOL_VERSION = 4;\n\nconst Id = Type.Integer({ minimum: 1 });\nconst Name = Type.String({ minLength: 1 });\nconst Reload = Type.Integer({ minimum: 1 });\n/** Arrays a sender may pass as readonly. */\nconst List = <T extends TSchema>(item: T) => Type.Immutable(Type.Array(item));\n\nconst RootRefSchema = Type.Object({ rootId: Name, codeVersion: Type.Integer({ minimum: 1 }) });\nexport type RootRef = Static<typeof RootRefSchema>;\n\nconst WireErrorSchema = Type.Object({\n\tcode: Type.Enum(CHORD_ERROR_CODES),\n\tmessage: Type.String(),\n\treason: Type.Optional(Type.String()),\n});\nexport type WireError = Static<typeof WireErrorSchema>;\n\nconst WireReloadOptionsSchema = Type.Object({\n\tremove: Type.Optional(List(Type.String())),\n\tgateDeadline: Type.Optional(Type.Number()),\n\tretireDeadline: Type.Optional(Type.Number()),\n});\nexport type WireReloadOptions = Static<typeof WireReloadOptionsSchema>;\n\n/** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */\nconst WireReloadReportSchema = Type.Object({\n\tcodeVersion: Type.Integer(),\n\tprevious: Type.Integer(),\n\tchanged: List(Type.String()),\n\tremoved: List(Type.String()),\n\tprepared: List(Type.String()),\n\tgated: List(Type.String()),\n});\nexport type WireReloadReport = Static<typeof WireReloadReportSchema>;\n\nconst FrameSchema = Type.Union([\n\tType.Object({\n\t\tt: Type.Literal(\"hello\"),\n\t\t/** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */\n\t\tprotocol: Type.Optional(Type.Integer({ minimum: 1 })),\n\t\tname: Name,\n\t\tkind: Type.Union([Type.Literal(\"host\"), Type.Literal(\"client\")]),\n\t\tcodeVersion: Type.Integer({ minimum: 0 }),\n\t\t/** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */\n\t\tacks: Type.Optional(Type.Boolean()),\n\t}),\n\t/** Every frame received so far except `ack` frames, counted from the link's start, once processed. */\n\tType.Object({ t: Type.Literal(\"ack\"), n: Type.Integer({ minimum: 1 }) }),\n\tType.Object({\n\t\tt: Type.Literal(\"hold\"),\n\t\tid: Id,\n\t\t/**\n\t\t * Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after\n\t\t * checking it against both; the target refuses an input its own contract places elsewhere.\n\t\t */\n\t\tat: Name,\n\t\t/** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */\n\t\ttoken: DescriptionSchema,\n\t\t/** Normalized with the consumer's contract. */\n\t\tinput: Type.Unknown(),\n\t\t/** A forwarded principal. Honored only on frames from the parent link. */\n\t\tprincipal: Type.Optional(Type.Unknown()),\n\t\t/**\n\t\t * The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored\n\t\t * only on frames from the parent link; present means the hold is a client's (not a reload participant).\n\t\t */\n\t\torigin: Type.Optional(Name),\n\t\t/** False: no state for this hold until `sub` (a method-only binding). */\n\t\tstate: Type.Optional(Type.Literal(false)),\n\t\t/** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */\n\t\tagain: Type.Optional(Type.Literal(true)),\n\t}),\n\tType.Object({ t: Type.Literal(\"release\"), id: Id }),\n\tType.Object({\n\t\tt: Type.Literal(\"shape\"),\n\t\tid: Id,\n\t\tvariant: Type.Optional(Type.String()),\n\t\tmembers: List(Type.String()),\n\t\tcontract: Type.String(),\n\t\t/** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */\n\t\tstate: List(Name),\n\t}),\n\tType.Object({ t: Type.Literal(\"gone\"), id: Id, error: WireErrorSchema }),\n\tType.Object({\n\t\tt: Type.Literal(\"call\"),\n\t\tid: Id,\n\t\thold: Id,\n\t\tmember: Name,\n\t\targs: Type.Optional(Type.Unknown()),\n\t\t/** Absent: the receiving host starts a root (browsers never carry roots). */\n\t\troot: Type.Optional(RootRefSchema),\n\t}),\n\tType.Object({\n\t\tt: Type.Literal(\"result\"),\n\t\tid: Id,\n\t\tvalue: Type.Optional(Type.Unknown()),\n\t\terror: Type.Optional(WireErrorSchema),\n\t}),\n\tType.Object({ t: Type.Literal(\"cancel\"), id: Id }),\n\t/** Starts the state of a hold opened with `state: false` (answered with a unit). */\n\tType.Object({ t: Type.Literal(\"sub\"), hold: Id }),\n\t/** Stops the state of a hold. */\n\tType.Object({ t: Type.Literal(\"unsub\"), hold: Id }),\n\t/** Sends member `m` again as a reset (a relay that had to drop what waited for it). */\n\tType.Object({ t: Type.Literal(\"resync\"), hold: Id, m: Name }),\n\tType.Object({\n\t\tt: Type.Literal(\"state\"),\n\t\thold: Id,\n\t\tm: Name,\n\t\t/** `snap`/`reset` without `value`: the value is `undefined`. */\n\t\tas: Type.Union([Type.Literal(\"snap\"), Type.Literal(\"reset\"), Type.Literal(\"ops\"), Type.Literal(\"error\")]),\n\t\tvalue: Type.Optional(Type.Unknown()),\n\t\t/** Encoded with the stream's delta encoder; the decoder validates each op. */\n\t\tops: Type.Optional(List(List(Type.Unknown()))),\n\t\terror: Type.Optional(WireErrorSchema),\n\t}),\n\tType.Object({ t: Type.Literal(\"ping\"), n: Type.Integer() }),\n\tType.Object({ t: Type.Literal(\"pong\"), n: Type.Integer() }),\n\t/** Ends the link (consumed by the link itself). `reason: \"protocol-version <n>\"`: the sender speaks version n. */\n\tType.Object({ t: Type.Literal(\"bye\"), reason: Type.Optional(Type.String()) }),\n\t/** The root ended at its origin: its leases on objects end (sent on every link the root's calls used). */\n\tType.Object({ t: Type.Literal(\"root_end\"), rootId: Name }),\n\tType.Object({ t: Type.Literal(\"invalidate\"), pattern: Type.Record(Type.String(), Type.Unknown()) }),\n\tType.Object({\n\t\tt: Type.Literal(\"prepare\"),\n\t\treload: Reload,\n\t\tcodeVersion: Type.Integer({ minimum: 1 }),\n\t\tplugins: List(Type.String()),\n\t\toptions: WireReloadOptionsSchema,\n\t}),\n\tType.Object({\n\t\tt: Type.Literal(\"vote\"),\n\t\treload: Reload,\n\t\terror: Type.Optional(WireErrorSchema),\n\t\treport: Type.Optional(WireReloadReportSchema),\n\t}),\n\tType.Object({ t: Type.Literal(\"commit\"), reload: Reload }),\n\t/** The parent dropped `codeVersion`: roots of it may still come from there no longer. */\n\tType.Object({ t: Type.Literal(\"retire\"), codeVersion: Type.Integer({ minimum: 1 }) }),\n\tType.Object({ t: Type.Literal(\"abort\"), reload: Reload }),\n]);\nexport type Frame = Static<typeof FrameSchema>;\n\n/** A frame that passes validation; anything else is a protocol violation. */\nexport const isFrame = (value: unknown): value is Frame => Value.Check(FrameSchema, value);\n\nexport function toWireError(error: unknown): WireError {\n\tif (error instanceof ChordError) {\n\t\treturn error.reason === undefined\n\t\t\t? { code: error.code, message: error.message }\n\t\t\t: { code: error.code, message: error.message, reason: error.reason };\n\t}\n\treturn { code: \"unavailable\", message: error instanceof Error ? error.message : String(error) };\n}\n\nexport const fromWireError = (error: WireError): ChordError =>\n\tnew ChordError(error.code, error.message.replace(/^[a-z_]+(\\/[a-z_]+)?: /, \"\"), { reason: error.reason });\n"]}
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,GAAG,EACH,IAAI,EACJ,OAAO,EACP,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,KAAK,EACL,GAAG,EAIH,GAAG,EACH,KAAK,EACL,OAAO,GACP,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE5D,oHAAoH;AACpH,0EAA0E;AAC1E,yEAAyE;AACzE,oDAAoD;AACpD,uHAAuH;AACvH,iEAAiE;AACjE,6GAA6G;AAC7G,yBAAyB;AACzB,EAAE;AACF,wHAAwH;AACxH,mHAAmH;AACnH,mFAAmF;AAEnF;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAElC,MAAM,EAAE,GAAG,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;AAC/B,MAAM,IAAI,GAAG,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC;AACnC,MAAM,MAAM,GAAG,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;AACnC,8EAA8E;AAC9E,MAAM,IAAI,GA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O,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC","sourcesContent":["import {\n\tarr,\n\tbool,\n\tcompile,\n\tint,\n\tlit,\n\tmap,\n\tnum,\n\tobj,\n\toneOf,\n\topt,\n\ttype Properties,\n\ttype Schema,\n\ttype Static,\n\tstr,\n\tunion,\n\tunknown,\n} from \"@draht/schema\";\nimport { DescriptionSchema } from \"./contract.ts\";\nimport { CHORD_ERROR_CODES, ChordError } from \"./errors.ts\";\n\n// JSON frames between two hosts (or a host and a client). Ids are chosen by the side that creates the hold, call or\n// subscription; every frame type has one direction, so ids never collide:\n// consumer → provider: hold, release, call, cancel, sub, unsub, resync\n// provider → consumer: shape, gone, result, state\n// State is addressed by (hold id, member): a hold implies the state of its variant, sent as units (a shape followed by\n// a snapshot of each member the consumer lacks; see Connection).\n// both: hello, ping, pong, bye, root_end, ack; parent → child: invalidate, prepare, commit, abort, retire;\n// child → parent: vote\n//\n// Each frame is declared once, as the schema every received frame is checked against (`isFrame`); the types are derived\n// from it. Payloads (hold inputs, call args, results, snapshots) stay `unknown`: they are validated where they are\n// used, against the contract. State ops are checked op by op by the delta decoder.\n\n/**\n * The link protocol version, announced in `hello`. Peers of different versions do not talk: the side that notices\n * closes the link with reason `protocol-version <its version>`, so the other side learns it too\n * (`LinkOptions.onProtocolMismatch`).\n */\nexport const PROTOCOL_VERSION = 4;\n\nconst Id = int({ minimum: 1 });\nconst Name = str({ minLength: 1 });\nconst Reload = int({ minimum: 1 });\n/** Arrays a sender may pass as readonly: the same schema, a readonly type. */\nconst List = <T>(item: Schema<T>) => arr(item) as Schema<readonly T[]>;\n/** An object that admits fields it does not name (a newer peer's), as every frame does. */\nconst Open = <const P extends Properties>(properties: P) => obj(properties, { open: true });\n\nconst RootRefSchema = Open({ rootId: Name, codeVersion: int({ minimum: 1 }) });\nexport type RootRef = Static<typeof RootRefSchema>;\n\nconst WireErrorSchema = Open({\n\tcode: oneOf(CHORD_ERROR_CODES),\n\tmessage: str(),\n\treason: opt(str()),\n});\nexport type WireError = Static<typeof WireErrorSchema>;\n\nconst WireReloadOptionsSchema = Open({\n\tremove: opt(List(str())),\n\tgateDeadline: opt(num()),\n\tretireDeadline: opt(num()),\n});\nexport type WireReloadOptions = Static<typeof WireReloadOptionsSchema>;\n\n/** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */\nconst WireReloadReportSchema = Open({\n\tcodeVersion: int(),\n\tprevious: int(),\n\tchanged: List(str()),\n\tremoved: List(str()),\n\tprepared: List(str()),\n\tgated: List(str()),\n});\nexport type WireReloadReport = Static<typeof WireReloadReportSchema>;\n\nconst FrameSchema = union([\n\tOpen({\n\t\tt: lit(\"hello\"),\n\t\t/** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */\n\t\tprotocol: opt(int({ minimum: 1 })),\n\t\tname: Name,\n\t\tkind: union([lit(\"host\"), lit(\"client\")]),\n\t\tcodeVersion: int({ minimum: 0 }),\n\t\t/** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */\n\t\tacks: opt(bool()),\n\t}),\n\t/** Every frame received so far except `ack` frames, counted from the link's start, once processed. */\n\tOpen({ t: lit(\"ack\"), n: int({ minimum: 1 }) }),\n\tOpen({\n\t\tt: lit(\"hold\"),\n\t\tid: Id,\n\t\t/**\n\t\t * Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after\n\t\t * checking it against both; the target refuses an input its own contract places elsewhere.\n\t\t */\n\t\tat: Name,\n\t\t/** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */\n\t\ttoken: DescriptionSchema,\n\t\t/** Normalized with the consumer's contract. */\n\t\tinput: unknown(),\n\t\t/** A forwarded principal. Honored only on frames from the parent link. */\n\t\tprincipal: opt(unknown()),\n\t\t/**\n\t\t * The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored\n\t\t * only on frames from the parent link; present means the hold is a client's (not a reload participant).\n\t\t */\n\t\torigin: opt(Name),\n\t\t/** False: no state for this hold until `sub` (a method-only binding). */\n\t\tstate: opt(lit(false)),\n\t\t/** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */\n\t\tagain: opt(lit(true)),\n\t}),\n\tOpen({ t: lit(\"release\"), id: Id }),\n\tOpen({\n\t\tt: lit(\"shape\"),\n\t\tid: Id,\n\t\tvariant: opt(str()),\n\t\tmembers: List(str()),\n\t\tcontract: str(),\n\t\t/** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */\n\t\tstate: List(Name),\n\t}),\n\tOpen({ t: lit(\"gone\"), id: Id, error: WireErrorSchema }),\n\tOpen({\n\t\tt: lit(\"call\"),\n\t\tid: Id,\n\t\thold: Id,\n\t\tmember: Name,\n\t\targs: opt(unknown()),\n\t\t/** Absent: the receiving host starts a root (browsers never carry roots). */\n\t\troot: opt(RootRefSchema),\n\t}),\n\tOpen({\n\t\tt: lit(\"result\"),\n\t\tid: Id,\n\t\tvalue: opt(unknown()),\n\t\terror: opt(WireErrorSchema),\n\t}),\n\tOpen({ t: lit(\"cancel\"), id: Id }),\n\t/** Starts the state of a hold opened with `state: false` (answered with a unit). */\n\tOpen({ t: lit(\"sub\"), hold: Id }),\n\t/** Stops the state of a hold. */\n\tOpen({ t: lit(\"unsub\"), hold: Id }),\n\t/** Sends member `m` again as a reset (a relay that had to drop what waited for it). */\n\tOpen({ t: lit(\"resync\"), hold: Id, m: Name }),\n\tOpen({\n\t\tt: lit(\"state\"),\n\t\thold: Id,\n\t\tm: Name,\n\t\t/** `snap`/`reset` without `value`: the value is `undefined`. */\n\t\tas: union([lit(\"snap\"), lit(\"reset\"), lit(\"ops\"), lit(\"error\")]),\n\t\tvalue: opt(unknown()),\n\t\t/** Encoded with the stream's delta encoder; the decoder validates each op. */\n\t\tops: opt(List(List(unknown()))),\n\t\terror: opt(WireErrorSchema),\n\t}),\n\tOpen({ t: lit(\"ping\"), n: int() }),\n\tOpen({ t: lit(\"pong\"), n: int() }),\n\t/** Ends the link (consumed by the link itself). `reason: \"protocol-version <n>\"`: the sender speaks version n. */\n\tOpen({ t: lit(\"bye\"), reason: opt(str()) }),\n\t/** The root ended at its origin: its leases on objects end (sent on every link the root's calls used). */\n\tOpen({ t: lit(\"root_end\"), rootId: Name }),\n\tOpen({ t: lit(\"invalidate\"), pattern: map(unknown()) }),\n\tOpen({\n\t\tt: lit(\"prepare\"),\n\t\treload: Reload,\n\t\tcodeVersion: int({ minimum: 1 }),\n\t\tplugins: List(str()),\n\t\toptions: WireReloadOptionsSchema,\n\t}),\n\tOpen({\n\t\tt: lit(\"vote\"),\n\t\treload: Reload,\n\t\terror: opt(WireErrorSchema),\n\t\treport: opt(WireReloadReportSchema),\n\t}),\n\tOpen({ t: lit(\"commit\"), reload: Reload }),\n\t/** The parent dropped `codeVersion`: roots of it may still come from there no longer. */\n\tOpen({ t: lit(\"retire\"), codeVersion: int({ minimum: 1 }) }),\n\tOpen({ t: lit(\"abort\"), reload: Reload }),\n]);\nexport type Frame = Static<typeof FrameSchema>;\n\n/** A frame that passes validation; anything else is a protocol violation. */\nexport const isFrame: (value: unknown) => value is Frame = compile(FrameSchema).check;\n\nexport function toWireError(error: unknown): WireError {\n\tif (error instanceof ChordError) {\n\t\treturn error.reason === undefined\n\t\t\t? { code: error.code, message: error.message }\n\t\t\t: { code: error.code, message: error.message, reason: error.reason };\n\t}\n\treturn { code: \"unavailable\", message: error instanceof Error ? error.message : String(error) };\n}\n\nexport const fromWireError = (error: WireError): ChordError =>\n\tnew ChordError(error.code, error.message.replace(/^[a-z_]+(\\/[a-z_]+)?: /, \"\"), { reason: error.reason });\n"]}
package/docs/guide.md CHANGED
@@ -36,17 +36,17 @@ Chord builds applications out of **objects** that live in several processes (a s
36
36
  ## Quick start
37
37
 
38
38
  ```ts
39
- import { Type } from "typebox";
39
+ import { num, obj, str } from "@draht/schema";
40
40
  import { createHost, method, remote } from "@draht/chord";
41
41
 
42
42
  // contract.ts: shared by provider and consumers
43
43
  export const Counter = remote("demo.counter", {
44
44
  version: 1,
45
- input: Type.Object({ name: Type.String() }),
45
+ input: obj({ name: str() }),
46
46
  variants: {
47
47
  default: {
48
- state: { count: Type.Number() },
49
- methods: { increment: method(Type.Object({ by: Type.Number() })) },
48
+ state: { count: num() },
49
+ methods: { increment: method(obj({ by: num() })) },
50
50
  },
51
51
  },
52
52
  });
@@ -54,7 +54,7 @@ export const Counter = remote("demo.counter", {
54
54
  const host = createHost({ name: "server", self: { kind: "server" } });
55
55
 
56
56
  host.serve(Counter, ({ name }, _principal, self) => {
57
- const count = self.state("count", Type.Number(), 0);
57
+ const count = self.state("count", num(), 0);
58
58
  return {
59
59
  variant: "default",
60
60
  count,
@@ -82,7 +82,7 @@ Remote types can be reached from other hosts. Everything that crosses the wire h
82
82
  ```ts
83
83
  export const Chat = remote("draht.chat", {
84
84
  version: 1,
85
- input: Type.Object({ session: Type.String(), conversation: Type.Number() }),
85
+ input: obj({ session: str(), conversation: num() }),
86
86
  host: hostFamily("session:", "session"), // lives on `session:S1` for `{ session: "S1", … }`
87
87
  variants: {
88
88
  viewer: {
@@ -91,7 +91,7 @@ export const Chat = remote("draht.chat", {
91
91
  participant: {
92
92
  state: { view: ConversationViewSchema },
93
93
  methods: {
94
- send: method(SendInputSchema, Type.Object({ submissionId: Type.Number() })),
94
+ send: method(SendInputSchema, obj({ submissionId: num() })),
95
95
  stop: method(), // no arguments, no result: `chat.stop(ctx)`
96
96
  },
97
97
  },
@@ -119,10 +119,10 @@ Local types are reachable only inside their host. Their members may be anything:
119
119
  ```ts
120
120
  export const Index = local("draht.index", {
121
121
  version: 1,
122
- input: Type.Object({ session: Type.String() }),
122
+ input: obj({ session: str() }),
123
123
  members: {
124
- search: method(Type.Object({ query: Type.String() }), Type.Array(HitSchema)),
125
- onChange: method(Type.Function([ChangeSchema], Type.Void()), UnsubscribeSchema),
124
+ search: method(obj({ query: str() }), arr(HitSchema)),
125
+ onChange: method({ type: "function", parameters: [ChangeSchema], returnType: { type: "void" } }, UnsubscribeSchema),
126
126
  harness: opaque("draht.durable-harness@1"),
127
127
  },
128
128
  });
@@ -181,7 +181,7 @@ A reload runs the factory again over the same object. Declarations that keep som
181
181
  ```ts
182
182
  host.serve(StatusStore, ({ session }, _host, self) => {
183
183
  const status = self.state("status", StatusSchema, { running: false, tasks: 0 });
184
- const errors = self.state("errors", Type.Array(Type.String()), []);
184
+ const errors = self.state("errors", arr(str()), []);
185
185
  const catalog = self.get(Catalog, {});
186
186
  const db = self.resource("db", {
187
187
  version: 1,
@@ -230,7 +230,7 @@ host.serve(Visits, (_, _p, self) => {
230
230
 
231
231
  // right
232
232
  host.serve(Visits, (_, _p, self) => {
233
- const visits = self.state("visits", Type.Number(), 0);
233
+ const visits = self.state("visits", num(), 0);
234
234
  return {
235
235
  hit: async (ctx) => {
236
236
  visits.change(ctx, (n) => n + 1);
@@ -240,7 +240,7 @@ host.serve(Visits, (_, _p, self) => {
240
240
  });
241
241
  ```
242
242
 
243
- **Methods** are declared with `method(args?, result?)` in the contract. Without `args` a method takes none: callers write `ref.hit(ctx)` (or `ref.hit()`), and its implementation is `(ctx) => …`. Without `result` it returns nothing: the implementation returns nothing, and callers get `undefined`. `method(undefined, Type.Number())` takes no arguments and returns a number.
243
+ **Methods** are declared with `method(args?, result?)` in the contract. Without `args` a method takes none: callers write `ref.hit(ctx)` (or `ref.hit()`), and its implementation is `(ctx) => …`. Without `result` it returns nothing: the implementation returns nothing, and callers get `undefined`. `method(undefined, num())` takes no arguments and returns a number.
244
244
 
245
245
  ## Activation
246
246
 
@@ -428,7 +428,7 @@ chat.release();
428
428
  ## State
429
429
 
430
430
  ```ts
431
- const todos = self.state("todos", Type.Array(TodoSchema), []);
431
+ const todos = self.state("todos", arr(TodoSchema), []);
432
432
 
433
433
  todos.change(ctx, (draft) => {
434
434
  draft.push({ id: "t1", text: "Write docs", done: false });
@@ -457,7 +457,7 @@ view.replace(ctx, rebuilt, { diff: true }); // always diff
457
457
 
458
458
  ```ts
459
459
  const db = self.resource("db", { version: 1, open: () => openSqlite(path), close: (db) => db.close() });
460
- const notes = self.state("notes", Type.Array(NoteSchema), { init: () => db.value.all("SELECT * FROM notes") });
460
+ const notes = self.state("notes", arr(NoteSchema), { init: () => db.value.all("SELECT * FROM notes") });
461
461
  ```
462
462
 
463
463
  `init(ctx)` runs once the resources are open and the references live, before the object goes live, so no method,
package/docs/spec.md CHANGED
@@ -3,7 +3,7 @@
3
3
  This document specifies the runtime in `src`. Where it and the code disagree, the disagreement is a bug. [Known limitations and decisions](#12-known-limitations-and-decisions) lists what the runtime does not do yet and the choices the sections below leave open.
4
4
 
5
5
  Hard constraints:
6
- - Chord's runtime depends only on its own `delta` module (tracker, applyImmutable, encoder/decoder, diff) and Node/browser built-ins plus `typebox` for schemas. No other draht packages.
6
+ - Chord's runtime depends only on its own `delta` module (tracker, applyImmutable, encoder/decoder, diff) and Node/browser built-ins, plus `@draht/telemetry` for telemetry and `@draht/schema` for schemas. No other draht packages.
7
7
  - Built-in plugins are trusted, loaded from source in-process. The plugin loader uses dynamic `import()` with a cache-busting query (owner-approved exception, `TODO(loader)`: replace with an isolating, evicting loader; old module copies leak; TUI plugins need isolation).
8
8
  - Hot reload is required. Host restart only for Chord/runtime code changes or host-level crash recovery.
9
9
 
@@ -29,23 +29,23 @@ Contracts are runtime values for every type (shipped bundles have no TypeScript;
29
29
  ```ts
30
30
  export const Chat = remote("draht.chat", {
31
31
  version: 1, // contract version: a plain number, bumped only on breaking changes
32
- input: Type.Object({ session: Type.String(), conversation: Type.Number() }),
32
+ input: obj({ session: str(), conversation: num() }),
33
33
  host: hostFamily("session:", "session"), // where its objects live: `session:` + input.session
34
34
  variants: {
35
35
  viewer: { state: { view: ViewSchema } },
36
36
  participant: {
37
37
  state: { view: ViewSchema },
38
- methods: { send: method(SendSchema, Type.Object({ submissionId: Type.Number() })) },
38
+ methods: { send: method(SendSchema, obj({ submissionId: num() })) },
39
39
  },
40
40
  },
41
41
  });
42
42
 
43
43
  export const Index = local("draht.index", {
44
44
  version: 1,
45
- input: Type.Object({ session: Type.String() }),
45
+ input: obj({ session: str() }),
46
46
  members: {
47
- search: method(Type.Object({ query: Type.String() }), Type.Array(Hit)),
48
- onChange: method(Type.Function([Change], Type.Void()), Unsubscribe), // non-JSON allowed for locals
47
+ search: method(obj({ query: str() }), arr(Hit)),
48
+ onChange: method({ type: "function", parameters: [Change], returnType: { type: "void" } }, Unsubscribe), // non-JSON allowed for locals
49
49
  harness: opaque("draht.durable-harness@1"), // native object, by name+version
50
50
  },
51
51
  });
@@ -81,7 +81,7 @@ Factories are synchronous; returning a promise throws. A declaration has a name
81
81
  host.serve(StatusStore, ({ session }, _host, self) => {
82
82
  const status = self.state("status", StatusSchema, { running: false, tasks: 0 }, // schema required, initial value
83
83
  { version: 2, migrate: (old, from) => upgrade(old, from) }); // per cell; default version 1
84
- const errors = self.state("errors", Type.Array(Type.String()), []);
84
+ const errors = self.state("errors", arr(str()), []);
85
85
  const catalog = self.get(Catalog, {}); // reference; identity = canonical address (+ at)
86
86
  const watch = self.resource("watch", {
87
87
  version: 1, deps: [catalog], exclusive: false,
@@ -278,7 +278,7 @@ The tests cover at least: lifetime/references/linger/forced disposal/gone; activ
278
278
  - **Joining during a reload.** Participants are the child hosts in step when a reload starts. A child whose hello arrives while it runs is decided when it ends: in step, or reconciled to the committed code version; a child already behind is fenced at once, so the calls its roots make meanwhile are admitted in the parent's code version. A reconciliation that is running when a reload starts syncs its child only after that reload ended, against the code version it committed. A reconciliation announces the parent's retired code versions before its `prepare`.
279
279
  - **Two-version rule.** An object of a changed type created after a commit has only new code; a previous-code-version root calling it gets `superseded`.
280
280
  - **Validation.** Remote calls are validated at reference dispatch, in-host too: a direct binding against the provider's schema, a binding through an adapter against the consumer's. A provider validates each snapshot and reset of a remote state member once per (re)subscription, against the consumer's contract through an `accepts` adapter and the provider's otherwise; ops are validated only in dev mode. At reload, the new provider's description must cover the old provider's when the version is unchanged, in addition to the check against live consumers and facets' `uses`.
281
- - **Contracts.** Local contracts list their members, so a loading reference knows whether a member is a method, state or opaque. Canonical identity omits input fields equal to their default; with TypeBox, use `Type.Optional(Type.X({ default }))` to let callers omit them. Provider variants must cover consumer variants; members the consumer's contract does not list are hidden. Schema change detection compares canonical JSON, so reordering `anyOf` branches counts as a change. Fingerprints use a non-cryptographic 64-bit hash: synchronous and browser-safe; contracts are trusted.
281
+ - **Contracts.** Local contracts list their members, so a loading reference knows whether a member is a method, state or opaque. Canonical identity omits input fields equal to their default; use `opt(str({ default }))` (@draht/schema) to let callers omit them. Provider variants must cover consumer variants; members the consumer's contract does not list are hidden. Schema change detection compares canonical JSON, so reordering `anyOf` branches counts as a change. Fingerprints use a non-cryptographic 64-bit hash: synchronous and browser-safe; contracts are trusted.
282
282
  - **Principals.** A root ctx at ingress acts as its principal (`host.root(fn, { principal })`); contexts inside objects act as `host`. The acceptor decides a link's kind and name (`accept(link, { principal, kind, name })`); only configured host links are addressable, carry roots and may vote, and control frames are accepted only from the parent. Clients never carry roots or code versions. Relaying needs a matching `route`; `authorize(principal, hostName)` runs before `resolve` and again after, and revoking or re-stamping a principal closes its relays at once. `invalidatePrincipal(match)` re-stamps or closes matching links and propagates pattern matches to child hosts.
283
283
  - **Cells and readables.** A value returned from `change` replaces the value and is always validated; `replace` transfers ownership without copying; by default (`{ diff }` overrides) it publishes a diff when the new value reuses a container of the old one at the same key, else `r`. `subscribe(fn)` delivers values, starting with the current one; `events(fn)` delivers `snap`, then `ops`, or `reset`. Reference state members are stable readables that throw `not_ready` while loading and `not_in_variant` outside the variant, and reset when their source moves; a listener added before they are readable gets its snapshot then. Remote state members stay hydrated while the reference is held.
284
284
  - **References and calls.** A reference's identity is its address; a second `self.get` of the same address in one run returns the same reference. A reference call without ctx, or with a task ctx, starts a fresh root in the current code version; a ctx whose call or root already settled is refused (`aborted/expired`), one from another host `invalid/foreign_ctx`. Calling a reference inside a factory throws `not_ready`.
package/docs/tutorial.md CHANGED
@@ -45,11 +45,12 @@ shuts down its objects and connections.
45
45
 
46
46
  Before callers can use an object, they need to agree on its name and members.
47
47
  That agreement is a **contract**: a runtime value that also gives TypeScript its
48
- types. A **schema** describes a value's shape. We use TypeBox's `Type` to write
49
- schemas. `method(args, result)` declares a method by its argument and result
50
- schemas: `method()` takes no arguments and returns nothing, and
51
- `method(undefined, Type.String())`, used below, takes no arguments and returns a
52
- string.
48
+ types. A **schema** describes a value's shape: plain JSON Schema, which we write
49
+ with the builders of `@draht/schema` (`obj`, `str`, `num`, ...;
50
+ `{ open: true }` lets an object carry fields it does not name).
51
+ `method(args, result)` declares a method by its argument and result schemas:
52
+ `method()` takes no arguments and returns nothing, and
53
+ `method(undefined, str())`, used below, takes no arguments and returns a string.
53
54
 
54
55
  Start with a label for a named list. `local` means only code inside this host
55
56
  can reach it. The input `{ list: "family" }` identifies which list we want;
@@ -59,8 +60,8 @@ it is not an argument to `label`.
59
60
  ```ts
60
61
  const TodoLabel = local("tutorial.todos", {
61
62
  version: 1,
62
- input: Type.Object({ list: Type.String() }),
63
- members: { label: method(undefined, Type.String()) },
63
+ input: obj({ list: str() }, { open: true }),
64
+ members: { label: method(undefined, str()) },
64
65
  });
65
66
  ```
66
67
 
@@ -116,17 +117,17 @@ name, because it holds nothing a reload must keep.
116
117
 
117
118
  <!-- example:03-contract -->
118
119
  ```ts
119
- const Todo = Type.Object({ text: Type.String(), done: Type.Boolean() });
120
- const Rows = Type.Array(Todo);
120
+ const Todo = obj({ text: str(), done: bool() }, { open: true });
121
+ const Rows = arr(Todo);
121
122
  const TodoStore = local("tutorial.todos", {
122
123
  version: 1,
123
- input: Type.Object({ list: Type.String() }),
124
+ input: obj({ list: str() }, { open: true }),
124
125
  members: {
125
- label: method(undefined, Type.String()),
126
+ label: method(undefined, str()),
126
127
  rows: Rows,
127
- openCount: Type.Number(),
128
- add: method(Type.Object({ text: Type.String() })),
129
- finish: method(Type.Object({ index: Type.Integer() })),
128
+ openCount: num(),
129
+ add: method(obj({ text: str() }, { open: true })),
130
+ finish: method(obj({ index: int() }, { open: true })),
130
131
  reset: method(Rows),
131
132
  },
132
133
  });
@@ -230,13 +231,13 @@ to a declared resource, without reading the resource during the factory.
230
231
  ```ts
231
232
  const Database = local("tutorial.database", {
232
233
  version: 1,
233
- input: Type.Object({}),
234
+ input: obj({}, { open: true }),
234
235
  members: { db: opaque<{ saved: string[] }>("tutorial.database@1") },
235
236
  });
236
237
  const SavedTodos = local("tutorial.saved-todos", {
237
238
  version: 1,
238
- input: Type.Object({ list: Type.String() }),
239
- members: { add: method(Type.Object({ text: Type.String() })) },
239
+ input: obj({ list: str() }, { open: true }),
240
+ members: { add: method(obj({ text: str() }, { open: true })) },
240
241
  });
241
242
  const host = createHost({ self: "server" });
242
243
  let opens = 0;
@@ -338,13 +339,13 @@ puts every `Todos` object on the host named `server`. Section 6 uses that.
338
339
  ```ts
339
340
  const Todos = remote("tutorial.todo-view", {
340
341
  version: 1,
341
- input: Type.Object({ list: Type.String() }),
342
+ input: obj({ list: str() }, { open: true }),
342
343
  host: hostNamed("server"),
343
344
  variants: {
344
345
  viewer: { state: { rows: Rows } },
345
346
  editor: {
346
347
  state: { rows: Rows },
347
- methods: { add: method(Type.Object({ text: Type.String() })) },
348
+ methods: { add: method(obj({ text: str() }, { open: true })) },
348
349
  },
349
350
  },
350
351
  });
@@ -499,8 +500,8 @@ test; they are not stored application state.
499
500
  ```ts
500
501
  const Activity = local("tutorial.activity", {
501
502
  version: 1,
502
- input: Type.Object({}),
503
- members: { seen: Type.Number() },
503
+ input: obj({}, { open: true }),
504
+ members: { seen: num() },
504
505
  });
505
506
  const host = createHost({ self: "server" });
506
507
  host.serve(TodoStore, todoFactory);
@@ -509,7 +510,7 @@ const seeded = Promise.withResolvers<void>();
509
510
  const stopped = Promise.withResolvers<void>();
510
511
  host.serve(Activity, (_input, _principal, self) => {
511
512
  const todos = self.get(TodoStore, { list: "family" });
512
- const seen = self.state("seen", Type.Number(), 0);
513
+ const seen = self.state("seen", num(), 0);
513
514
  self.on("rows", todos.rows, (rows, ctx) => {
514
515
  seen.replace(ctx, rows?.length ?? 0);
515
516
  if (rows?.length === 1) observed.resolve();
@@ -570,7 +571,7 @@ default lifetime, `"referenced"`, are still created only when referenced.
570
571
  <!-- example:08 -->
571
572
  ```ts
572
573
  const Actions = defineRegistry<(ctx: Ctx) => Promise<number>>("tutorial.actions");
573
- const Menu = local("tutorial.menu", { version: 1, input: Type.Object({}) });
574
+ const Menu = local("tutorial.menu", { version: 1, input: obj({}, { open: true }) });
574
575
  let click: (() => Promise<number>) | undefined;
575
576
  const storeFacet: Facet = {
576
577
  name: "todo-store",
@@ -745,7 +746,7 @@ const { label: _label, ...members } = TodoStore.def.members;
745
746
  const RenamedStore = local("tutorial.todos", {
746
747
  version: 2,
747
748
  input: TodoStore.def.input,
748
- members: { ...members, heading: method(undefined, Type.String()) },
749
+ members: { ...members, heading: method(undefined, str()) },
749
750
  });
750
751
  await host.reload([
751
752
  {
@@ -890,7 +891,7 @@ tutorial's source-matching check, not by the application.
890
891
  ```ts
891
892
  import assert from "node:assert/strict";
892
893
  import { readFileSync } from "node:fs";
893
- import { type Static, Type } from "typebox";
894
+ import { arr, bool, int, num, obj, type Static, str } from "@draht/schema";
894
895
  import { it, onTestFinished } from "vitest";
895
896
  import {
896
897
  type Ctx,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@draht/chord",
3
- "version": "2026.10.31",
3
+ "version": "2026.11.5",
4
4
  "description": "Typed host runtime for plugins, contracts, replicated state, and RPC over JSON links",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -61,7 +61,7 @@
61
61
  "src/delta/README.md"
62
62
  ],
63
63
  "scripts": {
64
- "clean": "shx rm -rf dist",
64
+ "clean": "node ../../scripts/package-files.mjs clean dist",
65
65
  "build": "tsc -p tsconfig.build.json",
66
66
  "test": "vitest --run",
67
67
  "prepublishOnly": "npm run clean && npm run build"
@@ -84,11 +84,10 @@
84
84
  "node": "^22.23.4 || ^24.22.1 || ^26.12.1"
85
85
  },
86
86
  "dependencies": {
87
- "@draht/telemetry": "2026.10.31",
88
- "typebox": "^1.3.27"
87
+ "@draht/schema": "2026.11.5",
88
+ "@draht/telemetry": "2026.11.5"
89
89
  },
90
90
  "devDependencies": {
91
- "shx": "0.3.4",
92
91
  "vitest": "^3.2.4",
93
92
  "@types/ws": "^8.18.1",
94
93
  "ws": "^8.21.0"