@gjermundgaraba/effect-actions 0.35.0 → 0.37.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 (48) hide show
  1. package/README.md +7 -7
  2. package/dist/Action.d.mts +2 -2
  3. package/dist/Action.mjs +1 -1
  4. package/dist/ActionEntity.d.mts +162 -75
  5. package/dist/ActionEntity.mjs +74 -55
  6. package/dist/ActionHttp.d.mts +7 -4
  7. package/dist/ActionRpc.d.mts +69 -17
  8. package/dist/ActionRpc.mjs +29 -11
  9. package/dist/Event.d.mts +62 -8
  10. package/dist/Event.mjs +49 -2
  11. package/dist/RequestPolicy.d.mts +3 -9
  12. package/dist/RequestPolicy.mjs +18 -6
  13. package/dist/authentication/provider.d.mts +0 -22
  14. package/dist/authentication/refusal.mjs +0 -4
  15. package/dist/contract/authorizer.d.mts +0 -4
  16. package/dist/contract/call.mjs +0 -4
  17. package/dist/contract/caller.mjs +0 -1
  18. package/dist/contract/declared.d.mts +0 -1
  19. package/dist/contract/feed.d.mts +0 -3
  20. package/dist/contract/feed.mjs +41 -24
  21. package/dist/contract/hub.mjs +0 -10
  22. package/dist/contract/implementation.d.mts +4 -27
  23. package/dist/contract/implementation.mjs +0 -9
  24. package/dist/contract/progress.d.mts +0 -1
  25. package/dist/contract/serving.mjs +15 -9
  26. package/dist/contract/subscribe.mjs +0 -1
  27. package/dist/contract/wake.d.mts +14 -0
  28. package/dist/contract/wake.mjs +4 -3
  29. package/dist/contract/webhooks.mjs +0 -13
  30. package/dist/entity/wakes.mjs +29 -22
  31. package/dist/http/client.mjs +8 -2
  32. package/dist/http/streamed.d.mts +6 -5
  33. package/dist/http/streamed.mjs +17 -3
  34. package/dist/rpc/erased.d.mts +0 -11
  35. package/dist/rpc/erased.mjs +7 -8
  36. package/dist/rpc/watch.mjs +4 -2
  37. package/docs/ActionEntity-failures.md +0 -1
  38. package/docs/ActionEntity.md +17 -9
  39. package/docs/ActionHttp.md +1 -1
  40. package/docs/ActionRpc.md +21 -1
  41. package/docs/Authentication-failures.md +1 -1
  42. package/docs/Event.md +3 -1
  43. package/docs/setup.md +2 -2
  44. package/examples/kitchen-sink/src/browser.ts +9 -21
  45. package/examples/shopping-carts/README.md +1 -1
  46. package/examples/shopping-carts/src/entities.ts +4 -2
  47. package/package.json +12 -12
  48. package/examples/shopping-carts/src/Rpc.ts +0 -6
package/dist/Event.mjs CHANGED
@@ -5,7 +5,7 @@ import { EventImplementation, sourcesOf } from "./contract/feed.mjs";
5
5
  import { assertEventName, assertOnce } from "./contract/names.mjs";
6
6
  import { Events, layerMemory } from "./contract/hub.mjs";
7
7
  import { Gap } from "./contract/occurrence.mjs";
8
- import { Array as Array$1, Data, Effect, Match, Predicate, Schema } from "effect";
8
+ import { Array as Array$1, Data, Effect, Match, Option, Predicate, Schema } from "effect";
9
9
  // src/contract/Event.ts
10
10
  const TypeId = "~@gjermundgaraba/effect-actions/Event";
11
11
  /** Whether `u` is an event type `make` defined: a binding's list tells events from actions by it. */
@@ -24,6 +24,53 @@ function make(name, options) {
24
24
  payload: codecOf(options.payload)
25
25
  };
26
26
  }
27
+ const appendedId = (cursor) => {
28
+ const id = Number(cursor);
29
+ return cursor !== null && Number.isSafeInteger(id) && id >= 0 && String(id) === cursor ? Option.some(id) : Option.none();
30
+ };
31
+ /**
32
+ * A check source for a store that appends entries under increasing integer ids, such as a table's
33
+ * `INTEGER PRIMARY KEY`: its cursor is the id of the last entry a subscriber read, and an
34
+ * occurrence's `eventId` its entry's id. A new subscriber starts after the newest entry. `event`
35
+ * types the options alone, as `Event.appended(MessagePosted, { … })` in `implement`'s builder.
36
+ *
37
+ * **Gotchas**
38
+ *
39
+ * - A cursor that is not an id up to `newest`'s as the check spells one, digits without a sign, exponent or leading zero, such as another store's or one past a store emptied since, is answered with `truncated: true` and the newest id: the subscriber goes on from there.
40
+ * - A store deleting its oldest entries sends no gap for those a subscriber resuming before them missed: a cursor is stale only past `newest`.
41
+ * - Ids that start again, as a store kept in memory restarts them, make an old cursor read entries it never saw as the ones after it: such a store's cursor carries its epoch in a `check` of its own.
42
+ */
43
+ const appended = (_event, { newest, after, id, nextPoll, ...source }) => ({
44
+ ...source,
45
+ check: (input, cursor) => Effect.gen(function* () {
46
+ const last = yield* newest(input);
47
+ const from = Option.filter(appendedId(cursor), (at) => at <= last);
48
+ if (Option.isNone(from)) return {
49
+ events: [],
50
+ cursor: String(last),
51
+ truncated: cursor !== null,
52
+ nextPoll
53
+ };
54
+ if (from.value === last) return {
55
+ events: [],
56
+ cursor: String(last),
57
+ nextPoll
58
+ };
59
+ const read = yield* after(input, from.value);
60
+ const lastItem = read.items.at(-1);
61
+ const reached = lastItem === void 0 ? from.value : id(lastItem);
62
+ const through = Math.max(read.through ?? reached, reached);
63
+ return {
64
+ events: read.items.map((data) => ({
65
+ eventId: String(id(data)),
66
+ data
67
+ })),
68
+ cursor: String(through),
69
+ hasMore: read.hasMore === true && through > from.value,
70
+ nextPoll
71
+ };
72
+ })
73
+ });
27
74
  /** The server serves no event type of that name, or no longer does. */
28
75
  var NotServed = class extends Schema.TaggedError()("NotServed", {}) {};
29
76
  /**
@@ -100,4 +147,4 @@ function implement(events, sources, options) {
100
147
  }, listed.some((event) => event.caller !== Anyone), options?.authorize);
101
148
  return new EventImplementation(listed, sourcesOf(listed, !Array.isArray(events), sources), authorizer);
102
149
  }
103
- export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, implement, isEvent, layerMemory, make };
150
+ export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, appended, implement, isEvent, layerMemory, make };
@@ -13,22 +13,16 @@ export interface Options {
13
13
  */
14
14
  readonly allowedOrigins?: readonly string[];
15
15
  }
16
- /** One request, as a Node `upgrade` handler or a router middleware sees it. */
17
- export interface Request {
18
- /** The request target: `/a?b` or an absolute URL. Only its path is read. */
19
- readonly target: string;
20
- readonly host: string | undefined;
21
- readonly origin: string | undefined;
22
- }
23
16
  /**
24
- * Build a Host/Origin policy once at startup. `allows` takes no services, so a
25
- * raw request or Node upgrade handler applies the same rule as the router.
17
+ * Build a Host/Origin policy once at startup. `allows` takes a web `Request` and no
18
+ * services, so a Worker's `fetch` or a raw web handler applies the same rule as the router.
26
19
  * The middleware answers refused requests with status 403 and text `Forbidden`.
27
20
  *
28
21
  * **Gotchas**
29
22
  * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
30
23
  * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
31
24
  * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
25
+ * - A request sending no Host header is judged by its absolute target's host, as a Worker's in-process `fetch` sends one; a Node server's path-only target has none, and is refused.
32
26
  */
33
27
  export declare const make: (options: Options) => {
34
28
  allows: (request: Request) => boolean;
@@ -2,6 +2,13 @@ import { Effect } from "effect";
2
2
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
3
3
  // src/http/RequestPolicy.ts
4
4
  const uncheckedProbePath = "/healthz";
5
+ const authorityOf = (target) => {
6
+ const authority = target.indexOf("://");
7
+ if (authority === -1) return;
8
+ const rest = target.slice(authority + 3);
9
+ const stop = rest.search(/[/?#]/u);
10
+ return stop === -1 ? rest : rest.slice(0, stop);
11
+ };
5
12
  const pathOf = (target) => {
6
13
  const authority = target.indexOf("://");
7
14
  const start = authority === -1 ? 0 : target.indexOf("/", authority + 3);
@@ -12,28 +19,33 @@ const pathOf = (target) => {
12
19
  };
13
20
  const forbidden = HttpServerResponse.text("Forbidden", { status: 403 });
14
21
  /**
15
- * Build a Host/Origin policy once at startup. `allows` takes no services, so a
16
- * raw request or Node upgrade handler applies the same rule as the router.
22
+ * Build a Host/Origin policy once at startup. `allows` takes a web `Request` and no
23
+ * services, so a Worker's `fetch` or a raw web handler applies the same rule as the router.
17
24
  * The middleware answers refused requests with status 403 and text `Forbidden`.
18
25
  *
19
26
  * **Gotchas**
20
27
  * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
21
28
  * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
22
29
  * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
30
+ * - A request sending no Host header is judged by its absolute target's host, as a Worker's in-process `fetch` sends one; a Node server's path-only target has none, and is refused.
23
31
  */
24
32
  const make = (options) => {
25
33
  const { host } = options.publicUrl;
26
34
  const origins = /* @__PURE__ */ new Set([options.publicUrl.origin, ...options.allowedOrigins ?? []]);
27
- const allows = (request) => {
35
+ const decide = (request) => {
28
36
  if (pathOf(request.target) === uncheckedProbePath) return true;
29
- if (request.host !== host) return false;
37
+ if ((request.host ?? authorityOf(request.target)) !== host) return false;
30
38
  return request.origin === void 0 || origins.has(request.origin);
31
39
  };
32
40
  return {
33
- allows,
41
+ allows: (request) => decide({
42
+ target: request.url,
43
+ host: request.headers.get("host") ?? void 0,
44
+ origin: request.headers.get("origin") ?? void 0
45
+ }),
34
46
  middleware: HttpRouter.middleware((httpEffect) => Effect.gen(function* () {
35
47
  const request = yield* HttpServerRequest.HttpServerRequest;
36
- return allows({
48
+ return decide({
37
49
  target: request.originalUrl,
38
50
  host: request.headers["host"],
39
51
  origin: request.headers["origin"]
@@ -33,35 +33,14 @@ export interface SecurityMiddleware<I, Name extends string = string> {
33
33
  };
34
34
  }
35
35
  type Response = Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, unknown>;
36
- /** What a provider holds for the surfaces serving its descriptor, beside its identity. */
37
36
  interface Runtime$1 {
38
- /** The descriptor the provider was built from, the one a binding naming it must hold. */
39
37
  readonly descriptor: unknown;
40
- /**
41
- * The verifier itself, for a surface answering refusals its own way, such as RPC: the
42
- * credential to the identity, or a refusal, or an error the descriptor declares. An empty
43
- * credential, as the native decoder gives an absent one, is refused without reaching it.
44
- */
45
38
  readonly authenticate: (credential: Credential) => Effect.Effect<unknown, unknown, unknown>;
46
- /** The native security middleware's implementation, keyed by its scheme. */
47
39
  readonly middleware: Readonly<Record<string, (route: Response, options: {
48
40
  readonly credential: Credential;
49
41
  }) => Response>>;
50
- /**
51
- * A protected HTTP route as it leaves the layer's middleware, a step-up refusal it fails with
52
- * answered with its challenge under Bearer; as it is under another scheme.
53
- */
54
42
  readonly stepUp: HttpApiMiddleware.HttpApiMiddleware<never, never, never>;
55
- /**
56
- * An MCP endpoint's request: decoded here, and a protected tool's call promotes what it
57
- * verified. Where `optional`, a request presenting no credential, which the scheme decodes as
58
- * empty, passes signed out.
59
- */
60
43
  readonly http: <E, R>(route: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>, optional: boolean) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R | HttpRouter.Provided>;
61
- /**
62
- * A route of the host's own: the request is decoded here, the route gets the identity
63
- * itself, and a refusal it fails with is answered as an action route's.
64
- */
65
44
  readonly route: <E, R>(route: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse, Exclude<E, Refusal>, HttpRouter.Provided>;
66
45
  }
67
46
  /**
@@ -81,7 +60,6 @@ export interface Descriptor<I, A, S extends Security, Name extends string = stri
81
60
  readonly schema?: Codec | undefined;
82
61
  readonly "~provider": Context.Key<Provider<I, Name>, Runtime$1>;
83
62
  readonly "~middleware": Context.Key<SecurityMiddleware<I, Name>, unknown>;
84
- /** An MCP request's verified identity, which a protected tool's call promotes. */
85
63
  readonly "~verified": Context.Key<never, unknown>;
86
64
  }
87
65
  /**
@@ -37,10 +37,6 @@ const answer = (error, metadataUrl) => {
37
37
  var SteppedUpRefusal = class extends Context.Service()("effect-actions/SteppedUp") {};
38
38
  const isStepUp = (error) => isRefusal(error) && (!Predicate.isTagged(error, "Forbidden") || error.scopes !== void 0);
39
39
  const recordStepUp = (call) => Effect.tapError(call, (error) => isStepUp(error) ? Effect.flatMap(Effect.serviceOption(SteppedUpRefusal), (slot) => Option.isSome(slot) ? Ref.set(slot.value, Option.some(error)) : Effect.void) : Effect.void);
40
- /**
41
- * `run` as the caller of `called`: unchanged where it is public or nothing authenticates, and
42
- * otherwise with the identity its request verified, a step-up it fails with recorded.
43
- */
44
40
  const asCaller = (authentication, called, run) => authentication === void 0 || called.caller === Anyone ? run : recordStepUp(promote(authentication, run));
45
41
  const answerStepUp = (route, metadataUrl) => Effect.gen(function* () {
46
42
  const slot = yield* Ref.make(Option.none());
@@ -1,8 +1,4 @@
1
1
  import "./implementation.mjs";
2
- import { Refusal } from "./errors.mjs";
3
2
  import { Effect } from "effect";
4
- /** `T`, read only once it is inferred: an implementation's build channels. */
5
3
  type Deferred$1<T> = [T][T extends unknown ? 0 : never];
6
- /** What `implement` takes as `authorize` for contracts `C`: the rule, or an Effect building it. */
7
- export type Authorizer<C, RA, EAX, RAX> = ((contract: C) => Effect.Effect<void, Refusal, RA>) | Effect.Effect<(contract: C) => Effect.Effect<void, Refusal, RA>, EAX, RAX>;
8
4
  export { Deferred$1 as Deferred };
@@ -24,10 +24,6 @@ const jsonRoundTrip = (schema) => {
24
24
  value: received
25
25
  })));
26
26
  };
27
- /**
28
- * A call's or a watch's input as it is sent, `{}` decoded where it is left out: its JSON, and the
29
- * value the server decodes from it.
30
- */
31
27
  const sentInput = (event, input) => inputOf(event, input === void 0 ? [] : [input]).pipe(Effect.flatMap(jsonRoundTrip(event.input)), Effect.mapError(InvalidInput.fromSchemaError));
32
28
  const sendingJson = (action) => Schema.encodeUnknownEffect(Schema.toCodecJson(action.input), { errors: "all" });
33
29
  const sendingValue = (action) => {
@@ -7,7 +7,6 @@ import { Context, Effect, Function } from "effect";
7
7
  */
8
8
  const Anyone = Symbol.for("@gjermundgaraba/effect-actions/Anyone");
9
9
  const CallerKeyed = Context.Reference("effect-actions/CallerKeyed", { defaultValue: Function.constUndefined });
10
- /** The caller's principal: none for a public one, or on a surface with no authentication. */
11
10
  const principalOf = (called, keyed) => keyed === void 0 || called.caller === Anyone ? Effect.undefined : Effect.map(Effect.service(called.caller), keyed.principal);
12
11
  const assertAuthentication = (contracts, authentication, noun = "action") => {
13
12
  for (const contract of contracts) if (contract.caller !== Anyone && (authentication === void 0 || contract.caller.key !== authentication.identity.key)) throw new Error(`Protected ${noun} '${contract.name}' requires its matching authentication descriptor (give it the authentication whose identity the ${noun}'s caller names)`);
@@ -16,7 +16,6 @@ type Single<T> = true extends Types.IsUnion<T> ? never : T;
16
16
  * `E` may be one of several.
17
17
  */
18
18
  export type Certain<E extends Errors> = true extends Types.IsUnion<E> ? never : number extends E["length"] ? never : { readonly [K in keyof E]: Single<E[K]>; }[number];
19
- /** The errors a binding declares for every call, and its protected actions' authentication's. */
20
19
  export interface Declaring {
21
20
  readonly error: Errors;
22
21
  readonly authentication?: {
@@ -80,11 +80,8 @@ export declare class EventImplementation<E extends Any, R, EX, RX, RA = never, E
80
80
  /** The event types this implementation answers. */
81
81
  readonly events: readonly E[];
82
82
  constructor(events: readonly E[], running: Running<EX, RX>, authorizer: Memoized<ErasedAuthorize<Any>, EAX, RAX>);
83
- /** Select event types while retaining their sources, authorization and shared builder. */
84
83
  static share(events: readonly Any[], app: AnyEventImplementation): AnyEventImplementation;
85
- /** The builders of `app`, its sources' and its authorizer's, as one layer. */
86
84
  static layerOf(app: AnyEventImplementation): Layer.Layer<never, unknown, unknown>;
87
- /** The event types of `app` with what runs them, behind its authorizer. */
88
85
  static feedsOf(app: AnyEventImplementation): Effect.Effect<readonly Feed[], never, unknown>;
89
86
  private static held;
90
87
  private static own;
@@ -1,6 +1,7 @@
1
1
  import { jsonRoundTrip } from "./call.mjs";
2
2
  import { Anyone } from "./caller.mjs";
3
- import { canonicalInput } from "./canonical.mjs";
3
+ import { canonical, canonicalInput } from "./canonical.mjs";
4
+ import { sha256Hex } from "./digest.mjs";
4
5
  import { Unauthenticated } from "./errors.mjs";
5
6
  import { Events, attachmentsOf, reaches } from "./hub.mjs";
6
7
  import { builderLayer, memoized, notMadeHere } from "./implementation.mjs";
@@ -10,9 +11,10 @@ import { AnyOccurrence, Gap } from "./occurrence.mjs";
10
11
  import { fedOf, pagedFrom } from "./pages.mjs";
11
12
  import { reported } from "./reported.mjs";
12
13
  import { Wake } from "./wake.mjs";
13
- import { Array, DateTime, Duration, Effect, Layer, Option, Predicate, Stream } from "effect";
14
+ import { Array, DateTime, Duration, Effect, Exit, Layer, Option, Predicate, Stream } from "effect";
14
15
  // src/contract/feed.ts
15
16
  const defaultNextPoll = Duration.seconds(5);
17
+ const shortestNextPoll = Duration.seconds(1);
16
18
  const longestNextPoll = Duration.minutes(5);
17
19
  const logPageSize = 100;
18
20
  const pageLimit = (maxEvents) => Math.min(Math.max(Math.floor(maxEvents), 1), logPageSize);
@@ -45,7 +47,10 @@ const answeredPage = ({ answered, items }) => pageFrom(items, {
45
47
  cursor: answered.cursor,
46
48
  truncated: answered.truncated === true,
47
49
  hasMore: answered.hasMore === true,
48
- nextPoll: Duration.min(Duration.fromInputUnsafe(answered.nextPoll ?? defaultNextPoll), longestNextPoll)
50
+ nextPoll: Duration.clamp(Duration.fromInputUnsafe(answered.nextPoll ?? defaultNextPoll), {
51
+ minimum: shortestNextPoll,
52
+ maximum: longestNextPoll
53
+ })
49
54
  });
50
55
  const checkRun = (event, source, { wakes }) => {
51
56
  const occurrenceOf = occurrencesOf(event);
@@ -68,24 +73,39 @@ const checkRun = (event, source, { wakes }) => {
68
73
  })), cursor, woken, polls)))
69
74
  };
70
75
  };
71
- const currentRun = (event, source, checking) => checkRun(event, {
72
- key: source.key,
73
- notified: true,
74
- check: (input, cursor) => Effect.gen(function* () {
75
- const at = yield* checking.revision(yield* keyOf(source, input));
76
- if (cursor === at) return {
77
- cursor: at,
78
- events: []
79
- };
80
- return {
81
- cursor: at,
82
- events: [{
83
- eventId: at,
84
- data: yield* source.current(input)
85
- }]
86
- };
87
- })
88
- }, checking);
76
+ const currentRun = (event, source, checking) => {
77
+ const sent = jsonRoundTrip(event.payload);
78
+ return checkRun(event, {
79
+ key: source.key,
80
+ notified: true,
81
+ check: (input, cursor) => Effect.gen(function* () {
82
+ const key = yield* keyOf(source, input);
83
+ const at = yield* checking.revision(key);
84
+ const { digest: seen, revision } = cursor?.match(/^(?<digest>[0-9a-f]*)\.(?<revision>.*)$/su)?.groups ?? {};
85
+ if (cursor !== null && revision === at) return {
86
+ cursor,
87
+ events: [],
88
+ nextPoll: source.nextPoll
89
+ };
90
+ const data = yield* source.current(input);
91
+ const snapshot = yield* Effect.exit(sent(data));
92
+ const digest = Exit.isSuccess(snapshot) ? yield* sha256Hex(canonical([
93
+ yield* canonicalInput(event.input, input),
94
+ key ?? null,
95
+ snapshot.value.json
96
+ ])) : "";
97
+ const next = `${digest}.${at}`;
98
+ return {
99
+ cursor: next,
100
+ events: digest === seen ? [] : [{
101
+ eventId: next,
102
+ data: Exit.isSuccess(snapshot) ? snapshot.value.value : data
103
+ }],
104
+ nextPoll: source.nextPoll
105
+ };
106
+ })
107
+ }, checking);
108
+ };
89
109
  const logRun = (event, source, log) => {
90
110
  const occurrenceOf = occurrencesOf(event);
91
111
  const delivered = (input, key, { cursor, at, value: logged }) => Effect.gen(function* () {
@@ -203,18 +223,15 @@ var EventImplementation = class EventImplementation {
203
223
  this.#running = running;
204
224
  this.#authorizer = authorizer;
205
225
  }
206
- /** Select event types while retaining their sources, authorization and shared builder. */
207
226
  static share(events, app) {
208
227
  const source = EventImplementation.own(app);
209
228
  return new EventImplementation(events, source.#running, source.#authorizer);
210
229
  }
211
- /** The builders of `app`, its sources' and its authorizer's, as one layer. */
212
230
  static layerOf(app) {
213
231
  const source = EventImplementation.own(app);
214
232
  const runs = Layer.mergeAll(Layer.empty, ...EventImplementation.held(app).map(([, run]) => run.layer));
215
233
  return builderLayer(app.events, { layer: runs }, source.#authorizer);
216
234
  }
217
- /** The event types of `app` with what runs them, behind its authorizer. */
218
235
  static feedsOf(app) {
219
236
  const source = EventImplementation.own(app);
220
237
  return Effect.gen(function* () {
@@ -40,16 +40,6 @@ const holding = (set, value) => Effect.acquireRelease(Effect.sync(() => {
40
40
  set.add(value);
41
41
  return value;
42
42
  }), () => Effect.sync(() => set.delete(value)));
43
- /**
44
- * An `Events` for as long as the scope lasts, over the log storage `log` makes: what
45
- * `Stored.layerEvents` provides over SQL, its subscribers' wakes in memory and its logs where
46
- * `log` keeps them.
47
- *
48
- * **Gotchas**
49
- *
50
- * - Make it once per database, around the handlers that announce and the surfaces that serve, as `layerMemory` is built.
51
- * - A log's storage is made once per event for the life of the scope, its position read on every append and read: a storage emptied behind its back starts a new epoch, and a cursor from before reads a gap.
52
- */
53
43
  const makeEvents = (options) => Effect.gen(function* () {
54
44
  const revisions = options.revisions ?? memoryRevisions();
55
45
  const scope = yield* Effect.scope;
@@ -5,30 +5,19 @@ import { Any as Any$1 } from "../Event.mjs";
5
5
  import { AnyEventImplementation, EventOf } from "./feed.mjs";
6
6
  import { Reporting } from "./progress.mjs";
7
7
  import { Context, Effect, Layer, Scope, Stream } from "effect";
8
- /** Decoded values at the dispatch boundary every surface shares. */
9
8
  export type ErasedValue = Any["input"]["Type"];
10
9
  export type WrittenHandler<R> = {
11
10
  bivarianceHack(input: ErasedValue, reporting?: Reporting): Effect.Effect<ErasedValue, ErasedValue, R> | Stream.Stream<ErasedValue, ErasedValue, R>;
12
11
  }["bivarianceHack"];
13
- /**
14
- * A handler behind its action's authentication, authorization and declared errors, as a surface
15
- * calls it. For an action answering a stream it succeeds at once with the call's stream, which
16
- * `elementsOf` reads, the refusals included. `reporting` is where its progress goes, ignored for
17
- * an action declaring no `progress`, so a surface may hand one to every call.
18
- */
19
12
  export type ErasedHandler<R> = (input: ErasedValue, reporting?: Reporting) => Effect.Effect<ErasedValue, ErasedValue, R>;
20
13
  /**
21
14
  * Authorization for protected contracts: it refuses, and fails with nothing else. It runs only for
22
15
  * protected actions, after authentication and before the handler.
23
16
  */
24
17
  export type Authorize<A extends Any, R = never> = (action: A) => Effect.Effect<void, Refusal, R>;
25
- /** An authorization rule over contracts `C`, erased: it refuses, or lets the call run. */
26
18
  export type ErasedAuthorize<C = Any> = (contract: C) => Effect.Effect<void, unknown, unknown>;
27
- /** Each action of an implementation with its handler, as `dispatch` makes it. */
28
19
  export type Bound = ReadonlyArray<readonly [Any, ErasedHandler<unknown>]>;
29
- /** Each action of an implementation with its handler as written, as its builder made them. */
30
20
  export type Written = ReadonlyArray<readonly [Any, WrittenHandler<unknown>]>;
31
- /** A build shared by every layer an implementation reaches, through the one key it is provided under. */
32
21
  export interface Memoized<S, E, R> {
33
22
  readonly key: Context.Key<S, S>;
34
23
  readonly layer: Layer.Layer<S, E, R>;
@@ -58,17 +47,8 @@ export declare class Implementation<A extends Any, RequestServices, EX, RX, RA =
58
47
  readonly "~authorizeBuildServices": RAX;
59
48
  /** The contracts this implementation answers. */
60
49
  readonly actions: readonly A[];
61
- constructor(actions: readonly A[],
62
- /** Builds each action paired with its handler: its own builder, or the one it shares. */
63
- handlers: Memoized<Written, EX, RX>,
64
- /** Builds its authorizer. */
65
- authorizer: Memoized<ErasedAuthorize, EAX, RAX>);
66
- /** Select contracts while retaining their handlers, authorization and shared builder. */
50
+ constructor(actions: readonly A[], handlers: Memoized<Written, EX, RX>, authorizer: Memoized<ErasedAuthorize, EAX, RAX>);
67
51
  static share(actions: readonly Any[], app: AnyImplementation): AnyImplementation;
68
- /**
69
- * The key of what runs a call of `app`'s actions: its handlers' memoized layer's, which each
70
- * `implement` makes, so it is unique to the implementation. Every selection retains it.
71
- */
72
52
  static runKey(app: AnyImplementation): string;
73
53
  /**
74
54
  * The builders of `app`, its handlers' and its authorizer's, as a layer. Effect memoizes each
@@ -76,10 +56,6 @@ export declare class Implementation<A extends Any, RequestServices, EX, RX, RA =
76
56
  * implementation sharing its builder, shares one run.
77
57
  */
78
58
  static layerOf(app: AnyImplementation): Layer.Layer<never, unknown, unknown>;
79
- /**
80
- * The actions of `app` with their handlers, behind its authorizer, from the context
81
- * `layerOf(app)` provides.
82
- */
83
59
  static boundOf(app: AnyImplementation, keyed: Keyed | undefined): Effect.Effect<Bound, never, unknown>;
84
60
  private static own;
85
61
  }
@@ -141,9 +117,10 @@ type Listing<O> = O extends unknown ? NonNullable<O["actions" & keyof O]> : neve
141
117
  /**
142
118
  * No key of any member of `O` beyond those of `Keys`, so a misspelled option is refused
143
119
  * rather than ignored: options inferred whole, as a type parameter, skip TypeScript's own
144
- * check, and `keyof` a union holds only the keys every member has.
120
+ * check, and `keyof` a union holds only the keys every member has. An index signature of `O`,
121
+ * a record built at runtime, names no key, so it is left to the runtime check.
145
122
  */
146
- export type Known<O, Keys> = { readonly [K in Exclude<O extends unknown ? keyof O : never, keyof Keys>]?: never; };
123
+ export type Known<O, Keys> = { readonly [K in Exclude<O extends unknown ? keyof O : never, keyof Keys> as string extends K ? never : number extends K ? never : K]?: never; };
147
124
  /**
148
125
  * The parameters of an optional options argument of type `O`: required where `O` names what
149
126
  * only a given argument holds, such as listed actions, so explicit type arguments cannot
@@ -73,15 +73,10 @@ var Implementation = class Implementation {
73
73
  this.#handlers = handlers;
74
74
  this.#authorizer = authorizer;
75
75
  }
76
- /** Select contracts while retaining their handlers, authorization and shared builder. */
77
76
  static share(actions, app) {
78
77
  const source = Implementation.own(app);
79
78
  return new Implementation(actions, source.#handlers, source.#authorizer);
80
79
  }
81
- /**
82
- * The key of what runs a call of `app`'s actions: its handlers' memoized layer's, which each
83
- * `implement` makes, so it is unique to the implementation. Every selection retains it.
84
- */
85
80
  static runKey(app) {
86
81
  return Implementation.own(app).#handlers.key.key;
87
82
  }
@@ -94,10 +89,6 @@ var Implementation = class Implementation {
94
89
  const source = Implementation.own(app);
95
90
  return builderLayer(app.actions, source.#handlers, source.#authorizer);
96
91
  }
97
- /**
98
- * The actions of `app` with their handlers, behind its authorizer, from the context
99
- * `layerOf(app)` provides.
100
- */
101
92
  static boundOf(app, keyed) {
102
93
  const { actions } = app;
103
94
  const source = Implementation.own(app);
@@ -1,7 +1,6 @@
1
1
  import { Codec } from "./codec.mjs";
2
2
  import { ErasedValue } from "./implementation.mjs";
3
3
  import { Data, Effect, Scope, Stream } from "effect";
4
- /** Where a call's progress goes: each value reported, checked by its schema, is given to `progress`. */
5
4
  export interface Reporting {
6
5
  readonly progress: (value: ErasedValue) => Effect.Effect<void>;
7
6
  }
@@ -11,23 +11,29 @@ const selectFrom = (served, actions) => {
11
11
  events: select(eventKind, eventsOf(served), listed.events)
12
12
  };
13
13
  };
14
- const servedBy = (kind, what, bound, apps, listed) => {
14
+ const servedBy = (kind, bound, apps, listed) => {
15
15
  const { noun, holds } = kind;
16
16
  if (listed !== void 0) assertHeld(notHeld.byBinding, listed, bound);
17
- const held = apps.flatMap(holds);
18
- if (listed === void 0 && apps.length > 0 && !held.some((contract) => bound.includes(contract))) {
19
- const names = new Set(bound.map(({ name }) => name));
20
- throw new Error(`No ${noun} of these implementations is in this ${what}: ${markingOthers(held, names) || "none"} (pass an implementation of a bound ${noun}, or bind one of these)`);
21
- }
22
- const served = select(kind, apps, listed ?? bound.filter((contract) => held.includes(contract)));
17
+ const held = new Set(apps.flatMap(holds));
18
+ const served = select(kind, apps, listed ?? bound.filter((contract) => held.has(contract)));
23
19
  assertOnce(`served ${noun}`, served.flatMap(holds), heldOnce);
24
20
  return served;
25
21
  };
22
+ const assertBound = ({ noun, holds }, what, bound, apps, served, otherServed) => {
23
+ if (served.length === 0 && apps.length > 0 && (bound.length > 0 || otherServed.length === 0)) {
24
+ const names = new Set(bound.map(({ name }) => name));
25
+ throw new Error(`No ${noun} of these implementations is in this ${what}: ${markingOthers(apps.flatMap(holds), names) || "none"} (pass an implementation of a bound ${noun}, or bind one of these)`);
26
+ }
27
+ };
26
28
  const servingOf = (what, binding, served, options) => {
27
29
  const listed = selection(options.actions);
28
- const apps = servedBy(actionKind, what, binding.actions, toList(served), listed.actions);
30
+ const implementations = toList(served);
31
+ const eventImplementations = eventsOf(served);
32
+ const apps = servedBy(actionKind, binding.actions, implementations, listed.actions);
33
+ const events = servedBy(eventKind, binding.events, eventImplementations, listed.events);
34
+ if (listed.actions === void 0) assertBound(actionKind, what, binding.actions, implementations, apps, events);
35
+ if (listed.events === void 0) assertBound(eventKind, what, binding.events, eventImplementations, events, apps);
29
36
  const actions = apps.flatMap((app) => app.actions);
30
- const events = servedBy(eventKind, what, binding.events, eventsOf(served), listed.events);
31
37
  const eventTypes = events.flatMap((app) => app.events);
32
38
  assertAuthentication(actions, binding.authentication);
33
39
  assertAuthentication(eventTypes, binding.authentication, "event");
@@ -3,7 +3,6 @@ import { CallbackCategory, SubscriptionError, Unsupported } from "../Event.mjs";
3
3
  import { SubscriptionOf } from "./push.mjs";
4
4
  import { Schema, Struct } from "effect";
5
5
  // src/contract/subscribe.ts
6
- /** The error for `event` that is not delivered by `mode` where it is asked for. */
7
6
  const deliveryUnsupported = (event, mode) => SubscriptionError.of(event, new Unsupported({
8
7
  feature: "deliveryMode",
9
8
  value: mode
@@ -0,0 +1,14 @@
1
+ import { Unavailable } from "./errors.mjs";
2
+ import { Context, Effect } from "effect";
3
+ declare const Wake_base: Context.ServiceClass<Wake, "effect-actions/Wake", {
4
+ readonly wakeAt: (at: number) => Effect.Effect<void, Unavailable>;
5
+ readonly until: (at: number) => Effect.Effect<void>;
6
+ }>;
7
+ /**
8
+ * An entity's wake, which `ActionEntity.layer` provides to its activation: `wakeAt` schedules the
9
+ * persisted tell `ActionEntity.wakeAt` promises, and `until` waits in the activation for one, so
10
+ * a stopped activation is built again when it is due, where a timer is cut by Effect's reaper and
11
+ * keeps a Durable Object awake. Absent outside an entity.
12
+ */
13
+ export declare class Wake extends Wake_base {}
14
+ export {};
@@ -1,9 +1,10 @@
1
1
  import { Context } from "effect";
2
2
  // src/contract/wake.ts
3
3
  /**
4
- * How an entity's activation waits until a time, which `ActionEntity.layer` provides to its
5
- * `services`: a wait that builds a stopped activation again when it is due, where a timer is cut
6
- * by Effect's reaper and keeps a Durable Object awake. Absent outside an entity.
4
+ * An entity's wake, which `ActionEntity.layer` provides to its activation: `wakeAt` schedules the
5
+ * persisted tell `ActionEntity.wakeAt` promises, and `until` waits in the activation for one, so
6
+ * a stopped activation is built again when it is due, where a timer is cut by Effect's reaper and
7
+ * keeps a Durable Object awake. Absent outside an entity.
7
8
  */
8
9
  var Wake = class extends Context.Service()("effect-actions/Wake") {};
9
10
  export { Wake };
@@ -14,24 +14,16 @@ import { Context, Effect, Option } from "effect";
14
14
  * `Event.SubscriptionError`.
15
15
  */
16
16
  var Webhooks = class extends Context.Service()("effect-actions/Webhooks") {};
17
- /** Whether a surface offers `event` by webhook: a protected one, its caller an identity. */
18
17
  const offersWebhook = (event) => event.caller !== Anyone;
19
18
  const offeredByWebhook = (feed) => offersWebhook(feed.event);
20
19
  const deliversByWebhook = (feed) => feed.webhook === void 0 && offeredByWebhook(feed);
21
- /**
22
- * Who subscribes to `feed`'s webhooks, and where they are held: the holder the feed names, a
23
- * reached entity, or else the surface's own `Webhooks`; none where the event is not offered by
24
- * webhook. Its principal is read from the caller each time it runs.
25
- */
26
20
  const webhookSubscriber = (feed, keyed, webhooks) => keyed !== void 0 && offeredByWebhook(feed) ? Option.map(feed.webhook === void 0 ? webhooks : Option.some(feed.webhook), (holder) => Effect.map(Effect.service(feed.event.caller), (identity) => ({
27
21
  webhooks: holder,
28
22
  feed,
29
23
  keyed,
30
24
  principal: keyed.principal(identity)
31
25
  }))) : Option.none();
32
- /** As `webhookSubscriber`, failing as `Unsupported` where the event is not offered by webhook. */
33
26
  const subscriberOf = (feed, keyed, webhooks) => Option.getOrElse(webhookSubscriber(feed, keyed, webhooks), () => Effect.fail(deliveryUnsupported(feed.event.name, "webhook")));
34
- /** A surface's answers to a webhook subscribe and unsubscribe of `feed`, run as its subscriber. */
35
27
  const webhookAnswers = (feed, keyed, webhooks) => {
36
28
  const served = subscriberOf(feed, keyed, webhooks);
37
29
  return {
@@ -46,11 +38,6 @@ const webhookAnswers = (feed, keyed, webhooks) => {
46
38
  }))
47
39
  };
48
40
  };
49
- /**
50
- * The feeds of `events` a surface's layer serves, and the `Webhooks` it offers them by: run as
51
- * the layer builds, which serves the webhooks it delivers itself, those of the feeds `holds`
52
- * admits, and restores their kept subscriptions.
53
- */
54
41
  const servingFeeds = Effect.fnUntraced(function* (events, keyed, holds = () => true) {
55
42
  const feeds = yield* acquireFeeds(events);
56
43
  const webhooks = yield* Effect.serviceOption(Webhooks);