@dxos/effect 0.8.4-main.fffef41 → 0.8.4-staging.60fe92afc8

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 (86) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +1 -1
  3. package/dist/lib/browser/chunk-CGS2ULMK.mjs +11 -0
  4. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +530 -353
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing.mjs +31 -0
  9. package/dist/lib/browser/testing.mjs.map +7 -0
  10. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  11. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  12. package/dist/lib/node-esm/index.mjs +530 -353
  13. package/dist/lib/node-esm/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/lib/node-esm/testing.mjs +31 -0
  16. package/dist/lib/node-esm/testing.mjs.map +7 -0
  17. package/dist/types/src/EffectEx.d.ts +5 -0
  18. package/dist/types/src/EffectEx.d.ts.map +1 -0
  19. package/dist/types/src/Performance.d.ts +25 -0
  20. package/dist/types/src/Performance.d.ts.map +1 -0
  21. package/dist/types/src/RuntimeProvider.d.ts +21 -0
  22. package/dist/types/src/RuntimeProvider.d.ts.map +1 -0
  23. package/dist/types/src/SchemaEx.d.ts +4 -0
  24. package/dist/types/src/SchemaEx.d.ts.map +1 -0
  25. package/dist/types/src/atom-kvs.d.ts +19 -0
  26. package/dist/types/src/atom-kvs.d.ts.map +1 -0
  27. package/dist/types/src/dynamic-runtime.d.ts +56 -0
  28. package/dist/types/src/dynamic-runtime.d.ts.map +1 -0
  29. package/dist/types/src/dynamic-runtime.test.d.ts +2 -0
  30. package/dist/types/src/dynamic-runtime.test.d.ts.map +1 -0
  31. package/dist/types/src/index.d.ts +8 -7
  32. package/dist/types/src/index.d.ts.map +1 -1
  33. package/dist/types/src/{ast.d.ts → internal/ast.d.ts} +45 -21
  34. package/dist/types/src/internal/ast.d.ts.map +1 -0
  35. package/dist/types/src/internal/async-task-tagging.d.ts +6 -0
  36. package/dist/types/src/internal/async-task-tagging.d.ts.map +1 -0
  37. package/dist/types/src/internal/context.d.ts.map +1 -0
  38. package/dist/types/src/{errors.d.ts → internal/errors.d.ts} +16 -0
  39. package/dist/types/src/internal/errors.d.ts.map +1 -0
  40. package/dist/types/src/{jsonPath.d.ts → internal/json-path.d.ts} +11 -3
  41. package/dist/types/src/internal/json-path.d.ts.map +1 -0
  42. package/dist/types/src/internal/resource.d.ts.map +1 -0
  43. package/dist/types/src/internal/url.d.ts.map +1 -0
  44. package/dist/types/src/json-path.test.d.ts +2 -0
  45. package/dist/types/src/json-path.test.d.ts.map +1 -0
  46. package/dist/types/src/testing.d.ts +5 -14
  47. package/dist/types/src/testing.d.ts.map +1 -1
  48. package/dist/types/src/types.d.ts +8 -0
  49. package/dist/types/src/types.d.ts.map +1 -0
  50. package/dist/types/tsconfig.tsbuildinfo +1 -1
  51. package/package.json +33 -21
  52. package/src/EffectEx.ts +18 -0
  53. package/src/Performance.ts +45 -0
  54. package/src/RuntimeProvider.ts +35 -0
  55. package/src/SchemaEx.ts +46 -0
  56. package/src/ast.test.ts +36 -9
  57. package/src/atom-kvs.ts +35 -0
  58. package/src/dynamic-runtime.test.ts +465 -0
  59. package/src/dynamic-runtime.ts +195 -0
  60. package/src/index.ts +12 -7
  61. package/src/{ast.ts → internal/ast.ts} +121 -91
  62. package/src/internal/async-task-tagging.ts +51 -0
  63. package/src/{errors.ts → internal/errors.ts} +72 -8
  64. package/src/{jsonPath.ts → internal/json-path.ts} +26 -3
  65. package/src/{resource.ts → internal/resource.ts} +2 -2
  66. package/src/interrupt.test.ts +3 -1
  67. package/src/{jsonPath.test.ts → json-path.test.ts} +55 -8
  68. package/src/layers.test.ts +4 -2
  69. package/src/resource.test.ts +1 -1
  70. package/src/sanity.test.ts +6 -4
  71. package/src/testing.ts +5 -29
  72. package/src/types.ts +11 -0
  73. package/src/url.test.ts +1 -1
  74. package/dist/types/src/ast.d.ts.map +0 -1
  75. package/dist/types/src/context.d.ts.map +0 -1
  76. package/dist/types/src/errors.d.ts.map +0 -1
  77. package/dist/types/src/jsonPath.d.ts.map +0 -1
  78. package/dist/types/src/jsonPath.test.d.ts +0 -2
  79. package/dist/types/src/jsonPath.test.d.ts.map +0 -1
  80. package/dist/types/src/resource.d.ts.map +0 -1
  81. package/dist/types/src/url.d.ts.map +0 -1
  82. /package/dist/types/src/{context.d.ts → internal/context.d.ts} +0 -0
  83. /package/dist/types/src/{resource.d.ts → internal/resource.d.ts} +0 -0
  84. /package/dist/types/src/{url.d.ts → internal/url.d.ts} +0 -0
  85. /package/src/{context.ts → internal/context.ts} +0 -0
  86. /package/src/{url.ts → internal/url.ts} +0 -0
@@ -10,7 +10,7 @@ import * as SchemaAST from 'effect/SchemaAST';
10
10
  import { invariant } from '@dxos/invariant';
11
11
  import { isNonNullable } from '@dxos/util';
12
12
 
13
- import { type JsonPath, type JsonProp } from './jsonPath';
13
+ import { type JsonPath, type JsonProp } from './json-path';
14
14
 
15
15
  //
16
16
  // Refs
@@ -19,75 +19,66 @@ import { type JsonPath, type JsonProp } from './jsonPath';
19
19
  // https://effect-ts.github.io/effect/schema/SchemaAST.ts.html
20
20
  //
21
21
 
22
- // TODO(wittjosiah): What is a "simple type"?
23
- export type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';
24
-
25
- const isTupleType = (node: SchemaAST.AST): boolean => {
26
- // NOTE: Arrays are represented as tuples with no elements and a rest part.
27
- return SchemaAST.isTupleType(node) && node.elements.length > 0;
28
- };
29
-
30
22
  /**
31
- * Get the base type; e.g., traverse through refinements.
23
+ * Unwraps and collects refinement filters.
32
24
  */
33
- export const getSimpleType = (node: SchemaAST.AST): SimpleType | undefined => {
34
- if (
35
- SchemaAST.isDeclaration(node) ||
36
- SchemaAST.isObjectKeyword(node) ||
37
- SchemaAST.isTypeLiteral(node) ||
38
- // TODO(wittjosiah): Tuples are actually arrays.
39
- isTupleType(node) ||
40
- isDiscriminatedUnion(node)
41
- ) {
42
- return 'object';
25
+ const reduceRefinements = (
26
+ type: SchemaAST.AST,
27
+ refinements: SchemaAST.Refinement['filter'][] = [],
28
+ ): { type: SchemaAST.AST; refinements: SchemaAST.Refinement['filter'][] } => {
29
+ if (SchemaAST.isRefinement(type)) {
30
+ const filter = type.filter;
31
+ const nextType = {
32
+ ...type.from,
33
+ annotations: { ...type.from.annotations, ...type.annotations },
34
+ } as SchemaAST.AST;
35
+ return reduceRefinements(nextType, [...refinements, filter]);
43
36
  }
44
37
 
45
- if (SchemaAST.isStringKeyword(node)) {
46
- return 'string';
47
- }
48
- if (SchemaAST.isNumberKeyword(node)) {
49
- return 'number';
50
- }
51
- if (SchemaAST.isBooleanKeyword(node)) {
52
- return 'boolean';
53
- }
54
-
55
- if (SchemaAST.isEnums(node)) {
56
- return 'enum';
57
- }
38
+ return { type, refinements };
39
+ };
58
40
 
59
- if (SchemaAST.isLiteral(node)) {
60
- return 'literal';
61
- }
41
+ /**
42
+ * Get the base type of a property.
43
+ *
44
+ * Unwraps refinements and optional unions.
45
+ */
46
+ export const getBaseType = (
47
+ prop: SchemaAST.PropertySignature | SchemaProperty,
48
+ ): { type: SchemaAST.AST; refinements: SchemaAST.Refinement['filter'][] } => {
49
+ const encoded = SchemaAST.encodedBoundAST(prop.type);
50
+ // Extract property ast from optional union.
51
+ const unwrapped = prop.isOptional && encoded._tag === 'Union' ? encoded.types[0] : encoded;
52
+ return reduceRefinements(unwrapped);
62
53
  };
63
54
 
64
- export const isSimpleType = (node: SchemaAST.AST): boolean => !!getSimpleType(node);
55
+ export type SchemaProperty = Pick<SchemaAST.PropertySignature, 'name' | 'type' | 'isOptional' | 'isReadonly'> & {
56
+ /** Can be used to validate the property to the spec of the initial AST. */
57
+ refinements: SchemaAST.Refinement['filter'][];
58
+ };
65
59
 
66
- export namespace SimpleType {
67
- /**
68
- * Returns the default empty value for a given SimpleType.
69
- * Used for initializing new array values etc.
70
- */
71
- export const getDefaultValue = (type: SimpleType): any => {
72
- switch (type) {
73
- case 'string': {
74
- return '';
75
- }
76
- case 'number': {
77
- return 0;
78
- }
79
- case 'boolean': {
80
- return false;
81
- }
82
- case 'object': {
83
- return {};
84
- }
85
- default: {
86
- throw new Error(`Unsupported type for default value: ${type}`);
87
- }
88
- }
89
- };
90
- }
60
+ /**
61
+ * Get the property types of an AST.
62
+ */
63
+ export const getProperties = (ast: SchemaAST.AST): SchemaProperty[] => {
64
+ const properties = SchemaAST.getPropertySignatures(ast);
65
+ return properties.map((prop) => {
66
+ const { type, refinements } = getBaseType(prop);
67
+ // Merge PropertySignature-level annotations (e.g., title, description set via .annotations())
68
+ // onto the unwrapped base type so downstream consumers see them.
69
+ const mergedType =
70
+ prop.annotations && Reflect.ownKeys(prop.annotations).length > 0
71
+ ? ({ ...type, annotations: { ...type.annotations, ...prop.annotations } } as SchemaAST.AST)
72
+ : type;
73
+ return {
74
+ type: mergedType,
75
+ refinements,
76
+ name: prop.name,
77
+ isOptional: prop.isOptional,
78
+ isReadonly: prop.isReadonly,
79
+ };
80
+ });
81
+ };
91
82
 
92
83
  //
93
84
  // Branded types
@@ -111,23 +102,14 @@ export type TestFn = (node: SchemaAST.AST, path: Path, depth: number) => VisitRe
111
102
 
112
103
  export type VisitorFn = (node: SchemaAST.AST, path: Path, depth: number) => void;
113
104
 
114
- const defaultTest: TestFn = isSimpleType;
115
-
116
105
  /**
117
106
  * Visit leaf nodes.
118
107
  * Refs:
119
108
  * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor
120
109
  * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test
121
110
  */
122
- export const visit: {
123
- (node: SchemaAST.AST, visitor: VisitorFn): void;
124
- (node: SchemaAST.AST, test: TestFn, visitor: VisitorFn): void;
125
- } = (node: SchemaAST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {
126
- if (!visitor) {
127
- visitNode(node, defaultTest, testOrVisitor);
128
- } else {
129
- visitNode(node, testOrVisitor as TestFn, visitor);
130
- }
111
+ export const visit = (node: SchemaAST.AST, testOrVisitor: TestFn | VisitorFn, visitor: VisitorFn): void => {
112
+ visitNode(node, testOrVisitor as TestFn, visitor);
131
113
  };
132
114
 
133
115
  const visitNode = (
@@ -282,10 +264,10 @@ export const findProperty = (
282
264
  //
283
265
 
284
266
  const defaultAnnotations: Record<string, SchemaAST.Annotated> = {
285
- ['ObjectKeyword' as const]: SchemaAST.objectKeyword,
286
- ['StringKeyword' as const]: SchemaAST.stringKeyword,
287
- ['NumberKeyword' as const]: SchemaAST.numberKeyword,
288
- ['BooleanKeyword' as const]: SchemaAST.booleanKeyword,
267
+ ObjectKeyword: SchemaAST.objectKeyword,
268
+ StringKeyword: SchemaAST.stringKeyword,
269
+ NumberKeyword: SchemaAST.numberKeyword,
270
+ BooleanKeyword: SchemaAST.booleanKeyword,
289
271
  };
290
272
 
291
273
  /**
@@ -344,10 +326,45 @@ export const isOption = (node: SchemaAST.AST): boolean => {
344
326
  /**
345
327
  * Determines if the node is a union of literal types.
346
328
  */
347
- export const isLiteralUnion = (node: SchemaAST.AST): boolean => {
329
+ export const isLiteralUnion = (node: SchemaAST.AST): node is SchemaAST.Union<SchemaAST.Literal> => {
348
330
  return SchemaAST.isUnion(node) && node.types.every(SchemaAST.isLiteral);
349
331
  };
350
332
 
333
+ /**
334
+ * Extracts the literal values from a schema that is a union of literals
335
+ * (e.g. `Schema.Literal('a', 'b')` or `Schema.Union(Schema.Literal('a'), Schema.Literal('b'))`).
336
+ * Returns an empty array if the schema is not a literal union.
337
+ */
338
+ export const getLiteralValues = <S extends Schema.Schema<any, any, any>>(
339
+ schema: S,
340
+ ): ReadonlyArray<Schema.Schema.Type<S>> => {
341
+ if (!isLiteralUnion(schema.ast)) {
342
+ return [];
343
+ }
344
+ return schema.ast.types.map((node) => node.literal as Schema.Schema.Type<S>);
345
+ };
346
+
347
+ /**
348
+ * Determines if the node is an array type.
349
+ */
350
+ export const isArrayType = (node: SchemaAST.AST): node is SchemaAST.TupleType => {
351
+ return SchemaAST.isTupleType(node) && node.elements.length === 0 && node.rest.length === 1;
352
+ };
353
+
354
+ /**
355
+ * Get the type of the array elements.
356
+ */
357
+ export const getArrayElementType = (node: SchemaAST.AST): SchemaAST.AST | undefined => {
358
+ return isArrayType(node) ? node.rest.at(0)?.type : undefined;
359
+ };
360
+
361
+ /**
362
+ * Determines if the node is a tuple type.
363
+ */
364
+ export const isTupleType = (node: SchemaAST.AST): boolean => {
365
+ return SchemaAST.isTupleType(node) && node.elements.length > 0;
366
+ };
367
+
351
368
  /**
352
369
  * Determines if the node is a discriminated union.
353
370
  */
@@ -427,6 +444,32 @@ export const getDiscriminatedType = (
427
444
  return schema.ast;
428
445
  };
429
446
 
447
+ /**
448
+ * If a property signature is optional (T | undefined), returns the inner non-undefined AST node.
449
+ * Otherwise returns the property signature unchanged, preserving its annotations.
450
+ */
451
+ export const unwrapOptional = (property: SchemaAST.PropertySignature): SchemaAST.PropertySignature | SchemaAST.AST => {
452
+ if (!property.isOptional || !SchemaAST.isUnion(property.type) || !isOption(property.type)) {
453
+ return property;
454
+ }
455
+
456
+ return property.type.types[0];
457
+ };
458
+
459
+ /**
460
+ * Determines if the node is a nested object type.
461
+ */
462
+ export const isNestedType = (node: SchemaAST.AST): boolean => {
463
+ return (
464
+ SchemaAST.isDeclaration(node) ||
465
+ SchemaAST.isObjectKeyword(node) ||
466
+ SchemaAST.isTypeLiteral(node) ||
467
+ // TODO(wittjosiah): Tuples are actually arrays.
468
+ isTupleType(node) ||
469
+ isDiscriminatedUnion(node)
470
+ );
471
+ };
472
+
430
473
  /**
431
474
  * Maps AST nodes.
432
475
  * The user is responsible for recursively calling {@link mapAst} on the SchemaAST.
@@ -475,19 +518,6 @@ export const mapAst = (
475
518
  }
476
519
  };
477
520
 
478
- /**
479
- * @returns true if AST is for Array(T) or optional(Array(T)).
480
- */
481
- export const isArrayType = (node: SchemaAST.AST): boolean => {
482
- return (
483
- SchemaAST.isTupleType(node) ||
484
- (SchemaAST.isUnion(node) &&
485
- node.types.some(isArrayType) &&
486
- node.types.some(SchemaAST.isUndefinedKeyword) &&
487
- node.types.length === 2)
488
- );
489
- };
490
-
491
521
  const getIndexSignatures = (ast: SchemaAST.AST): Array<SchemaAST.IndexSignature> => {
492
522
  const annotation = SchemaAST.getSurrogateAnnotation(ast);
493
523
  if (Option.isSome(annotation)) {
@@ -0,0 +1,51 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import { pipe } from 'effect/Function';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as Predicate from 'effect/Predicate';
10
+ import * as Tracer from 'effect/Tracer';
11
+
12
+ const runInTask = Symbol('runInTask');
13
+
14
+ /**
15
+ * Traces effect frames using console.createTask so that the proper stack-trace is visible in Chrome Devtools debugger.
16
+ */
17
+ export const asyncTaskTaggingLayer = () => {
18
+ if (Predicate.hasProperty(console, 'createTask') === false) {
19
+ return Layer.empty;
20
+ }
21
+
22
+ const makeTracer = Effect.gen(function* () {
23
+ const oldTracer = yield* Effect.tracer;
24
+ return Tracer.make({
25
+ span: (name, ...args) => {
26
+ const span = oldTracer.span(name, ...args);
27
+ const trace = (console as any).createTask(name);
28
+ (span as any)[runInTask] = (f: any) => trace.run(f);
29
+ return span;
30
+ },
31
+ context: (f, fiber) => {
32
+ const maybeParentSpan = Context.getOption(Tracer.ParentSpan)(fiber.currentContext);
33
+
34
+ if (maybeParentSpan._tag === 'None') {
35
+ return oldTracer.context(f, fiber);
36
+ }
37
+ const parentSpan = maybeParentSpan.value;
38
+ if (parentSpan._tag === 'ExternalSpan') {
39
+ return oldTracer.context(f, fiber);
40
+ }
41
+ const span = parentSpan;
42
+ if (runInTask in span && typeof span[runInTask] === 'function') {
43
+ return span[runInTask](() => oldTracer.context(f, fiber));
44
+ }
45
+
46
+ return oldTracer.context(f, fiber);
47
+ },
48
+ });
49
+ });
50
+ return pipe(makeTracer, Effect.map(Layer.setTracer), Layer.unwrapEffect);
51
+ };
@@ -8,10 +8,10 @@ import * as Effect from 'effect/Effect';
8
8
  import * as Exit from 'effect/Exit';
9
9
  import * as GlobalValue from 'effect/GlobalValue';
10
10
  import * as Option from 'effect/Option';
11
+ import * as Runtime from 'effect/Runtime';
11
12
  import type * as Tracer from 'effect/Tracer';
12
13
 
13
14
  const spanSymbol = Symbol.for('effect/SpanAnnotation');
14
- const originalSymbol = Symbol.for('effect/OriginalAnnotation');
15
15
  const spanToTrace = GlobalValue.globalValue('effect/Tracer/spanToTrace', () => new WeakMap());
16
16
  const locationRegex = /\((.*)\)/g;
17
17
 
@@ -21,12 +21,19 @@ const locationRegex = /\((.*)\)/g;
21
21
  * Unwraps error proxy.
22
22
  */
23
23
  const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
24
+ if (typeof error !== 'object' || error === null) {
25
+ return error;
26
+ }
27
+
24
28
  const span = error[spanSymbol];
25
29
 
26
30
  const lines = typeof error.stack === 'string' ? error.stack.split('\n') : [];
27
31
  const out = [];
28
32
 
29
- let atStack = false;
33
+ // Very hacky way to remove effect runtime internal stack frames.
34
+ let atStack = false,
35
+ inCore = false,
36
+ passedScheduler = false;
30
37
  for (let i = 0; i < lines.length; i++) {
31
38
  if (!atStack && !lines[i].startsWith(' at ')) {
32
39
  out.push(lines[i]);
@@ -44,6 +51,26 @@ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
44
51
  if (lines[i].includes('effect_internal_function')) {
45
52
  break;
46
53
  }
54
+
55
+ const filename = lines[i].match(/\/([a-zA-Z0-9_\-.]+):\d+:\d+\)$/)?.[1];
56
+
57
+ if (!inCore && ['core-effect.ts'].includes(filename)) {
58
+ inCore = true;
59
+ }
60
+
61
+ if (inCore && !passedScheduler && ['Scheduler.ts'].includes(filename)) {
62
+ passedScheduler = true;
63
+ continue;
64
+ }
65
+
66
+ if (passedScheduler && !['Scheduler.ts'].includes(filename)) {
67
+ inCore = false;
68
+ }
69
+
70
+ if (inCore) {
71
+ continue;
72
+ }
73
+
47
74
  out.push(
48
75
  lines[i]
49
76
  .replace(/at .*effect_instruction_i.*\((.*)\)/, 'at $1')
@@ -82,9 +109,7 @@ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
82
109
 
83
110
  out.push(...appendStacks);
84
111
 
85
- if (error[originalSymbol]) {
86
- error = error[originalSymbol];
87
- }
112
+ error = Cause.originalError(error);
88
113
  if (error.cause) {
89
114
  error.cause = prettyErrorStack(error.cause);
90
115
  }
@@ -118,9 +143,10 @@ export const causeToError = (cause: Cause.Cause<any>): Error => {
118
143
  const errors = [...Chunk.toArray(Cause.failures(cause)), ...Chunk.toArray(Cause.defects(cause))];
119
144
 
120
145
  const getStackFrames = (): string[] => {
121
- const o: { stack: string } = {} as any;
122
- Error.captureStackTrace(o, getStackFrames);
123
- return o.stack.split('\n').slice(1);
146
+ // Bun requies the target object for `captureStackTrace` to be an Error.
147
+ const err = new Error();
148
+ Error.captureStackTrace(err, causeToError);
149
+ return err.stack!.split('\n').slice(1);
124
150
  };
125
151
 
126
152
  const stackFrames = getStackFrames();
@@ -174,6 +200,44 @@ export const runAndForwardErrors = async <A, E>(
174
200
  return unwrapExit(exit);
175
201
  };
176
202
 
203
+ /** Alias for {@link runAndForwardErrors} — preferred name when accessed via `EffectEx.runPromise`. */
204
+ export const runPromise = runAndForwardErrors;
205
+
206
+ /**
207
+ * Runs the embedded effect asynchronously and throws any failures and defects as errors.
208
+ */
209
+ export const runInRuntime: {
210
+ <R>(
211
+ runtime: Runtime.Runtime<R>,
212
+ ): <A, E>(effect: Effect.Effect<A, E, R>, options?: { signal?: AbortSignal } | undefined) => Promise<A>;
213
+ <R, A, E>(
214
+ runtime: Runtime.Runtime<R>,
215
+ effect: Effect.Effect<A, E, R>,
216
+ options?: { signal?: AbortSignal } | undefined,
217
+ ): Promise<A>;
218
+ } = (...args: any[]): any => {
219
+ if (args.length === 1) {
220
+ const [runtime] = args as [Runtime.Runtime<any>];
221
+ return async (
222
+ effect: Effect.Effect<any, any, any>,
223
+ options?: { signal?: AbortSignal } | undefined,
224
+ ): Promise<any> => {
225
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
226
+ return unwrapExit(exit);
227
+ };
228
+ } else {
229
+ const [runtime, effect, options] = args as [
230
+ Runtime.Runtime<any>,
231
+ Effect.Effect<any, any, any>,
232
+ { signal?: AbortSignal } | undefined,
233
+ ];
234
+ return (async () => {
235
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
236
+ return unwrapExit(exit);
237
+ })();
238
+ }
239
+ };
240
+
177
241
  /**
178
242
  * Like `Effect.promise` but also caputes spans for defects.
179
243
  * Workaround for: https://github.com/Effect-TS/effect/issues/5436
@@ -7,11 +7,15 @@ import * as Schema from 'effect/Schema';
7
7
  import { JSONPath } from 'jsonpath-plus';
8
8
 
9
9
  import { invariant } from '@dxos/invariant';
10
+ import { getDeep, setDeep } from '@dxos/util';
10
11
 
11
12
  export type JsonProp = string & { __JsonPath: true; __JsonProp: true };
12
13
  export type JsonPath = string & { __JsonPath: true };
13
14
 
15
+ // TODO(burdon): Start with "$."?
16
+
14
17
  const PATH_REGEX = /^($|[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*|\[\d+\](?:\.)?)*$)/;
18
+
15
19
  const PROP_REGEX = /^\w+$/;
16
20
 
17
21
  /**
@@ -51,7 +55,7 @@ export const isJsonPath = (value: unknown): value is JsonPath => {
51
55
  * @param path Array of string or number segments
52
56
  * @returns Valid JsonPath or undefined if invalid
53
57
  */
54
- export const createJsonPath = (path: (string | number)[]): JsonPath => {
58
+ export const createJsonPath = (path: readonly (string | number)[]): JsonPath => {
55
59
  const candidatePath = path
56
60
  .map((p, i) => {
57
61
  if (typeof p === 'number') {
@@ -81,7 +85,7 @@ export const fromEffectValidationPath = (effectPath: string): JsonPath => {
81
85
  * Splits a JsonPath into its constituent parts.
82
86
  * Handles property access and array indexing.
83
87
  */
84
- export const splitJsonPath = (path: JsonPath): string[] => {
88
+ export const splitJsonPath = (path: JsonPath): (string | number)[] => {
85
89
  if (!isJsonPath(path)) {
86
90
  return [];
87
91
  }
@@ -89,14 +93,33 @@ export const splitJsonPath = (path: JsonPath): string[] => {
89
93
  return (
90
94
  path
91
95
  .match(/[a-zA-Z_$][\w$]*|\[\d+\]/g)
92
- ?.map((part) => (part.startsWith('[') ? part.replace(/[[\]]/g, '') : part)) ?? []
96
+ ?.map((part) => part.replace(/[[\]]/g, ''))
97
+ .map((part) => {
98
+ const parsed = Number.parseInt(part, 10);
99
+ return Number.isNaN(parsed) ? part : parsed;
100
+ }) ?? []
93
101
  );
94
102
  };
95
103
 
96
104
  /**
97
105
  * Applies a JsonPath to an object.
98
106
  */
107
+ // TODO(burdon): Reconcile with getValue.
99
108
  export const getField = (object: any, path: JsonPath): any => {
100
109
  // By default, JSONPath returns an array of results.
101
110
  return JSONPath({ path, json: object })[0];
102
111
  };
112
+
113
+ /**
114
+ * Get value from object using JsonPath.
115
+ */
116
+ export const getValue = <T extends object>(obj: T, path: JsonPath): any => {
117
+ return getDeep(obj, splitJsonPath(path));
118
+ };
119
+
120
+ /**
121
+ * Set value on object using JsonPath.
122
+ */
123
+ export const setValue = <T extends object>(obj: T, path: JsonPath, value: any): T => {
124
+ return setDeep(obj, splitJsonPath(path), value);
125
+ };
@@ -17,14 +17,14 @@ export const acquireReleaseResource = <T extends Lifecycle>(
17
17
  Effect.gen(function* () {
18
18
  const resource = getResource();
19
19
  yield* Effect.promise(async () => {
20
- resource.open?.();
20
+ await resource.open?.();
21
21
  return undefined;
22
22
  });
23
23
  return resource;
24
24
  }),
25
25
  (resource) =>
26
26
  Effect.promise(async () => {
27
- resource.close?.();
27
+ await resource.close?.();
28
28
  return undefined;
29
29
  }),
30
30
  );
@@ -7,6 +7,8 @@ import * as Cause from 'effect/Cause';
7
7
  import * as Effect from 'effect/Effect';
8
8
  import * as Fiber from 'effect/Fiber';
9
9
 
10
+ import { runAndForwardErrors } from './internal/errors';
11
+
10
12
  const doWork = Effect.fn('doWork')(function* () {
11
13
  yield* Effect.sleep('1 minute');
12
14
  return 'work done';
@@ -18,7 +20,7 @@ it.effect.skip(
18
20
  function* (_) {
19
21
  const resultFiber = yield* doWork().pipe(Effect.fork);
20
22
  setTimeout(() => {
21
- void Effect.runPromise(Fiber.interrupt(resultFiber));
23
+ void runAndForwardErrors(Fiber.interrupt(resultFiber));
22
24
  }, 2_000);
23
25
 
24
26
  const result = yield* resultFiber;
@@ -4,7 +4,15 @@
4
4
 
5
5
  import { describe, expect, test } from 'vitest';
6
6
 
7
- import { type JsonPath, createJsonPath, getField, isJsonPath, splitJsonPath } from './jsonPath';
7
+ import {
8
+ type JsonPath,
9
+ createJsonPath,
10
+ getField,
11
+ getValue,
12
+ isJsonPath,
13
+ setValue,
14
+ splitJsonPath,
15
+ } from './internal/json-path';
8
16
 
9
17
  describe('createJsonPath', () => {
10
18
  test('supported path subset', () => {
@@ -32,9 +40,9 @@ describe('createJsonPath', () => {
32
40
 
33
41
  test('path splitting', () => {
34
42
  const cases = [
35
- ['foo.bar[0].baz', ['foo', 'bar', '0', 'baz']],
36
- ['users[1].name', ['users', '1', 'name']],
37
- ['data[0][1]', ['data', '0', '1']],
43
+ ['foo.bar[0].baz', ['foo', 'bar', 0, 'baz']],
44
+ ['users[1].name', ['users', 1, 'name']],
45
+ ['data[0][1]', ['data', 0, 1]],
38
46
  ['simple.path', ['simple', 'path']],
39
47
  ['root', ['root']],
40
48
  ] as const;
@@ -47,15 +55,15 @@ describe('createJsonPath', () => {
47
55
  test('path splitting - extended cases', () => {
48
56
  const cases = [
49
57
  // Multiple consecutive array indices.
50
- ['matrix[0][1][2]', ['matrix', '0', '1', '2']],
58
+ ['matrix[0][1][2]', ['matrix', 0, 1, 2]],
51
59
  // Properties with underscores and $.
52
60
  ['$_foo.bar_baz', ['$_foo', 'bar_baz']],
53
61
  // Deep nesting.
54
- ['very.deep.nested[0].property.path[5]', ['very', 'deep', 'nested', '0', 'property', 'path', '5']],
62
+ ['very.deep.nested[0].property.path[5]', ['very', 'deep', 'nested', 0, 'property', 'path', 5]],
55
63
  // Single character properties.
56
- ['a[0].b.c', ['a', '0', 'b', 'c']],
64
+ ['a[0].b.c', ['a', 0, 'b', 'c']],
57
65
  // Properties containing numbers.
58
- ['prop123.item456[7]', ['prop123', 'item456', '7']],
66
+ ['prop123.item456[7]', ['prop123', 'item456', 7]],
59
67
  ] as const;
60
68
 
61
69
  cases.forEach(([input, expected]) => {
@@ -99,3 +107,42 @@ describe('createJsonPath', () => {
99
107
  expect(getField({ a: 'foo' }, 'a' as JsonPath)).toBe('foo');
100
108
  });
101
109
  });
110
+
111
+ describe('Types', () => {
112
+ test('checks sanity', async ({ expect }) => {
113
+ const obj = {};
114
+ expect(obj).to.exist;
115
+ });
116
+ });
117
+
118
+ describe('get/set deep', () => {
119
+ test('get/set operations', ({ expect }) => {
120
+ const obj = {
121
+ name: 'test',
122
+ items: ['a', 'b', 'c'],
123
+ nested: {
124
+ prop: 'value',
125
+ arr: [1, 2, 3],
126
+ },
127
+ };
128
+
129
+ // Basic property access.
130
+ expect(getValue(obj, 'name' as JsonPath)).toBe('test');
131
+
132
+ // Array index access.
133
+ expect(getValue(obj, 'items[1]' as JsonPath)).toBe('b');
134
+
135
+ // Nested property access.
136
+ expect(getValue(obj, 'nested.prop' as JsonPath)).toBe('value');
137
+
138
+ // Nested array access.
139
+ expect(getValue(obj, 'nested.arr[2]' as JsonPath)).toBe(3);
140
+
141
+ // Setting values.
142
+ const updated1 = setValue(obj, 'items[1]' as JsonPath, 'x');
143
+ expect(updated1.items[1]).toBe('x');
144
+
145
+ const updated2 = setValue(obj, 'nested.arr[0]' as JsonPath, 99);
146
+ expect(updated2.nested.arr[0]).toBe(99);
147
+ });
148
+ });
@@ -10,6 +10,8 @@ import * as Layer from 'effect/Layer';
10
10
  import * as ManagedRuntime from 'effect/ManagedRuntime';
11
11
  import { test } from 'vitest';
12
12
 
13
+ import { runAndForwardErrors } from './internal/errors';
14
+
13
15
  class ClientConfig extends Context.Tag('ClientConfig')<ClientConfig, { endpoint: string }>() {}
14
16
 
15
17
  class Client extends Context.Tag('Client')<Client, { call: () => Effect.Effect<void> }>() {
@@ -76,7 +78,7 @@ class ClientPlugin {
76
78
  async run() {
77
79
  const layer = Layer.provide(Client.layer, this._serverPlugin.clientConfigLayer);
78
80
 
79
- await Effect.runPromise(
81
+ await runAndForwardErrors(
80
82
  Effect.gen(function* () {
81
83
  const client = yield* Client;
82
84
  yield* client.call();
@@ -89,7 +91,7 @@ test.skip('plugins', async () => {
89
91
  const serverPlugin = new ServerPlugin();
90
92
  console.log('ServerPlugin created');
91
93
 
92
- await Effect.runPromise(Effect.sleep(Duration.millis(500)));
94
+ await runAndForwardErrors(Effect.sleep(Duration.millis(500)));
93
95
  console.log('wake up');
94
96
 
95
97
  {