@opencode/util 0.0.0-dev-1361 → 0.0.0-dev-1362

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.
@@ -6,8 +6,8 @@ declare const NodeTypeId: unique symbol;
6
6
  declare const ReplacementTypeId: unique symbol;
7
7
  export type Tag<Name extends string = string> = Name & Brand.Brand<"LayerNode.Tag">;
8
8
  export type Graph<A, E = never, T extends Tag | undefined = Tag | undefined> = GraphValue<A, E, T>;
9
- export type Node<A, E = never, T extends Tag | undefined = undefined, Mockable extends boolean = true> = NodeValue<A, E, T, Mockable>;
10
- export type Provider<A, E = never, T extends Tag | undefined = undefined, Mockable extends boolean = true> = ProviderNode<A, E, T, Mockable>;
9
+ export type Node<A, E = never, T extends Tag | undefined = undefined, HasService extends boolean = true> = NodeValue<A, E, T, HasService>;
10
+ export type Provider<A, E = never, T extends Tag | undefined = undefined, HasService extends boolean = true> = ProviderNode<A, E, T, HasService>;
11
11
  export type Replacement = ReplacementValue;
12
12
  export type Replacements = readonly Replacement[];
13
13
  type AnyGraph = Graph<never, unknown>;
@@ -25,8 +25,9 @@ type LayerOutput<Item extends Layer.Any, A = Layer.Success<Item>> = A extends un
25
25
  type ListOutput<Items extends readonly AnyGraph[], A = never> = [Items] extends [
26
26
  readonly [infer Head extends AnyGraph, ...infer Tail extends readonly AnyGraph[]]
27
27
  ] ? ListOutput<Tail, A | Output<Head>> : A;
28
- type MockShape<A, All = A> = A extends unknown ? [All] extends [A] ? [A] extends [Context.ServiceClass.Shape<string, infer S>] ? [S] extends [object] ? S : never : [A] extends [object] ? A : never : never : never;
29
- type IsMockable<Service> = [Service] extends [never] ? false : true;
28
+ type IsSingle<T, All = T> = 0 extends 1 & T ? false : [T] extends [never] ? false : T extends unknown ? [All] extends [T] ? true : false : false;
29
+ type MockShape<A> = [IsSingle<A>] extends [true] ? [A] extends [Context.ServiceClass.Shape<string, infer S>] ? [S] extends [object] ? S : never : [A] extends [object] ? A : never : never;
30
+ type HasServiceKey<Service> = [Service] extends [never] ? false : true;
30
31
  type Definition = {
31
32
  readonly kind: "group";
32
33
  readonly name: string;
@@ -54,21 +55,23 @@ declare class GraphValue<in A, out E, out T extends Tag | undefined> {
54
55
  constructor(definition: Definition);
55
56
  get name(): string;
56
57
  }
57
- declare class NodeValue<in out A, in out E, in out T extends Tag | undefined, Mockable extends boolean = true> extends GraphValue<A, E, T> {
58
+ declare class NodeValue<in out A, in out E, in out T extends Tag | undefined, HasService extends boolean = true> extends GraphValue<A, E, T> {
58
59
  readonly tag: T;
59
60
  readonly [NodeTypeId]: (_: [A, E, T]) => [A, E, T];
60
- private readonly mockable;
61
+ private readonly hasService;
61
62
  constructor(definition: Exclude<Definition, {
62
63
  kind: "group";
63
64
  }>, tag: T);
65
+ /** The service this node was declared for. Only nodes declared with a `service` have one. */
66
+ get service(): HasService extends true ? Context.Key<A, unknown> : undefined;
64
67
  /** Replace this declaration, including every dependency on it, without acquiring its old wiring. */
65
68
  replace<const Target extends AnyNode | Layer.Any>(this: Node<A, E, T, boolean>, replacement: Target & CheckReplacement<A, E, T, Target>): Replacement;
66
69
  /** Replace this single-service declaration with a partial mock backed by `Layer.mock`. */
67
- mock(this: [Mockable] extends [true] ? ([MockShape<A>] extends [never] ? never : Node<A, E, T, true>) : never, implementation: Layer.PartialEffectful<MockShape<A>>): Replacement;
70
+ mock(this: [HasService] extends [true] ? ([MockShape<A>] extends [never] ? never : Node<A, E, T, true>) : never, implementation: Layer.PartialEffectful<MockShape<A>>): Replacement;
68
71
  }
69
- declare class ProviderNode<in out A, in out E, in out T extends Tag | undefined, Mockable extends boolean = true> extends NodeValue<A, E, T, Mockable> {
72
+ declare class ProviderNode<in out A, in out E, in out T extends Tag | undefined, HasService extends boolean = true> extends NodeValue<A, E, T, HasService> {
70
73
  /** Decorate the implementation while preserving its dependency wiring and service contract. */
71
- mapLayer(this: Provider<A, E, T, Mockable>, f: <R>(layer: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>): Provider<A, E, T, Mockable>;
74
+ mapLayer(this: Provider<A, E, T, HasService>, f: <R>(layer: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>): Provider<A, E, T, HasService>;
72
75
  }
73
76
  declare class ReplacementValue {
74
77
  private readonly checked;
@@ -94,8 +97,16 @@ type CheckDependencies<Implementation extends Layer.Any, Items extends GraphList
94
97
  ] extends [never] ? unknown : {
95
98
  readonly "Missing dependencies": Exclude<Layer.Services<Implementation>, ListOutput<Items>>;
96
99
  };
97
- type CheckService<Implementation extends Layer.Any, Service> = [Service] extends [never] ? unknown : [Exclude<Context.Service.Identifier<Service>, LayerOutput<Implementation>>] extends [never] ? unknown : {
98
- readonly "Service must be provided by layer": Context.Service.Identifier<Service>;
100
+ type CheckService<Implementation extends Layer.Any, Service, Id = Context.Service.Identifier<Service>> = [
101
+ Service
102
+ ] extends [never] ? unknown : [Id] extends [never] ? [LayerOutput<Implementation>] extends [never] ? unknown : {
103
+ readonly "Extra layer outputs require a named node": LayerOutput<Implementation>;
104
+ } : [IsSingle<Id>] extends [true] ? [Exclude<Id, LayerOutput<Implementation>>] extends [never] ? [Exclude<LayerOutput<Implementation>, Id>] extends [never] ? unknown : {
105
+ readonly "Extra layer outputs require a named node": Exclude<LayerOutput<Implementation>, Id>;
106
+ } : {
107
+ readonly "Service must be provided by layer": Id;
108
+ } : {
109
+ readonly "Service must be a single service key": Service;
99
110
  };
100
111
  type Identity<Service extends Context.Service.Any> = {
101
112
  readonly service: Service;
@@ -129,12 +140,14 @@ export interface Tags<Config extends TagConfig> {
129
140
  };
130
141
  readonly make: <Name extends TagNames<Config>>(name: Name) => TagMaker<Config, Name>;
131
142
  }
132
- export type TagMaker<Config extends TagConfig, Name extends TagNames<Config>> = <const Implementation extends Layer.Any, const Items extends GraphList, const Service extends Context.Service.Any = never>(input: BaseInput<Implementation, Items, Service> & CheckTags<Items, Name | Config[Name][number]>) => Provider<LayerOutput<Implementation>, Layer.Error<Implementation> | GraphError<Items[number]>, Tag<Name>, IsMockable<Service>>;
143
+ export type TagMaker<Config extends TagConfig, Name extends TagNames<Config>> = <const Implementation extends Layer.Any, const Items extends GraphList, const Service extends Context.Service.Any = never>(input: BaseInput<Implementation, Items, Service> & CheckTags<Items, Name | Config[Name][number]>) => Provider<LayerOutput<Implementation>, Layer.Error<Implementation> | GraphError<Items[number]>, Tag<Name>, HasServiceKey<Service>>;
133
144
  export declare function tags<const Config extends {
134
145
  readonly [Name in keyof Config]: readonly (keyof Config & string)[];
135
146
  }>(config: Config): Tags<Config>;
136
- export declare function make<const Implementation extends Layer.Any, const Items extends GraphList, const T extends Tag | undefined = undefined, const Service extends Context.Service.Any = never>(input: BaseInput<Implementation, Items, Service> & TagInput<T>): Provider<LayerOutput<Implementation>, Layer.Error<Implementation> | GraphError<Items[number]>, T, IsMockable<Service>>;
137
- export declare function unbound<R, Shape, const T extends Tag>(service: Context.Key<R, Shape>, tag: T): Node<R, never, T>;
147
+ export declare function make<const Implementation extends Layer.Any, const Items extends GraphList, const T extends Tag | undefined = undefined, const Service extends Context.Service.Any = never>(input: BaseInput<Implementation, Items, Service> & TagInput<T>): Provider<LayerOutput<Implementation>, Layer.Error<Implementation> | GraphError<Items[number]>, T, HasServiceKey<Service>>;
148
+ export declare function unbound<R, Shape, const T extends Tag>(service: Context.Key<R, Shape> & ([IsSingle<NoInfer<R>>] extends [true] ? unknown : {
149
+ readonly "Service must be a single service key": NoInfer<R>;
150
+ }), tag: T): Node<R, never, T>;
138
151
  /** Ordered, associative composition. Only these roots' outputs are exposed; their dependencies remain private. */
139
152
  export declare function group<const Items extends readonly AnyGraph[]>(dependencies: Items): Graph<ListOutput<Items>, GraphError<Items[number]>, GraphTag<Items[number]>>;
140
153
  export interface CompileOptions {
@@ -142,5 +155,24 @@ export interface CompileOptions {
142
155
  /** Share subgraphs rooted at this tag; give the remaining wiring a fresh map for each build. */
143
156
  readonly shared?: Tag;
144
157
  }
158
+ export interface Host<T extends Tag = Tag> {
159
+ readonly tag: T;
160
+ /** What the host built for the `tag` nodes its children reach (see `tagged`). */
161
+ readonly context: Context.Context<never>;
162
+ /** The host's replacements: its `tag` ones are already built into `context`, the rest apply to children too. */
163
+ readonly replacements?: Replacements;
164
+ }
165
+ export interface ChildOptions {
166
+ readonly host: Host;
167
+ /** This child's own replacements, applied after `host.replacements`. They cannot target `host.tag` nodes. */
168
+ readonly replacements?: Replacements;
169
+ }
170
+ /** Every `tag` node `root` reaches, after `replacements`, including transitive `tag` dependencies. */
171
+ export declare function tagged(root: Graph<never, unknown>, tag: Tag, replacements?: Replacements): Graph<never, unknown, Tag<string> | undefined>[];
145
172
  /** Resolve the final overrides before validating or acquiring anything. Effect owns acquisition and finalization. */
146
173
  export declare function compile<A, E>(root: Graph<A, E>, options?: CompileOptions): Layer.Layer<A, E>;
174
+ /**
175
+ * Compile a graph that stands on a host: every `host.tag` node reads its service from `host.context` instead of
176
+ * being built, so children never acquire, retain, or release the host's services. The rest is fresh for each build.
177
+ */
178
+ export declare function compileChild<A, E>(root: Graph<A, E>, options: ChildOptions): Layer.Layer<A, E>;
@@ -21,6 +21,10 @@ class NodeValue extends GraphValue {
21
21
  super(definition);
22
22
  this.tag = tag;
23
23
  }
24
+ /** The service this node was declared for. Only nodes declared with a `service` have one. */
25
+ get service() {
26
+ return this[GraphTypeId].service;
27
+ }
24
28
  /** Replace this declaration, including every dependency on it, without acquiring its old wiring. */
25
29
  replace(replacement) {
26
30
  if (replacement instanceof NodeValue) {
@@ -34,7 +38,7 @@ class NodeValue extends GraphValue {
34
38
  }
35
39
  /** Replace this single-service declaration with a partial mock backed by `Layer.mock`. */
36
40
  mock(implementation) {
37
- const service = this[GraphTypeId].service;
41
+ const service = this.service;
38
42
  if (!service)
39
43
  throw new Error(`Cannot mock layer node without a service: ${this.name}`);
40
44
  return new ReplacementValue(this, makeProvider({
@@ -87,13 +91,51 @@ export function unbound(service, tag) {
87
91
  export function group(dependencies) {
88
92
  return new GraphValue({ kind: "group", name: "group", dependencies: [...dependencies] });
89
93
  }
94
+ /** Every `tag` node `root` reaches, after `replacements`, including transitive `tag` dependencies. */
95
+ export function tagged(root, tag, replacements = []) {
96
+ const targets = replacementTargets(replacements);
97
+ const seen = new Set();
98
+ const found = [];
99
+ const visit = (graph) => {
100
+ if (seen.has(graph))
101
+ return;
102
+ seen.add(graph);
103
+ const replacement = targets.get(graph);
104
+ if (replacement && replacement !== graph)
105
+ return visit(replacement);
106
+ if (graph instanceof NodeValue && graph.tag === tag)
107
+ found.push(graph);
108
+ const definition = graph[GraphTypeId];
109
+ if (definition.kind !== "unbound")
110
+ definition.dependencies.forEach(visit);
111
+ };
112
+ visit(root);
113
+ return found;
114
+ }
90
115
  /** Resolve the final overrides before validating or acquiring anything. Effect owns acquisition and finalization. */
91
116
  export function compile(root, options = {}) {
92
- const shared = options.shared;
93
- const replacements = new Map(options.replacements?.map((item) => {
117
+ return compileGraph(root, options.replacements ?? [], options.shared);
118
+ }
119
+ /**
120
+ * Compile a graph that stands on a host: every `host.tag` node reads its service from `host.context` instead of
121
+ * being built, so children never acquire, retain, or release the host's services. The rest is fresh for each build.
122
+ */
123
+ export function compileChild(root, options) {
124
+ const own = options.replacements ?? [];
125
+ const rejected = own.find((item) => item[ReplacementTypeId].source.tag === options.host.tag);
126
+ if (rejected) {
127
+ throw new Error(`Cannot replace ${rejected[ReplacementTypeId].source.name} in a child graph: its host builds ${options.host.tag} nodes`);
128
+ }
129
+ return compileGraph(root, [...(options.host.replacements ?? []), ...own], undefined, options.host);
130
+ }
131
+ function replacementTargets(replacements) {
132
+ return new Map(replacements.map((item) => {
94
133
  const replacement = item[ReplacementTypeId];
95
134
  return [replacement.source, replacement.target];
96
135
  }));
136
+ }
137
+ function compileGraph(root, list, shared, host) {
138
+ const replacements = replacementTargets(list);
97
139
  const makeDomain = (isShared) => ({
98
140
  shared: isShared,
99
141
  cache: new Map(),
@@ -102,6 +144,9 @@ export function compile(root, options = {}) {
102
144
  const domains = { shared: makeDomain(true), local: makeDomain(false) };
103
145
  const stack = [];
104
146
  const resolveDefinition = (graph, domain) => {
147
+ // Host nodes keep their tag through any replacement, so the host's choice is already in its context.
148
+ if (host && graph instanceof NodeValue && graph.tag === host.tag)
149
+ return [borrow(graph, host.context)];
105
150
  const replacement = replacements.get(graph);
106
151
  if (replacement && replacement !== graph)
107
152
  return resolve(replacement, domain);
@@ -147,10 +192,12 @@ export function compile(root, options = {}) {
147
192
  };
148
193
  const roots = resolve(root);
149
194
  return Layer.fromBuild((memoMap, scope) => {
150
- const local = shared === undefined ? memoMap : Layer.makeMemoMapUnsafe();
195
+ const local = shared === undefined && host === undefined ? memoMap : Layer.makeMemoMapUnsafe();
151
196
  const ambient = Layer.succeed(Layer.CurrentMemoMap, memoMap);
152
197
  const layers = new Map();
153
198
  const build = (node) => {
199
+ if (node.borrowed)
200
+ return node.implementation;
154
201
  const cached = layers.get(node);
155
202
  if (cached)
156
203
  return cached;
@@ -164,6 +211,21 @@ export function compile(root, options = {}) {
164
211
  return buildContext(roots.map(build).reduce((result, layer) => layer.pipe(Layer.provideMerge(result)), Layer.empty), memoMap, scope);
165
212
  });
166
213
  }
214
+ function borrow(node, context) {
215
+ const service = node[GraphTypeId].service;
216
+ const value = service && Context.getOrUndefined(context, service);
217
+ if (service && value === undefined) {
218
+ throw new Error(`Host context is missing ${node.name}; build it on the host before its children`);
219
+ }
220
+ return {
221
+ name: node.name,
222
+ // Side-effect-only host nodes (`service === undefined`) already ran on the host and expose no service output.
223
+ implementation: service ? Layer.succeedContext(Context.make(service, value)) : Layer.empty,
224
+ dependencies: [],
225
+ shared: false,
226
+ borrowed: true,
227
+ };
228
+ }
167
229
  // The node's scope releases sequentially in reverse order, so a finalizer added before the build runs last and one
168
230
  // added after it runs first: together they bracket the release of everything this node acquired. The build must
169
231
  // not start before the first finalizer is added; Layer builds fork their scopes as soon as they are called.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/util",
4
- "version": "0.0.0-dev-1361",
4
+ "version": "0.0.0-dev-1362",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {