@effect-vfs/nfs 0.4.0 → 0.6.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.
@@ -1,178 +1,349 @@
1
+ import * as ByteSize from "effect/ByteSize";
2
+ import * as Context from "effect/Context";
3
+ import * as Data from "effect/Data";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Result from "effect/Result";
7
+ import * as Schema from "effect/Schema";
8
+ import * as SchemaIssue from "effect/SchemaIssue";
9
+ import * as SchemaTransformation from "effect/SchemaTransformation";
10
+ import * as SynchronizedRef from "effect/SynchronizedRef";
1
11
  /** @internal */
2
12
  export class XdrDecodeError extends Data.TaggedError("XdrDecodeError") {
3
- constructor(message) {
4
- super({ detail: message });
5
- }
6
13
  get message() {
7
14
  return this.detail;
8
15
  }
9
16
  }
10
- const padding = (length) => (4 - length % 4) % 4;
11
- const assertLimit = (name, value) => {
12
- if (!Number.isSafeInteger(value) || value < 0)
13
- throw new RangeError(`${name} must be a non-negative safe integer`);
14
- };
15
17
  /** @internal */
16
- export class Reader {
17
- bytes;
18
- limits;
19
- #view;
20
- #offset = 0;
21
- constructor(bytes, limits) {
22
- this.bytes = bytes;
23
- this.limits = limits;
24
- assertLimit("maxOpaqueBytes", ByteSize.toNumberUnsafe(limits.maxOpaqueBytes));
25
- assertLimit("maxStringBytes", ByteSize.toNumberUnsafe(limits.maxStringBytes));
26
- assertLimit("maxArrayElements", limits.maxArrayElements);
27
- this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
28
- }
29
- get remaining() {
30
- return this.bytes.length - this.#offset;
31
- }
32
- #require(length) {
33
- if (length > this.remaining)
34
- throw new XdrDecodeError("Truncated XDR value");
35
- }
36
- uint32() {
37
- this.#require(4);
38
- const value = this.#view.getUint32(this.#offset);
39
- this.#offset += 4;
40
- return value;
41
- }
42
- int32() {
43
- this.#require(4);
44
- const value = this.#view.getInt32(this.#offset);
45
- this.#offset += 4;
46
- return value;
18
+ export class XdrEncodeError extends Data.TaggedError("XdrEncodeError") {
19
+ get message() {
20
+ return this.detail;
47
21
  }
48
- uint64() {
49
- this.#require(8);
50
- const value = this.#view.getBigUint64(this.#offset);
51
- this.#offset += 8;
52
- return value;
22
+ }
23
+ const valid = (n) => Number.isSafeInteger(n) && n >= 0;
24
+ const padding = (n) => (4 - n % 4) % 4;
25
+ const u32 = (n) => {
26
+ const bytes = new Uint8Array(4);
27
+ new DataView(bytes.buffer).setUint32(0, n);
28
+ return bytes;
29
+ };
30
+ const join = (parts) => {
31
+ const bytes = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
32
+ parts.reduce((at, part) => {
33
+ bytes.set(part, at);
34
+ return at + part.length;
35
+ }, 0);
36
+ return bytes;
37
+ };
38
+ const need = (bytes, at, count, path) => count <= bytes.length - at
39
+ ? Result.succeed(void 0) :
40
+ Result.fail(new XdrDecodeError({ reason: "truncated", offset: at, path, detail: "Truncated XDR value" }));
41
+ const CodecImpl = Symbol("XdrCodec");
42
+ const codec = (read, write) => ({ [CodecImpl]: { read, write } });
43
+ const readWord = (bytes, at, _limits, path) => Result.map(need(bytes, at, 4, path), () => [new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(at), at + 4]);
44
+ const writeWord = (value, _limits, at, path, budget) => Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff
45
+ ? budget < 4
46
+ ? Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" }))
47
+ : Result.succeed(u32(value))
48
+ : Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "uint32 out of range" }));
49
+ const readMany = (item, count, bytes, at, limits, path) => {
50
+ const values = [];
51
+ let position = at;
52
+ for (let index = 0; index < count; index++) {
53
+ const result = item[CodecImpl].read(bytes, position, limits, [...path, index]);
54
+ if (Result.isFailure(result))
55
+ return Result.fail(result.failure);
56
+ values.push(result.success[0]);
57
+ position = result.success[1];
53
58
  }
54
- boolean() {
55
- const value = this.uint32();
56
- if (value > 1)
57
- throw new XdrDecodeError(`Invalid XDR boolean: ${value}`);
58
- return value === 1;
59
+ return Result.succeed([values, position]);
60
+ };
61
+ const writeMany = (item, values, limits, at, path, budget) => {
62
+ const parts = [];
63
+ let position = at;
64
+ for (const [index, value] of values.entries()) {
65
+ const result = item[CodecImpl].write(value, limits, position, [...path, index], budget - (position - at));
66
+ if (Result.isFailure(result))
67
+ return Result.fail(result.failure);
68
+ parts.push(result.success);
69
+ position += result.success.length;
59
70
  }
60
- fixedOpaque(length) {
61
- assertLimit("fixed opaque length", length);
62
- const pad = padding(length);
63
- this.#require(length + pad);
64
- const value = this.bytes.slice(this.#offset, this.#offset + length);
65
- this.#offset += length;
66
- for (let index = 0; index < pad; index++) {
67
- if (this.bytes[this.#offset + index] !== 0)
68
- throw new XdrDecodeError("XDR padding must be zero");
71
+ return Result.succeed([parts, position]);
72
+ };
73
+ const textEncoder = new TextEncoder();
74
+ const textDecoder = new TextDecoder("utf-8", { fatal: true });
75
+ /** @internal */
76
+ export const XdrCodec = {
77
+ uint32: codec(readWord, writeWord),
78
+ int32: codec((bytes, at, limits, path) => Result.map(readWord(bytes, at, limits, path), ([n, next]) => [n | 0, next]), (n, limits, at, path, budget) => Number.isInteger(n) && n >= -0x8000_0000 && n <= 0x7fff_ffff
79
+ ? writeWord(n >>> 0, limits, at, path, budget)
80
+ : Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "int32 out of range" }))),
81
+ uint64: codec((bytes, at, _limits, path) => Result.map(need(bytes, at, 8, path), () => [new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(at), at + 8]), (n, _limits, at, path, budget) => {
82
+ const primitive = (() => {
83
+ try {
84
+ return Result.succeed(BigInt.prototype.valueOf.call(n));
85
+ }
86
+ catch {
87
+ return Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "uint64 out of range" }));
88
+ }
89
+ })();
90
+ return Result.flatMap(primitive, (value) => {
91
+ if (value < 0n || value > 0xffffffffffffffffn) {
92
+ return Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "uint64 out of range" }));
93
+ }
94
+ if (budget < 8) {
95
+ return Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" }));
96
+ }
97
+ const bytes = new Uint8Array(8);
98
+ new DataView(bytes.buffer).setBigUint64(0, value);
99
+ return Result.succeed(bytes);
100
+ });
101
+ }),
102
+ boolean: codec((bytes, at, limits, path) => Result.flatMap(readWord(bytes, at, limits, path), ([n, next]) => n <= 1
103
+ ? Result.succeed([n === 1, next])
104
+ : Result.fail(new XdrDecodeError({ reason: "invalid-boolean", offset: at, path, detail: `Invalid XDR boolean: ${n}` }))), (value, limits, at, path, budget) => writeWord(value ? 1 : 0, limits, at, path, budget)),
105
+ fixedOpaque: (length) => codec((bytes, at, _limits, path) => !valid(length) ?
106
+ Result.fail(new XdrDecodeError({ reason: "invalid-limit", offset: at, path, detail: "Invalid fixed opaque length" }))
107
+ : Result.flatMap(need(bytes, at, length + padding(length), path), () => bytes.subarray(at + length, at + length + padding(length)).every((b) => b === 0)
108
+ ? Result.succeed([bytes.slice(at, at + length), at + length + padding(length)])
109
+ : Result.fail(new XdrDecodeError({ reason: "padding", offset: at + length, path, detail: "XDR padding must be zero" }))), (value, _limits, at, path, budget) => {
110
+ if (!valid(length) || !(value instanceof Uint8Array) || value.length !== length) {
111
+ return Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "fixed opaque length mismatch" }));
69
112
  }
70
- this.#offset += pad;
71
- return value;
72
- }
73
- opaque(maxBytes = this.limits.maxOpaqueBytes) {
74
- assertLimit("opaque limit", ByteSize.toNumberUnsafe(maxBytes));
75
- const length = this.uint32();
76
- if (BigInt(length) > maxBytes || BigInt(length) > this.limits.maxOpaqueBytes) {
77
- throw new XdrDecodeError("XDR opaque value exceeds its limit");
113
+ if (length + padding(length) > budget) {
114
+ return Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" }));
78
115
  }
79
- return this.fixedOpaque(length);
80
- }
81
- string(maxBytes = this.limits.maxStringBytes) {
82
- assertLimit("string limit", ByteSize.toNumberUnsafe(maxBytes));
83
- const bytes = this.opaque(ByteSize.min(maxBytes, this.limits.maxStringBytes));
116
+ const bytes = new Uint8Array(length + padding(length));
117
+ bytes.set(value);
118
+ return Result.succeed(bytes);
119
+ }),
120
+ opaque: (maxBytes) => codec((bytes, at, limits, path) => Result.flatMap(readWord(bytes, at, limits, path), ([length, start]) => {
121
+ const max = Number(maxBytes ?? limits.maxOpaqueBytes);
122
+ if (!valid(max)) {
123
+ return Result.fail(new XdrDecodeError({ reason: "invalid-limit", offset: at, path, detail: "Invalid opaque limit" }));
124
+ }
125
+ if (length > max || BigInt(length) > limits.maxOpaqueBytes) {
126
+ return Result.fail(new XdrDecodeError({
127
+ reason: "length-limit",
128
+ offset: at,
129
+ path,
130
+ detail: "XDR opaque value exceeds its limit"
131
+ }));
132
+ }
133
+ return Result.flatMap(need(bytes, start, length + padding(length), path), () => bytes.subarray(start + length, start + length + padding(length)).every((b) => b === 0)
134
+ ? Result.succeed([bytes.slice(start, start + length), start + length + padding(length)])
135
+ : Result.fail(new XdrDecodeError({
136
+ reason: "padding",
137
+ offset: start + length,
138
+ path,
139
+ detail: "XDR padding must be zero"
140
+ })));
141
+ }), (value, limits, at, path, budget) => {
142
+ const max = Number(maxBytes ?? limits.maxOpaqueBytes);
143
+ if (!valid(max)) {
144
+ return Result.fail(new XdrEncodeError({ reason: "invalid-limit", offset: at, path, detail: "Invalid opaque limit" }));
145
+ }
146
+ if (!(value instanceof Uint8Array) || value.length > max || BigInt(value.length) > limits.maxOpaqueBytes ||
147
+ value.length > 0xffff_ffff) {
148
+ return Result.fail(new XdrEncodeError({
149
+ reason: "length-limit",
150
+ offset: at,
151
+ path,
152
+ detail: "XDR opaque value exceeds its limit"
153
+ }));
154
+ }
155
+ if (4 + value.length + padding(value.length) > budget) {
156
+ return Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" }));
157
+ }
158
+ const bytes = new Uint8Array(4 + value.length + padding(value.length));
159
+ new DataView(bytes.buffer).setUint32(0, value.length);
160
+ bytes.set(value, 4);
161
+ return Result.succeed(bytes);
162
+ }),
163
+ string: (maxBytes) => codec((bytes, at, limits, path) => Result.flatMap(XdrCodec.opaque(ByteSize.min(maxBytes ?? limits.maxStringBytes, limits.maxStringBytes))[CodecImpl].read(bytes, at, limits, path), ([value, next]) => {
84
164
  try {
85
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
165
+ return Result.succeed([textDecoder.decode(value), next]);
86
166
  }
87
167
  catch {
88
- throw new XdrDecodeError("Invalid UTF-8 in XDR string");
168
+ return Result.fail(new XdrDecodeError({ reason: "invalid-utf8", offset: at, path, detail: "Invalid UTF-8 in XDR string" }));
89
169
  }
90
- }
91
- array(decode, maxElements = this.limits.maxArrayElements) {
92
- assertLimit("array limit", maxElements);
93
- const length = this.uint32();
94
- if (length > maxElements || length > this.limits.maxArrayElements) {
95
- throw new XdrDecodeError("XDR array exceeds its element limit");
170
+ }), (value, limits, at, path, budget) => {
171
+ if (Object.prototype.toString.call(value) !== "[object String]") {
172
+ return Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "Invalid XDR string" }));
96
173
  }
97
- const values = Array.from({ length });
98
- for (let index = 0; index < length; index++)
99
- values[index] = decode(this);
100
- return values;
101
- }
102
- discriminant(cases) {
103
- const value = this.uint32();
104
- if (!Object.prototype.hasOwnProperty.call(cases, value)) {
105
- throw new XdrDecodeError(`Invalid XDR discriminant: ${value}`);
174
+ if (value.length + 4 > budget) {
175
+ return Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" }));
106
176
  }
107
- // SAFETY: The own-property check proves that value indexes the supplied discriminant table.
108
- return cases[value];
109
- }
110
- finish() {
111
- if (this.remaining !== 0)
112
- throw new XdrDecodeError("Trailing bytes after XDR message");
113
- }
114
- }
115
- /** @internal */
116
- export class Writer {
117
- #chunks = [];
118
- #length = 0;
119
- get length() {
120
- return this.#length;
121
- }
122
- #append(bytes) {
123
- this.#chunks.push(bytes);
124
- this.#length += bytes.length;
125
- }
126
- uint32(value) {
127
- if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff)
128
- throw new RangeError("uint32 out of range");
129
- const bytes = new Uint8Array(4);
130
- new DataView(bytes.buffer).setUint32(0, value);
131
- this.#append(bytes);
132
- return this;
133
- }
134
- int32(value) {
135
- if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) {
136
- throw new RangeError("int32 out of range");
177
+ return XdrCodec.opaque(ByteSize.min(maxBytes ?? limits.maxStringBytes, limits.maxStringBytes))[CodecImpl].write(textEncoder.encode(value), limits, at, path, budget);
178
+ }),
179
+ array: (item, maximum) => codec((bytes, at, limits, path) => Result.flatMap(readWord(bytes, at, limits, path), ([count, start]) => !valid(maximum ?? limits.maxArrayElements)
180
+ ? Result.fail(new XdrDecodeError({ reason: "invalid-limit", offset: at, path, detail: "Invalid array limit" }))
181
+ : count > (maximum ?? limits.maxArrayElements) || count > limits.maxArrayElements
182
+ ? Result.fail(new XdrDecodeError({
183
+ reason: "length-limit",
184
+ offset: at,
185
+ path,
186
+ detail: "XDR array exceeds its element limit"
187
+ }))
188
+ : readMany(item, count, bytes, start, limits, path)), (values, limits, at, path, budget) => !Array.isArray(values) || !valid(maximum ?? limits.maxArrayElements) ||
189
+ values.length > (maximum ?? limits.maxArrayElements) || values.length > limits.maxArrayElements ||
190
+ values.length > 0xffff_ffff
191
+ ? Result.fail(new XdrEncodeError({
192
+ reason: "length-limit",
193
+ offset: at,
194
+ path,
195
+ detail: "XDR array exceeds its element limit"
196
+ }))
197
+ : budget < 4 ?
198
+ Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" }))
199
+ : Result.map(writeMany(item, values, limits, at + 4, path, budget - 4), ([parts]) => join([u32(values.length), ...parts]))),
200
+ fixedArray: (item, count) => codec((bytes, at, limits, path) => !valid(count) || count > limits.maxArrayElements
201
+ ? Result.fail(new XdrDecodeError({ reason: "invalid-limit", offset: at, path, detail: "Invalid fixed array length" }))
202
+ : readMany(item, count, bytes, at, limits, path), (values, limits, at, path, budget) => !Array.isArray(values) || values.length !== count || count > limits.maxArrayElements
203
+ ? Result.fail(new XdrEncodeError({ reason: "length-limit", offset: at, path, detail: "fixed array length mismatch" }))
204
+ : Result.map(writeMany(item, values, limits, at, path, budget), ([parts]) => join(parts))),
205
+ dependent: (head, select) => codec((bytes, at, limits, path) => Result.flatMap(head[CodecImpl].read(bytes, at, limits, [...path, "head"]), ([header, start]) => {
206
+ const body = select(header);
207
+ return body === undefined ?
208
+ Result.fail(new XdrDecodeError({ reason: "discriminant", offset: at, path, detail: "Unknown XDR discriminant" }))
209
+ : Result.map(body[CodecImpl].read(bytes, start, limits, [...path, "body"]), ([value, next]) => [{ head: header, body: value }, next]);
210
+ }), (value, limits, at, path, budget) => {
211
+ if (value == null || Object(value) !== value) {
212
+ return Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "Invalid dependent XDR value" }));
137
213
  }
138
- return this.uint32(value >>> 0);
139
- }
140
- uint64(value) {
141
- if (value < 0n || value > 0xffffffffffffffffn)
142
- throw new RangeError("uint64 out of range");
143
- return this.uint32(Number(value >> 32n)).uint32(Number(value & 0xffffffffn));
144
- }
145
- boolean(value) {
146
- return this.uint32(value ? 1 : 0);
147
- }
148
- fixedOpaque(value) {
149
- this.#append(new Uint8Array(value));
150
- const pad = padding(value.length);
151
- if (pad > 0)
152
- this.#append(new Uint8Array(pad));
153
- return this;
154
- }
155
- opaque(value) {
156
- return this.uint32(value.length).fixedOpaque(value);
157
- }
158
- string(value) {
159
- return this.opaque(new TextEncoder().encode(value));
160
- }
161
- array(values, encode) {
162
- this.uint32(values.length);
163
- for (const value of values)
164
- encode(this, value);
165
- return this;
166
- }
167
- bytes() {
168
- const bytes = new Uint8Array(this.#length);
169
- let offset = 0;
170
- for (const chunk of this.#chunks) {
171
- bytes.set(chunk, offset);
172
- offset += chunk.length;
214
+ const body = select(value.head);
215
+ return body === undefined ?
216
+ Result.fail(new XdrEncodeError({ reason: "discriminant", offset: at, path, detail: "Unknown XDR discriminant" }))
217
+ : Result.flatMap(head[CodecImpl].write(value.head, limits, at, [...path, "head"], budget), (prefix) => Result.map(body[CodecImpl].write(value.body, limits, at + prefix.length, [...path, "body"], budget - prefix.length), (suffix) => join([prefix, suffix])));
218
+ }),
219
+ struct: (fields) => {
220
+ const entries = Object.entries(fields);
221
+ return codec((bytes, at, limits, path) => Result.map(entries.reduce((state, [name, field]) => Result.flatMap(state, ([values, position]) => Result.map(field[CodecImpl].read(bytes, position, limits, [...path, name]), ([value, next]) => [[...values, [name, value]], next])), Result.succeed([[], at])),
222
+ // SAFETY: Every entry comes from the corresponding field descriptor and retains its key.
223
+ ([values, next]) => [Object.fromEntries(values), next]), (value, limits, at, path, budget) => value == null || Object(value) !== value ?
224
+ Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "Invalid XDR struct value" })) :
225
+ Result.map(entries.reduce((state, [name, field]) => Result.flatMap(state, ([parts, position]) => Result.map(
226
+ // SAFETY: name comes from Object.entries(fields), so it is a key of F.
227
+ field[CodecImpl].write(value[name], limits, position, [...path, name], budget - (position - at)), (part) => [[...parts, part], position + part.length])), Result.succeed([[], at])), ([parts]) => join(parts)));
228
+ },
229
+ discriminant: (cases) => codec((bytes, at, limits, path) => Result.flatMap(readWord(bytes, at, limits, path), ([tag, start]) => {
230
+ const selected = cases[tag];
231
+ return Object.hasOwn(cases, tag) && selected !== undefined
232
+ ? Result.map(selected[CodecImpl].read(bytes, start, limits, [...path, tag]), ([value, next]) =>
233
+ // SAFETY: The own-key check selects the descriptor for this numeric tag.
234
+ [
235
+ { tag, value },
236
+ next
237
+ ])
238
+ : Result.fail(new XdrDecodeError({
239
+ reason: "discriminant",
240
+ offset: at,
241
+ path,
242
+ detail: `Invalid XDR discriminant: ${tag}`
243
+ }));
244
+ }), (value, limits, at, path, budget) => {
245
+ if (value == null || Object(value) !== value) {
246
+ return Result.fail(new XdrEncodeError({ reason: "range", offset: at, path, detail: "Invalid XDR discriminant value" }));
173
247
  }
174
- return bytes;
175
- }
176
- }
177
- import * as ByteSize from "effect/ByteSize";
178
- import * as Data from "effect/Data";
248
+ // SAFETY: discriminant cases use numeric own keys, and the value type carries one of those keys.
249
+ const tag = Number(value.tag);
250
+ const selected = cases[tag];
251
+ return Object.hasOwn(cases, tag) && selected !== undefined
252
+ ? budget < 4 ?
253
+ Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path, detail: "XDR output exceeds its limit" })) :
254
+ Result.map(selected[CodecImpl].write(value.value, limits, at + 4, [...path, tag], budget - 4), (body) => join([u32(tag), body]))
255
+ : Result.fail(new XdrEncodeError({
256
+ reason: "discriminant",
257
+ offset: at,
258
+ path,
259
+ detail: `Invalid XDR discriminant: ${String(value.tag)}`
260
+ }));
261
+ })
262
+ };
263
+ const validateLimits = (limits) => valid(ByteSize.toNumberUnsafe(limits.maxOpaqueBytes)) && valid(ByteSize.toNumberUnsafe(limits.maxStringBytes)) &&
264
+ valid(limits.maxArrayElements)
265
+ ? Result.succeed(limits) :
266
+ Result.fail(new XdrDecodeError({ reason: "invalid-limit", offset: 0, path: [], detail: "Invalid XDR limits" }));
267
+ const validateEncodeLimits = (limits) => valid(ByteSize.toNumberUnsafe(limits.maxOpaqueBytes)) && valid(ByteSize.toNumberUnsafe(limits.maxStringBytes)) &&
268
+ valid(limits.maxArrayElements)
269
+ ? Result.succeed(limits) :
270
+ Result.fail(new XdrEncodeError({ reason: "invalid-limit", offset: 0, path: [], detail: "Invalid XDR limits" }));
271
+ const validateOutput = (maxBytes) => valid(maxBytes)
272
+ ? Result.succeed(maxBytes)
273
+ : Result.fail(new XdrEncodeError({ reason: "invalid-limit", offset: 0, path: [], detail: "Invalid XDR output limit" }));
274
+ const lift = (run) => Effect.suspend(() => Result.match(run(), { onFailure: Effect.fail, onSuccess: Effect.succeed }));
275
+ const encodeValue = (value, description, limits, at, maxBytes) => Result.flatMap(description[CodecImpl].write(value, limits, at, [], maxBytes - at), (bytes) => bytes.length <= maxBytes - at
276
+ ? Result.succeed(bytes) :
277
+ Result.fail(new XdrEncodeError({ reason: "output-limit", offset: at, path: [], detail: "XDR output exceeds its limit" })));
278
+ export const Xdr = Context.Service("@effect-vfs/nfs/Xdr");
279
+ const decode = (bytes, limits, description) => lift(() => Result.flatMap(validateLimits(limits), () => Result.flatMap(description[CodecImpl].read(bytes, 0, limits, []), ([value, at]) => at === bytes.length
280
+ ? Result.succeed(value) :
281
+ Result.fail(new XdrDecodeError({
282
+ reason: "trailing-bytes",
283
+ offset: at,
284
+ path: [],
285
+ detail: "Trailing bytes after XDR message"
286
+ })))));
287
+ const encode = (value, description, limits, maxBytes) => lift(() => Result.flatMap(validateEncodeLimits(limits), () => Result.flatMap(validateOutput(maxBytes), () => encodeValue(value, description, limits, 0, maxBytes))));
288
+ const openReader = (source, limits) => Effect.flatMap(lift(() => validateLimits(limits)), () => Effect.map(SynchronizedRef.make({ at: 0, sealed: false }), (state) => {
289
+ const bytes = source.slice();
290
+ const read = (description) => SynchronizedRef.modifyEffect(state, (current) => current.sealed
291
+ ? Effect.fail(new XdrDecodeError({ reason: "sealed", offset: current.at, path: [], detail: "XDR reader is sealed" }))
292
+ : lift(() => description[CodecImpl].read(bytes, current.at, limits, [])).pipe(Effect.map(([value, at]) => [value, { at, sealed: false }])));
293
+ const position = SynchronizedRef.modifyEffect(state, (current) => current.sealed
294
+ ? Effect.fail(new XdrDecodeError({ reason: "sealed", offset: current.at, path: [], detail: "XDR reader is sealed" }))
295
+ : Effect.succeed([current.at, current]));
296
+ const remaining = SynchronizedRef.modifyEffect(state, (current) => current.sealed
297
+ ? Effect.fail(new XdrDecodeError({ reason: "sealed", offset: current.at, path: [], detail: "XDR reader is sealed" }))
298
+ : Effect.succeed([bytes.length - current.at, current]));
299
+ const finish = SynchronizedRef.modifyEffect(state, (current) => current.sealed ?
300
+ Effect.fail(new XdrDecodeError({ reason: "sealed", offset: current.at, path: [], detail: "XDR reader is sealed" })) :
301
+ current.at !== bytes.length
302
+ ? Effect.fail(new XdrDecodeError({
303
+ reason: "trailing-bytes",
304
+ offset: current.at,
305
+ path: [],
306
+ detail: "Trailing bytes after XDR message"
307
+ })) :
308
+ Effect.succeed([void 0, { ...current, sealed: true }]));
309
+ return { read, position, remaining, finish };
310
+ }));
311
+ const openWriter = (limits, maxBytes) => Effect.flatMap(lift(() => Result.flatMap(validateEncodeLimits(limits), () => validateOutput(maxBytes))), () => Effect.map(
312
+ // SAFETY: The empty parts array is the initial immutable writer state.
313
+ SynchronizedRef.make({ parts: [], length: 0, sealed: false }), (state) => {
314
+ const sealed = (at) => Effect.fail(new XdrEncodeError({ reason: "sealed", offset: at, path: [], detail: "XDR writer is sealed" }));
315
+ const write = (description, value) => SynchronizedRef.modifyEffect(state, (current) => current.sealed ?
316
+ sealed(current.length)
317
+ : lift(() => encodeValue(value, description, limits, current.length, maxBytes)).pipe(Effect.map((part) => [void 0, {
318
+ parts: [...current.parts, part],
319
+ length: current.length + part.length,
320
+ sealed: false
321
+ }])));
322
+ const appendEncoded = (bytes) => SynchronizedRef.modifyEffect(state, (current) => current.sealed ?
323
+ sealed(current.length)
324
+ : bytes.length > maxBytes - current.length ?
325
+ Effect.fail(new XdrEncodeError({
326
+ reason: "output-limit",
327
+ offset: current.length,
328
+ path: [],
329
+ detail: "XDR output exceeds its limit"
330
+ }))
331
+ : Effect.succeed([void 0, {
332
+ parts: [...current.parts, bytes.slice()],
333
+ length: current.length + bytes.length,
334
+ sealed: false
335
+ }]));
336
+ const length = SynchronizedRef.modifyEffect(state, (current) => current.sealed ? sealed(current.length) : Effect.succeed([current.length, current]));
337
+ const bytes = SynchronizedRef.modifyEffect(state, (current) => current.sealed ? sealed(current.length) : Effect.succeed([join(current.parts), current]));
338
+ const finish = SynchronizedRef.modifyEffect(state, (current) => current.sealed
339
+ ? sealed(current.length)
340
+ : Effect.succeed([join(current.parts), { ...current, sealed: true }]));
341
+ return { write, appendEncoded, length, bytes, finish };
342
+ }));
343
+ export const make = { decode, encode, openReader, openWriter };
344
+ export const layer = Layer.succeed(Xdr, make);
345
+ /** Compiles a self-contained whole-value Schema codec. @internal */
346
+ export const compile = (description, valueSchema, limits, maxBytes) => Schema.Uint8Array.pipe(Schema.decodeTo(valueSchema, SchemaTransformation.transformEffect({
347
+ decode: (bytes, options) => decode(bytes, limits, description).pipe(Effect.mapError((error) => new SchemaIssue.InvalidValue({ message: error.detail }, bytes, options))),
348
+ encode: (value, options) => encode(value, description, limits, maxBytes).pipe(Effect.mapError((error) => new SchemaIssue.InvalidValue({ message: error.detail }, value, options)))
349
+ })));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@effect-vfs/nfs",
3
- "version": "0.4.0",
4
- "description": "Read-only NFSv4.1 server for one live Effect VFS volume.",
3
+ "version": "0.6.0",
4
+ "description": "NFSv4.1 server for one live Effect VFS volume, with guarded experimental writes.",
5
5
  "homepage": "https://github.com/lloydrichards/effect-virtual-fs#readme",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -39,16 +39,16 @@
39
39
  "type-check": "tsc --noEmit"
40
40
  },
41
41
  "peerDependencies": {
42
- "effect": "4.0.0-rc.114"
42
+ "effect": "4.0.0-rc.115"
43
43
  },
44
44
  "dependencies": {
45
45
  "@effect-vfs/core": "workspace:*"
46
46
  },
47
47
  "devDependencies": {
48
- "@effect/platform-node-shared": "4.0.0-rc.114",
49
- "@effect/vitest": "4.0.0-rc.114",
48
+ "@effect/platform-node-shared": "4.0.0-rc.115",
49
+ "@effect/vitest": "4.0.0-rc.115",
50
50
  "@repo/config-typescript": "workspace:*",
51
- "effect": "4.0.0-rc.114",
51
+ "effect": "4.0.0-rc.115",
52
52
  "vitest": "^5.0.1"
53
53
  }
54
54
  }