@effect-dynamodb/schema 1.39.0 → 1.40.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 (72) hide show
  1. package/dist/Aggregate.d.ts +11 -4
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +9 -2
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoModel.d.ts +13 -0
  6. package/dist/DynamoModel.d.ts.map +1 -1
  7. package/dist/DynamoModel.js.map +1 -1
  8. package/dist/DynamoSchema.d.ts +5 -0
  9. package/dist/DynamoSchema.d.ts.map +1 -1
  10. package/dist/DynamoSchema.js.map +1 -1
  11. package/dist/Entity.d.ts +61 -8
  12. package/dist/Entity.d.ts.map +1 -1
  13. package/dist/Entity.js +182 -5
  14. package/dist/Entity.js.map +1 -1
  15. package/dist/KeyComposer.d.ts +157 -3
  16. package/dist/KeyComposer.d.ts.map +1 -1
  17. package/dist/KeyComposer.js +355 -9
  18. package/dist/KeyComposer.js.map +1 -1
  19. package/dist/internal/AggregateEdges.d.ts +3 -3
  20. package/dist/internal/AggregateSchemas.d.ts +181 -14
  21. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  22. package/dist/internal/AggregateSchemas.js +505 -45
  23. package/dist/internal/AggregateSchemas.js.map +1 -1
  24. package/dist/internal/AggregateTypes.d.ts +396 -36
  25. package/dist/internal/AggregateTypes.d.ts.map +1 -1
  26. package/dist/internal/CompositeCodec.d.ts +274 -6
  27. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  28. package/dist/internal/CompositeCodec.js +829 -25
  29. package/dist/internal/CompositeCodec.js.map +1 -1
  30. package/dist/internal/EffectInstances.d.ts +81 -0
  31. package/dist/internal/EffectInstances.d.ts.map +1 -0
  32. package/dist/internal/EffectInstances.js +656 -0
  33. package/dist/internal/EffectInstances.js.map +1 -0
  34. package/dist/internal/EntitySchemas.d.ts +103 -27
  35. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  36. package/dist/internal/EntitySchemas.js +778 -131
  37. package/dist/internal/EntitySchemas.js.map +1 -1
  38. package/dist/internal/EntityTypes.d.ts +67 -11
  39. package/dist/internal/EntityTypes.d.ts.map +1 -1
  40. package/dist/internal/FailingAsBefore.d.ts +25 -0
  41. package/dist/internal/FailingAsBefore.d.ts.map +1 -0
  42. package/dist/internal/FailingAsBefore.js +42 -0
  43. package/dist/internal/FailingAsBefore.js.map +1 -0
  44. package/dist/internal/InstanceReads.d.ts +33 -0
  45. package/dist/internal/InstanceReads.d.ts.map +1 -0
  46. package/dist/internal/InstanceReads.js +165 -0
  47. package/dist/internal/InstanceReads.js.map +1 -0
  48. package/dist/internal/KeyText136.d.ts +4 -2
  49. package/dist/internal/KeyText136.d.ts.map +1 -1
  50. package/dist/internal/KeyText136.js +40 -9
  51. package/dist/internal/KeyText136.js.map +1 -1
  52. package/dist/internal/NumericKey.d.ts +21 -2
  53. package/dist/internal/NumericKey.d.ts.map +1 -1
  54. package/dist/internal/NumericKey.js +19 -1
  55. package/dist/internal/NumericKey.js.map +1 -1
  56. package/dist/internal/PackedCodec.d.ts +8 -1
  57. package/dist/internal/PackedCodec.d.ts.map +1 -1
  58. package/dist/internal/PackedCodec.js +49 -13
  59. package/dist/internal/PackedCodec.js.map +1 -1
  60. package/dist/internal/SchemaAccessors.d.ts +160 -1
  61. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  62. package/dist/internal/SchemaAccessors.js +994 -1
  63. package/dist/internal/SchemaAccessors.js.map +1 -1
  64. package/dist/internal/SharedKeyAttribute.d.ts +60 -6
  65. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  66. package/dist/internal/SharedKeyAttribute.js +127 -12
  67. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  68. package/dist/internal/SparseKey.d.ts +46 -0
  69. package/dist/internal/SparseKey.d.ts.map +1 -0
  70. package/dist/internal/SparseKey.js +69 -0
  71. package/dist/internal/SparseKey.js.map +1 -0
  72. package/package.json +1 -1
@@ -0,0 +1,656 @@
1
+ /**
2
+ * @internal Effect's own declarations whose values DynamoDB hands back as plain maps, and how each
3
+ * is rebuilt from that map.
4
+ *
5
+ * The marshaller stores a class instance as the map of its enumerable properties, its prototype's
6
+ * included, so a `BigDecimal`, a `Duration`, a zone, a cookie, a version, an address or a DNS record
7
+ * is stored as a map carrying its marker. Each declaration's guard looks for that marker, so it takes
8
+ * the map back as it is: a value that passes the guard and isn't one (`BigDecimal` arithmetic throws,
9
+ * a named zone can't format, a key composed from it is `[object Object]`).
10
+ *
11
+ * {@link effectDeclarationOf} is the one place that decides whether a declaration is one of Effect's:
12
+ * every path that treats these types differently asks it, so none can recognise a type another
13
+ * doesn't. A declaration is Effect's when its parse function is the one Effect's exported schema has.
14
+ * A `.check()`, an annotation and a brand keep that function, and a refinement Effect builds on one of
15
+ * these keeps its base's; a `Schema.declare` of one's own has its own, whatever it's named, and so has
16
+ * a declaration from another copy of `effect`. Those are read as they always were.
17
+ */
18
+ import { BigDecimal, DateTime, Duration, Effect, Result, Schema, SchemaAST } from "effect";
19
+ import * as Cookies from "effect/http/Cookies";
20
+ import * as UrlParams from "effect/http/UrlParams";
21
+ import * as Dns from "effect/net/Dns";
22
+ import * as Host from "effect/net/Host";
23
+ import * as IpInterface from "effect/net/IpInterface";
24
+ import * as IpNetwork from "effect/net/IpNetwork";
25
+ import * as NetAddress from "effect/net/NetAddress";
26
+ import * as SemVer from "effect/SemVer";
27
+ import * as SemVerRange from "effect/SemVerRange";
28
+ import { BETA_DATE_MARKER, DATE_MARKER, ZONE_MARKER } from "./PackedCodec.js";
29
+ const DECLARATIONS = [
30
+ [Schema.DateTimeUtc, "DateTime"],
31
+ [Schema.DateTimeZoned, "DateTime"],
32
+ [Schema.BigDecimal, "BigDecimal"],
33
+ [Schema.Duration, "Duration"],
34
+ [Schema.TimeZone, "TimeZone"],
35
+ [Schema.TimeZoneNamed, "TimeZone"],
36
+ [Schema.TimeZoneOffset, "TimeZone"],
37
+ [Schema.Cookie, "Cookie"],
38
+ [Schema.Cookies, "Cookies"],
39
+ [Schema.UrlParams, "UrlParams"],
40
+ [Schema.SemVer, "SemVer"],
41
+ [Schema.SemVerRange, "SemVerRange"],
42
+ [Schema.Ipv4Address, "NetAddress"],
43
+ [Schema.Ipv6Address, "NetAddress"],
44
+ [Schema.IpAddress, "NetAddress"],
45
+ [Schema.MacAddress, "NetAddress"],
46
+ [Schema.Ipv4Network, "NetAddress"],
47
+ [Schema.Ipv6Network, "NetAddress"],
48
+ [Schema.IpNetwork, "NetAddress"],
49
+ [Schema.Ipv4Interface, "NetAddress"],
50
+ [Schema.Ipv6Interface, "NetAddress"],
51
+ [Schema.IpInterface, "NetAddress"],
52
+ [Schema.InetAddressV4, "NetAddress"],
53
+ [Schema.InetAddressV6, "NetAddress"],
54
+ [Schema.InetAddress, "NetAddress"],
55
+ [Schema.HostPort, "NetAddress"],
56
+ [Schema.SocketAddress, "NetAddress"],
57
+ [Schema.UnixPathAddress, "NetAddress"],
58
+ [Schema.DnsARecord, "DnsRecord"],
59
+ [Schema.DnsAaaaRecord, "DnsRecord"],
60
+ [Schema.DnsCaaRecord, "DnsRecord"],
61
+ [Schema.DnsCnameRecord, "DnsRecord"],
62
+ [Schema.DnsMxRecord, "DnsRecord"],
63
+ [Schema.DnsNaptrRecord, "DnsRecord"],
64
+ [Schema.DnsNsRecord, "DnsRecord"],
65
+ [Schema.DnsPtrRecord, "DnsRecord"],
66
+ [Schema.DnsSoaRecord, "DnsRecord"],
67
+ [Schema.DnsSrvRecord, "DnsRecord"],
68
+ [Schema.DnsTlsaRecord, "DnsRecord"],
69
+ [Schema.DnsTxtRecord, "DnsRecord"],
70
+ ];
71
+ const representationIdOf = (ast) => ast.annotations?.representation?.id;
72
+ /** Each declaration's parse function, with its kind and, where it has one, its representation. */
73
+ const KNOWN = new Map(DECLARATIONS.map(([schema, kind]) => [
74
+ schema.ast.run,
75
+ { kind, id: representationIdOf(schema.ast) },
76
+ ]));
77
+ /** Each read node's parser ({@link readingDeclaration}), with the declaration's own it runs. */
78
+ const READ_PARSERS = new WeakMap();
79
+ /**
80
+ * Which of Effect's declarations this node is, or `undefined` for any other node. Only the
81
+ * declaration itself counts: a transformation over one stores what it encodes to, and is reached
82
+ * through its encoding. A declaration's read node ({@link readingDeclaration}) is the declaration it
83
+ * reads.
84
+ */
85
+ export const effectDeclarationOf = (ast) => {
86
+ if (!SchemaAST.isDeclaration(ast) || ast.encoding !== undefined)
87
+ return undefined;
88
+ const known = KNOWN.get(READ_PARSERS.get(ast.run) ?? ast.run);
89
+ if (known === undefined)
90
+ return undefined;
91
+ if (known.id !== undefined && representationIdOf(ast) !== known.id)
92
+ return undefined;
93
+ return known.kind;
94
+ };
95
+ /**
96
+ * The last step each of Effect's own codecs takes onto one of these declarations
97
+ * (`Schema.DateTimeUtcFromString`, `Schema.DurationFromMillis`, ...): it makes the instance itself,
98
+ * so the declaration's parser is never handed a stored map, and there's nothing to rebuild.
99
+ */
100
+ const INSTANCE_STEPS = new WeakSet();
101
+ for (const exported of Object.values(Schema)) {
102
+ const ast = exported?.ast;
103
+ if (ast === undefined || !SchemaAST.isDeclaration(ast) || !KNOWN.has(ast.run))
104
+ continue;
105
+ const step = ast.encoding?.[0]?.transformation;
106
+ if (step !== undefined)
107
+ INSTANCE_STEPS.add(step);
108
+ }
109
+ /**
110
+ * Which of Effect's declarations a read takes this node's parser for, whether or not the node has an
111
+ * encoding: a transformation onto one hands its parser whatever its steps make of what's stored, and
112
+ * a step that passes the stored map through leaves the parser taking it for an instance. One of
113
+ * Effect's own codecs isn't one: its step makes the instance ({@link INSTANCE_STEPS}).
114
+ */
115
+ export const readDeclarationOf = (ast) => {
116
+ if (!SchemaAST.isDeclaration(ast))
117
+ return undefined;
118
+ if (ast.encoding !== undefined && INSTANCE_STEPS.has(ast.encoding[0].transformation)) {
119
+ return undefined;
120
+ }
121
+ const known = KNOWN.get(READ_PARSERS.get(ast.run) ?? ast.run);
122
+ if (known === undefined)
123
+ return undefined;
124
+ if (known.id !== undefined && representationIdOf(ast) !== known.id)
125
+ return undefined;
126
+ return known.kind;
127
+ };
128
+ /** Whether a node is a read node {@link readingDeclaration} built. */
129
+ export const isReadingDeclaration = (ast) => SchemaAST.isDeclaration(ast) && READ_PARSERS.has(ast.run);
130
+ const isMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
131
+ /** A plain record, what unmarshalling produces, as opposed to a class instance. */
132
+ const isPlain = (value) => {
133
+ if (value === null || typeof value !== "object")
134
+ return false;
135
+ const proto = Object.getPrototypeOf(value);
136
+ return proto === Object.prototype || proto === null;
137
+ };
138
+ const markedBy = (value, marker) => isMap(value) && Object.hasOwn(value, marker);
139
+ const resultOf = (result) => Result.isSuccess(result) ? result.success : undefined;
140
+ const attempt = (make) => {
141
+ try {
142
+ return make();
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ };
148
+ /**
149
+ * A stored integer as a bigint. The unmarshaller hands an integer back as a number while it's a safe
150
+ * one and as a bigint past that, so either is exact; a number that isn't a safe integer is no integer
151
+ * this was written from.
152
+ */
153
+ const exactInteger = (value) => typeof value === "bigint"
154
+ ? value
155
+ : typeof value === "number" && Number.isSafeInteger(value)
156
+ ? BigInt(value)
157
+ : undefined;
158
+ const isUint32 = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 0xffffffff;
159
+ const BIG_DECIMAL = "~effect/BigDecimal";
160
+ const DURATION = "~effect/Duration";
161
+ const COOKIE = "~effect/http/Cookies/Cookie";
162
+ const COOKIES = "~effect/http/Cookies";
163
+ const URL_PARAMS = "~effect/http/UrlParams";
164
+ const SEMVER = "~effect/SemVer";
165
+ const SEMVER_RANGE = "~effect/SemVerRange";
166
+ const NET_ADDRESS = "~effect/net/NetAddress";
167
+ const IP_NETWORK = "~effect/net/IpNetwork";
168
+ const IP_INTERFACE = "~effect/net/IpInterface";
169
+ const HOST = "~effect/net/Host";
170
+ const DNS_RECORD = "~effect/net/Dns/DnsRecord";
171
+ /**
172
+ * A stored `normalized` is left where it is, in the map: on an instance it's the slot
173
+ * `BigDecimal.normalize` caches in, and a map there would be handed out as the normalized decimal.
174
+ */
175
+ const rebuildBigDecimal = (value) => {
176
+ if (!markedBy(value, BIG_DECIMAL) || Object.hasOwn(value, "normalized"))
177
+ return undefined;
178
+ const unscaled = exactInteger(value.value);
179
+ const scale = value.scale;
180
+ if (unscaled === undefined || typeof scale !== "number" || !Number.isSafeInteger(scale)) {
181
+ return undefined;
182
+ }
183
+ return BigDecimal.make(unscaled, scale);
184
+ };
185
+ const rebuildDuration = (value) => {
186
+ if (!markedBy(value, DURATION) || !isMap(value.value))
187
+ return undefined;
188
+ const stored = value.value;
189
+ switch (stored._tag) {
190
+ case "Millis":
191
+ return typeof stored.millis === "number" && Number.isFinite(stored.millis)
192
+ ? Duration.millis(stored.millis)
193
+ : undefined;
194
+ case "Nanos": {
195
+ const nanos = exactInteger(stored.nanos);
196
+ return nanos === undefined ? undefined : Duration.nanos(nanos);
197
+ }
198
+ case "Infinity":
199
+ return Duration.infinity;
200
+ case "NegativeInfinity":
201
+ return Duration.negativeInfinity;
202
+ default:
203
+ return undefined;
204
+ }
205
+ };
206
+ /** A zone from its stored form: a named one from its id, an offset one from its offset. */
207
+ export const reviveTimeZone = (zone) => {
208
+ if (!isPlain(zone))
209
+ return undefined;
210
+ try {
211
+ if (zone._tag === "Named" && typeof zone.id === "string") {
212
+ return DateTime.zoneMakeNamedUnsafe(zone.id);
213
+ }
214
+ if (zone._tag === "Offset" && typeof zone.offset === "number") {
215
+ return DateTime.zoneMakeOffset(zone.offset);
216
+ }
217
+ }
218
+ catch {
219
+ return undefined;
220
+ }
221
+ return undefined;
222
+ };
223
+ /**
224
+ * Rebuild a `DateTime` from a MARSHALLED instance (#133).
225
+ *
226
+ * Before #133 an aggregate stored some `DateTime`s by marshalling the instance
227
+ * itself, which keeps its own enumerable properties:
228
+ *
229
+ * - `Utc`: `{ epochMilliseconds, <type-id>, _tag: "Utc" }`
230
+ * - `Zoned`: the same plus `zone`, itself `{ id, _tag: "Named" }` or
231
+ * `{ offset, _tag: "Offset" }` (a named zone's `Intl` formatter marshals to
232
+ * an empty map and is not needed).
233
+ *
234
+ * The type-id key is `~effect/time/DateTime` on effect 4.0.0-rc and
235
+ * `~effect/DateTime` on 4.0.0, so it is deliberately NOT inspected: the instant
236
+ * and the tag are what identify the value, and they are all a `DateTime` holds.
237
+ * A zoned value is rebuilt only when its zone is recoverable.
238
+ *
239
+ * Returns `undefined` for anything else — including a genuine `DateTime`, which
240
+ * needs no rebuilding.
241
+ */
242
+ export const reviveMarshalledDateTime = (value) => {
243
+ if (!isPlain(value))
244
+ return undefined;
245
+ const epochMs = value.epochMilliseconds;
246
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs))
247
+ return undefined;
248
+ if (value._tag === "Utc")
249
+ return DateTime.makeUnsafe(epochMs);
250
+ if (value._tag === "Zoned") {
251
+ const timeZone = reviveTimeZone(value.zone);
252
+ return timeZone === undefined ? undefined : DateTime.makeZonedUnsafe(epochMs, { timeZone });
253
+ }
254
+ return undefined;
255
+ };
256
+ const rebuildDateTime = (value) => isMap(value) && (DATE_MARKER in value || BETA_DATE_MARKER in value)
257
+ ? reviveMarshalledDateTime(value)
258
+ : undefined;
259
+ const rebuildTimeZone = (value) => markedBy(value, ZONE_MARKER) ? reviveTimeZone(value) : undefined;
260
+ const COOKIE_PROTO = Object.getPrototypeOf(Cookies.makeCookieUnsafe("a", "b"));
261
+ /** An expiry as it's stored, ISO text, back as the `Date` it was written from. */
262
+ const expiryOf = (text) => {
263
+ const date = new Date(text);
264
+ return Number.isNaN(date.getTime()) || date.toISOString() !== text ? undefined : date;
265
+ };
266
+ /**
267
+ * A cookie's options as stored: `expires` is the ISO text of the `Date` written, and a `maxAge`
268
+ * that's a `Duration` is one again. An `expires` that's anything else isn't one this can rebuild:
269
+ * 1.39.0 stored a `Date` as the empty map the marshaller makes of one, and the cookie it stood for
270
+ * would be written back without it, so that cookie stays the map it was read as.
271
+ */
272
+ const cookieOptions = (options) => {
273
+ if (!isMap(options))
274
+ return undefined;
275
+ const rebuilt = {};
276
+ for (const [key, value] of Object.entries(options)) {
277
+ if (key === "expires") {
278
+ const expires = typeof value === "string" ? expiryOf(value) : undefined;
279
+ if (expires === undefined)
280
+ return undefined;
281
+ rebuilt[key] = expires;
282
+ continue;
283
+ }
284
+ if (key === "maxAge" && markedBy(value, DURATION)) {
285
+ const maxAge = rebuildDuration(value);
286
+ if (maxAge === undefined)
287
+ return undefined;
288
+ rebuilt[key] = maxAge;
289
+ continue;
290
+ }
291
+ rebuilt[key] = value;
292
+ }
293
+ return rebuilt;
294
+ };
295
+ /**
296
+ * A cookie on its own prototype with the fields stored, so `valueEncoded` stays exactly what was
297
+ * written: rebuilding it from `value` could encode it otherwise.
298
+ */
299
+ const rebuildCookie = (value) => {
300
+ if (!markedBy(value, COOKIE))
301
+ return undefined;
302
+ const { name, valueEncoded } = value;
303
+ if (typeof name !== "string" ||
304
+ typeof value.value !== "string" ||
305
+ typeof valueEncoded !== "string") {
306
+ return undefined;
307
+ }
308
+ const fields = { name, value: value.value, valueEncoded };
309
+ if (Object.hasOwn(value, "options")) {
310
+ const options = value.options === undefined ? undefined : cookieOptions(value.options);
311
+ if (value.options !== undefined && options === undefined)
312
+ return undefined;
313
+ fields.options = options;
314
+ }
315
+ return Object.assign(Object.create(COOKIE_PROTO), fields);
316
+ };
317
+ const rebuildCookies = (value) => {
318
+ if (!markedBy(value, COOKIES) || !isMap(value.cookies))
319
+ return undefined;
320
+ const cookies = [];
321
+ for (const stored of Object.values(value.cookies)) {
322
+ const cookie = rebuildCookie(stored);
323
+ if (cookie === undefined)
324
+ return undefined;
325
+ cookies.push(cookie);
326
+ }
327
+ return Cookies.fromIterable(cookies);
328
+ };
329
+ const rebuildUrlParams = (value) => {
330
+ if (!markedBy(value, URL_PARAMS) || !Array.isArray(value.params))
331
+ return undefined;
332
+ const params = [];
333
+ for (const pair of value.params) {
334
+ if (!Array.isArray(pair) || pair.length !== 2)
335
+ return undefined;
336
+ const [key, text] = pair;
337
+ if (typeof key !== "string" || typeof text !== "string")
338
+ return undefined;
339
+ params.push([key, text]);
340
+ }
341
+ return UrlParams.make(params);
342
+ };
343
+ const rebuildSemVer = (value) => {
344
+ if (!markedBy(value, SEMVER))
345
+ return undefined;
346
+ const { major, minor, patch, prerelease, build } = value;
347
+ if (!Array.isArray(prerelease) || !Array.isArray(build))
348
+ return undefined;
349
+ return attempt(() => SemVer.make({ major, minor, patch, prerelease, build }));
350
+ };
351
+ const RANGE_PROTO = Object.getPrototypeOf(SemVerRange.any);
352
+ const isComparator = (value) => isMap(value) &&
353
+ value._tag === "Comparator" &&
354
+ typeof value.operator === "string" &&
355
+ isMap(value.version) &&
356
+ Array.isArray(value.version.components) &&
357
+ value.version.components.every((part) => typeof part === "number") &&
358
+ Array.isArray(value.version.prerelease);
359
+ /** A range is its comparator sets, plain data: the range module has no constructor for them. */
360
+ const rebuildSemVerRange = (value) => {
361
+ if (!markedBy(value, SEMVER_RANGE) || !Array.isArray(value.sets))
362
+ return undefined;
363
+ const sets = [];
364
+ for (const set of value.sets) {
365
+ if (!Array.isArray(set) || !set.every(isComparator))
366
+ return undefined;
367
+ sets.push(set.map((comparator) => {
368
+ const version = comparator.version;
369
+ return {
370
+ _tag: "Comparator",
371
+ operator: comparator.operator,
372
+ version: { components: version.components, prerelease: version.prerelease },
373
+ };
374
+ }));
375
+ }
376
+ return Object.assign(Object.create(RANGE_PROTO), { sets });
377
+ };
378
+ const ipv4 = (value) => {
379
+ if (!markedBy(value, NET_ADDRESS) || !isUint32(value.value))
380
+ return undefined;
381
+ const word = value.value;
382
+ return resultOf(NetAddress.ipv4FromOctets([
383
+ word >>> 24,
384
+ (word >>> 16) & 0xff,
385
+ (word >>> 8) & 0xff,
386
+ word & 0xff,
387
+ ]));
388
+ };
389
+ const ipv6 = (value) => {
390
+ if (!markedBy(value, NET_ADDRESS))
391
+ return undefined;
392
+ const words = [value.w0, value.w1, value.w2, value.w3];
393
+ if (!words.every(isUint32))
394
+ return undefined;
395
+ return resultOf(NetAddress.ipv6FromSegments(words.flatMap((word) => [word >>> 16, word & 0xffff])));
396
+ };
397
+ const ipAddress = (value) => {
398
+ if (!isMap(value))
399
+ return undefined;
400
+ return value._tag === "Ipv4Address"
401
+ ? ipv4(value)
402
+ : value._tag === "Ipv6Address"
403
+ ? ipv6(value)
404
+ : undefined;
405
+ };
406
+ const isPort = (value) => typeof value === "number";
407
+ /** An address, network, interface, socket address or host and port, by its tag. */
408
+ const rebuildNetAddress = (value) => {
409
+ if (!isMap(value))
410
+ return undefined;
411
+ switch (value._tag) {
412
+ case "Ipv4Address":
413
+ case "Ipv6Address":
414
+ return ipAddress(value);
415
+ case "MacAddress":
416
+ return markedBy(value, NET_ADDRESS) && value.bytes instanceof Uint8Array
417
+ ? resultOf(NetAddress.macAddressFromOctets([...value.bytes]))
418
+ : undefined;
419
+ case "IpNetwork":
420
+ case "IpInterface": {
421
+ const marker = value._tag === "IpNetwork" ? IP_NETWORK : IP_INTERFACE;
422
+ const address = ipAddress(value.address);
423
+ if (!markedBy(value, marker) || address === undefined)
424
+ return undefined;
425
+ if (typeof value.prefixLength !== "number")
426
+ return undefined;
427
+ return value._tag === "IpNetwork"
428
+ ? resultOf(IpNetwork.make(address, value.prefixLength))
429
+ : resultOf(IpInterface.make(address, value.prefixLength));
430
+ }
431
+ case "InetAddressV4": {
432
+ const address = ipAddress(value.address);
433
+ if (!markedBy(value, NET_ADDRESS) || !isPort(value.port))
434
+ return undefined;
435
+ return address !== undefined && address._tag === "Ipv4Address"
436
+ ? resultOf(NetAddress.inetAddressV4(address, value.port))
437
+ : undefined;
438
+ }
439
+ case "InetAddressV6": {
440
+ const address = ipAddress(value.address);
441
+ if (!markedBy(value, NET_ADDRESS) || !isPort(value.port))
442
+ return undefined;
443
+ if (typeof value.scopeId !== "number")
444
+ return undefined;
445
+ return address !== undefined && address._tag === "Ipv6Address"
446
+ ? resultOf(NetAddress.inetAddressV6(address, value.port, { scopeId: value.scopeId }))
447
+ : undefined;
448
+ }
449
+ case "HostPort": {
450
+ if (!markedBy(value, HOST) || !isPort(value.port))
451
+ return undefined;
452
+ const host = typeof value.host === "string" ? value.host : ipAddress(value.host);
453
+ return host === undefined ? undefined : resultOf(Host.hostPort(host, value.port));
454
+ }
455
+ case "UnixPathAddress":
456
+ return markedBy(value, NET_ADDRESS) && typeof value.path === "string"
457
+ ? NetAddress.unixPathAddress(value.path)
458
+ : undefined;
459
+ default:
460
+ return undefined;
461
+ }
462
+ };
463
+ /** A value inside a DNS record: an address or a `Duration` is rebuilt, anything else kept. */
464
+ const recordField = (value) => markedBy(value, DURATION)
465
+ ? rebuildDuration(value)
466
+ : isMap(value) && (Object.hasOwn(value, NET_ADDRESS) || Object.hasOwn(value, HOST))
467
+ ? rebuildNetAddress(value)
468
+ : value;
469
+ const rebuildDnsRecord = (value) => {
470
+ if (!markedBy(value, DNS_RECORD) || typeof value._tag !== "string")
471
+ return undefined;
472
+ const fields = {};
473
+ for (const [key, field] of Object.entries(value)) {
474
+ if (key === "_tag" || key === DNS_RECORD)
475
+ continue;
476
+ const rebuilt = recordField(field);
477
+ if (rebuilt === undefined && field !== undefined)
478
+ return undefined;
479
+ fields[key] = rebuilt;
480
+ }
481
+ return resultOf(Dns.makeRecord(value._tag, fields));
482
+ };
483
+ const REBUILDS = {
484
+ DateTime: rebuildDateTime,
485
+ BigDecimal: rebuildBigDecimal,
486
+ Duration: rebuildDuration,
487
+ TimeZone: rebuildTimeZone,
488
+ Cookie: rebuildCookie,
489
+ Cookies: rebuildCookies,
490
+ UrlParams: rebuildUrlParams,
491
+ SemVer: rebuildSemVer,
492
+ SemVerRange: rebuildSemVerRange,
493
+ NetAddress: rebuildNetAddress,
494
+ DnsRecord: rebuildDnsRecord,
495
+ };
496
+ /** What marshalling stores of an object: its enumerable properties, its prototype's included. */
497
+ const writtenProperties = (value) => {
498
+ const properties = [];
499
+ for (const key in value) {
500
+ const property = value[key];
501
+ if (property !== undefined && typeof property !== "function")
502
+ properties.push([key, property]);
503
+ }
504
+ return properties;
505
+ };
506
+ const sameNumber = (written, stored) => {
507
+ if (typeof stored !== "number" && typeof stored !== "bigint")
508
+ return false;
509
+ if (typeof written === typeof stored)
510
+ return written === stored;
511
+ const [integer, float] = typeof written === "bigint" ? [written, stored] : [stored, written];
512
+ return Number.isSafeInteger(float) && BigInt(float) === integer;
513
+ };
514
+ /**
515
+ * Whether a cookie's options, written, are what's stored. The marshaller writes the expiry of one
516
+ * of Effect's cookies as the ISO text of its `Date`, where the `Date`, valid and holding nothing of
517
+ * its own, would be an empty map; everything else is marshalled as it is.
518
+ */
519
+ const optionsWriteAs = (options, stored) => {
520
+ if (options === null || typeof options !== "object" || !isPlain(stored)) {
521
+ return writesAs(options, stored);
522
+ }
523
+ const properties = writtenProperties(options);
524
+ return (properties.length === Object.keys(stored).length &&
525
+ properties.every(([key, property]) => {
526
+ if (!Object.hasOwn(stored, key))
527
+ return false;
528
+ const dated = key === "expires" &&
529
+ property instanceof Date &&
530
+ !Number.isNaN(property.getTime()) &&
531
+ writtenProperties(property).length === 0;
532
+ return dated
533
+ ? stored[key] === property.toISOString()
534
+ : writesAs(property, stored[key]);
535
+ }));
536
+ };
537
+ /**
538
+ * Whether a value, written, is what's stored: the marshaller's walk of it, against what the
539
+ * unmarshaller handed back. Anything this can't say for sure isn't the same.
540
+ */
541
+ const writesAs = (written, stored) => {
542
+ if (typeof written === "number" || typeof written === "bigint")
543
+ return sameNumber(written, stored);
544
+ if (written === null || typeof written !== "object")
545
+ return written === stored;
546
+ if (written instanceof Uint8Array) {
547
+ return (stored instanceof Uint8Array &&
548
+ stored.length === written.length &&
549
+ written.every((byte, index) => byte === stored[index]));
550
+ }
551
+ if (written instanceof Set) {
552
+ if (!(stored instanceof Set) || stored.size !== written.size)
553
+ return false;
554
+ const members = [...stored];
555
+ return [...written].every((member) => members.some((other) => writesAs(member, other)));
556
+ }
557
+ if (Array.isArray(written)) {
558
+ const elements = written.filter((element) => element !== undefined && typeof element !== "function");
559
+ return (Array.isArray(stored) &&
560
+ stored.length === elements.length &&
561
+ elements.every((element, index) => writesAs(element, stored[index])));
562
+ }
563
+ if (!isPlain(stored))
564
+ return false;
565
+ const properties = written instanceof Map ? [...written] : writtenProperties(written);
566
+ const cookie = Object.getPrototypeOf(written) === COOKIE_PROTO;
567
+ return (properties.length === Object.keys(stored).length &&
568
+ properties.every(([key, property]) => typeof key === "string" &&
569
+ Object.hasOwn(stored, key) &&
570
+ (cookie && key === "options"
571
+ ? optionsWriteAs(property, stored[key])
572
+ : writesAs(property, stored[key]))));
573
+ };
574
+ /**
575
+ * The instance with every stored property its rebuild made no use of, as its own: what an instance
576
+ * was given on top of its fields (`Object.assign(duration, { source })`) was stored with it, and is
577
+ * written again with it. On a copy of the instance, so nothing shared is touched; the instance
578
+ * itself when there's nothing to carry.
579
+ */
580
+ const carrying = (instance, stored) => {
581
+ const written = new Set();
582
+ for (const key in instance)
583
+ written.add(key);
584
+ const carried = Object.keys(stored).filter((key) => !written.has(key));
585
+ if (carried.length === 0)
586
+ return instance;
587
+ const copy = Object.create(Object.getPrototypeOf(instance), Object.getOwnPropertyDescriptors(instance));
588
+ for (const key of carried) {
589
+ Object.defineProperty(copy, key, {
590
+ value: stored[key],
591
+ enumerable: true,
592
+ writable: true,
593
+ configurable: true,
594
+ });
595
+ }
596
+ return copy;
597
+ };
598
+ /**
599
+ * The kinds whose instance is rebuilt only if writing it stores what was read. A date's marker
600
+ * changed between releases, so a date is rebuilt as it always was. A cookie's expiry is held as a
601
+ * `Date` and written as its ISO text, which is how {@link optionsWriteAs} compares it.
602
+ */
603
+ const EXACT = {
604
+ DateTime: false,
605
+ BigDecimal: true,
606
+ Duration: true,
607
+ TimeZone: true,
608
+ Cookie: true,
609
+ Cookies: true,
610
+ UrlParams: true,
611
+ SemVer: true,
612
+ SemVerRange: true,
613
+ NetAddress: true,
614
+ DnsRecord: true,
615
+ };
616
+ /**
617
+ * The instance a stored value of this kind stands for, or `undefined` when the value isn't the map
618
+ * one is stored as, or holds what can't be rebuilt exactly. A real instance is never one: it carries
619
+ * its marker on its prototype, where the map carries it as its own.
620
+ *
621
+ * The instance carries every stored property its rebuild made no use of ({@link carrying}), so
622
+ * writing it again stores what was read. Where it still wouldn't (a property the rebuild dropped
623
+ * from inside the map), the value isn't rebuilt, and stays the map it always was.
624
+ */
625
+ export const rebuildStored = (kind, value) => {
626
+ const rebuilt = REBUILDS[kind](value);
627
+ if (kind === "DateTime" || typeof rebuilt !== "object" || rebuilt === null || !isMap(value)) {
628
+ return rebuilt;
629
+ }
630
+ const instance = carrying(rebuilt, value);
631
+ return EXACT[kind] && !writesAs(instance, value) ? undefined : instance;
632
+ };
633
+ /**
634
+ * One of Effect's declarations as a read takes it: its own parser decides on what's stored, exactly
635
+ * as it always did, and what it takes is returned as the instance it stands for. Where that can't be
636
+ * rebuilt exactly, it's returned as the parser returned it. A value the parser refuses is refused as
637
+ * it was. The declaration's checks, and everything holding it, see what's returned.
638
+ *
639
+ * Encoding goes through the declaration's own parser, untouched. Annotations, checks, context and
640
+ * the encoding chain are the declaration's: a transformation onto one runs its steps as it did, and
641
+ * only what its parser then returns is rebuilt. A step that made a real instance itself has made
642
+ * what's returned, the same object.
643
+ */
644
+ export const readingDeclaration = (ast, kind) => {
645
+ const parse = ast.run;
646
+ const read = (typeParameters) => {
647
+ const parser = parse(typeParameters);
648
+ return (input, self, options) => Effect.map(parser(input, self, options), (parsed) => {
649
+ const rebuilt = attempt(() => rebuildStored(kind, parsed));
650
+ return rebuilt === undefined ? parsed : rebuilt;
651
+ });
652
+ };
653
+ READ_PARSERS.set(read, parse);
654
+ return new SchemaAST.Declaration(ast.typeParameters, read, ast.annotations, ast.checks, ast.encoding, ast.context, ast.encodingChecks, ast.encodingRun ?? parse);
655
+ };
656
+ //# sourceMappingURL=EffectInstances.js.map