@dxos/effect 0.10.0 → 0.11.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 (36) hide show
  1. package/dist/lib/index.mjs +919 -0
  2. package/dist/lib/index.mjs.map +1 -0
  3. package/dist/lib/testing.mjs +23 -0
  4. package/dist/lib/testing.mjs.map +1 -0
  5. package/dist/types/src/EffectEx.d.ts +1 -1
  6. package/dist/types/src/EffectEx.d.ts.map +1 -1
  7. package/dist/types/src/RuntimeProvider.d.ts +6 -0
  8. package/dist/types/src/RuntimeProvider.d.ts.map +1 -1
  9. package/dist/types/src/atom-kvs.d.ts +7 -1
  10. package/dist/types/src/atom-kvs.d.ts.map +1 -1
  11. package/dist/types/src/index.d.ts +1 -0
  12. package/dist/types/src/index.d.ts.map +1 -1
  13. package/dist/types/src/internal/errors.d.ts +0 -5
  14. package/dist/types/src/internal/errors.d.ts.map +1 -1
  15. package/dist/types/tsconfig.tsbuildinfo +1 -1
  16. package/package.json +15 -17
  17. package/src/EffectEx.ts +1 -9
  18. package/src/RuntimeProvider.ts +8 -0
  19. package/src/atom-kvs.ts +7 -1
  20. package/src/index.ts +1 -0
  21. package/src/internal/errors.ts +0 -16
  22. package/src/otel.test.ts +1 -1
  23. package/dist/lib/browser/chunk-CGS2ULMK.mjs +0 -11
  24. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +0 -7
  25. package/dist/lib/browser/index.mjs +0 -849
  26. package/dist/lib/browser/index.mjs.map +0 -7
  27. package/dist/lib/browser/meta.json +0 -1
  28. package/dist/lib/browser/testing.mjs +0 -31
  29. package/dist/lib/browser/testing.mjs.map +0 -7
  30. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  31. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  32. package/dist/lib/node-esm/index.mjs +0 -849
  33. package/dist/lib/node-esm/index.mjs.map +0 -7
  34. package/dist/lib/node-esm/meta.json +0 -1
  35. package/dist/lib/node-esm/testing.mjs +0 -31
  36. package/dist/lib/node-esm/testing.mjs.map +0 -7
@@ -1,849 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- __export
4
- } from "./chunk-HSLMI22Q.mjs";
5
-
6
- // src/atom-kvs.ts
7
- import { Atom } from "@effect-atom/atom-react";
8
- import * as BrowserKeyValueStore from "@effect/platform-browser/BrowserKeyValueStore";
9
- var defaultRuntime = Atom.runtime(BrowserKeyValueStore.layerLocalStorage);
10
- var createKvsStore = (options) => {
11
- const runtime2 = options.runtime ?? defaultRuntime;
12
- return Atom.kvs({
13
- runtime: runtime2,
14
- key: options.key,
15
- schema: options.schema,
16
- defaultValue: options.defaultValue
17
- }).pipe(Atom.keepAlive);
18
- };
19
-
20
- // src/dynamic-runtime.ts
21
- var dynamic_runtime_exports = {};
22
- __export(dynamic_runtime_exports, {
23
- make: () => make
24
- });
25
- import * as Context from "effect/Context";
26
- import * as Effect2 from "effect/Effect";
27
- import * as Exit2 from "effect/Exit";
28
- import * as Option2 from "effect/Option";
29
- import * as Runtime2 from "effect/Runtime";
30
-
31
- // src/internal/errors.ts
32
- import * as Cause from "effect/Cause";
33
- import * as Chunk from "effect/Chunk";
34
- import * as Effect from "effect/Effect";
35
- import * as Exit from "effect/Exit";
36
- import * as GlobalValue from "effect/GlobalValue";
37
- import * as Option from "effect/Option";
38
- import * as Runtime from "effect/Runtime";
39
- var spanSymbol = /* @__PURE__ */ Symbol.for("effect/SpanAnnotation");
40
- var spanToTrace = GlobalValue.globalValue("effect/Tracer/spanToTrace", () => /* @__PURE__ */ new WeakMap());
41
- var locationRegex = /\((.*)\)/g;
42
- var prettyErrorStack = (error, appendStacks = []) => {
43
- if (typeof error !== "object" || error === null) {
44
- return error;
45
- }
46
- const span = error[spanSymbol];
47
- const lines = typeof error.stack === "string" ? error.stack.split("\n") : [];
48
- const out = [];
49
- let atStack = false, inCore = false, passedScheduler = false;
50
- for (let i = 0; i < lines.length; i++) {
51
- if (!atStack && !lines[i].startsWith(" at ")) {
52
- out.push(lines[i]);
53
- continue;
54
- }
55
- atStack = true;
56
- if (lines[i].includes(" at new BaseEffectError") || lines[i].includes(" at new YieldableError")) {
57
- i++;
58
- continue;
59
- }
60
- if (lines[i].includes("Generator.next")) {
61
- break;
62
- }
63
- if (lines[i].includes("effect_internal_function")) {
64
- break;
65
- }
66
- const filename = lines[i].match(/\/([a-zA-Z0-9_\-.]+):\d+:\d+\)$/)?.[1];
67
- if (!inCore && [
68
- "core-effect.ts"
69
- ].includes(filename)) {
70
- inCore = true;
71
- }
72
- if (inCore && !passedScheduler && [
73
- "Scheduler.ts"
74
- ].includes(filename)) {
75
- passedScheduler = true;
76
- continue;
77
- }
78
- if (passedScheduler && ![
79
- "Scheduler.ts"
80
- ].includes(filename)) {
81
- inCore = false;
82
- }
83
- if (inCore) {
84
- continue;
85
- }
86
- out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>").replace(/at Arguments\./, "at "));
87
- }
88
- if (span) {
89
- let current = span;
90
- let i = 0;
91
- while (current && current._tag === "Span" && i < 10) {
92
- const stackFn = spanToTrace.get(current);
93
- if (typeof stackFn === "function") {
94
- const stack = stackFn();
95
- if (typeof stack === "string") {
96
- const locationMatchAll = stack.matchAll(locationRegex);
97
- let match = false;
98
- for (const [, location] of locationMatchAll) {
99
- match = true;
100
- out.push(` at ${current.name} (${location})`);
101
- }
102
- if (!match) {
103
- out.push(` at ${current.name} (${stack.replace(/^at /, "")})`);
104
- }
105
- } else {
106
- out.push(` at ${current.name}`);
107
- }
108
- } else {
109
- out.push(` at ${current.name}`);
110
- }
111
- current = Option.getOrUndefined(current.parent);
112
- i++;
113
- }
114
- }
115
- out.push(...appendStacks);
116
- error = Cause.originalError(error);
117
- if (error.cause) {
118
- error.cause = prettyErrorStack(error.cause);
119
- }
120
- Object.defineProperty(error, "stack", {
121
- value: out.join("\n"),
122
- writable: true,
123
- enumerable: false,
124
- configurable: true
125
- });
126
- return error;
127
- };
128
- var causeToError = (cause) => {
129
- if (Cause.isEmpty(cause)) {
130
- return new Error("Fiber failed without a cause");
131
- } else if (Cause.isInterruptedOnly(cause)) {
132
- return new Error("Fiber was interrupted");
133
- } else {
134
- const errors = [
135
- ...Chunk.toArray(Cause.failures(cause)),
136
- ...Chunk.toArray(Cause.defects(cause))
137
- ];
138
- const getStackFrames = () => {
139
- const err = new Error();
140
- Error.captureStackTrace(err, causeToError);
141
- return err.stack.split("\n").slice(1);
142
- };
143
- const stackFrames = getStackFrames();
144
- const newErrors = errors.map((error) => prettyErrorStack(error, stackFrames));
145
- if (newErrors.length === 1) {
146
- return newErrors[0];
147
- } else {
148
- return new AggregateError(newErrors);
149
- }
150
- }
151
- };
152
- var throwCause = (cause) => {
153
- throw causeToError(cause);
154
- };
155
- var unwrapExit = (exit2) => {
156
- if (Exit.isSuccess(exit2)) {
157
- return exit2.value;
158
- }
159
- return throwCause(exit2.cause);
160
- };
161
- var runAndForwardErrors = async (effect, options) => {
162
- const exit2 = await Effect.runPromiseExit(effect, options);
163
- return unwrapExit(exit2);
164
- };
165
- var runPromise = runAndForwardErrors;
166
- var runInRuntime = (...args) => {
167
- if (args.length === 1) {
168
- const [runtime2] = args;
169
- return async (effect, options) => {
170
- const exit2 = await Runtime.runPromiseExit(runtime2, effect, options);
171
- return unwrapExit(exit2);
172
- };
173
- } else {
174
- const [runtime2, effect, options] = args;
175
- return (async () => {
176
- const exit2 = await Runtime.runPromiseExit(runtime2, effect, options);
177
- return unwrapExit(exit2);
178
- })();
179
- }
180
- };
181
- var promiseWithCauseCapture = (evaluate) => Effect.promise(async (signal) => {
182
- try {
183
- const result = await evaluate(signal);
184
- return Effect.succeed(result);
185
- } catch (err) {
186
- return Effect.die(err);
187
- }
188
- }).pipe(Effect.flatten);
189
-
190
- // src/dynamic-runtime.ts
191
- var validateTags = (context, tags) => Effect2.gen(function* () {
192
- const missingTags = [];
193
- for (const tag of tags) {
194
- const option = Context.getOption(context, tag);
195
- if (Option2.isNone(option)) {
196
- missingTags.push(tag.key);
197
- }
198
- }
199
- if (missingTags.length > 0) {
200
- return yield* Effect2.die(new Error(`Missing required tags in runtime: ${missingTags.join(", ")}`));
201
- }
202
- });
203
- function make(managedRuntime, tags) {
204
- const managedRuntimeAny = managedRuntime;
205
- let cachedRuntime;
206
- let validatedRuntimePromise;
207
- const getValidatedRuntimeAsync = async () => {
208
- if (!validatedRuntimePromise) {
209
- validatedRuntimePromise = managedRuntimeAny.runPromise(Effect2.gen(function* () {
210
- const rt = yield* managedRuntimeAny.runtimeEffect;
211
- yield* validateTags(rt.context, tags);
212
- return rt;
213
- }));
214
- }
215
- return validatedRuntimePromise;
216
- };
217
- const getValidatedRuntime = () => {
218
- const validationExit = managedRuntimeAny.runSyncExit(Effect2.gen(function* () {
219
- const rt = yield* managedRuntimeAny.runtimeEffect;
220
- yield* validateTags(rt.context, tags);
221
- return rt;
222
- }));
223
- return unwrapExit(validationExit);
224
- };
225
- return {
226
- managedRuntime: managedRuntimeAny,
227
- runPromise: async (effect) => {
228
- const runtime2 = await getValidatedRuntimeAsync();
229
- return Runtime2.runPromise(runtime2)(effect);
230
- },
231
- runSync: (effect) => {
232
- const runtime2 = getValidatedRuntime();
233
- return Runtime2.runSync(runtime2)(effect);
234
- },
235
- runSyncExit: (effect) => {
236
- const validationExit = managedRuntimeAny.runSyncExit(Effect2.gen(function* () {
237
- const rt = yield* managedRuntimeAny.runtimeEffect;
238
- yield* validateTags(rt.context, tags);
239
- return rt;
240
- }));
241
- if (Exit2.isSuccess(validationExit)) {
242
- const runtime2 = validationExit.value;
243
- return Runtime2.runSyncExit(runtime2)(effect);
244
- }
245
- return validationExit;
246
- },
247
- runPromiseExit: async (effect) => {
248
- try {
249
- const runtime2 = await getValidatedRuntimeAsync();
250
- return Runtime2.runPromiseExit(runtime2)(effect);
251
- } catch (error) {
252
- return Exit2.die(error);
253
- }
254
- },
255
- runFork: (effect) => {
256
- const runtime2 = getValidatedRuntime();
257
- return Runtime2.runFork(runtime2)(effect);
258
- },
259
- runtimeEffect: Effect2.gen(function* () {
260
- if (cachedRuntime) {
261
- return cachedRuntime;
262
- }
263
- const rt = yield* managedRuntimeAny.runtimeEffect;
264
- yield* validateTags(rt.context, tags);
265
- const runtime2 = rt;
266
- cachedRuntime = runtime2;
267
- return runtime2;
268
- }).pipe(Effect2.catchAll(() => (
269
- // This should never happen since validateTags uses Effect.die
270
- Effect2.die(new Error("Unexpected error in runtimeEffect validation"))
271
- ))),
272
- dispose: async () => {
273
- await managedRuntimeAny.dispose();
274
- }
275
- };
276
- }
277
-
278
- // src/EffectEx.ts
279
- var EffectEx_exports = {};
280
- __export(EffectEx_exports, {
281
- acquireReleaseResource: () => acquireReleaseResource,
282
- asyncTaskTaggingLayer: () => asyncTaskTaggingLayer,
283
- causeToError: () => causeToError,
284
- contextFromScope: () => contextFromScope,
285
- promiseWithCauseCapture: () => promiseWithCauseCapture,
286
- runAndForwardErrors: () => runAndForwardErrors,
287
- runInRuntime: () => runInRuntime,
288
- runPromise: () => runPromise,
289
- throwCause: () => throwCause,
290
- unwrapExit: () => unwrapExit
291
- });
292
-
293
- // src/internal/async-task-tagging.ts
294
- import * as Context2 from "effect/Context";
295
- import * as Effect3 from "effect/Effect";
296
- import { pipe } from "effect/Function";
297
- import * as Layer from "effect/Layer";
298
- import * as Predicate from "effect/Predicate";
299
- import * as Tracer from "effect/Tracer";
300
- var runInTask = /* @__PURE__ */ Symbol("runInTask");
301
- var asyncTaskTaggingLayer = () => {
302
- if (Predicate.hasProperty(console, "createTask") === false) {
303
- return Layer.empty;
304
- }
305
- const makeTracer = Effect3.gen(function* () {
306
- const oldTracer = yield* Effect3.tracer;
307
- return Tracer.make({
308
- span: (name, ...args) => {
309
- const span = oldTracer.span(name, ...args);
310
- const trace = console.createTask(name);
311
- span[runInTask] = (f) => trace.run(f);
312
- return span;
313
- },
314
- context: (f, fiber) => {
315
- const maybeParentSpan = Context2.getOption(Tracer.ParentSpan)(fiber.currentContext);
316
- if (maybeParentSpan._tag === "None") {
317
- return oldTracer.context(f, fiber);
318
- }
319
- const parentSpan = maybeParentSpan.value;
320
- if (parentSpan._tag === "ExternalSpan") {
321
- return oldTracer.context(f, fiber);
322
- }
323
- const span = parentSpan;
324
- if (runInTask in span && typeof span[runInTask] === "function") {
325
- return span[runInTask](() => oldTracer.context(f, fiber));
326
- }
327
- return oldTracer.context(f, fiber);
328
- }
329
- });
330
- });
331
- return pipe(makeTracer, Effect3.map(Layer.setTracer), Layer.unwrapEffect);
332
- };
333
-
334
- // src/internal/context.ts
335
- import * as Effect4 from "effect/Effect";
336
- import { Context as Context3 } from "@dxos/context";
337
- var contextFromScope = () => Effect4.gen(function* () {
338
- const ctx = new Context3();
339
- yield* Effect4.addFinalizer(() => Effect4.promise(() => ctx.dispose()));
340
- return ctx;
341
- });
342
-
343
- // src/internal/resource.ts
344
- import * as Effect5 from "effect/Effect";
345
- var acquireReleaseResource = (getResource) => Effect5.acquireRelease(Effect5.gen(function* () {
346
- const resource = getResource();
347
- yield* Effect5.promise(async () => {
348
- await resource.open?.();
349
- return void 0;
350
- });
351
- return resource;
352
- }), (resource) => Effect5.promise(async () => {
353
- await resource.close?.();
354
- return void 0;
355
- }));
356
-
357
- // src/Performance.ts
358
- var Performance_exports = {};
359
- __export(Performance_exports, {
360
- addTrackEntry: () => addTrackEntry
361
- });
362
- import * as Effect6 from "effect/Effect";
363
- var addTrackEntry = (options) => (effect) => Effect6.gen(function* () {
364
- const start = performance.now();
365
- const exit2 = yield* Effect6.exit(effect);
366
- const resolvedOptions = typeof options === "function" ? options(exit2) : options;
367
- performance.measure(resolvedOptions.name, {
368
- start,
369
- detail: {
370
- ...resolvedOptions.detail,
371
- devtools: resolvedOptions.devtools
372
- }
373
- });
374
- return yield* exit2;
375
- });
376
-
377
- // src/RuntimeProvider.ts
378
- var RuntimeProvider_exports = {};
379
- __export(RuntimeProvider_exports, {
380
- currentRuntime: () => currentRuntime,
381
- provide: () => provide2,
382
- runPromise: () => runPromise3
383
- });
384
- import * as Effect7 from "effect/Effect";
385
- import * as Runtime3 from "effect/Runtime";
386
- var currentRuntime = () => Effect7.runtime().pipe(Effect7.map(Effect7.succeed));
387
- var runPromise3 = (provider) => async (effect) => {
388
- const runtime2 = await runAndForwardErrors(provider);
389
- return unwrapExit(await effect.pipe(Runtime3.runPromiseExit(runtime2)));
390
- };
391
- var provide2 = (runtimeProvider) => (effect) => Effect7.flatMap(runtimeProvider, (runtime2) => Effect7.provide(effect, runtime2));
392
-
393
- // src/SchemaEx.ts
394
- var SchemaEx_exports = {};
395
- __export(SchemaEx_exports, {
396
- JsonPath: () => JsonPath,
397
- JsonProp: () => JsonProp,
398
- ParamKeyAnnotation: () => ParamKeyAnnotation,
399
- UrlParser: () => UrlParser,
400
- VisitResult: () => VisitResult,
401
- createJsonPath: () => createJsonPath,
402
- findAnnotation: () => findAnnotation,
403
- findNode: () => findNode,
404
- findProperty: () => findProperty,
405
- fromEffectValidationPath: () => fromEffectValidationPath,
406
- getAnnotation: () => getAnnotation2,
407
- getArrayElementType: () => getArrayElementType,
408
- getBaseType: () => getBaseType,
409
- getDiscriminatedType: () => getDiscriminatedType,
410
- getDiscriminatingProps: () => getDiscriminatingProps,
411
- getField: () => getField,
412
- getLiteralValues: () => getLiteralValues,
413
- getParamKeyAnnotation: () => getParamKeyAnnotation,
414
- getProperties: () => getProperties,
415
- getValue: () => getValue,
416
- isArrayType: () => isArrayType,
417
- isDiscriminatedUnion: () => isDiscriminatedUnion,
418
- isJsonPath: () => isJsonPath,
419
- isLiteralUnion: () => isLiteralUnion,
420
- isNestedType: () => isNestedType,
421
- isOption: () => isOption,
422
- isTupleType: () => isTupleType2,
423
- mapAst: () => mapAst,
424
- setValue: () => setValue,
425
- splitJsonPath: () => splitJsonPath,
426
- unwrapOptional: () => unwrapOptional,
427
- visit: () => visit
428
- });
429
-
430
- // src/internal/ast.ts
431
- import * as Function from "effect/Function";
432
- import * as Option3 from "effect/Option";
433
- import * as Schema from "effect/Schema";
434
- import * as SchemaAST from "effect/SchemaAST";
435
- import { invariant } from "@dxos/invariant";
436
- import { isNonNullable } from "@dxos/util";
437
- var reduceRefinements = (type, refinements = []) => {
438
- if (SchemaAST.isRefinement(type)) {
439
- const filter = type.filter;
440
- const nextType = {
441
- ...type.from,
442
- annotations: {
443
- ...type.from.annotations,
444
- ...type.annotations
445
- }
446
- };
447
- return reduceRefinements(nextType, [
448
- ...refinements,
449
- filter
450
- ]);
451
- }
452
- return {
453
- type,
454
- refinements
455
- };
456
- };
457
- var getBaseType = (prop) => {
458
- const encoded = SchemaAST.encodedBoundAST(prop.type);
459
- const unwrapped = prop.isOptional && encoded._tag === "Union" ? encoded.types[0] : encoded;
460
- return reduceRefinements(unwrapped);
461
- };
462
- var getProperties = (ast) => {
463
- const properties = SchemaAST.getPropertySignatures(ast);
464
- return properties.map((prop) => {
465
- const { type, refinements } = getBaseType(prop);
466
- const mergedType = prop.annotations && Reflect.ownKeys(prop.annotations).length > 0 ? {
467
- ...type,
468
- annotations: {
469
- ...type.annotations,
470
- ...prop.annotations
471
- }
472
- } : type;
473
- return {
474
- type: mergedType,
475
- refinements,
476
- name: prop.name,
477
- isOptional: prop.isOptional,
478
- isReadonly: prop.isReadonly
479
- };
480
- });
481
- };
482
- var VisitResult = /* @__PURE__ */ (function(VisitResult2) {
483
- VisitResult2[VisitResult2["CONTINUE"] = 0] = "CONTINUE";
484
- VisitResult2[VisitResult2["SKIP"] = 1] = "SKIP";
485
- VisitResult2[VisitResult2["EXIT"] = 2] = "EXIT";
486
- return VisitResult2;
487
- })({});
488
- var visit = (node, testOrVisitor, visitor) => {
489
- visitNode(node, testOrVisitor, visitor);
490
- };
491
- var visitNode = (node, test, visitor, path = [], depth = 0) => {
492
- const $result = test?.(node, path, depth);
493
- const result = $result === void 0 ? 0 : typeof $result === "boolean" ? $result ? 0 : 1 : $result;
494
- if (result === 2) {
495
- return result;
496
- }
497
- if (result !== 1) {
498
- visitor(node, path, depth);
499
- }
500
- if (SchemaAST.isTypeLiteral(node)) {
501
- for (const prop of SchemaAST.getPropertySignatures(node)) {
502
- const currentPath = [
503
- ...path,
504
- prop.name.toString()
505
- ];
506
- const result2 = visitNode(prop.type, test, visitor, currentPath, depth + 1);
507
- if (result2 === 2) {
508
- return result2;
509
- }
510
- }
511
- } else if (SchemaAST.isTupleType(node)) {
512
- for (const [i, element] of node.elements.entries()) {
513
- const currentPath = [
514
- ...path,
515
- i
516
- ];
517
- const result2 = visitNode(element.type, test, visitor, currentPath, depth);
518
- if (result2 === 2) {
519
- return result2;
520
- }
521
- }
522
- } else if (SchemaAST.isUnion(node)) {
523
- for (const type of node.types) {
524
- const result2 = visitNode(type, test, visitor, path, depth);
525
- if (result2 === 2) {
526
- return result2;
527
- }
528
- }
529
- } else if (SchemaAST.isRefinement(node)) {
530
- const result2 = visitNode(node.from, test, visitor, path, depth);
531
- if (result2 === 2) {
532
- return result2;
533
- }
534
- }
535
- };
536
- var findNode = (node, test) => {
537
- if (test(node)) {
538
- return node;
539
- } else if (SchemaAST.isTypeLiteral(node)) {
540
- for (const prop of SchemaAST.getPropertySignatures(node)) {
541
- const child = findNode(prop.type, test);
542
- if (child) {
543
- return child;
544
- }
545
- }
546
- for (const prop of getIndexSignatures(node)) {
547
- const child = findNode(prop.type, test);
548
- if (child) {
549
- return child;
550
- }
551
- }
552
- } else if (SchemaAST.isTupleType(node)) {
553
- for (const [_, element] of node.elements.entries()) {
554
- const child = findNode(element.type, test);
555
- if (child) {
556
- return child;
557
- }
558
- }
559
- } else if (SchemaAST.isUnion(node)) {
560
- if (isLiteralUnion(node)) {
561
- return void 0;
562
- }
563
- for (const type of node.types) {
564
- const child = findNode(type, test);
565
- if (child) {
566
- return child;
567
- }
568
- }
569
- } else if (SchemaAST.isRefinement(node)) {
570
- return findNode(node.from, test);
571
- }
572
- };
573
- var findProperty = (schema, path) => {
574
- const getProp = (node, path2) => {
575
- const [name, ...rest] = path2;
576
- const typeNode = findNode(node, SchemaAST.isTypeLiteral);
577
- invariant(typeNode);
578
- for (const prop of SchemaAST.getPropertySignatures(typeNode)) {
579
- if (prop.name === name) {
580
- if (rest.length) {
581
- return getProp(prop.type, rest);
582
- } else {
583
- return prop.type;
584
- }
585
- }
586
- }
587
- };
588
- return getProp(schema.ast, path.split("."));
589
- };
590
- var defaultAnnotations = {
591
- ObjectKeyword: SchemaAST.objectKeyword,
592
- StringKeyword: SchemaAST.stringKeyword,
593
- NumberKeyword: SchemaAST.numberKeyword,
594
- BooleanKeyword: SchemaAST.booleanKeyword
595
- };
596
- var getAnnotation2 = (annotationId, noDefault = true) => (node) => {
597
- const id = Function.pipe(SchemaAST.getIdentifierAnnotation(node), Option3.getOrUndefined);
598
- const value = Function.pipe(SchemaAST.getAnnotation(annotationId)(node), Option3.getOrUndefined);
599
- if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {
600
- return void 0;
601
- }
602
- return value;
603
- };
604
- var findAnnotation = (node, annotationId, noDefault = true) => {
605
- const getAnnotationById = getAnnotation2(annotationId, noDefault);
606
- const getBaseAnnotation = (node2) => {
607
- const value = getAnnotationById(node2);
608
- if (value !== void 0) {
609
- return value;
610
- }
611
- if (SchemaAST.isUnion(node2)) {
612
- if (isOption(node2)) {
613
- return getAnnotationById(node2.types[0]);
614
- }
615
- }
616
- };
617
- return getBaseAnnotation(node);
618
- };
619
- var isOption = (node) => {
620
- return SchemaAST.isUnion(node) && node.types.length === 2 && SchemaAST.isUndefinedKeyword(node.types[1]);
621
- };
622
- var isLiteralUnion = (node) => {
623
- return SchemaAST.isUnion(node) && node.types.every(SchemaAST.isLiteral);
624
- };
625
- var getLiteralValues = (schema) => {
626
- if (!isLiteralUnion(schema.ast)) {
627
- return [];
628
- }
629
- return schema.ast.types.map((node) => node.literal);
630
- };
631
- var isArrayType = (node) => {
632
- return SchemaAST.isTupleType(node) && node.elements.length === 0 && node.rest.length === 1;
633
- };
634
- var getArrayElementType = (node) => {
635
- return isArrayType(node) ? node.rest.at(0)?.type : void 0;
636
- };
637
- var isTupleType2 = (node) => {
638
- return SchemaAST.isTupleType(node) && node.elements.length > 0;
639
- };
640
- var isDiscriminatedUnion = (node) => {
641
- return SchemaAST.isUnion(node) && !!getDiscriminatingProps(node)?.length;
642
- };
643
- var getDiscriminatingProps = (node) => {
644
- invariant(SchemaAST.isUnion(node));
645
- if (isOption(node)) {
646
- return;
647
- }
648
- return node.types.reduce((shared, type) => {
649
- const props = SchemaAST.getPropertySignatures(type).filter((p) => SchemaAST.isLiteral(p.type)).map((p) => p.name.toString());
650
- return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));
651
- }, []);
652
- };
653
- var getDiscriminatedType = (node, value = {}) => {
654
- invariant(SchemaAST.isUnion(node));
655
- invariant(value);
656
- const props = getDiscriminatingProps(node);
657
- if (!props?.length) {
658
- return;
659
- }
660
- for (const type of node.types) {
661
- const match = SchemaAST.getPropertySignatures(type).filter((prop) => props?.includes(prop.name.toString())).every((prop) => {
662
- invariant(SchemaAST.isLiteral(prop.type));
663
- return prop.type.literal === value[prop.name.toString()];
664
- });
665
- if (match) {
666
- return type;
667
- }
668
- }
669
- const fields = Object.fromEntries(props.map((prop) => {
670
- const literals = node.types.map((type) => {
671
- const literal = SchemaAST.getPropertySignatures(type).find((p) => p.name.toString() === prop);
672
- invariant(SchemaAST.isLiteral(literal.type));
673
- return literal.type.literal;
674
- }).filter(isNonNullable);
675
- return literals.length ? [
676
- prop,
677
- Schema.Literal(...literals)
678
- ] : void 0;
679
- }).filter(isNonNullable));
680
- const schema = Schema.Struct(fields);
681
- return schema.ast;
682
- };
683
- var unwrapOptional = (property) => {
684
- if (!property.isOptional || !SchemaAST.isUnion(property.type) || !isOption(property.type)) {
685
- return property;
686
- }
687
- return property.type.types[0];
688
- };
689
- var isNestedType = (node) => {
690
- return SchemaAST.isDeclaration(node) || SchemaAST.isObjectKeyword(node) || SchemaAST.isTypeLiteral(node) || // TODO(wittjosiah): Tuples are actually arrays.
691
- isTupleType2(node) || isDiscriminatedUnion(node);
692
- };
693
- var mapAst = (ast, f) => {
694
- switch (ast._tag) {
695
- case "TypeLiteral": {
696
- return new SchemaAST.TypeLiteral(ast.propertySignatures.map((prop) => new SchemaAST.PropertySignature(prop.name, f(prop.type, prop.name), prop.isOptional, prop.isReadonly, prop.annotations)), ast.indexSignatures, ast.annotations);
697
- }
698
- case "Union": {
699
- return SchemaAST.Union.make(ast.types.map(f), ast.annotations);
700
- }
701
- case "TupleType": {
702
- return new SchemaAST.TupleType(ast.elements.map((t, index) => new SchemaAST.OptionalType(f(t.type, index), t.isOptional, t.annotations)), ast.rest.map((t) => new SchemaAST.Type(f(t.type, void 0), t.annotations)), ast.isReadonly, ast.annotations);
703
- }
704
- case "Suspend": {
705
- const newAst = f(ast.f(), void 0);
706
- return new SchemaAST.Suspend(() => newAst, ast.annotations);
707
- }
708
- default: {
709
- return ast;
710
- }
711
- }
712
- };
713
- var getIndexSignatures = (ast) => {
714
- const annotation = SchemaAST.getSurrogateAnnotation(ast);
715
- if (Option3.isSome(annotation)) {
716
- return getIndexSignatures(annotation.value);
717
- }
718
- switch (ast._tag) {
719
- case "TypeLiteral":
720
- return ast.indexSignatures.slice();
721
- case "Suspend":
722
- return getIndexSignatures(ast.f());
723
- case "Refinement":
724
- return getIndexSignatures(ast.from);
725
- }
726
- return [];
727
- };
728
-
729
- // src/internal/json-path.ts
730
- import * as Option4 from "effect/Option";
731
- import * as Schema2 from "effect/Schema";
732
- import { JSONPath } from "jsonpath-plus";
733
- import { invariant as invariant2 } from "@dxos/invariant";
734
- import { getDeep, setDeep } from "@dxos/util";
735
- var PATH_REGEX = /^($|[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*|\[\d+\](?:\.)?)*$)/;
736
- var PROP_REGEX = /^\w+$/;
737
- var JsonPath = Schema2.String.pipe(Schema2.pattern(PATH_REGEX)).annotations({
738
- title: "JSON path",
739
- description: "JSON path to a property"
740
- });
741
- var JsonProp = Schema2.NonEmptyString.pipe(Schema2.pattern(PROP_REGEX, {
742
- message: () => "Property name must contain only letters, numbers, and underscores"
743
- }));
744
- var isJsonPath = (value) => {
745
- return Option4.isSome(Schema2.validateOption(JsonPath)(value));
746
- };
747
- var createJsonPath = (path) => {
748
- const candidatePath = path.map((p, i) => {
749
- if (typeof p === "number") {
750
- return `[${p}]`;
751
- } else {
752
- return i === 0 ? p : `.${p}`;
753
- }
754
- }).join("");
755
- invariant2(isJsonPath(candidatePath), `Invalid JsonPath: ${candidatePath}`);
756
- return candidatePath;
757
- };
758
- var fromEffectValidationPath = (effectPath) => {
759
- const jsonPath = effectPath.replace(/\.\[(\d+)\]/g, "[$1]");
760
- invariant2(isJsonPath(jsonPath), `Invalid JsonPath: ${jsonPath}`);
761
- return jsonPath;
762
- };
763
- var splitJsonPath = (path) => {
764
- if (!isJsonPath(path)) {
765
- return [];
766
- }
767
- return path.match(/[a-zA-Z_$][\w$]*|\[\d+\]/g)?.map((part) => part.replace(/[[\]]/g, "")).map((part) => {
768
- const parsed = Number.parseInt(part, 10);
769
- return Number.isNaN(parsed) ? part : parsed;
770
- }) ?? [];
771
- };
772
- var getField = (object, path) => {
773
- return JSONPath({
774
- path,
775
- json: object
776
- })[0];
777
- };
778
- var getValue = (obj, path) => {
779
- return getDeep(obj, splitJsonPath(path));
780
- };
781
- var setValue = (obj, path, value) => {
782
- return setDeep(obj, splitJsonPath(path), value);
783
- };
784
-
785
- // src/internal/url.ts
786
- import * as Function2 from "effect/Function";
787
- import * as Option5 from "effect/Option";
788
- import * as SchemaAST2 from "effect/SchemaAST";
789
- import { decamelize } from "@dxos/util";
790
- var ParamKeyAnnotationId = /* @__PURE__ */ Symbol.for("@dxos/schema/annotation/ParamKey");
791
- var getParamKeyAnnotation = SchemaAST2.getAnnotation(ParamKeyAnnotationId);
792
- var ParamKeyAnnotation = (value) => (self) => self.annotations({
793
- [ParamKeyAnnotationId]: value
794
- });
795
- var UrlParser = class {
796
- _schema;
797
- constructor(_schema) {
798
- this._schema = _schema;
799
- }
800
- /**
801
- * Parse URL params.
802
- */
803
- parse(_url) {
804
- const url = new URL(_url);
805
- return Object.entries(this._schema.fields).reduce((params, [key, type]) => {
806
- let value = url.searchParams.get(decamelize(key));
807
- if (value == null) {
808
- value = url.searchParams.get(key);
809
- }
810
- if (value != null) {
811
- if (SchemaAST2.isNumberKeyword(type.ast)) {
812
- params[key] = parseInt(value);
813
- } else if (SchemaAST2.isBooleanKeyword(type.ast)) {
814
- params[key] = value === "true" || value === "1";
815
- } else {
816
- params[key] = value;
817
- }
818
- }
819
- return params;
820
- }, {});
821
- }
822
- /**
823
- * Return URL with encoded params.
824
- */
825
- create(_url, params) {
826
- const url = new URL(_url);
827
- Object.entries(params).forEach(([key, value]) => {
828
- if (value !== void 0) {
829
- const field = this._schema.fields[key];
830
- if (field) {
831
- const { key: serializedKey } = Function2.pipe(getParamKeyAnnotation(field.ast), Option5.getOrElse(() => ({
832
- key: decamelize(key)
833
- })));
834
- url.searchParams.set(serializedKey, String(value));
835
- }
836
- }
837
- });
838
- return url;
839
- }
840
- };
841
- export {
842
- dynamic_runtime_exports as DynamicRuntime,
843
- EffectEx_exports as EffectEx,
844
- Performance_exports as Performance,
845
- RuntimeProvider_exports as RuntimeProvider,
846
- SchemaEx_exports as SchemaEx,
847
- createKvsStore
848
- };
849
- //# sourceMappingURL=index.mjs.map