@volter/world-core 2.0.36 → 3.0.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 (205) hide show
  1. package/README.md +4 -5
  2. package/app-route.cjs +12 -6
  3. package/app-route.d.cts +1 -1
  4. package/dist/app-route.cjs +12 -6
  5. package/dist/app-route.d.cts +1 -1
  6. package/dist/generated/pack-facts.json +1410 -3069
  7. package/dist/inject.cjs +64 -9
  8. package/dist/pack-facts.cjs +44 -0
  9. package/dist/src/actions.d.ts +3 -3
  10. package/dist/src/actions.js +22 -16
  11. package/dist/src/ancestry.d.ts +14 -2
  12. package/dist/src/ancestry.js +92 -2
  13. package/dist/src/anthropic-wire.d.ts +39 -0
  14. package/dist/src/anthropic-wire.js +136 -0
  15. package/dist/src/bytes.d.ts +7 -0
  16. package/dist/src/bytes.js +35 -0
  17. package/dist/src/changeset.d.ts +1 -1
  18. package/dist/src/changeset.js +0 -0
  19. package/dist/src/clickhouse/index.d.ts +3 -0
  20. package/dist/src/clickhouse/index.js +6 -0
  21. package/dist/src/clickhouse/sql.d.ts +233 -0
  22. package/dist/src/clickhouse/sql.js +4329 -0
  23. package/dist/src/clickhouse/types.d.ts +18 -0
  24. package/dist/src/clickhouse/types.js +47 -0
  25. package/dist/src/clickhouse/values.d.ts +146 -0
  26. package/dist/src/clickhouse/values.js +858 -0
  27. package/dist/src/client-bundle.js +2 -3
  28. package/dist/src/cors.d.ts +15 -0
  29. package/dist/src/cors.js +31 -0
  30. package/dist/src/derived-core.d.ts +487 -24
  31. package/dist/src/derived-core.js +788 -144
  32. package/dist/src/derived-real.d.ts +13 -0
  33. package/dist/src/derived-real.js +518 -0
  34. package/dist/src/derived.d.ts +35 -1
  35. package/dist/src/derived.js +61 -9
  36. package/dist/src/emit.js +1 -2
  37. package/dist/src/events.d.ts +206 -0
  38. package/dist/src/events.js +341 -0
  39. package/dist/src/executor.d.ts +3 -0
  40. package/dist/src/executor.js +19 -2
  41. package/dist/src/file-response.d.ts +6 -0
  42. package/dist/src/file-response.js +30 -0
  43. package/dist/src/fork.js +3 -2
  44. package/dist/src/git/history.d.ts +7 -0
  45. package/dist/src/git/history.js +24 -0
  46. package/dist/src/git/index.d.ts +1 -0
  47. package/dist/src/git/index.js +1 -0
  48. package/dist/src/git/lfs.d.ts +28 -0
  49. package/dist/src/git/lfs.js +66 -0
  50. package/dist/src/git/objects.js +3 -8
  51. package/dist/src/git/smart-http.d.ts +3 -1
  52. package/dist/src/git/smart-http.js +67 -6
  53. package/dist/src/graphql-wire.d.ts +29 -0
  54. package/dist/src/graphql-wire.js +101 -0
  55. package/dist/src/grpc-wire.d.ts +67 -0
  56. package/dist/src/grpc-wire.js +170 -0
  57. package/dist/src/h2.d.ts +40 -0
  58. package/dist/src/h2.js +656 -0
  59. package/dist/src/head.d.ts +32 -3
  60. package/dist/src/head.js +161 -40
  61. package/dist/src/history.d.ts +1 -1
  62. package/dist/src/history.js +6 -6
  63. package/dist/src/hpack.json +1 -0
  64. package/dist/src/index.d.ts +64 -75
  65. package/dist/src/index.js +58 -101
  66. package/dist/src/log.js +28 -19
  67. package/dist/src/machines.d.ts +50 -0
  68. package/dist/src/machines.js +151 -0
  69. package/dist/src/managed-database.d.ts +86 -0
  70. package/dist/src/managed-database.js +283 -0
  71. package/dist/src/multipart.d.ts +11 -0
  72. package/dist/src/multipart.js +51 -0
  73. package/dist/src/observe.d.ts +15 -5
  74. package/dist/src/observe.js +23 -9
  75. package/dist/src/openai-wire.d.ts +108 -0
  76. package/dist/src/openai-wire.js +337 -0
  77. package/dist/src/pack-assets.d.ts +3 -4
  78. package/dist/src/pack-assets.js +15 -10
  79. package/dist/src/pack-fetch.d.ts +77 -0
  80. package/dist/src/pack-fetch.js +449 -0
  81. package/dist/src/pack-paths.d.ts +12 -0
  82. package/dist/src/pack-paths.js +86 -0
  83. package/dist/src/packRegistry.d.ts +69 -162
  84. package/dist/src/packRegistry.js +55 -20
  85. package/dist/src/people.d.ts +13 -0
  86. package/dist/src/people.js +18 -0
  87. package/dist/src/placeholder-image.d.ts +5 -0
  88. package/dist/src/placeholder-image.js +114 -0
  89. package/dist/src/protobuf.d.ts +28 -0
  90. package/dist/src/protobuf.js +332 -0
  91. package/dist/src/redis/engine.js +1 -1
  92. package/dist/src/request-scope.d.ts +1 -1
  93. package/dist/src/request-scope.js +6 -4
  94. package/dist/src/resource-blob.d.ts +5 -0
  95. package/dist/src/resource-blob.js +11 -0
  96. package/dist/src/runtime.d.ts +85 -0
  97. package/dist/src/runtime.js +104 -0
  98. package/dist/src/s3/wire.d.ts +60 -0
  99. package/dist/src/s3/wire.js +157 -0
  100. package/dist/src/scenario.d.ts +3 -0
  101. package/dist/src/scenario.js +2 -0
  102. package/dist/src/schema-sample.d.ts +1 -0
  103. package/dist/src/schema-sample.js +21 -0
  104. package/dist/src/sealed-box.d.ts +14 -0
  105. package/dist/src/sealed-box.js +225 -0
  106. package/dist/src/serve-http.d.ts +14 -0
  107. package/dist/src/serve-http.js +27 -3
  108. package/dist/src/serve.d.ts +6 -0
  109. package/dist/src/serve.js +69 -14
  110. package/dist/src/signing.d.ts +135 -0
  111. package/dist/src/signing.js +222 -0
  112. package/dist/src/sigv4.d.ts +48 -0
  113. package/dist/src/sigv4.js +167 -0
  114. package/dist/src/smtp.d.ts +16 -0
  115. package/dist/src/smtp.js +72 -0
  116. package/dist/src/sockets.d.ts +51 -0
  117. package/dist/src/sockets.js +90 -0
  118. package/dist/src/state-system.d.ts +1 -0
  119. package/dist/src/state-system.js +1 -1
  120. package/dist/src/storage.d.ts +1 -1
  121. package/dist/src/storage.js +3 -3
  122. package/dist/src/trace-context.js +1 -1
  123. package/dist/src/twin-fetch.d.ts +0 -7
  124. package/dist/src/twin-fetch.js +0 -14
  125. package/dist/src/vendor-call.d.ts +6 -0
  126. package/dist/src/vendor-call.js +41 -0
  127. package/dist/src/world-store.js +1 -1
  128. package/dist/vendor-hosts.cjs +36 -125
  129. package/dist/vendor-hosts.d.cts +8 -0
  130. package/generated/pack-facts.json +1410 -3069
  131. package/inject.cjs +64 -9
  132. package/pack-facts.cjs +44 -0
  133. package/package.json +17 -3
  134. package/src/actions.ts +23 -16
  135. package/src/ancestry.ts +74 -2
  136. package/src/anthropic-wire.ts +137 -0
  137. package/src/bytes.ts +42 -0
  138. package/src/changeset.ts +5 -5
  139. package/src/clickhouse/index.ts +6 -0
  140. package/src/clickhouse/sql.ts +3059 -0
  141. package/src/clickhouse/types.ts +44 -0
  142. package/src/clickhouse/values.ts +697 -0
  143. package/src/client-bundle.ts +2 -3
  144. package/src/cors.ts +34 -0
  145. package/src/derived-core.ts +1013 -146
  146. package/src/derived-real.ts +434 -0
  147. package/src/derived.ts +73 -3
  148. package/src/emit.ts +1 -2
  149. package/src/events.ts +449 -0
  150. package/src/executor.ts +24 -2
  151. package/src/file-response.ts +27 -0
  152. package/src/fork.ts +3 -2
  153. package/src/git/history.ts +19 -0
  154. package/src/git/index.ts +1 -0
  155. package/src/git/lfs.ts +67 -0
  156. package/src/git/objects.ts +3 -5
  157. package/src/git/smart-http.ts +56 -6
  158. package/src/graphql-wire.ts +106 -0
  159. package/src/grpc-wire.ts +159 -0
  160. package/src/h2.ts +627 -0
  161. package/src/head.ts +132 -41
  162. package/src/history.ts +6 -6
  163. package/src/hpack.json +1 -0
  164. package/src/index.ts +82 -329
  165. package/src/log.ts +27 -18
  166. package/src/machines.ts +151 -0
  167. package/src/managed-database.ts +299 -0
  168. package/src/multipart.ts +51 -0
  169. package/src/observe.ts +31 -15
  170. package/src/openai-wire.ts +371 -0
  171. package/src/pack-assets.ts +15 -11
  172. package/src/pack-fetch.ts +458 -0
  173. package/src/pack-paths.ts +72 -0
  174. package/src/packRegistry.ts +79 -167
  175. package/src/people.ts +31 -0
  176. package/src/placeholder-image.ts +88 -0
  177. package/src/protobuf.ts +251 -0
  178. package/src/redis/engine.ts +1 -1
  179. package/src/request-scope.ts +8 -4
  180. package/src/resource-blob.ts +13 -0
  181. package/src/runtime.ts +344 -0
  182. package/src/s3/wire.ts +172 -0
  183. package/src/scenario.ts +4 -0
  184. package/src/schema-sample.ts +24 -0
  185. package/src/sealed-box.ts +182 -0
  186. package/src/serve-http.ts +31 -3
  187. package/src/serve.ts +58 -14
  188. package/src/signing.ts +231 -0
  189. package/src/sigv4.ts +158 -0
  190. package/src/smtp.ts +76 -0
  191. package/src/sockets.ts +140 -0
  192. package/src/state-system.ts +2 -2
  193. package/src/storage.ts +3 -3
  194. package/src/trace-context.ts +1 -1
  195. package/src/twin-fetch.ts +0 -20
  196. package/src/vendor-call.ts +41 -0
  197. package/src/world-store.ts +1 -1
  198. package/vendor-hosts.cjs +36 -125
  199. package/vendor-hosts.d.cts +8 -0
  200. package/dist/src/mirror-shell.d.ts +0 -2
  201. package/dist/src/mirror-shell.js +0 -13
  202. package/dist/src/v1-removed.d.ts +0 -159
  203. package/dist/src/v1-removed.js +0 -124
  204. package/src/mirror-shell.ts +0 -15
  205. package/src/v1-removed.ts +0 -172
@@ -0,0 +1,28 @@
1
+ export type ProtoField = {
2
+ name: string;
3
+ json: string;
4
+ number: number;
5
+ type: string;
6
+ kind: 'scalar' | 'message' | 'enum';
7
+ repeated?: true;
8
+ map?: {
9
+ key: string;
10
+ value: string;
11
+ valueKind: 'scalar' | 'message' | 'enum';
12
+ };
13
+ };
14
+ export type ProtoSchema = {
15
+ messages: Record<string, ProtoField[]>;
16
+ enums: Record<string, Record<string, number>>;
17
+ rpcs: Record<string, {
18
+ operation: string;
19
+ request: string;
20
+ response: string;
21
+ serverStreams?: true;
22
+ clientStreams?: true;
23
+ }>;
24
+ };
25
+ /** A message's JSON form (proto3 JSON) as its binary encoding. */
26
+ export declare function encodeMessage(schema: ProtoSchema, type: string, value: unknown): Uint8Array;
27
+ /** A message's binary encoding as its JSON form (proto3 JSON; a field at its default is left out). */
28
+ export declare function decodeMessage(schema: ProtoSchema, type: string, bytes: Uint8Array): unknown;
@@ -0,0 +1,332 @@
1
+ // PROTOCOL BUFFERS (architecture, "Other wires": the gRPC wire): a message's proto3 JSON form
2
+ // (https://protobuf.dev/programming-guides/json/) to its binary encoding (https://protobuf.dev/programming-guides/encoding/)
3
+ // and back, over the schema the derive writes for a proto unit (`src/generated/proto.gen.json`, twin-standard's
4
+ // `protoSchema`). A handler reads and answers the JSON form; the wire carries the bytes. The JSON form names a field by
5
+ // its JSON name, writes 64-bit integers as decimal strings, bytes as base64, enums by their value names, a map as an
6
+ // object, and leaves out a field holding its default; `google.protobuf.Timestamp`, `Duration`, the wrappers and `Empty`
7
+ // take their own JSON forms. Importing it does nothing.
8
+ const VARINT = new Set(['int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'bool']);
9
+ const FIXED64 = new Set(['fixed64', 'sfixed64', 'double']);
10
+ const FIXED32 = new Set(['fixed32', 'sfixed32', 'float']);
11
+ const LONG = new Set(['int64', 'uint64', 'sint64', 'fixed64', 'sfixed64']);
12
+ const WRAPPERS = {
13
+ 'google.protobuf.DoubleValue': 'double', 'google.protobuf.FloatValue': 'float', 'google.protobuf.Int64Value': 'int64',
14
+ 'google.protobuf.UInt64Value': 'uint64', 'google.protobuf.Int32Value': 'int32', 'google.protobuf.UInt32Value': 'uint32',
15
+ 'google.protobuf.BoolValue': 'bool', 'google.protobuf.StringValue': 'string', 'google.protobuf.BytesValue': 'bytes',
16
+ };
17
+ const ENC = new TextEncoder();
18
+ const DEC = new TextDecoder();
19
+ const wireOf = (f) => f.kind === 'enum' || VARINT.has(f.type) ? 0 : FIXED64.has(f.type) ? 1 : FIXED32.has(f.type) ? 5 : 2;
20
+ // ── writing ────────────────────────────────────────────────────────────────────────────────────
21
+ class Writer {
22
+ parts = [];
23
+ varint(v) {
24
+ let x = BigInt.asUintN(64, v);
25
+ while (x >= 0x80n) {
26
+ this.parts.push(Number((x & 0x7fn) | 0x80n));
27
+ x >>= 7n;
28
+ }
29
+ this.parts.push(Number(x));
30
+ }
31
+ tag(number, wire) { this.varint((BigInt(number) << 3n) | BigInt(wire)); }
32
+ bytes(b) { this.varint(BigInt(b.length)); for (const x of b)
33
+ this.parts.push(x); }
34
+ raw(b) { for (const x of b)
35
+ this.parts.push(x); }
36
+ fixed(v, size, float = false) {
37
+ const buf = new DataView(new ArrayBuffer(size));
38
+ if (float) {
39
+ if (size === 8)
40
+ buf.setFloat64(0, Number(v), true);
41
+ else
42
+ buf.setFloat32(0, Number(v), true);
43
+ }
44
+ else if (size === 8)
45
+ buf.setBigUint64(0, BigInt.asUintN(64, BigInt(v)), true);
46
+ else
47
+ buf.setUint32(0, Number(BigInt.asUintN(32, BigInt(v))), true);
48
+ for (const x of new Uint8Array(buf.buffer))
49
+ this.parts.push(x);
50
+ }
51
+ done() { return Uint8Array.from(this.parts); }
52
+ }
53
+ const zigzag = (v, bits) => (v << 1n) ^ (v >> BigInt(bits - 1));
54
+ const b64decode = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
55
+ const b64encode = (b) => btoa(Array.from(b, (x) => String.fromCharCode(x)).join(''));
56
+ function enumNumber(schema, type, v) {
57
+ if (typeof v === 'number')
58
+ return v;
59
+ const n = schema.enums[type]?.[String(v)];
60
+ if (n === undefined)
61
+ throw new Error(`protobuf: ${String(v)} is not a value of ${type}`);
62
+ return n;
63
+ }
64
+ function writeScalar(w, type, v) {
65
+ switch (type) {
66
+ case 'int32':
67
+ case 'int64':
68
+ case 'uint32':
69
+ case 'uint64':
70
+ w.varint(BigInt(v));
71
+ break;
72
+ case 'sint32':
73
+ w.varint(zigzag(BigInt(v), 32));
74
+ break;
75
+ case 'sint64':
76
+ w.varint(zigzag(BigInt(v), 64));
77
+ break;
78
+ case 'bool':
79
+ w.varint(v ? 1n : 0n);
80
+ break;
81
+ case 'fixed64':
82
+ case 'sfixed64':
83
+ w.fixed(BigInt(v), 8);
84
+ break;
85
+ case 'double':
86
+ w.fixed(Number(v), 8, true);
87
+ break;
88
+ case 'fixed32':
89
+ case 'sfixed32':
90
+ w.fixed(Number(v), 4);
91
+ break;
92
+ case 'float':
93
+ w.fixed(Number(v), 4, true);
94
+ break;
95
+ default: throw new Error(`protobuf: ${type} is not a packable scalar`);
96
+ }
97
+ }
98
+ /** A well-known type's JSON form as the message it stands for, or undefined for any other type. */
99
+ function wellKnownIn(type, v) {
100
+ if (type === 'google.protobuf.Timestamp' && typeof v === 'string') {
101
+ const ms = Date.parse(v);
102
+ const frac = /\.(\d+)/.exec(v)?.[1] ?? '';
103
+ return { seconds: String(Math.floor(ms / 1000)), nanos: Number(frac.padEnd(9, '0').slice(0, 9)) };
104
+ }
105
+ if (type === 'google.protobuf.Duration' && typeof v === 'string') {
106
+ const [s, f = ''] = v.replace(/s$/, '').split('.');
107
+ return { seconds: s, nanos: (s.startsWith('-') ? -1 : 1) * Number(f.padEnd(9, '0').slice(0, 9)) };
108
+ }
109
+ if (WRAPPERS[type] !== undefined)
110
+ return { value: v };
111
+ return undefined;
112
+ }
113
+ function writeValue(schema, w, f, v) {
114
+ if (f.kind === 'message') {
115
+ w.tag(f.number, 2);
116
+ w.bytes(encodeMessage(schema, f.type, v));
117
+ return;
118
+ }
119
+ if (f.kind === 'enum') {
120
+ w.tag(f.number, 0);
121
+ w.varint(BigInt(enumNumber(schema, f.type, v)));
122
+ return;
123
+ }
124
+ if (f.type === 'string') {
125
+ w.tag(f.number, 2);
126
+ w.bytes(ENC.encode(String(v)));
127
+ return;
128
+ }
129
+ if (f.type === 'bytes') {
130
+ w.tag(f.number, 2);
131
+ w.bytes(typeof v === 'string' ? b64decode(v) : v);
132
+ return;
133
+ }
134
+ w.tag(f.number, wireOf(f));
135
+ writeScalar(w, f.type, v);
136
+ }
137
+ /** A message's JSON form (proto3 JSON) as its binary encoding. */
138
+ export function encodeMessage(schema, type, value) {
139
+ const known = wellKnownIn(type, value);
140
+ const v = (known ?? (value && typeof value === 'object' ? value : {}));
141
+ const fields = schema.messages[type];
142
+ if (!fields)
143
+ throw new Error(`protobuf: ${type} is not a message of the schema`);
144
+ const w = new Writer();
145
+ for (const f of fields) {
146
+ const x = v[f.json] ?? v[f.name];
147
+ if (x === undefined || x === null)
148
+ continue;
149
+ if (f.map) {
150
+ for (const [k, mv] of Object.entries(x)) {
151
+ const entry = new Writer();
152
+ const keyType = f.map.key;
153
+ writeValue(schema, entry, { number: 1, type: keyType, kind: 'scalar' }, keyType === 'bool' ? k === 'true' : k);
154
+ writeValue(schema, entry, { number: 2, type: f.map.value, kind: f.map.valueKind }, mv);
155
+ w.tag(f.number, 2);
156
+ w.bytes(entry.done());
157
+ }
158
+ }
159
+ else if (f.repeated) {
160
+ const list = x;
161
+ if (f.kind === 'enum' || (f.kind === 'scalar' && f.type !== 'string' && f.type !== 'bytes')) {
162
+ // proto3 packs repeated scalars and enums
163
+ const packed = new Writer();
164
+ for (const item of list) {
165
+ if (f.kind === 'enum')
166
+ packed.varint(BigInt(enumNumber(schema, f.type, item)));
167
+ else
168
+ writeScalar(packed, f.type, item);
169
+ }
170
+ w.tag(f.number, 2);
171
+ w.bytes(packed.done());
172
+ }
173
+ else
174
+ for (const item of list)
175
+ writeValue(schema, w, f, item);
176
+ }
177
+ else
178
+ writeValue(schema, w, f, x);
179
+ }
180
+ return w.done();
181
+ }
182
+ // ── reading ────────────────────────────────────────────────────────────────────────────────────
183
+ class Reader {
184
+ b;
185
+ at = 0;
186
+ constructor(b) {
187
+ this.b = b;
188
+ }
189
+ get done() { return this.at >= this.b.length; }
190
+ varint() {
191
+ let out = 0n;
192
+ let shift = 0n;
193
+ for (;;) {
194
+ if (this.at >= this.b.length)
195
+ throw new Error('protobuf: a varint runs past the end');
196
+ const x = this.b[this.at++];
197
+ out |= BigInt(x & 0x7f) << shift;
198
+ if (!(x & 0x80))
199
+ return out;
200
+ shift += 7n;
201
+ }
202
+ }
203
+ take(n) {
204
+ if (n < 0 || this.at + n > this.b.length)
205
+ throw new Error(`protobuf: a field runs past the message's end (${n} bytes at ${this.at} of ${this.b.length})`);
206
+ const out = this.b.subarray(this.at, this.at + n);
207
+ this.at += n;
208
+ return out;
209
+ }
210
+ bytes() { return this.take(Number(this.varint())); }
211
+ skip(wire) {
212
+ if (wire === 0)
213
+ this.varint();
214
+ else if (wire === 1)
215
+ this.take(8);
216
+ else if (wire === 5)
217
+ this.take(4);
218
+ else if (wire === 2)
219
+ this.bytes();
220
+ else
221
+ throw new Error(`protobuf: wire type ${wire} is not supported`);
222
+ }
223
+ }
224
+ const unzigzag = (v) => (v >> 1n) ^ -(v & 1n);
225
+ function readScalar(r, type) {
226
+ switch (type) {
227
+ case 'int32': return Number(BigInt.asIntN(32, r.varint()));
228
+ case 'uint32': return Number(BigInt.asUintN(32, r.varint()));
229
+ case 'int64': return String(BigInt.asIntN(64, r.varint()));
230
+ case 'uint64': return String(BigInt.asUintN(64, r.varint()));
231
+ case 'sint32': return Number(unzigzag(r.varint()));
232
+ case 'sint64': return String(unzigzag(r.varint()));
233
+ case 'bool': return r.varint() !== 0n;
234
+ case 'fixed64': return String(new DataView(r.take(8).slice().buffer).getBigUint64(0, true));
235
+ case 'sfixed64': return String(new DataView(r.take(8).slice().buffer).getBigInt64(0, true));
236
+ case 'double': return new DataView(r.take(8).slice().buffer).getFloat64(0, true);
237
+ case 'fixed32': return new DataView(r.take(4).slice().buffer).getUint32(0, true);
238
+ case 'sfixed32': return new DataView(r.take(4).slice().buffer).getInt32(0, true);
239
+ case 'float': return new DataView(r.take(4).slice().buffer).getFloat32(0, true);
240
+ default: throw new Error(`protobuf: ${type} is not a scalar`);
241
+ }
242
+ }
243
+ function enumName(schema, type, n) {
244
+ for (const [name, v] of Object.entries(schema.enums[type] ?? {}))
245
+ if (v === n)
246
+ return name;
247
+ return n;
248
+ }
249
+ function readValue(schema, r, f, wire) {
250
+ if (f.kind === 'message')
251
+ return decodeMessage(schema, f.type, r.bytes());
252
+ if (f.kind === 'enum')
253
+ return enumName(schema, f.type, Number(BigInt.asIntN(32, r.varint())));
254
+ if (f.type === 'string')
255
+ return DEC.decode(r.bytes());
256
+ if (f.type === 'bytes')
257
+ return b64encode(r.bytes());
258
+ void wire;
259
+ return readScalar(r, f.type);
260
+ }
261
+ /** A well-known message's JSON form from its decoded fields, or the fields as they are for any other type. */
262
+ function wellKnownOut(type, m) {
263
+ if (type === 'google.protobuf.Timestamp') {
264
+ const whole = new Date(Number(m.seconds ?? 0) * 1000).toISOString().replace(/\.000Z$/, '');
265
+ const nanos = Number(m.nanos ?? 0);
266
+ return `${whole}${protoFraction(nanos)}Z`;
267
+ }
268
+ if (type === 'google.protobuf.Duration') {
269
+ const seconds = BigInt(String(m.seconds ?? '0'));
270
+ const nanos = Number(m.nanos ?? 0);
271
+ const negative = seconds < 0n || nanos < 0;
272
+ return `${negative ? '-' : ''}${seconds < 0n ? -seconds : seconds}${protoFraction(Math.abs(nanos))}s`;
273
+ }
274
+ if (WRAPPERS[type] !== undefined)
275
+ return m.value ?? (WRAPPERS[type] === 'bool' ? false : WRAPPERS[type] === 'string' || WRAPPERS[type] === 'bytes' ? '' : 0);
276
+ return m;
277
+ }
278
+ /** ProtoJSON emits 0, 3, 6 or 9 fractional digits, retaining the full nanosecond value. */
279
+ function protoFraction(nanos) {
280
+ if (!nanos)
281
+ return '';
282
+ const digits = String(nanos).padStart(9, '0');
283
+ return `.${digits.slice(0, nanos % 1e6 === 0 ? 3 : nanos % 1000 === 0 ? 6 : 9)}`;
284
+ }
285
+ /** A message's binary encoding as its JSON form (proto3 JSON; a field at its default is left out). */
286
+ export function decodeMessage(schema, type, bytes) {
287
+ const fields = schema.messages[type];
288
+ if (!fields)
289
+ throw new Error(`protobuf: ${type} is not a message of the schema`);
290
+ const byNumber = new Map(fields.map((f) => [f.number, f]));
291
+ const out = {};
292
+ const r = new Reader(bytes);
293
+ while (!r.done) {
294
+ const key = Number(r.varint());
295
+ const number = key >>> 3;
296
+ const wire = key & 7;
297
+ const f = byNumber.get(number);
298
+ if (!f) {
299
+ r.skip(wire);
300
+ continue;
301
+ }
302
+ if (f.map) {
303
+ const entry = new Reader(r.bytes());
304
+ let k;
305
+ let v;
306
+ while (!entry.done) {
307
+ const ek = Number(entry.varint());
308
+ if ((ek >>> 3) === 1)
309
+ k = readValue(schema, entry, { type: f.map.key, kind: 'scalar' }, ek & 7);
310
+ else if ((ek >>> 3) === 2)
311
+ v = readValue(schema, entry, { type: f.map.value, kind: f.map.valueKind }, ek & 7);
312
+ else
313
+ entry.skip(ek & 7);
314
+ }
315
+ (out[f.json] ??= {})[String(k ?? '')] = v;
316
+ }
317
+ else if (f.repeated) {
318
+ const list = (out[f.json] ??= []);
319
+ // a packed run of scalars or enums, or one element
320
+ if (wire === 2 && (f.kind === 'enum' || (f.kind === 'scalar' && f.type !== 'string' && f.type !== 'bytes'))) {
321
+ const packed = new Reader(r.bytes());
322
+ while (!packed.done)
323
+ list.push(f.kind === 'enum' ? enumName(schema, f.type, Number(BigInt.asIntN(32, packed.varint()))) : readScalar(packed, f.type));
324
+ }
325
+ else
326
+ list.push(readValue(schema, r, f, wire));
327
+ }
328
+ else
329
+ out[f.json] = readValue(schema, r, f, wire);
330
+ }
331
+ return wellKnownOut(type, out);
332
+ }
@@ -80,7 +80,7 @@ export class ReadOnlyError extends Error {
80
80
  this.name = 'ReadOnlyError';
81
81
  }
82
82
  }
83
- /** Redis's type name for a stream, as TYPE answers it (a Redis type, not the `stream` pack: scripts/architecture.test.ts). */
83
+ /** Redis's type name for a stream, as TYPE answers it (a Redis type, not a pack name: scripts/architecture-auto.ts A2). */
84
84
  const STREAM = 'stream';
85
85
  export const KEY_TYPES = ['string', 'list', 'set', 'hash', 'zset', STREAM];
86
86
  /** The subject-id prefix of a context's database. */
@@ -19,7 +19,7 @@ export declare function runAsReadOnlyRequest<T>(fn: () => T | Promise<T>): Promi
19
19
  refused: ReadOnlyRequestError;
20
20
  }>;
21
21
  /** Run `fn` as the VENDOR's own move (a pack's catch-up): its writes land even under a read-only
22
- * request. Outside one it changes nothing. */
22
+ * request, and are recorded as the World's own moves, never as the caller's API call (inVendorMove). */
23
23
  export declare function runAsVendorMove<T>(fn: () => T): T;
24
24
  /** Whether this runs as the vendor's own move (runAsVendorMove). */
25
25
  export declare function inVendorMove(): boolean;
@@ -11,7 +11,7 @@
11
11
  // runs under `runAsVendorMove` and still lands under a read-only request, as a real vendor renews a
12
12
  // subscription whoever is looking.
13
13
  //
14
- // Created on first use, never at import: a browser bundle of a mirror client carries the kernel and
14
+ // Created on first use, never at import: a browser bundle carries the kernel and
15
15
  // has no AsyncLocalStorage (see serve.ts identitySlot).
16
16
  import { AsyncLocalStorage } from 'node:async_hooks';
17
17
  import { runWithTraceparent, traceparentForDelivery } from "./trace-context.js";
@@ -23,11 +23,13 @@ export function isReadOnlyRequest(request) {
23
23
  }
24
24
  /** A write a read-only request attempted: refused before anything was written (rule D3's 405). */
25
25
  export class ReadOnlyRequestError extends Error {
26
+ // a field, not a parameter property: Node runs this module with its types stripped (an application importing the
27
+ // World clock), and stripping takes no parameter property
26
28
  service;
27
29
  constructor(service) {
28
30
  super(`${service}: this request is read-only (${READ_ONLY_REQUEST_HEADER}: 1); it cannot write`);
29
- this.service = service;
30
31
  this.name = 'ReadOnlyRequestError';
32
+ this.service = service;
31
33
  }
32
34
  }
33
35
  let writeScopeStore;
@@ -50,14 +52,14 @@ export async function runAsReadOnlyRequest(fn) {
50
52
  }
51
53
  }
52
54
  /** Run `fn` as the VENDOR's own move (a pack's catch-up): its writes land even under a read-only
53
- * request. Outside one it changes nothing. */
55
+ * request, and are recorded as the World's own moves, never as the caller's API call (inVendorMove). */
54
56
  export function runAsVendorMove(fn) {
55
57
  const current = writeScope().getStore();
56
58
  // the vendor's move is its own span of the request's trace (a delivery's shape): what it writes is joined to the
57
59
  // trace, never to the request's caller, who did not make it
58
60
  const own = traceparentForDelivery();
59
61
  const run = own ? () => runWithTraceparent(own, fn) : fn;
60
- return current ? writeScope().run({ ...current, vendorMove: true }, run) : run();
62
+ return writeScope().run(current ? { ...current, vendorMove: true } : { readOnly: false, vendorMove: true, refusals: [] }, run);
61
63
  }
62
64
  /** Whether this runs as the vendor's own move (runAsVendorMove). */
63
65
  export function inVendorMove() { return writeScopeStore?.getStore()?.vendorMove === true; }
@@ -1,5 +1,10 @@
1
1
  /** Read a resource payload at this branch, then its retained ancestors. */
2
2
  export declare function readResourceBlob(service: string, key: string, root?: string): Promise<Uint8Array | null>;
3
+ /** Write a resource payload on this branch (a stored object's bytes), where a read finds it first. */
4
+ export declare function writeResourceBlob(service: string, key: string, bytes: Uint8Array, root?: string): Promise<void>;
5
+ /** Remove this branch's copy of a resource payload; an ancestor's stays its own (the row that named it is what a
6
+ * deletion ends). */
7
+ export declare function removeResourceBlob(service: string, key: string, root?: string): Promise<void>;
3
8
  /** A service's resources dir at this branch, then at each retained ancestor's: where a read resolves a payload, and
4
9
  * what a listing that mints ids covers, so a branch serves bytes its parent received and never re-mints a parent's id. */
5
10
  export declare function resourceChain(service: string, root?: string): string[];
@@ -12,6 +12,17 @@ export async function readResourceBlob(service, key, root) {
12
12
  }
13
13
  return null;
14
14
  }
15
+ /** Write a resource payload on this branch (a stored object's bytes), where a read finds it first. */
16
+ export async function writeResourceBlob(service, key, bytes, root) {
17
+ assertResourceKey(key);
18
+ await getActiveBlobStore().put(join(worldPaths(service, root).resources, key), bytes);
19
+ }
20
+ /** Remove this branch's copy of a resource payload; an ancestor's stays its own (the row that named it is what a
21
+ * deletion ends). */
22
+ export async function removeResourceBlob(service, key, root) {
23
+ assertResourceKey(key);
24
+ await getActiveBlobStore().remove(join(worldPaths(service, root).resources, key));
25
+ }
15
26
  /** A service's resources dir at this branch, then at each retained ancestor's: where a read resolves a payload, and
16
27
  * what a listing that mints ids covers, so a branch serves bytes its parent received and never re-mints a parent's id. */
17
28
  export function resourceChain(service, root) {
@@ -0,0 +1,85 @@
1
+ export { clearRegistry, getPack, hasPack, listPacks, packOf, registerPack, pullPosture, assertContinuousPullAllowed, pullOnSchedule, resolvePullVendor, DEFAULT_PULL_POSTURE, DEFAULT_PULL_TRIGGER, PROTOCOL_VERSION, PROTOCOL_MAJOR, protocolStanding } from './packRegistry.js';
2
+ export type { PackTransport, PullPosture, PullTrigger, PullVendor, RoundTripWrite, TwinPack } from './packRegistry.js';
3
+ export { parseScenarioDocument, scenarioFaultResult, ScenarioEngine, ScenarioError, statefulTwinManifest, twinManifest } from './scenario.js';
4
+ export { WORLD_CLOCK_ENV, worldNow } from './world-clock.js';
5
+ export { WORLD_ENV_NAMES_ENV, worldEnvValue } from './world-env.js';
6
+ export { createTwinFetchFromHandler, TWIN_PREFIX_HEADER, TWIN_REQUEST_SCOPES, twinPublicBase, withRequestScopes } from './twin-fetch.js';
7
+ export { isReadOnlyRequest, READ_ONLY_REQUEST_HEADER, ReadOnlyRequestError, runAsReadOnlyRequest, runAsVendorMove, writesRefused } from './request-scope.js';
8
+ export { compileSurface, createDerivedFetch, matchOperation } from './derived.js';
9
+ export { currentTraceparent, deliveryTraceHeaders, newTraceparent, parseTraceparent, runWithRequestTrace, runWithTraceparent, TRACEPARENT_HEADER, traceparentForDelivery, validTraceparent } from './trace-context.js';
10
+ export type { Traceparent } from './trace-context.js';
11
+ export type { DerivedCall, DerivedCoreOutcome, DerivedFetch, DerivedFetchOptions, DerivedHandler, DerivedOperation, DerivedOwner, DerivedSurface } from './derived.js';
12
+ export { authRefusal, bindSemantics, coreFor, crossCutting, flagOf, derivedRequestScopes, observeTransitions, resourcesOfType as twinResourcesOfType, semanticsContext, stateOf, transitionFor, parseBracketForm, readParams, render as renderDerived, serveCore, sse, vendorError } from './derived-core.js';
13
+ export { deliverEvents, fillEnvelope, signEvent, signEventAll, verifyEvent } from './events.js';
14
+ export { equalSecrets, hmac, jwks, jwtDecode, jwtSign, jwtVerify, keyId, lettersFrom, md5, sha256, SIGNING_ALGORITHMS, uuidFrom } from './signing.js';
15
+ export type { HandlerCrypto, Jwk, Jwks, JwtVerdict, SigningKey } from './signing.js';
16
+ export type { EventDelivery, EventRender, EventScheme, EventsDecl, EventTransport, EventWrite } from './events.js';
17
+ export type { Actor, CoreScope, DerivedManifest, ErrorSpec, FieldRule, Handler, HandlerContext, ResourceDecl, WriteHookContext, ScreenDecl, Semantics, SemanticsContext, StateField, Transition, TransitionObserver, SeedCall } from './derived-core.js';
18
+ export type { RemoteExecute, RemoteExecuteRequest, RemoteExecuteResponse } from './remote-execute.js';
19
+ export type { TwinFetchAdapterConfig, TwinFetchHandlerRequest, TwinFetchHandlerResult, TwinStream, TwinStreamConnection, TwinStreamSink } from './twin-fetch.js';
20
+ export type { PackScenarioAdapter, ScenarioDecision, ScenarioDocument, ScenarioExtractorSpec, ScenarioFault, ScenarioFaultResult, ScenarioFeatures, ScenarioHandler, ScenarioMatcher, ScenarioMissRecord, ScenarioStatus } from './scenario.js';
21
+ export { emitTwinEvent, eventSubscriptionMatches, listEmittable, runEmitCli } from './emit.js';
22
+ export type { EmitDeliveryResult, EmitEndpoint, EmitReport, EmittableEvent, SynthesizedDelivery, TwinEmitter } from './emit.js';
23
+ export { DEFAULT_RATE_BUDGET, MAX_RATE_BUDGET_CEILING, MAX_RATE_BUDGET_WINDOW_MS, MIN_RATE_BUDGET_WEIGHT, MIN_RATE_BUDGET_WINDOW_MS, RateBudget, RateBudgetError, declareRateBudget, hasRateBudgetDeclaration, listRateBudgets, priceCall, rateBudgetPath, rateBudgetPolicy, rateBudgetWeight, resetToSeconds, assertBudgetGuardIntact, } from './rateBudget.js';
24
+ export type { RateBudgetDeclaration, RateBudgetErrorKind, RateBudgetOptions, RateBudgetPolicy, RateBudgetReservation, RateBudgetSnapshot, RateBudgetWeightRule, } from './rateBudget.js';
25
+ export { GenericWorldStateSchema, WorldActorSchema, WorldExternalRefSchema, WorldServiceEventSchema, WorldSubjectSchema, } from './schemas.js';
26
+ export { loadWorldConfig, } from './worldConfig.js';
27
+ export type { WorldConfig, WorldServiceConfig, } from './worldConfig.js';
28
+ export { DELTA_TYPE_SUFFIX, diffSubjectFields, hashFieldValue, subjectKey, deltaAfterFields } from './hash.js';
29
+ export type { FieldChange, SubjectFields, } from './hash.js';
30
+ export { appendDurable, appendEvent, createEvent, emptyGenericState, genericWorldReducer, listEvents, loadState, projectionLockPath, readJsonFile, rebuildGenericState, rebuildState, scrubService, scrubWorld, stateDirName, twinLog, withFileLock, worldPaths, worldStateRoot, ownerStoreRoots, WORLD_DATA_ENV, } from './storage.js';
31
+ export type { AppendEventResult, CommitQueuedEventsResult, GenericWorldState, EnqueueEventResult, QueuedWorldServiceEvent, WorldPaths, WorldReducer, WorldServiceEvent, } from './types.js';
32
+ export type { ScrubResult } from './storage.js';
33
+ export { FsWorldStore, MemoryWorldStore, getActiveWorldStore, setActiveWorldStore, withWorldStore, hydrateInto, flushFrom, } from './world-store.js';
34
+ export type { WorldStore, WorldStat, HydrationSource, HydrationSink } from './world-store.js';
35
+ export type { CheckLoader } from './head.js';
36
+ export { SqlWorldStore } from './world-store-sql.js';
37
+ export type { SqlExec } from './world-store-sql.js';
38
+ export { FsBlobStore, MemoryBlobStore, blobDigest, getActiveBlobStore, setActiveBlobStore, withBlobStore, readBlobRange, } from './blob-store.js';
39
+ export type { BlobStore } from './blob-store.js';
40
+ export { applyTwinWrite, applyTwinWriteAtomic, createTwinServer, CALLER_HEADER, callerForHeader, callerFromHeader, journalTwinRequest, readTwinRequestJournalFrom, type TwinRequestJournalCursor, twinRequestJournalFailures, twinRequestCredentials, readTwinRequestJournal, recordedInput, resolveTwinRead, twinRequestJournalEnabled, twinRequestJournalPath, twinResources, } from './serve.js';
41
+ export type { AtomicTwinWriteDecision, TwinRequestJournalEntry, TwinResource, TwinWriteInput, TwinWriteResult, } from './serve.js';
42
+ export { createTwinProxy } from './proxy.js';
43
+ export type { TwinProxy, TwinProxyOptions, VendorRoute } from './proxy.js';
44
+ export { forkTwin, isFork, readForkMeta, } from './fork.js';
45
+ export type { ForkMeta } from './fork.js';
46
+ export { appendAction, appendTransactionCommit, checkPrecondition, confirmAction, listActions, listTransactionCommits, pendingActions, pushablePendingActions, isTwinBookkeeping, pendingTransactionCommits, projectResources, projectOwnerResources, OwnerStoreAmbiguousError, revertAction, TwinActionPreconditionError, subjectAliases, resolveSubjectId, runWithCorrelationId, currentCorrelationId } from './actions.js';
47
+ export type { ActionProjection, ProjectedDelivery, ProjectedResource, ProjectedResourcePatch, ProjectedResourceRef, TwinAction, TwinActionOp, TwinActionPrecondition, TwinActionPreconditionOp, TwinActionRevertSpec, TwinTransactionCommit, TwinTransactionCommitOp, TwinTransactionPrecondition, TwinTransactionRevertSpec, } from './actions.js';
48
+ export { approveChangeset, assertMarkerBelongsTo, assertSafeChangesetName, assertValidVerifiers, buildChangeset, captureMarker, changesetContentHash, changesetHashMatches, changesetReadiness, approverOf, CHANGESET_KIND, diffLedgers, formatApplication, formatChangeset, formatRebaseReport, narrateActions, narrationDrift, rebaseChangeset, formatChangesetStatus, formatLedgerDelta, formatReplayReport, formatVerification, MARKER_KIND, normalizeChangeset, parseVerifierExpression, replayChangeset, runChangesetVerifiers, summarizeByVendor, twinWriteShape, withApplication, withVerification, worldBootMarker, WORLD_BOOT_MARKER_ID, } from './changeset.js';
49
+ export type { ApplyReceipt, RebaseActionResult, RebaseReport, RebaseTarget, Changeset, ChangesetAction, ChangesetApplication, CompensationEntry, ChangesetApproval, ChangesetReadiness, ChangesetVerification, ChangesetVerifier, ChangesetVerifierResult, LedgerDelta, LedgerPosition, LedgerRef, ReplayActionResult, ReplayReport, ReplayTarget, VendorSummary, WorldMarker, } from './changeset.js';
50
+ export { getActivePackAssets, setActivePackAssets, packAsset, assetContentType, confinedAssetPath, LocalPackAssets, BindingPackAssets, type PackAssetStore } from './pack-assets.js';
51
+ export { installedPackageDir, packRepository, isDerivedPack, vendorPackageDir, vendorOfPackModule } from './pack-paths.js';
52
+ export * as git from './git/index.js';
53
+ export * as s3 from './s3/wire.js';
54
+ export { PLACEHOLDER_REMOTE, beginPlaceholderPull, endPlaceholderPull, placeholderPullActive, placeholderPullMarkerPath, withPlaceholderPull, placeholderEventsFor } from './placeholder-remote.js';
55
+ export { aliasesFrom, ownFields, subjectHistory, rebaseBranch, cutCheckpoint, appendParentEntry, wholeLog, branchEntries, branchLogPath, branchMetaPath, CHECKPOINT_EVERY, dropCheckpoint, foldEntries, landedCopy, landedIds, parentEntries, parentLogPath, position, readBranchMeta, readTree, toEntry, toEvent, unpushedEntries, writeBranchMeta } from './log.js';
56
+ export type { BranchMeta, Entry, EntryOp, Receipt } from './log.js';
57
+ export { sealCredential, openSealedCredential, MemoryCredentialStorage, keySealer, transitSealer, type Rewrapped, type Sealer, type TransitSealerOptions, type SealedByVault, type SealedUnderKey } from './credential.js';
58
+ export type { CredentialPayload, CredentialStorage, SealedCredential } from './credential.js';
59
+ export { validateRemoteOrigin, buildRemoteExecute, type CredentialCustody } from './executor.js';
60
+ export type { TwinAuthStrategy } from './executor.js';
61
+ export { clearRoot, authStrategyFor, clearStateSystems, NO_SECRETS_CHECK, readRoot, registerAuthStrategy, registerStateSystem, rootPath, runChecks, stateSystemFor, writeRoot } from './state-system.js';
62
+ export type { Check, CheckVerdict, DeployPolicy, RootConfig, StateSystemAdapters } from './state-system.js';
63
+ export { observeAppends } from './actions.js';
64
+ export { appendActionIfAbsent, appendActionOccurrence } from './actions.js';
65
+ export { answerVendorErrors, performEntries, performAtHead, deployableEntries, headOf, boundRoot, loadChecks, loadCheck, openRootCredential, resealRootCredential, destinationOf, openSealedRecord, sealsThroughVault, rootCustody, sealingKey, setCheckLoader, setSealingKeySource, setSealer, currentSealer, openSealedAt, userKek, userKekPath, vendorOf, worldRootOf, RefusedWriteError, VendorWriteError, HeadError } from './head.js';
66
+ export type { BoundRoot, DeployReport, Head, PerformAction, PerformContext, PushOutcome } from './head.js';
67
+ export { observeResource, observeResources, collectObservations, foldObservations } from './observe.js';
68
+ export type { ObservedResource, ObserveReport, Observation } from './observe.js';
69
+ export { readTreeMap, readParentTreeMap, treeStamp, treeChangesSince, originEntries, appendOriginEntry, originLogPath, isUrlParent, parentPosition, positionAt, splitsBatch, assertBatchBoundary } from './log.js';
70
+ export { referenceField, registerReferences, packReferences, resolveReferences, type ReferenceDeclaration } from './references.js';
71
+ export { serveHttp, serveStream, nodeBuiltin, WORLD_BOOT_PATH, type HttpServer, type ServeHttpOptions, type HttpHandler } from './serve-http.js';
72
+ export { fileResponse, contentTypeOf } from './file-response.js';
73
+ export { bundleClient, filePathOf } from './client-bundle.js';
74
+ export { brandTokensResponse } from './brand-tokens.js';
75
+ export { multipartBoundary, multipartParts, type MultipartPart } from './multipart.js';
76
+ export { corsHeaders, withCors, type CorsDecl } from './cors.js';
77
+ export { vendorFetch, VendorUnreachableError } from './vendor-call.js';
78
+ export { closeManagedDatabases, EngineDatabaseError, EngineUnavailableError, managedDatabase, quoteIdent, useDatabaseDriver, WORLD_CLOCK_SETTING, worldClockSql, type DatabaseDriver } from './managed-database.js';
79
+ export type { Batch as EngineBatch, ManagedDatabase, Statement as EngineStatement, StatementResult as EngineStatementResult } from './managed-database.js';
80
+ export { readResourceBlob, readResourceBlobRange, removeResourceBlob, resourceBlobSize, resourceChain, writeResourceBlob } from './resource-blob.js';
81
+ export { assertStateRemovable, checkParent, stateGeneration, withAncestryLock, withHistoryLock, withHistoryLocks, withStateLock, withStateRemoval } from './ancestry.js';
82
+ export { captureHistory, captureParentHistory, historyChanges, historyAtInstant, historyDigest, historyEntries, historyLength, historyPrefix, inheritedHistory, originHead, publishOriginHistory, readHistoryView } from './history.js';
83
+ export type { HistoryView, HistoryLayout, HistoryReference, HistoryOrigin } from './history.js';
84
+ export { foldHistory } from './log.js';
85
+ export { volterHome } from './volter-home.js';